program story

조각에서 컨텍스트 사용

inputbox 2020. 10. 2. 22:13
반응형

조각에서 컨텍스트 사용


조각에서 컨텍스트를 얻으려면 어떻게해야합니까?

나는 누구의 생성자 맥락에서 소요 내 데이터베이스를 사용할 필요가 있지만, getApplicationContext()그리고 FragmentClass.this내가 무엇을 할 수 있는지 작동하지 않습니다?

데이터베이스 생성자

public Database(Context ctx)
{
    this.context = ctx;
    DBHelper = new DatabaseHelper(context);
}

를 사용할 수 있습니다 getActivity(). 이는 fragment.
활동은 context ( Activity확장 이후 Context) 입니다.


위의 답변으로 수행하려면 onAttachfragment 메서드를 재정의 할 수 있습니다 .

public static class DummySectionFragment extends Fragment{
...
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        DBHelper = new DatabaseHelper(activity);
    }
}

항상 getActivity () 메서드를 사용 하여 연결된 활동의 컨텍스트를 가져 오되getActivity , 항상 한 가지를 기억하십시오. Fragments는 약간 불안정하고 때때로 null을 반환하므로에서 컨텍스트를 가져 오기 전에 항상 조각 i Added () 메서드를 확인하십시오 getActivity().


내가 찾은 프래그먼트의 컨텍스트를 얻는 가장 쉽고 정확한 방법은 적어도 여기에서 메소드 ViewGroup를 호출 할 때 직접 가져 오는 것 onCreateView입니다 getActivity().

public class Animal extends Fragment { 
  Context thiscontext;
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
  {
    thiscontext = container.getContext();

@Override
public void onAttach(Activity activity) {
    // TODO Auto-generated method stub
    super.onAttach(activity);
    context=activity;
}

이전에 나는 onAttach (Activity activity)들어가기 위해 사용 context했습니다.Fragment

문제

onAttach (Activity activity)메서드는 API 레벨 23에서 더 이상 사용되지 않습니다.

해결책

지금 상황을 얻기 위해 Fragment우리가 사용할 수 있습니다onAttach (Context context)

onAttach (Context context)

  • 조각이 context. onCreate(Bundle)이 후에 호출됩니다.

선적 서류 비치

/**
 * Called when a fragment is first attached to its context.
 * {@link #onCreate(Bundle)} will be called after this.
 */
@CallSuper
public void onAttach(Context context) {
    mCalled = true;
    final Activity hostActivity = mHost == null ? null : mHost.getActivity();
    if (hostActivity != null) {
        mCalled = false;
        onAttach(hostActivity);
    }
}

샘플 코드

public class FirstFragment extends Fragment {


    private Context mContext;
    public FirstFragment() {
        // Required empty public constructor
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext=context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rooView=inflater.inflate(R.layout.fragment_first, container, false);

        Toast.makeText(mContext, "THIS IS SAMPLE TOAST", Toast.LENGTH_SHORT).show();
        // Inflate the layout for this fragment
        return rooView;
    }

}

노트

우리는 또한 사용할 수 있습니다 getActivity()얻을 contextFragments있지만 getActivity()반환 할 수 있습니다 null당신의이 경우 fragment현재 부모에 연결되어 있지 않습니다 activity,


또 다른 대안은 다음과 같습니다.

다음을 사용하여 컨텍스트를 가져올 수 있습니다.

getActivity().getApplicationContext();

to get the context inside the Fragment will be possible using getActivity() :

public Database()
{
    this.context = getActivity();
    DBHelper = new DatabaseHelper(this.context);
}
  • Be careful, to get the Activity associated with the fragment using getActivity(), you can use it but is not recommended it will cause memory leaks.

I think a better aproach must be getting the Activity from the onAttach() method:

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    context = activity;
}

You could also get the context from the inflater parameter, when overriding onCreateView.

public static class MyFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
        /* ... */
        Context context = inflater.getContext();
        /* ... */
    }
}

getContext() came in API 23. Replace it with getActivity() everywhere in the code.

See if it fixes the error. Try to use methods which are in between the target and minimun API level, else this error will come in place.


Since API level 23 there is getContext() but if you want to support older versions you can use getActivity().getApplicationContext() while I still recommend using the support version of Fragment which is android.support.v4.app.Fragment.


getActivity() is a child of Context so that should work for you


Use fragments from Support Library -

android.support.v4.app.Fragment

and then override

void onAttach (Context context) {
  this.context = context;
}

This way you can be sure that context will always be a non-null value.


You have different options:

  • If your minSDK <= 21, then you can use getActivity(), since this is a Context.
  • If your minSDK is >=23, then you can use getContext().

If you don't need to support old versions then go with getContext().


For Kotlin you can use context directly in fragments. But in some cased you will find an error like

Type mismatch: inferred type is Context? but Context was expected

for that you can do this

val ctx = context ?: return
textViewABC.setTextColor(ContextCompat.getColor(ctx, android.R.color.black))

Ideally, you should not need to use globals. The fragment has different notifications, one of them being onActivityCreated. You can get the instance of the activity in this lifecycle event of the fragment.

Then: you can dereference the fragment to get activity, context or applicationcontext as you desire:

this.getActivity() will give you the handle to the activity this.getContext() will give you a handle to the context this.getActivity().getApplicationContext() will give you the handle to the application context. You should preferably use the application context when passing it on to the db.


The simple way is to use getActivity(). But I think the major confusion of using the getActivity() method to get the context here is a null pointer exception.

For this, first check with the isAdded() method which will determine whether it's added or not, and then we can use the getActivity() to get the context of Activity.


You can call getActivity() or,

public void onAttach(Context context) {
    super.onAttach(context);
    this.activity = (CashActivity) context;
    this.money = this.activity.money;
}

In kotlin just use activity instead of getActivity()


getContext() method helps to use the Context of the class in a fragment activity.


I think you can use

public static class MyFragment extends Fragment {
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

      Context context = getActivity.getContext();

  }
}

public class MenuFragment extends Fragment implements View.OnClickListener {
    private Context mContext;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        FragmentMenuBinding binding=FragmentMenuBinding.inflate(inflater,container,false);
        View view=binding.getRoot();
        mContext=view.getContext();
        return view;
    }
}

Also you can use:

inflater.getContext();

but I would prefer to use

getActivity()

or

getContext

I need context for using arrayAdapter IN fragment, when I was using getActivity error occurs but when i replace it with getContext it works for me

listView LV=getView().findViewById(R.id.listOFsensors);
LV.setAdapter(new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_1 ,listSensorType));

You can use getActivity() or getContext in Fragment.

Documentation

/**
 * Return the {@link FragmentActivity} this fragment is currently associated with.
 * May return {@code null} if the fragment is associated with a {@link Context}
 * instead.
 *
 * @see #requireActivity()
 */
@Nullable
final public FragmentActivity getActivity() {
    return mHost == null ? null : (FragmentActivity) mHost.getActivity();
}

and

 /**
     * Return the {@link Context} this fragment is currently associated with.
     *
     * @see #requireContext()
     */
    @Nullable
    public Context getContext() {
        return mHost == null ? null : mHost.getContext();
    }

Pro tip

Check always if(getActivity!=null) because it can be null when fragment is not attached to activity. Sometimes doing long operation in fragment (like fetching data from rest api) takes some time. and if user navigate to another fragment. Then getActivity will be null. And you will get NPE if you did not handle it.


On you fragment

((Name_of_your_Activity) getActivity()).helper

On Activity

DbHelper helper = new DbHelper(this);

참고URL : https://stackoverflow.com/questions/8215308/using-context-in-a-fragment

반응형