簡體   English   中英

如何將2D數組從一個活動傳遞到另一個活動(包括該數組包含的所有信息)

[英]How to pass 2D array from one activity to another(including all the info the array contains)

我在活動A中有一個2D陣列設置,然后想在活動B中使用。我在網上查看了各種示例,但都無法正常工作。

下面的代碼編譯正常,但是我的Toast java.lang.nullpointerexception.出現錯誤java.lang.nullpointerexception. 所以在我看來,好像我的數組結構正在傳遞但內容為null 任何幫助是極大的贊賞。

這是我到目前為止所擁有的:

活動A

String[][] Question=new String[100][100];

Bundle b = new Bundle();
b.putSerializable("questionset", Question);
Intent intent = new Intent(this, QuizActivity.class);
startActivity(intent);

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

    }

我總是使用單例的存儲對象類來解決這些問題,並且可以在其中保存此類對象。

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

您的代碼缺少數組內容的初始化並將其傳遞給intent。 這是故意的嗎? 對我來說,上面的代碼效果很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM