pass matrix of values between two activities

2019-08-02 08:21发布

问题:

I can't pass a matrix of integers between two activities. here is the code:

  • Activity A:

    intent.putExtra("matrix_", (Serializable)matrix);

  • Activity B:

    Bundle extras = getIntent().getExtras();
    matrix =  (int[][]) extras.getSerializable("matrix_");
    

回答1:

When you are creating an object of intent, you can take advantage of following two methods for passing objects between two activities.

putParceble

putSerializable

What you can do with this, is have your class implement either Parcelable or Serializable.

Then you can pass around your custom classes across activities. I have found this very useful.

Here is a small snippet of code I am using

Matrix matrix  = new Matrix ();
Intent i = new Intent();

Bundle b = new Bundle();
b.putParcelable("CUSTOM_LISTING", matrix  );
i.putExtras(b);
i.setClass(this, NextActivity.class);
startActivity(i);

And in newly started activity code will be something like this...

Bundle b = this.getIntent().getExtras();
if(b!=null)
    mCurrentListing = b.getParcelable("CUSTOM_LISTING");

** EDITED WITH LINKS::: **

LINK1 consist of sample code

LINK2

LINK3



回答2:

There is a simple way to pass matrix through intent.

Activity A:

float[] values = new float[9];
matrix.getValues(values);
intent.putExtra("matrix_values", values);

Activity B:

float[] values = getIntent().getFloatArrayExtra("matrix_values");
Matrix matrix = new Matrix();
matrix.setValues(values);