将ArrayList对象传递给片段

时间:2016-08-02 20:39:42

标签: android android-fragments android-intent android-adapter android-tablayout

我很难解决这个问题。我正在尝试将三个不同的自定义对象的arraylists发送到可扩展列表视图单击的片段。这里是可扩展的列表视图代码(我只包括第一组的位置和子项,但实际上还有更多):

*/
public class MyWorkout extends BaseActivity{

ExpandableListView expandableListView;
HashMap<String, List<String>> Workouts_details;
List<String> Workout_list;
WorkoutsAdapter mAdapter;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_workout);
    mToolBar = activateToolbar();
    setUpNavigationDrawer();


    expandableListView = (ExpandableListView) findViewById(R.id.listViewWorkouts);
    Workouts_details = DataProvider.getInfo();
    Workout_list = new ArrayList<>(Workouts_details.keySet());
    mAdapter = new WorkoutsAdapter(this, Workouts_details, Workout_list);



    expandableListView.setAdapter(mAdapter);

    expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
        @Override
        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
            if (groupPosition == 0) {
                if (childPosition == 0) {
                    Intent intent = new Intent(getApplicationContext(), WorkoutDaysActivity.class);
                    intent.putExtra("workout", "w29w1");
                    startActivity(intent);
                }
                if (childPosition == 1) {
                  Intent intent = new Intent(getApplicationContext(), WorkoutDaysActivity.class);
                    intent.putExtra("workout", "w29w1");
                    startActivity(intent);
                }

从那里,每个childClick将应用程序发送到WorkoutDaysActivity,其中3个选项卡设置了片段。这是这个类的代码:

public class WorkoutDaysActivity extends BaseActivity{

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.workout_days);
    mToolBar = activateToolbar();
    setUpNavigationDrawer();


    ViewPager vp = (ViewPager) findViewById(R.id.view_pager);
    this.addPages(vp);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
//        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    tabLayout.setupWithViewPager(vp);
    tabLayout.setOnTabSelectedListener(listener(vp));

}

//ADD ALL PAGES
private void addPages(ViewPager pager) {
    MyFragPagerAdapter adapter = new  MyFragPagerAdapter(getSupportFragmentManager());
    Intent intent = getIntent();
    String workout = intent.getStringExtra("workout");
    Bundle args = new Bundle();
    args.putString("workout", workout);

    MondayFragment mondayFragment = new MondayFragment();
    mondayFragment.setArguments(args);
    adapter.addPage(mondayFragment);
    WedFragment wedFragment = new WedFragment();
    wedFragment.setArguments(args);
    adapter.addPage(wedFragment);
    FridayFragment fridayFragment = new FridayFragment();
    fridayFragment.setArguments(args);
    adapter.addPage(fridayFragment);
     pager.setAdapter(adapter);
}

private TabLayout.OnTabSelectedListener listener(final ViewPager pager) {
    return new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            pager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    };
}
 }

然后从那里,我有3个选项卡片段类。每个班级都是这样的:

public class WedFragment extends Fragment {

Bundle args = getArguments();
String workout3 = args.getString("workout");

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.wed_fragment, null);

//        //RECYCLERVIEW
    RecyclerView rv = (RecyclerView) view.findViewById(R.id.mRecyclerWed);
    rv.setLayoutManager(new LinearLayoutManager(this.getActivity()));
    rv.setAdapter(new MyRecyclerAdapter(this.getActivity(), getWedWorkout()));

    return view;


}

private ArrayList<Workout> getWedWorkout() {
    //COLLECTION OF MONDAY WORKOUT

    ArrayList<Workout> workout = new ArrayList<>();
    switch(workout3) {
        case "w29w1" : {
            Workout workouts = new Workout("Bench", "60", "6", "155", false);

            //ADD TO COLLECTION
            workout.add(workouts);

            workouts = new Workout("Bench", "70", "5", "175", false);
            workout.add(workouts);

            break;}
        case "w29w2" :{
            Workout workouts = new Workout("Squat", "60", "6", "155", false);

            //ADD TO COLLECTION
            workout.add(workouts);

            workouts = new Workout("Squat", "70", "5", "175", false);
            workout.add(workouts);

        break;}
    } return workout;



    //SINGLE EXERCISE


}

@Override
public String toString() {
    return "Wednesday";
}
}
编辑:我编辑了我的帖子,这就是我试图做的原因。在我看来它应该工作,实际上它没有。当应用程序尝试打开片段并崩溃时,我收到此错误:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bestworkouts.sheikoworkout/com.bestworkouts.sheikoworkout.WorkoutDaysActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3254)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3350)
                                                                                at android.app.ActivityThread.access$1100(ActivityThread.java:222)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:158)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7229)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
                                                                             Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
                                                                                at com.bestworkouts.sheikoworkout.Fragments.WedFragment.<init>(WedFragment.java:24)
                                                                                at com.bestworkouts.sheikoworkout.WorkoutDaysActivity.addPages(WorkoutDaysActivity.java:47)
                                                                                at com.bestworkouts.sheikoworkout.WorkoutDaysActivity.onCreate(WorkoutDaysActivity.java:27)
                                                                                at android.app.Activity.performCreate(Activity.java:6876)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3207)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3350) 
                                                                                at android.app.ActivityThread.access$1100(ActivityThread.java:222) 

2 个答案:

答案 0 :(得分:1)

我们在您的代码中尝试将ArrayList对象发送到Fragment的位置尚不清楚 - 但我建议您将您的课程(Workout)设为延长Parcelable ,然后发送ArrayList<Workout> - 您可以使用putParcelableArrayList(String key, ArrayList<? extends Parcelable> value)类的Bundle方法签名,然后设置Bundle作为fragment.setArguments(Bundle)方法的参数。基本上,你将拥有这样的代码:

ArrayList<Workout> workoutList = new ArrayList<Workout>();
workoutList.add(<some-workout-object>)
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("mondayWorkoutList", workoutList);
Fragment fragment = new MondayFragment();
fragment.setArguments(bundle);

查看Fragment tutorial有关如何使用Bundle将参数发送到Fragment的示例。您可能还想查看API documentation for Bundle class

我希望这会有所启发。

答案 1 :(得分:0)

作为一种解决方法,有时很容易将数组列表转换为字符串(或JSON字符串)并通过

发送
bundle.putString()

然后在片段中将字符串解析回数组列表。