Android pass Object from one activity to another

Passing Java Objects in Android is made easy by implementing the Parcelable interface. The With the help of the parcelable interface your can write your object to a parcel or read from a parcel, that way you can easily pass it around when calling the activity using bundles. In this example we have a ArrayList of Country objects that we use to display a ListView, so when the user taps on a given row in the List we pass the complete object to the new activity where the user can update the information and send the object back to the ListView for display. Most important thing is, if you look at the source for the Country.java, that you must maintain the same sequence as in the method writeToParcel as when reading them back in the createFromParcel routine.

Android pass Object from one activity to another Android pass Object to new activity Android return object to the calling activity

Layout Resource for the Main Activity - activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" 
    android:padding="10dp">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="How to pass object from one activity to another?"
        android:textAppearance="?android:attr/textAppearanceMedium" 
        android:paddingBottom="20dp"/>
    
    <ListView
        android:id="@+id/listView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@id/textView1" />
   
</RelativeLayout>

Layout Resource for the ListView Row - row_data.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/code"
        android:layout_width="50sp"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Code"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="5dp"
        android:layout_toRightOf="@+id/code"
        android:text="Name: "
        android:textAppearance="?android:attr/textAppearanceMedium" />
   
</RelativeLayout>

Layout Resource for the Object Edit Activity - country_edit.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relativeLayout1"
    android:layout_width="500dp"
    android:layout_height="300dp"
    android:orientation="vertical"
    android:padding="10dp" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Country Code"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/code"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/textView2"
        android:layout_marginLeft="5dp"
        android:layout_toRightOf="@+id/textView1"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="26dp"
        android:layout_toLeftOf="@+id/code"
        android:text="Name"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/textView2"
        android:layout_alignLeft="@+id/code"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="15dp"
        android:layout_toLeftOf="@+id/code"
        android:text="Continent"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/continent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/name"
        android:layout_below="@+id/name"
        android:ems="10" />
    
    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView3"
        android:layout_marginTop="15dp"
        android:layout_toLeftOf="@+id/code"
        android:text="Region"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/region"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/name"
        android:layout_below="@+id/continent"
        android:ems="10" />
    
    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView4"
        android:layout_marginTop="15dp"
        android:layout_toLeftOf="@+id/code"
        android:text="Popuation"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/population"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/textView5"
        android:layout_alignLeft="@+id/region"
        android:ems="10"
        android:inputType="number" />

    <Button
        android:id="@+id/save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/population"
        android:layout_below="@+id/population"
        android:text="Save" />

    <Button
        android:id="@+id/cancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/population"
        android:layout_below="@+id/population"
        android:text="Cancel" />
    
</RelativeLayout>

Country Object source implementing Parcelable interface - Country.java

package com.as400samplecode;

import android.os.Parcel;
import android.os.Parcelable;

public class Country implements Parcelable {
 
 String code = "";
 String name = "";
 String continent = "";
 String region = "";
 int population = 0;
 int listPosition = 0;
 
 public Country(String code, String name, String continent, String region, int population) {
  super();
  this.code = code;
  this.name = name;
  this.continent = continent;
  this.region = region;
  this.population = population;
 }
 
 public String getCode() {
  return code;
 }
 public void setCode(String code) {
  this.code = code;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getContinent() {
  return continent;
 }
 public void setContinent(String continent) {
  this.continent = continent;
 }
 public String getRegion() {
  return region;
 }
 public void setRegion(String region) {
  this.region = region;
 }
 public int getPopulation() {
  return population;
 }
 public void setPopulation(int population) {
  this.population = population;
 }
 

 public int getListPosition() {
  return listPosition;
 }

 public void setListPosition(int listPosition) {
  this.listPosition = listPosition;
 }

 @Override
 public int describeContents() {
  return 0;
 }

 @Override
 public void writeToParcel(Parcel dest, int flags) {
  
  dest.writeString(this.code);
  dest.writeString(this.name);
  dest.writeString(this.region);
  dest.writeString(this.continent);
  dest.writeInt(this.population);
  dest.writeInt(this.listPosition);
 
 }
 
 public static final Parcelable.Creator<Country> CREATOR
 = new Parcelable.Creator<Country>() {
  public Country createFromParcel(Parcel in) {
   return new Country(in);
  }

  public Country[] newArray(int size) {
   return new Country[size];
  }
 };
 
 private Country(Parcel in) {
  this.code = in.readString();
  this.name = in.readString();
  this.region = in.readString();
  this.continent = in.readString();
  this.population = in.readInt();
  this.listPosition = in.readInt();
    }
 
}

Main Activity displaying country in ListView - MainActivity.java

package com.as400samplecode;

import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

 private MyCustomAdapter dataAdapter = null;
 private View currentView = null;
 
