使用bundle,seListAdapter运行时错误将ArrayList从片段传递到另一个片段(扩展ListFragment)

时间:2014-04-16 07:42:39

标签: java android android-fragments arraylist android-listfragment

我尝试过将Array变量用于ArrayList,但是在ListFragment类中,调试它的值为null。

我认为在初始化ArrayList之前会创建ListFragment,这就是为什么它为null,但不确定。

建议我是否可以使用任何其他方式将膨胀的ArrayList从Fragment类发送到扩展ListFragment的其他Fragment类。

提前致谢。

目标(这是线索,需要做什么)

在Monday_fragment的onStart()方法中,使用findByView()方法在页面视图中查找保存条目按钮的标签。使用对按钮的引用将setOnClickListener()方法附加到保存按钮。您需要在此方法中保存页面上EditText字段中包含的时间和日记条目字符串。

使用findViewById()也可以获得对第一个EditText字段的引用,并使用它来将字段的文本作为字符串获取并将其保存为字符串。对下一个EditText - 日记条目重复此操作。您将需要一个可公开访问的变量来存储当天(星期一......星期五)的参考,日期时间字符串和日记条目字符串。使用这些字段创建一个新类(diaryLogs)来保存值和一个构造函数,它接受一个int(0 Mon,1 Tue,2 Wed etc)和两个字符串作为日期时间和日记条目来初始化对象的一个​​实例。由于将在同一天进行多个条目,因此使用ArrayList<日记日志>存储值。由于此值将在片段之间共享,因此在MainActivity类中将变量声明为static。使用ArrayList的.add()方法将新的diaryLog添加到setOnClickListener()方法中的ArrayList。对其他日记页面片段重复此操作。

monday_list片段由ListView和用于返回Monday_fragment页面的按钮组成。在monday_list xml文件中创建这些对象。创建一个扩展ListFragment类的Monday_list_fragment。在onCreateView()方法中inflate()monday_list资源。

在onCreate()方法中,您需要提供单个字符串数组作为用于填充页面上ListView的setListAdapter()方法中列表的源。字符串位于MainActivity中的静态ListArray变量中。但是,它们不是必需的形式,您必须解压缩diaryLog元素才能获得所需的字符串。要做到这一点,你必须创建一个足够大的String数组来保存要显示的字符串。由于日期/时间字符串后跟日记条目字符串,每个diaryLog元素将有两个这样的字符串。使用迭代器迭代ListArray。将日期字符串和日记字符串字符串复制到本地字符串中。然后使用此本地字符串作为setListAdapter()的相关参数,以便ListView显示所需的字符串。

在MainActivity java文件中添加click处理程序,以便单击Monday片段页面中的Save Diary Entries按钮可以使用FragmentManager使Monday_list_fragment可见。还要在MainActivity中添加一个单击处理程序,以便单击Return to Monday Diary按钮返回到Monday_fragment页面。

更新 Class MainActivity

public class MainActivity extends Activity {


    public static int Monday=0;
    /*public static int Tuesday=1;
    public static int Wednesday=2;
    public static int Thursday=3;
    public static int Friday=4;
    public static String timeEntry;
    public static String entryEntered;*/
   // public static ArrayList<String> logs;
    //public static String[] entry;
    //public static String time;
    //public static String text;
    //public static String totalEntry;
    //public static ArrayList<DiaryLogs> diaryLogs;
    //public static ArrayList<DiaryLogs> test;
    //public static DiaryLogs[] entryLogs;
    //public static ArrayAdapter<DiaryLogs> monAdapter;
    //public static ArrayList< String > myStringList;
  //public static ArrayList<DiaryLogs> entryLogs;


    public static ArrayList<String> myStringList;

    public static ArrayList<String> getMyStringList() {
        return myStringList;
    }




