Search code examples
javaandroidandroid-fragmentsarraylistbundle

Arraylist Passed in Fragment is Empty


I create a Method in the main activity which sends a ArrayList Bundle going to my Fragment class, but when I try to get the expected values in the Fragment, ArrayList declared in my fragment is null. Can someone help me check in my code?

MainActivity.java: sendBundleData() is the method in the MainActivity to send ArrayList bundles to the fragment

public class MainActivity extends AppCompatActivity {

private ActionBarDrawerToggle toggle;
private DrawerLayout drawerLayout;
private ListView lv;
private String[] arrValues;
private ArrayAdapter<String> adapter;
DBHelper helper;
public ArrayList<Bible> _bibleValues;

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

    /** Instance of DBHelper */
    helper = new DBHelper(MainActivity.this);

    /** Getting arraylist values from the DBHelper */
    try {
        _bibleValues=helper.queryData();
    } catch (SQLException e) {
        e.printStackTrace();
    }

    /** Initialize drawer layout */
    drawerLayout= (DrawerLayout) findViewById(R.id.drawerLayout_bibledashboard);

    //Getting the values of the String resources to the array
    arrValues=getApplicationContext().getResources().getStringArray(R.array.verse_chapter);

    //Setting the needed parameters in an Array Adapter
    adapter= new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,arrValues);
    lv= (ListView) findViewById(R.id.listview_verseTitle);
    lv.setAdapter(adapter);

    //Specify the OnItemCLick listener in the Listview
    lv.setOnItemClickListener(new DrawerItemClickListener());

    if (savedInstanceState == null){
        selectItem(0);
    }

    /** CHeck if we can createDatabase */
    try {
        helper.createDatabase();
    }catch (IOException e) {
        e.printStackTrace();
        throw  new Error("Unable to Create Database");
    }

    /** CHeck to open the database created */
    try {
        helper.openDatabase();
    }catch (SQLException e) {
        e.printStackTrace();
        throw new Error("Unable to open Database");
    }
    Log.d("Database Creation","Success");



    /** Display Sample Data Query in DATABASE
    try {
        verseList=helper.queryData();

        verseAdapter= new VerseAdapter(this,verseList);

    } catch (SQLException e) {
        e.printStackTrace();
    } */

    /** Setting up DrawerToggle */
    toggle= new ActionBarDrawerToggle(this,drawerLayout,R.string.drawer_opened,R.string.drawer_closed) {
        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            invalidateOptionsMenu();
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            invalidateOptionsMenu(); /** ENd of Coding */
        }
    }; //end of toggle '}'

    drawerLayout.addDrawerListener(toggle);

    /** Enabling ActionbarDrawer toggle */
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

} /** End of OnCreate */

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    toggle.onConfigurationChanged(newConfig);
}

@Override
protected void onPostCreate(@Nullable Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    toggle.syncState();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (toggle.onOptionsItemSelected(item)) {
    }
    return true;
}


/** Method for sending Bundle of arraylist to the Fragments*/

public void sendBundleData() {

    GenesisFragment gFragment= new GenesisFragment();
    Bundle args= new Bundle();
    args.putParcelableArrayList("verseValues",_bibleValues); /** Make the Object class Parcelable 1st */
    gFragment.setArguments(args);

}


private class DrawerItemClickListener implements ListView.OnItemClickListener {

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        selectItem(position);
    }
}

private void setActionBarTitles(int position) {
    String title;
    if (position==0) {
        title="Genesis";
    }else {
        title=arrValues[position];
    }

    getSupportActionBar().setTitle(title);
}

private void selectItem(int position) {
    Fragment fragment;
    switch (position) {
        case 0:
            fragment= new GenesisFragment();
            sendBundleData();
            break;
        default:
            fragment=new GenesisFragment();
            break;
    }

    FragmentTransaction ft= getFragmentManager().beginTransaction();
    ft.replace(R.id.bible_screenlayout,fragment);
    ft.addToBackStack(null);
    ft.commit();
    setActionBarTitles(position);
    drawerLayout.closeDrawer(lv);
}

My Fragment class: In the onCreate method of the fragment i try to retrieve the bundle

    public class GenesisFragment extends Fragment {

    ListView lv;
    ArrayList<Bible> verseList;
    VerseAdapter verseAdapter;



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

        Log.d("ON ATTACH","onAttache method!");
    }

    /** @Override */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("ON CREATE","onCreate");

        Bundle bundle=getArguments();

        verseList= new ArrayList<>();
        verseList=bundle.getParcelableArrayList("verseValues"); //retrieving bundles in the MainActivity



    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        verseAdapter= new VerseAdapter(getActivity(),verseList);
        // Inflate the layout for this fragment
        View v= inflater.inflate(R.layout.fragment_genesis, container, false);

        return v;



    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {

        lv=(ListView)getActivity().findViewById(R.id.listview_genesis);

        lv.setAdapter(verseAdapter);
        verseAdapter.notifyDataSetChanged();


    }
}

Solution

  • It's because you are setting arguments to a different fragment instance in sendBundleData() and are replacing a separate instance

    Pass the fragment as an argument to the method

    public void sendBundleData(Fragment fragment) {
    
    
    Bundle args= new Bundle();
    args.putParcelableArrayList("verseValues",_bibleValues); /** Make the Object class Parcelable 1st */
    fragment.setArguments(args);
    
    }
    

    and your switch case would look like

      switch (position) {
        case 0:
            fragment= new GenesisFragment();
            sendBundleData(fragment);
            break;
        default:
            fragment=new GenesisFragment();
            break;
    }