简体   繁体   中英

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.

The code below compiles OK but I get an error with my Toast of java.lang.nullpointerexception. so it looks to me as if my array structure is being passed through but the contents are null . Any help is greatly appreciated.

Here is what I have so far.:

Activity 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

    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. Is it intentional? For me the above code works pretty well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM