Lesson 69. Pass Parcelable Objects Using Intent

Lesson 69. Pass Parcelable Objects Using Intent


In this lesson:

– Parcelable support is added to the object
– transmitted by Intent

We worked a little with Parcel last lesson. This knowledge is sufficient to understand how to implement the Parcelable interface in your object. Let’s create our object, implement Parcelable interface in it and try to pass it to another Activity via Intent.

Let’s create a project:

Project name: P0691_Parcelable
Build Target: Android 2.3.3
Application name: Parcelable
Package name: en.startandroid.develop.p0691parcelable
Create Activity: MainActivity

IN strings.xml write down the texts:



    MainActivity
    SecondActivity
    Send
    Parcelable

IN main.xml draw a button:



    
    
    

Before encoding MainActivity.java, let’s create our own object for transmission MyObject.java:

package ru.startandroid.develop.p0691parcelable;

import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;

public class MyObject implements Parcelable {
  
  final static String LOG_TAG = "myLogs";

  public String s;
  public int i;

  // обычный конструктор
  public MyObject(String _s, int _i) {
    Log.d(LOG_TAG, "MyObject(String _s, int _i)");
    s = _s;
    i = _i;
  }

  public int describeContents() {
    return 0;
  }

  // упаковываем объект в Parcel
  public void writeToParcel(Parcel parcel, int flags) {
    Log.d(LOG_TAG, "writeToParcel");
    parcel.writeString(s);
    parcel.writeInt(i);
  }

  public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
    // распаковываем объект из Parcel
    public MyObject createFromParcel(Parcel in) {
      Log.d(LOG_TAG, "createFromParcel");
      return new MyObject(in);
    }

    public MyObject[] newArray(int size) {
      return new MyObject[size];
    }
  };

  // конструктор, считывающий данные из Parcel
  private MyObject(Parcel parcel) {
    Log.d(LOG_TAG, "MyObject(Parcel parcel)");
    s = parcel.readString();
    i = parcel.readInt();
  }

}

The object itself is not complicated: a couple of variables s and i, And the designer. Everything else is used to implement Parcelable. Let’s watch.

There is nothing I can say about the describeContents method. I didn’t understand why he needed it.

In the writeToParcel method, we get the Parcel input and pack our object into it. That is, in our case, we put the variables s and i there. we do not use flags.

CREATOR type Parcelable.Creator used to create an instance of our MyObject and populate it with Parcel data.

To do this, we use its createFromParcel method, which we must implement. We are given Parcel input, and we must return MyObject ready. In our example, we use the MyObject (Parcel parcel) constructor here, which is implemented a little further.

The meaning of the newArray method was unclear to me.

The MyObject (Parcel parcel) constructor accepts Parcel input and fills the object with data from it. We used this method a little earlier in CREATOR.createFromParcel.

Let’s create the second Activity, in which we will pass the object.

We first create a screen second.xml:



    
    

Kodyma SecondActivity.java:

package ru.startandroid.develop.p0691parcelable;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class SecondActivity extends Activity {
  
  final String LOG_TAG = "myLogs";

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.second);
    Log.d(LOG_TAG, "getParcelableExtra");
    MyObject myObj = (MyObject) getIntent().getParcelableExtra(
        MyObject.class.getCanonicalName());
    Log.d(LOG_TAG, "myObj: " + myObj.s + ", " + myObj.i);
  }

}

We extract our MyObject object from Intent and output s and i values ​​in the log.

Kodyma MainActivity.java:

package ru.startandroid.develop.p0691parcelable;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class MainActivity extends Activity {

  final String LOG_TAG = "myLogs";

  /** Called when the activity is first created. */
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
  }

  public void onclick(View v) {
    MyObject myObj = new MyObject("text", 1);
    Intent intent = new Intent(this, SecondActivity.class);
    intent.putExtra(MyObject.class.getCanonicalName(), myObj);
    Log.d(LOG_TAG, "startActivity");
    startActivity(intent);
  }
}

We create an Intent, place the MyObject object there. We use his class name as a key (of course, it’s optional, you can use his name). And we send Intent calling SecondActivity.

We will save everything and launch the application.

Click Send, Intent goes to SecondActivity

We look at the log:

MyObject (String _s, int _i)
startActivity
writeToParcel
getParcelableExtra
createFromParcel
MyObject (Plot Plot)
myObj: text, 1

Initially, the designer said MyObject (String _s, int _i) – this is what we created myObj.

startActivity – we start the Activity call

writeToParcel – we placed the object in Intent, and it looks like when it is sent it is packed in Parcel. Because Parcel does not know exactly how to package the object, it called the writeToParcel method where we implemented the package.

getParcelableExtra – extract the object from Intent

createFromParcel – this was called the CREATOR.createFromParcel method, to which Parcel was given input, and it must return MyObject. This method, in turn, uses a constructor to create MyObject MyObject (Plot Plot), In which we painted how to read Parcel and fill in the object.

myObj: text, 1 – logged the value of the object.

So. to us pass the object through Intent, We need to implement an interface in it Parcelable. In this case, Intent seamlessly packs, transfers and unpacks our object. And I suspect so much that he does it with the help of Parcel. That is in the implementation of the interface Parcelable we fully describe algorithm of packing and unpacking object, and Parcel then uses these algorithms. Because he himself cannot know how to properly unpack and create the object you want.

If anyone understands why I do not understand the methods, write in the forum in the branch of this lesson. I’ll add your info to the lesson.

In the next lesson:

– save the data when you rotate the screen




Discuss in the forum [52 replies]

Leave a Comment