Android Get Activity Returns Null

getActivity() returns null in Fragment function

commit schedules the transaction, i.e. it doesn't happen straightaway but is scheduled as work on the main thread the next time the main thread is ready.

I'd suggest adding an

onAttach(Activity activity)

method to your Fragment and putting a break point on it and seeing when it is called relative to your call to asd(). You'll see that it is called after the method where you make the call to asd() exits. The onAttach call is where the Fragment is attached to its activity and from this point getActivity() will return non-null (nb there is also an onDetach() call).

Android. Fragment getActivity() sometimes returns null

It seems that I found a solution to my problem.
Very good explanations are given here and here.
Here is my example:

pulic class MyActivity extends FragmentActivity{

private ViewPager pager;
private TitlePageIndicator indicator;
private TabsAdapter adapter;
private Bundle savedInstanceState;

@Override
public void onCreate(Bundle savedInstanceState) {

....
this.savedInstanceState = savedInstanceState;
pager = (ViewPager) findViewById(R.id.pager);;
indicator = (TitlePageIndicator) findViewById(R.id.indicator);
adapter = new TabsAdapter(getSupportFragmentManager(), false);

if (savedInstanceState == null){
adapter.addFragment(new FirstFragment());
adapter.addFragment(new SecondFragment());
}else{
Integer count = savedInstanceState.getInt("tabsCount");
String[] titles = savedInstanceState.getStringArray("titles");
for (int i = 0; i < count; i++){
adapter.addFragment(getFragment(i), titles[i]);
}
}

indicator.notifyDataSetChanged();
adapter.notifyDataSetChanged();

// push first task
FirstTask firstTask = new FirstTask(MyActivity.this);
// set first fragment as listener
firstTask.setTaskListener((TaskListener) getFragment(0));
firstTask.execute();

}

private Fragment getFragment(int position){
return savedInstanceState == null ? adapter.getItem(position) : getSupportFragmentManager().findFragmentByTag(getFragmentTag(position));
}

private String getFragmentTag(int position) {
return "android:switcher:" + R.id.pager + ":" + position;
}

@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tabsCount", adapter.getCount());
outState.putStringArray("titles", adapter.getTitles().toArray(new String[0]));
}

indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
Fragment currentFragment = adapter.getItem(position);
((Taskable) currentFragment).executeTask();
}

@Override
public void onPageScrolled(int i, float v, int i1) {}

@Override
public void onPageScrollStateChanged(int i) {}
});

The main idea in this code is that, while running your application normally, you create new fragments and pass them to the adapter. When you are resuming your application fragment manager already has this fragment's instance and you need to get it from fragment manager and pass it to the adapter.

UPDATE

Also, it is a good practice when using fragments to check isAdded before getActivity() is called. This helps avoid a null pointer exception when the fragment is detached from the activity. For example, an activity could contain a fragment that pushes an async task. When the task is finished, the onTaskComplete listener is called.

@Override
public void onTaskComplete(List<Feed> result) {

progress.setVisibility(View.GONE);
progress.setIndeterminate(false);
list.setVisibility(View.VISIBLE);

if (isAdded()) {

adapter = new FeedAdapter(getActivity(), R.layout.feed_item, result);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}

}

If we open the fragment, push a task, and then quickly press back to return to a previous activity, when the task is finished, it will try to access the activity in onPostExecute() by calling the getActivity() method. If the activity is already detached and this check is not there:

if (isAdded()) 

then the application crashes.

Fragment getActivity is always returning null from Async Task

Pass Activity to AsyncTask method

new Demo().execute(getActivity());

public class Demo extends AsyncTask<Activity,Void,Void>{
Activity activity=null;
@Override
protected Void doInBackground(Activity... params) {
activity=params[0]; //get the activity instance
//Do your task

return null;
}
}

Android Fragment getActivity() = null

In my experience, most cases of getActivity() returning null are in asynchronous callbacks.

For example, your fragment fires an AsyncTask, and then gets removed before the the background job is done, then when the background job finishes and calls getActivity() in onPostExecute(), it will get a null since the fragment is already detached from the activity.

My solution:

1.Check getActivity()==null at the beginning of every asynchronous callback, if it's the case then just abort the method.

2.Cancel asynchronous jobs in onDetach().

And I think this is a better solution than saving the activity instance in onAttach(), because since your fragment is removed, why bother doing all the jobs left in the callbacks(in most cases UI codes)?

Why does getActivity of my fragment returns null?

Your fragment has probably been detached from the activity. See this link for more details.



Related Topics



Leave a reply



Submit