    public void setMyStringList(ArrayList<String> myStringList) {
        this.myStringList = myStringList;
    }




    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        Home_fragment hf = new Home_fragment();
        fragmentTransaction.replace(android.R.id.content, hf);
        fragmentTransaction.commit();
        setContentView(R.layout.activity_main);



        }




    public void monClick(View view) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        Monday_fragment mf = new Monday_fragment();
        fragmentTransaction.replace(android.R.id.content, mf);
        fragmentTransaction.commit();
    }

    public void tuesClick(View view) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        Tuesday_fragment tf = new Tuesday_fragment();
        fragmentTransaction.replace(android.R.id.content, tf);
        fragmentTransaction.commit();
    }

    public void wedClick(View view) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        Wednesday_fragment wf = new Wednesday_fragment();
        fragmentTransaction.replace(android.R.id.content, wf);
        fragmentTransaction.commit();
    }

    public void thursClick(View view) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        Thursday_fragment thf = new Thursday_fragment();
        fragmentTransaction.replace(android.R.id.content, thf);
        fragmentTransaction.commit();
    }

    public void friClick(View view) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        Friday_fragment ff = new Friday_fragment();
        fragmentTransaction.replace(android.R.id.content, ff);
        fragmentTransaction.commit();
    }

    public void next_Home_Click(View view) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        Monday_fragment mf = new Monday_fragment();
        fragmentTransaction.replace(android.R.id.content, mf);
        fragmentTransaction.commit();
    }

    public void previous_Home_Click(View view) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        Friday_fragment ff = new Friday_fragment();
        fragmentTransaction.replace(android.R.id.content, ff);
        fragmentTransaction.commit();
    }

    public void next_Mon_Click(View view) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        Tuesday_fragment tf = new Tuesday_fragment();
        fragmentTransaction.replace(android.R.id.content, tf);
        fragmentTransaction.commit();
    }

    public void previous_Mon_Click(View view) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        Friday_fragment ff = new Friday_fragment();
        fragmentTransaction.replace(android.R.id.content, ff);
        fragmentTransaction.commit();

    }

    public void next_Tues_Click(View view) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        Wednesday_fragment wf = new Wednesday_fragment();
        fragmentTransaction.replace(android.R.id.content, wf);
        fragmentTransaction.commit();
    }

    public void previous_Tues_Click(View view) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        Monday_fragment mf = new Monday_fragment();
        fragmentTransaction.replace(android.R.id.content, mf);
        fragmentTransaction.commit();

    }

    public void next_Wed_Click(View view) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        Thursday_fragment thf = new Thursday_fragment();
        fragmentTransaction.replace(android.R.id.content, thf);
        fragmentTransaction.commit();
    }

    public void previous_Wed_Click(View view) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        Tuesday_fragment tf = new Tuesday_fragment();
        fragmentTransaction.replace(android.R.id.content, tf);
        fragmentTransaction.commit();

    }

    public void next_Thurs_Click(View view) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        Friday_fragment ff = new Friday_fragment();
        fragmentTransaction.replace(android.R.id.content, ff);
        fragmentTransaction.commit();
    }

    public void previous_Thurs_Click(View view) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        Wednesday_fragment wf = new Wednesday_fragment();
        fragmentTransaction.replace(android.R.id.content, wf);
        fragmentTransaction.commit();

    }

    public void next_Fri_Click(View view) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        Monday_fragment ff = new Monday_fragment();
        fragmentTransaction.replace(android.R.id.content, ff);
        fragmentTransaction.commit();
    }

    public void previous_Fri_Click(View view) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        Thursday_fragment wf = new Thursday_fragment();
        fragmentTransaction.replace(android.R.id.content, wf);
        fragmentTransaction.commit();

    }

    public void home_Click(View view) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        Home_fragment hf = new Home_fragment();
        fragmentTransaction.replace(android.R.id.content, hf);
        fragmentTransaction.commit();

    }

    @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 boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        switch (item.getItemId()) {
        case R.id.action_profile:
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager
                    .beginTransaction();
            Profile_fragment pf = new Profile_fragment();
            fragmentTransaction.replace(android.R.id.content, pf);
            fragmentTransaction.commit();

            break;
        case R.id.action_saveEntries:

            break;
        case R.id.action_sendAllEntries:
            //call delete dialog
            deleteDialog();
            break;
        }
        return false;
    }

    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(this).setIcon(R.drawable.ic_launcher)
                .setTitle("Save entries to DB first?")
                .setNegativeButton("No", new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        // if no, close app
                        MainActivity.this.finish();

                    }
                })
                .setPositiveButton(android.R.string.ok, new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        // if ok, save entries to Database

                    }
                })

                .create().show();

    }

    public void deleteDialog() {

        new AlertDialog.Builder(this).setIcon(R.drawable.ic_launcher)
                .setTitle("Are you sure? This will delete all entries.")
                .setNegativeButton(android.R.string.cancel, new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub


                    }
                })
                .setPositiveButton(android.R.string.ok, new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub


                    }
                })

                .create().show();

    }

}