 private static final int COUNTRY_EDIT = 1;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  //Generate list View from ArrayList
  displayListView();

 }

 private void displayListView() {

  //Array list of countries
  ArrayList<Country> countryList = new ArrayList<Country>();
  Country country = new Country("AFG","Afghanistan","Asia",
    "Southern and Central Asia", 101010);
  countryList.add(country);
  country = new Country("ALB","Albania","Europe","Southern Europe", 202020);
  countryList.add(country);
  country = new Country("DZA","Algeria","Africa","Northern Africa", 303030);
  countryList.add(country);
  country = new Country("ASM","American Samoa","Oceania","Polynesia", 404040);
  countryList.add(country);
  country = new Country("AND","Andorra","Europe","Southern Europe", 505050);
  countryList.add(country);
  country = new Country("AGO","Angola","Africa","Central Africa", 606060);
  countryList.add(country);
  country = new Country("AIA","Anguilla","North America","Caribbean", 707070);
  countryList.add(country);

  //create an ArrayAdaptar from the String Array
  dataAdapter = new MyCustomAdapter(this,
    R.layout.row_data, countryList);
  ListView listView = (ListView) findViewById(R.id.listView1);
  // Assign adapter to ListView
  listView.setAdapter(dataAdapter);

  listView.setOnItemClickListener(new OnItemClickListener() {
   public void onItemClick(AdapterView<?> parent, View view,
     int position, long id) {

    currentView = view;
    
    //get reference to the country Object
    Country country = (Country) view.getTag();
    Toast.makeText(getApplicationContext(),
      country.getCode(), Toast.LENGTH_SHORT).show();

    Intent countryEdit = new Intent(MainActivity.this,CountryEdit.class);
    Bundle b = new Bundle();
    //pass the country object as a parcel
    b.putParcelable("country", country);
    countryEdit.putExtras(b);
    startActivityForResult(countryEdit, COUNTRY_EDIT);

   }
  });

 }
 
 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data){

  switch(requestCode) {
  
  case COUNTRY_EDIT:
   if (resultCode == RESULT_OK) {

    //read the bundle and get the country object
    Bundle bundle = data.getExtras();
    Country country = bundle.getParcelable("country");
    
    //update the country object in the ArrayAdapter
    int listPosition = country.getListPosition();
    dataAdapter.setCountry(country, listPosition);
    
    //update the country name in the ListView
    currentView.setTag(country);
    TextView name = (TextView) currentView.findViewById(R.id.name);
    name.setText(country.getName());
   
   }
   break;

  }

 }   

 private class MyCustomAdapter extends ArrayAdapter<Country> {

  private ArrayList<Country> countryList;

  public MyCustomAdapter(Context context, int textViewResourceId,
    ArrayList<Country> countryList) {

   super(context, textViewResourceId, countryList);
   this.countryList = new ArrayList<Country>();
   this.countryList.addAll(countryList);
  }
  
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {

   TextView code = null;
   TextView name = null;

   if (convertView == null) {
    LayoutInflater vi = (LayoutInflater)getSystemService(
      Context.LAYOUT_INFLATER_SERVICE);
    convertView = vi.inflate(R.layout.row_data, null);

    code  = (TextView) convertView.findViewById(R.id.code);
    name = (TextView) convertView.findViewById(R.id.name);
   } 

   Country country = countryList.get(position);
   country.setListPosition(position);
   code.setText(country.getCode());
   name.setText(country.getName());
   convertView.setTag(country);

   return convertView;
  }
  
  public void setCountry(Country country, int position){
   this.countryList.set(position, country);
  }

 }


 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }

}

Activity editing country information - CountryEdit.java

package com.as400samplecode;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class CountryEdit extends Activity implements OnClickListener{

 private Country country;
 private TextView code;
 private EditText name, region, continent, population;
 
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.country_edit);
  
  Bundle bundle = this.getIntent().getExtras();
  country = bundle.getParcelable("country");

  Button save = (Button) findViewById(R.id.save);
  Button cancel = (Button) findViewById(R.id.cancel);
  save.setOnClickListener(this);
  cancel.setOnClickListener(this);
  
  code = (TextView) findViewById(R.id.code);
  name = (EditText) findViewById(R.id.name);
  region = (EditText) findViewById(R.id.region);
  continent = (EditText) findViewById(R.id.continent);
  population = (EditText) findViewById(R.id.population);
  
  code.setText(country.getCode());
  name.setText(country.getName());
  region.setText(country.getRegion());
  continent.setText(country.getContinent());
  population.setText(String.valueOf(country.getPopulation()));
  

 }


 public void onClick(View v) {

  Intent intent = new Intent();
  
  switch (v.getId()) {
  case R.id.save:
   
   country.setName(name.getText().toString());
   country.setRegion(region.getText().toString());
   country.setContinent(continent.getText().toString());
   country.setPopulation(Integer.parseInt(population.getText().toString()));
   
   Bundle b = new Bundle();
   b.putParcelable("country", country);
   intent.putExtras(b);
            setResult(RESULT_OK,intent); 
   finish();
   break;

  case R.id.cancel:
   setResult(RESULT_CANCELED,intent); 
   finish();
   break;

  }
  
 }
 

}

Reference

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.