// simple class that just has one member property as an examplepublic class MyParcelable implements Parcelable {private int mData;
/* everything below here is for implementing Parcelable */
// 99.9% of the time you can just ignore this@Overridepublic int describeContents() {return 0;}
// write your object's data to the passed-in Parcel@Overridepublic void writeToParcel(Parcel out, int flags) {out.writeInt(mData);}
// this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methodspublic static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() {public MyParcelable createFromParcel(Parcel in) {return new MyParcelable(in);}
public MyParcelable[] newArray(int size) {return new MyParcelable[size];}};
// example constructor that takes a Parcel and gives you an object populated with it's valuesprivate MyParcelable(Parcel in) {mData = in.readInt();}}
public class getsetclass implements Serializable {private int dt = 10;//pass any object, drwabalepublic int getDt() {return dt;}
public void setDt(int dt) {this.dt = dt;}}
在活动一
getsetclass d = new getsetclass ();d.setDt(50);LinkedHashMap<String, Object> obj = new LinkedHashMap<String, Object>();obj.put("hashmapkey", d);Intent inew = new Intent(SgParceLableSampelActivity.this,ActivityNext.class);Bundle b = new Bundle();b.putSerializable("bundleobj", obj);inew.putExtras(b);startActivity(inew);
在活动2中获取数据
try { setContentView(R.layout.main);Bundle bn = new Bundle();bn = getIntent().getExtras();HashMap<String, Object> getobj = new HashMap<String, Object>();getobj = (HashMap<String, Object>) bn.getSerializable("bundleobj");getsetclass d = (getsetclass) getobj.get("hashmapkey");} catch (Exception e) {Log.e("Err", e.getMessage());}
// send where details is objectClassName details = new ClassName();Intent i = new Intent(context, EditActivity.class);i.putExtra("Editing", details);startActivity(i);
//receiveClassName model = (ClassName) getIntent().getSerializableExtra("Editing");
And
Class ClassName implements Serializable {}
// Create an object of SharedPreferences.SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);//now get EditorSharedPreferences.Editor editor = sharedPref.edit();//put your valueeditor.putString("userName", "stackoverlow");
//commits your editseditor.commit();
package com.hmkcode.android;import java.io.Serializable;
public class Person implements Serializable{
private static final long serialVersionUID = 1L;
private String name;private int age;
// getters & setters....
@Overridepublic String toString() {return "Person [name=" + name + ", age=" + age + "]";}}
两个活动的两个布局
activity_main.xml
<LinearLayout 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"android:orientation="vertical"tools:context=".MainActivity" >
<LinearLayoutandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextViewandroid:id="@+id/tvName"android:layout_width="100dp"android:layout_height="wrap_content"android:layout_gravity="center"android:gravity="center_horizontal"android:text="Name" />
<EditTextandroid:id="@+id/etName"android:layout_width="wrap_content"android:layout_height="wrap_content"
android:ems="10" ><requestFocus /></EditText></LinearLayout>
<LinearLayoutandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextViewandroid:id="@+id/tvAge"android:layout_width="100dp"android:layout_height="wrap_content"android:layout_gravity="center"android:gravity="center_horizontal"android:text="Age" /><EditTextandroid:id="@+id/etAge"android:layout_width="wrap_content"android:layout_height="wrap_content"android:ems="10" /></LinearLayout>
<Buttonandroid:id="@+id/btnPassObject"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center_horizontal"android:text="Pass Object to Another Activity" />
</LinearLayout>
package com.hmkcode.android;
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;
public class MainActivity extends Activity implements OnClickListener {
Button btnPassObject;EditText etName, etAge;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);
btnPassObject = (Button) findViewById(R.id.btnPassObject);etName = (EditText) findViewById(R.id.etName);etAge = (EditText) findViewById(R.id.etAge);
btnPassObject.setOnClickListener(this);}
@Overridepublic void onClick(View view) {
// 1. create an intent pass class name or intnet action nameIntent intent = new Intent("com.hmkcode.android.ANOTHER_ACTIVITY");
// 2. create person objectPerson person = new Person();person.setName(etName.getText().toString());person.setAge(Integer.parseInt(etAge.getText().toString()));
// 3. put person in intent dataintent.putExtra("person", person);
// 4. start the activitystartActivity(intent);}
}
(2)AnotherActivity.java
package com.hmkcode.android;
import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.widget.TextView;
public class AnotherActivity extends Activity {
TextView tvPerson;
@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.activity_another);
// 1. get passed intentIntent intent = getIntent();
// 2. get person object from intentPerson person = (Person) intent.getSerializableExtra("person");
// 3. get reference to person textViewtvPerson = (TextView) findViewById(R.id.tvPerson);
// 4. display name & age on textViewtvPerson.setText(person.toString());
}}
Intent intent = new Intent(getApplicationContext(), Activity2.class);service.setSavedOrder(order);startActivity(intent);
在活动2中:
private Service service;private Order order;
@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_quality);
service = Service.getInstance();order = service.getSavedOrder();service.setSavedOrder(null) //If you don't want to save it for the entire session of the app.}
服务中:
private static Service instance;
private Service(){//Constructor content}
public static Service getInstance(){if(instance == null){instance = new Service();}return instance;}private Order savedOrder;
public Order getSavedOrder(){return savedOrder;}
public void setSavedOrder(Order order){this.savedOrder = order;}
public class MensajesProveedor implements Serializable {
private int idProveedor;
public MensajesProveedor() {}
public int getIdProveedor() {return idProveedor;}
public void setIdProveedor(int idProveedor) {this.idProveedor = idProveedor;}
}
你的第一个活动
MensajeProveedor mp = new MensajeProveedor();Intent i = new Intent(getApplicationContext(), NewActivity.class);i.putExtra("mensajes",mp);startActivity(i);
// This is the object to be sent, can be any objectpublic class AndroidPacket {
public String CustomerName;
//constructorpublic AndroidPacket(String cName){CustomerName = cName;}// other fields ....
// You can add those functions as LiveTemplate !public String toJson() {Gson gson = new Gson();return gson.toJson(this);}
public static AndroidPacket fromJson(String json) {Gson gson = new Gson();return gson.fromJson(json, AndroidPacket.class);}}
2个函数将它们添加到要发送的对象中
用法
将对象从A发送到B
// Convert the object to string using GsonAndroidPacket androidPacket = new AndroidPacket("Ahmad");String objAsJson = androidPacket.toJson();
Intent intent = new Intent(A.this, B.class);intent.putExtra("my_obj", objAsJson);startActivity(intent);
接收到B
@Overrideprotected void onCreate(Bundle savedInstanceState) {Bundle bundle = getIntent().getExtras();String objAsJson = bundle.getString("my_obj");AndroidPacket androidPacket = AndroidPacket.fromJson(objAsJson);
// Here you can use your ObjectLog.d("Gson", androidPacket.CustomerName);}
public class Example {private int id;private String name;
public Example(int id, String name) {this.id = id;this.name = name;}
public int getId() {return id;}
public void setId(int id) {this.id = id;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}}
我们需要传递示例类的对象
Example exampleObject=new Example(1,"hello");String jsonString = new Gson().toJson(exampleObject);Intent nextIntent=new Intent(this,NextActivity.class);nextIntent.putExtra("example",jsonString );startActivity(nextIntent);
对于读取,我们需要在NextActivity中执行反向操作
Example defObject=new Example(-1,null);//default value to return when example is not availableString defValue= new Gson().toJson(defObject);String jsonString=getIntent().getExtras().getString("example",defValue);//passed example objectExample exampleObject=new Gson().fromJson(jsonString,Example .class);
public class Place implements Serializable{private int id;private String name;
public void setId(int id) {this.id = id;}public int getId() {return id;}public String getName() {return name;}
public void setName(String name) {this.name = name;}}
然后你可以传递这个对象
Intent intent = new Intent(this, SecondAct.class);intent.putExtra("PLACE", Place);startActivity(intent);
int第二个活动你可以得到这样的数据
Place place= (Place) getIntent().getSerializableExtra("PLACE");
ObjectA obj = new ObjectA();
// Set values etc.
Intent i = new Intent(this, MyActivity.class);i.putExtra("com.package.ObjectA", obj);
startActivity(i);
ReceiveActivity.java
Bundle b = getIntent().getExtras();ObjectA obj = b.getParcelable("com.package.ObjectA");
Start another activity from this activity pass parameters via Bundle Object
Intent intent = new Intent(this, YourActivity.class);Intent.putExtra(AppConstants.EXTRAS.MODEL, cModel);startActivity(intent);Retrieve on another activity (YourActivity)
ContentResultData cModel = getIntent().getParcelableExtra(AppConstants.EXTRAS.MODEL);
We can send data one Activty1 to Activity2 with multiple ways like.1- Intent2- bundle3- create an object and send through intent.................................................1 - Using intentPass the data through intentIntent intentActivity1 = new Intent(Activity1.this, Activity2.class);intentActivity1.putExtra("name", "Android");startActivity(intentActivity1);Get the data in Activity2 calssIntent intent = getIntent();if(intent.hasExtra("name")){String userName = getIntent().getStringExtra("name");}..................................................2- Using BundleIntent intentActivity1 = new Intent(Activity1.this, Activity2.class);Bundle bundle = new Bundle();bundle.putExtra("name", "Android");intentActivity1.putExtra(bundle);startActivity(bundle);Get the data in Activity2 calssIntent intent = getIntent();if(intent.hasExtra("name")){String userName = getIntent().getStringExtra("name");}..................................................3- Put your Object into IntentIntent intentActivity1 = new Intent(Activity1.this, Activity2.class);intentActivity1.putExtra("myobject", myObject);startActivity(intentActivity1);Receive object in the Activity2 ClassIntent intent = getIntent();Myobject obj = (Myobject) intent.getSerializableExtra("myobject");