自定义对象类DiaryLogs

public class DiaryLogs {

    //public static ArrayList<DiaryLogs> entryLogs;

    String timeEntry, entryEntered;
    int day;

    // single constructor that takes an integer and two string
    public DiaryLogs(int day, String timeEntry, String entryEntered) {
        super();
        this.day = day;
        this.timeEntry = timeEntry;
        this.entryEntered = entryEntered;

    }

    public String getTimeEntry() {
        return timeEntry;
    }

    public void setTimeEntry(String timeEntry) {
        this.timeEntry = timeEntry;
    }

    public String getEntryEntered() {
        return entryEntered;
    }

    public void setEntryEntered(String entryEntered) {
        this.entryEntered = entryEntered;
    }

    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
    }

    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return this.timeEntry + "\n" + this.entryEntered;


    }


}

更新 班级Monday_fragment

public class Monday_fragment extends Fragment {

    //public ArrayList<String> myStringList;
    Bundle bundle;
    ArrayList<DiaryLogs> entryLogs;
    EditText timeText;
    EditText entryText;
    DiaryLogs dl;
    String timeEntry;
    String entryEntered;
    ArrayList<String> myStringList;

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

        return inflater.inflate(R.layout.monday_fragment, container, false);

    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        currentDateTime();
        super.onViewCreated(view, savedInstanceState);

    }

    public void currentDateTime() {
        EditText timeText = (EditText) getView().findViewById(
                R.id.dateTimeEText);
        SimpleDateFormat df = new SimpleDateFormat("d/M/yyyy:H:m");
        String dateTime = df.format(Calendar.getInstance().getTime());
        timeText.setText(dateTime);
    }

    /*public ArrayList<String> toStringList(Collection<DiaryLogs> entryLogs) {
        ArrayList<String> stringList = new ArrayList<String>();

        for (DiaryLogs myobj : entryLogs) {
            stringList.add(myobj.toString());
        }

        return stringList;
    }*/
    public ArrayList<String> toStringList(Collection<DiaryLogs> entryLogs) {
        ArrayList<String> stringList =  MainActivity.getMyStringList();

        for (DiaryLogs myobj : entryLogs) {
            String objctString = myobj.toString();

            stringList.add(objctString);
        }
        ((MainActivity)getActivity()).setMyStringList(stringList); 
        return stringList;
    }

    @Override
    public void onStart() {
        entryLogs = new ArrayList<DiaryLogs>();

        timeText = (EditText) getView().findViewById(R.id.dateTimeEText);

        entryText = (EditText) getView().findViewById(R.id.diaryEntryEText);

        Button saveBtn = (Button) getView()
                .findViewById(R.id.saveDiaryEntryBtn);
        saveBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                timeEntry = timeText.getText().toString();

                entryEntered = entryText.getText().toString();

                dl = new DiaryLogs(1, timeEntry, entryEntered);

                entryLogs.add(dl);

                //convert entryLogs to string array list
                //myStringList = toStringList(entryLogs);
                myStringList= MainActivity.getMyStringList();
                myStringList = toStringList(entryLogs);
                //myStringList.addAll(toStringList(entryLogs));

                Toast.makeText(getActivity(), "Entry added \n" + dl,
                        Toast.LENGTH_SHORT).show();
                        entryText.setText("");






            }

        }

        );
        System.out.println(entryLogs);

        Button showBtn = (Button) getView().findViewById(
                R.id.showDiaryEntriesBtn);
        showBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                if (myStringList != null) {
                    bundle = new Bundle();
                    FragmentManager fragmentManager = getFragmentManager();
                    FragmentTransaction fragmentTransaction = fragmentManager
                            .beginTransaction();
                    Monday_list_fragment mlf = new Monday_list_fragment();

                    bundle.putStringArrayList("list", myStringList);
                    mlf.setArguments(bundle);

                    fragmentTransaction.replace(android.R.id.content, mlf);
                    fragmentTransaction.commit();
                }
                if (myStringList == null) {
                    Toast.makeText(getActivity(),
                            "No entry have been added yet", Toast.LENGTH_SHORT)
                            .show();
                }
            }
        });

        super.onStart();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
    }

}

