2014-09-09 3 views
0

J'ai une activité principale avec un View Pager et un Spinner. Quand je change le spinner, je veux mettre à jour les fragments dans le ViewPager pour utiliser de nouvelles données.NullPointerException notifydatasetchanged()

J'ai essayé de communiquer de l'Activité au Fragment lorsqu'une sélection a été faite dans le Spinner mais je reçois toujours une exception NullPointerException. J'appelle la méthode updateListView() de l'Activity lorsque la sélection de Spinner a été confirmée. La ligne de code commentée provoque également un crash.

ListFragment lf = (ListFragment) mSectionsPagerAdapter.getItem(0); 
       lf.updateListView(); 

Voici mon code

public class ListFragment extends Fragment { 

ArrayList<Psalm> psalms; 
ListViewAdapter adapter; 
View v; 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){ 
    v = inflater.inflate(R.layout.fragment_list, parent, false); 

    psalms = GlobalSingleton.get(getActivity()).getPsalms().getPsalms(); 

    adapter = new ListViewAdapter(getActivity(), psalms); 

    ListView l = (ListView) v.findViewById(R.id.fragmentListListView); 
    l.setAdapter(adapter); 

    return v; 

} 

public void updateListView(){ 
    psalms = GlobalSingleton.get(getActivity()).getPsalms().getPsalms(); 

    System.out.println("HERE"); 
    ((ListViewAdapter) ((ListView) v.findViewById(R.id.fragmentListListView)).getAdapter()).notifyDataSetChanged(); 
    //adapter.notifyDataSetChanged(); 

} 

}

activité principale

public class MainActivity extends FragmentActivity implements ActionBar.TabListener { 


/** 
* The {@link android.support.v4.view.PagerAdapter} that will provide 
* fragments for each of the sections. We use a 
* {@link android.support.v4.app.FragmentPagerAdapter} derivative, which 
* will keep every loaded fragment in memory. If this becomes too memory 
* intensive, it may be best to switch to a 
* {@link android.support.v4.app.FragmentStatePagerAdapter}. 
*/ 
SectionsPagerAdapter mSectionsPagerAdapter; 

/** 
* The {@link ViewPager} that will host the section contents. 
*/ 
ViewPager mViewPager; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    try { 

     String[] files = getAssets().list(""); 

     ArrayList<Psalm> singPsalms = new ArrayList<Psalm>(); 
     ArrayList<Psalm> scottishPsalter = new ArrayList<Psalm>(); 

     for(String s: files){ 
      if(s.split("_")[0].equals("SingPsalms")){ 
       singPsalms.add(new Psalm(s.split("_")[1], s.split("_")[2], s.split("_")[3].replace(".txt", ""))); 
      } else if(s.split("_")[0].equals("ScottishPsalter")){ 
       scottishPsalter.add(new Psalm(s.split("_")[1] , s.split("_")[2], s.split("_")[3].replace(".txt", ""))); 
      } 
     } 

     Collections.sort(singPsalms, new PsalmComparator()); 

     GlobalSingleton.get(this).setSingPsalms(new Psalmody("Sing Psalms", singPsalms)); 
     GlobalSingleton.get(this).setScottishPsalter(new Psalmody("Scottish Psalter", scottishPsalter)); 
     GlobalSingleton.get(this).setSelectedPsalmody("Scottish Psalter"); 


    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 


    // Adapter 
    Spinner psalter = (Spinner) findViewById(R.id.spinner1); 
    SpinnerAdapter adapter = ArrayAdapter.createFromResource(this, R.array.psalter, android.R.layout.simple_spinner_dropdown_item); 
    psalter.setAdapter(adapter); 
    psalter.setOnItemSelectedListener(new OnItemSelectedListener() { 

     public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { 
      String selected = parent.getItemAtPosition(position).toString(); 

      if (!selected.equals(GlobalSingleton.get(getApplicationContext()).getSelectedPsalmody())){ 
       GlobalSingleton.get(getApplicationContext()).setSelectedPsalmody(selected); 

       System.out.println("HERE"); 
       ListFragment lf = (ListFragment) mSectionsPagerAdapter.getItem(0); 
       lf.updateListView(); 

      } 

     } 

     public void onNothingSelected(AdapterView<?> parent) { 
     } 
    }); 


    // Set up the action bar. 
    final ActionBar actionBar = getActionBar(); 
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); 

