[英]How to pass 2D array from one activity to another(including all the info the array contains)
I have a 2D array setup in Activity A which I would then like to use in activity B. I have looked at varying examples online but cant get any to work properly. 我在活动A中有一个2D阵列设置,然后想在活动B中使用。我在网上查看了各种示例,但都无法正常工作。
The code below compiles OK but I get an error with my Toast of java.lang.nullpointerexception.
下面的代码编译正常,但是我的Toast
java.lang.nullpointerexception.
出现错误java.lang.nullpointerexception.
so it looks to me as if my array structure is being passed through but the contents are null
. 所以在我看来,好像我的数组结构正在传递但内容为
null
。 Any help is greatly appreciated. 任何帮助是极大的赞赏。
Here is what I have so far.: 这是我到目前为止所拥有的:
Activity A 活动A
String[][] Question=new String[100][100];
Bundle b = new Bundle();
b.putSerializable("questionset", Question);
Intent intent = new Intent(this, QuizActivity.class);
startActivity(intent);
Activity B 活动B
try{
Bundle b=this.getIntent().getExtras();
String[][] Questions = (String[][]) b.getSerializable("questionset");
Toast.makeText(this, Questions[2][1].toString(), Toast.LENGTH_SHORT).show();
}
catch(Exception e){
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
I solve those problems always with a storage object class which is a singleton and where i can save such objects. 我总是使用单例的存储对象类来解决这些问题,并且可以在其中保存此类对象。
public class Model
{
private static Model instance;
private Model()
{
// singleton implementation
}
/**
* Returns a valid instance of the model.
*
* @return THE instance of the model.
*/
public static Model getInstance()
{
if (instance == null)
{
instance = new Model();
}
return instance;
}
private String[][] arr;
// + getter and setter methods for arr
}
String[][] Question=new String[100][100];
Question[2][1]="sample"; // here
Bundle b = new Bundle();
b.putSerializable("questionset", Question);
Intent intent = new Intent(this, QuizActivity.class);
intent.putExtras(b); // here
startActivity(intent);
Your code lacks initialization of array contents and passing it to intent. 您的代码缺少数组内容的初始化并将其传递给intent。 Is it intentional?
这是故意的吗? For me the above code works pretty well.
对我来说,上面的代码效果很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.