简体   繁体   中英

Why doesn't getActivity() on a listfragment work when ran from a dialogfragment

My ListFragment is in a viewpager and the actionbar has a button that opens a dialogfragment. Then I'm trying to call a function with non-static methods to update my simple adapter from that dialogfragment like this:

MyDialogFragment.java

public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle(R.string.dialogtitle);
    builder.setSingleChoiceItems(R.array.items, indx, new DialogInterface.OnClickListener() {

MyListFragment updateItems = new MyListFragment();      

               public void onClick(DialogInterface dialog, int id) {
                   updateItems.updater();
                   dialog.dismiss();
                   ...
}
}

MyListFragment.java

public void updater(){
      ArrayList<Map<String, String>> list = buildData();

String[] from = { "name", "address", "postalcode", "item", "item2", "item3" };
int[] to = { R.id.title, R.id.address, R.id.postalcode, R.id.item1, R.id.imageView1, R.id.item3 };

ListAdapter adapter = new SimpleAdapter(getActivity(), list,
    R.layout.rowlayout, from, to);
setListAdapter(adapter);    
}

ListAdapter adapter = new SimpleAdapter(getActivity(), list, R.layout.rowlayout, from, to) line gives me null pointer exception.

Fragment should be attached since I tried the lifecycle of that fragment by adding System.out.println("onAttach") (or onResume and etc.) to every step to make sure that the status of the fragment isn't changed when the dialog box is opened.

I also added a button to that listfragment to do "updater();" and it works as supposed to.

Any good ideas why this doesn't work when run from a different fragment?

Thank you for your help!

EDIT

Managed to get rid of the null pointer exception by adding Context context; to the start of the ListFragment and context = getActivity(); to the onCreate method and using that context instead of getActivity on the updater function. I added a couple of System.out.printlns to that function which are printed out just fine, but the listview itself still isn't updated. Can't understand why because the fragment as I know seems to be active (or attached) and the function works fine when ran from the fragment itself.

I found that the arraylist initialization is not done properly ..

Hope you try this ...

if any mistake occurs post your build data method .It will be fixed .

  ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
  list = buildData();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM