在碎片中传递的Arraylist是空的

时间:2016-08-01 13:21:10

标签: java android android-fragments arraylist bundle

我在main活动中创建一个Method,它将一个ArrayList Bundle发送到我的Fragment类,但是当我尝试在Fragment中获取期望值时,我片段中声明的ArrayList是null。有人可以帮我查一下我的代码吗?

MainActivity.java: sendBundleData()是MainActivity中将ArrayList包发送到片段的方法

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课程: 在片段的onCreate方法中,我尝试检索包

    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();


    }
}

1 个答案:

答案 0 :(得分:2)

这是因为您要在sendBundleData()中为不同的片段实例设置参数并替换单独的实例

将片段作为参数传递给方法

public void sendBundleData(Fragment fragment) {


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

}

并且您的开关案例看起来像

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