    // Create the adapter that will return a fragment for each of the three 
    // primary sections of the app. 
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); 

    // Set up the ViewPager with the sections adapter. 
    mViewPager = (ViewPager) findViewById(R.id.pager); 
    mViewPager.setAdapter(mSectionsPagerAdapter); 

    // When swiping between different sections, select the corresponding 
    // tab. We can also use ActionBar.Tab#select() to do this if we have 
    // a reference to the Tab. 
    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { 
     @Override 
     public void onPageSelected(int position) { 
      actionBar.setSelectedNavigationItem(position); 
     } 
    }); 

    // For each of the sections in the app, add a tab to the action bar. 
    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { 
     // Create a tab with text corresponding to the page title defined by 
     // the adapter. Also specify this Activity object, which implements 
     // the TabListener interface, as the callback (listener) for when 
     // this tab is selected. 
     actionBar.addTab(
       actionBar.newTab() 
       .setText(mSectionsPagerAdapter.getPageTitle(i)) 
       .setTabListener(this)); 
    } 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 

@Override 
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { 
    // When the given tab is selected, switch to the corresponding page in 
    // the ViewPager. 
    mViewPager.setCurrentItem(tab.getPosition()); 
} 

@Override 
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { 
} 

@Override 
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { 
} 

/** 
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to 
* one of the sections/tabs/pages. 
*/ 
public class SectionsPagerAdapter extends FragmentPagerAdapter { 

    public SectionsPagerAdapter(FragmentManager fm) { 
     super(fm); 
    } 

    @Override 
    public Fragment getItem(int position) { 
     // getItem is called to instantiate the fragment for the given page. 
     // Return a DummySectionFragment (defined as a static inner class 
     // below) with the page number as its lone argument. 
     Fragment fragment = null; 

     if (position == 0){ 
      fragment = new ListFragment(); 


     } else { 
      fragment = new GridFragment(); 

     } 
     return fragment; 
    } 

    @Override 
    public int getCount() { 
     // Show 3 total pages. 
     return 3; 
    } 

    @Override 
    public CharSequence getPageTitle(int position) { 
     Locale l = Locale.getDefault(); 
     switch (position) { 
     case 0: 
      return "List".toUpperCase(l); 
     case 1: 
      return "Grid".toUpperCase(l); 
     case 2: 
      return "Metre Seperated".toUpperCase(l); 
     } 
     return null; 
    } 
} 

}

+0

lorsque vous appelez 'updateListView'? – mmlooloo

+0

Dans l'activité parente –

+0

pouvez-vous le poster? – mmlooloo

Répondre

0

Utiliser le même objet de ListView sur lequel vous appelez setAdapter dans onCreateView pour appeler notifyDataSetChanged comme:

.... 
    l = (ListView) v.findViewById(R.id.fragmentListListView); 
    l.setAdapter(adapter); 
    return v; 
} 
ListView l; 
public void updateListView(){ 
    //.... 
    l.getAdapter()).notifyDataSetChanged(); 
    //adapter.notifyDataSetChanged(); 
} 
0

essayer ci-dessous le code. n'utilisez pas view et utilisez listview des membres.

public class ListFragment extends Fragment { 

ArrayList<Psalm> psalms; 
ListViewAdapter adapter; 
ListView l; 
View v; 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){ 
    v = inflater.inflate(R.layout.fragment_list, parent, false); 

    psalms = GlobalSingleton.get(getActivity()).getPsalms().getPsalms(); 

    adapter = new ListViewAdapter(getActivity(), psalms); 

    l = (ListView) v.findViewById(R.id.fragmentListListView); 
    l.setAdapter(adapter); 

    return v; 

} 

public void updateListView(){ 
    psalms = GlobalSingleton.get(getActivity()).getPsalms().getPsalms(); 

    System.out.println("HERE"); 
    if(l != null){ 
     l.getAdapter()).notifyDataSetChanged(); 
    } 

} 
+0

désolé homme, ne fonctionne pas –

+0

whats l'erreur? – mmlooloo

+0

bon cela signifie que vous appelez update avant que le fragment 'oncreatview' ne soit appelé. ou vous n'avez pas modifié les données de l'adaptateur. publiez votre activité complètement. – mmlooloo

Questions connexes