我有一堂这样的课
class Message implements Serializable
{
public String message, sender;
public Message (String msg, String from)
{
// check here that msg and from are not null. If so, use a default value or throw an NullPointerException
message = msg;
sender = from;
}
// Just a utility method for printing out the Message to System.out
public String toString () { return sender+":"+message; }
}
我在主要 Activity 中定义这个变量
Hashtable<String, ArrayList<Message>> table = new Hashtable<String, ArrayList<Message>>();
table.get(room_name).add(new Message("Hi", "Sender"));
Bundle bundle = new Bundle();
bundle.putSerializable("messages", table.get(sendTo));
在 fragment 中我用这段代码获取这些数据
ArrayList<Message> extractedMessages = (ArrayList<Message>)getArguments().getSerializable("messages");
System.out.println(extractedMessages.size());
但是我的应用程序崩溃了,我收到 extractedMessages.size()
的 java 空指针异常
我该如何解决这个问题?
最佳答案
解决方案是::
Bundle.putParcelable/Bundle.getParcelable
看看这个 answer .
- 使用这些方法:
putParcelable
和getParcelable
。
你也可以::
Intent intent = new Intent(context, SecondActity.class);
intent.putIntegerArrayListExtra("arraylist",myArrayList); //myArrayList is ArrayList<Integer>
startActivity(intent);
在第二个 Activity 中获取 arrayList。
ArrayList arrayList<Integer> = getIntent().getIntegerArrayListExtra("myArrayList")
<小时/>
{Edit} ---- 您可以使用 newInstance 将数据在 fragment 之间传递
这是实现它的方法之一,我使用构造函数来传递数据
FragmentOne.java
int myData=12;
FragmentManager manager = getActivity().getSupportFragmentManager();
Fragment frgObj=FragmentTwo.newInstance(myData);
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.container, frgObj,"FragmentTwo");
ft.addToBackStack(null);
ft.commit();
FragmentTwo.java
int myData;
public static FragmentTwo newInstance(int _myData){
FragmentTwo fragment = new FragmentTwo();
myData=_myData
return fragment;
}
<小时/>
{EDIT-3}
我为你做了一个项目download it from Here
- 安装在你的编辑器中并运行它....它还有很多其他东西 ....不用担心
- 检查我如何
从 Activity 启动 fragment
----> 然后 按钮的onClick
我如何启动 fragment
---> 那里通过 带有构造函数的数据,如edit2
中所示
关于java - 通过 bundle 传递数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25231125/