班级Monday_list_fragment

    public class Monday_list_fragment extends ListFragment {
    ArrayList<String> test;
    Bundle bundle;


    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        bundle = getArguments();
        System.out.println(bundle);
       //test = bundle.getStringArrayList("list");

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub

        return inflater
                .inflate(R.layout.monday_list_fragment, container, false);

    }

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

        super.onViewCreated(view, savedInstanceState);

       /* ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, test);
        // once adapter set throws runtime error
        setListAdapter(adapter);*/

    }



}

2 个答案:

答案 0 :(得分:3)

当对象为Bundle(or Intent)Parcelable时,您只能通过Serializable传递自定义对象的自定义对象或ArrayList。如果您的片段处于相同的活动,那么还有一件事就是您传递数组的原因。您只需在getter中为列表创建setterActivity,然后在listFragment中像((Activity)getActivity).getArraylist()一样访问它们。对于创建对象Parcelable,请执行以下操作。

import android.os.Parcel;
import android.os.Parcelable;

public class Address implements Parcelable {

private String name, address, city, state, phone, zip;

@Override
public int describeContents() {
    return 0;
}

/*
        THE ORDER YOU READ OBJECT FROM AND WRITE OBJECTS TO YOUR PARCEL MUST BE THE SAME
 */

@Override
public void writeToParcel(Parcel parcel, int i) {
    parcel.writeString(name);
    parcel.writeString(address);
    parcel.writeString(city);
    parcel.writeString(state);
    parcel.writeString(phone);
    parcel.writeString(zip);
}


public Address(Parcel p){
    name = p.readString();
    address = p.readString();
    city = p.readString();
    state = p.readString();
    phone = p.readString();
    zip = p.readString();
}

// THIS IS ALSO NECESSARY
public static final Creator<Address> CREATOR = new Creator<Address>() {
    @Override
    public Address createFromParcel(Parcel parcel) {
        return new Address(parcel);
    }

    @Override
    public Address[] newArray(int i) {
        return new Address[0];
    }
};
}

答案 1 :(得分:1)

我已经看到了您给定链接的代码,这就是我发布新Ans的原因。如果您仔细阅读代码,那么您已在ArrayAdapter<String>中声明了Monday_fragment,因此每次将此片段替换为其他片段时,此列表都会初始化。因此,只需在ArrayAdapter<String>MainActivity中创建一个getter, setter,然后在ArrayList<String> toStringList(Collection<DiaryLogs> entryLogs)中更改您的方法Monday_fragment,如下所示

public ArrayList<String> toStringList(Collection<DiaryLogs> entryLogs) {
    ArrayList<String> stringList =  ((MainActivity)getActivity()).getMyStringList();

    for (DiaryLogs myobj : entryLogs) {
        String objctString = myobj.toString();

        stringList.add(objctString);
    }
    ((MainActivity)getActivity()).setMyStringList(stringList); 
    return stringList;
}