Transmit data in different activities (four methods)

Source: Internet
Author: User

Four transfer methods:

1. Transmit data through intent;

2. Transmit data through static variables;

3. Transmit data through the clipboard;

4. pass data through global objects;

Classification:

1. Transmit data through intent;

The Code is as follows:

Layout:

<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="${relativePackage}.${activityClass}" >   <Button        android:id="@+id/btnintent"       android:layout_width="match_parent"       android:layout_height="wrap_content"       android:text="通过Intent传递数据"       android:textSize="18sp"       /></LinearLayout>
Code of the serializable class:

package com.example.transdata;import java.io.Serializable;public class Data implements Serializable{public int id;public String name;}
Code of the first activity:


package com.example.transdata;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends Activity implements OnClickListener{    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        Button btn = (Button) findViewById(R.id.btnintent);        btn.setOnClickListener(this);    }@Overridepublic void onClick(View v) {Intent intent = null;switch (v.getId()) {case R.id.btnintent:intent = new Intent(this, OtherActivity.class);intent.putExtra("intent_string", "通过Intent传递的字符串");intent.putExtra("intent_integer", 300);Data data = new Data();data.id = 1000;data.name = "Android";intent.putExtra("intent_object", data);startActivity(intent);break;default:break;}}}

Code of the second activity:


package com.example.transdata;import android.app.Activity;import android.os.Bundle;import android.widget.TextView;public class OtherActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.activity_other);TextView tvWord = (TextView) findViewById(R.id.tv_word);String intentString = getIntent().getStringExtra("intent_string");int intentInteger = getIntent().getExtras().getInt("intent_integer");Data data = (Data) getIntent().getExtras().get("intent_object");StringBuffer sb = new StringBuffer();sb.append(intentString);sb.append("\n");sb.append(intentInteger);sb.append("\n");sb.append(data.id);sb.append(data.name);tvWord.setText(sb.toString());}}

Note: The three data types of transmission are different: String, integer, and serializable;


intent.putExtra("intent_string", "通过Intent传递的字符串");intent.putExtra("intent_integer", 300);Data data = new Data();data.id = 1000;data.name = "Android";intent.putExtra("intent_object", data);

The data transmitted by the first activity in the second activity is also different:


String intentString = getIntent().getStringExtra("intent_string");int intentInteger = getIntent().getExtras().getInt("intent_integer");Data data = (Data) getIntent().getExtras().get("intent_object");

In addition, stringbuffer (variable, thread security) is used when data is displayed ):

StringBuffer sb = new StringBuffer();sb.append(intentString);sb.append("\n");sb.append(intentInteger);sb.append("\n");sb.append(data.id);sb.append(data.name);tvWord.setText(sb.toString());

2. Transmit data through static variables;

Intent has limitations in data transmission. intent cannot deliver objects that cannot be serialized. In this case, data can be transmitted using static variables.

The code of the newly created activity is as follows:

package com.example.transdata;import android.app.Activity;import android.os.Bundle;import android.widget.TextView;public class OtherActivity2 extends Activity {public static String name;public static int id;public static Data data;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.activity_other2);TextView tvWord = (TextView) findViewById(R.id.tv_word);StringBuffer sb = new StringBuffer();sb.append(name);sb.append("\n");sb.append(id);sb.append("\n");sb.append(data.id);sb.append("\n");sb.append(data.name);tvWord.setText(sb.toString());}}

In the layout of the main interface, add a new button. The main logic code is as follows:

case R.id.btnstatic:intent = new Intent(this, OtherActivity2.class);OtherActivity2.id = 3000;OtherActivity2.name="保时捷";OtherActivity2.data = new Data();OtherActivity2.data.id = 1000;OtherActivity2.data.name = "Android";startActivity(intent);break;

3. Transmit data through the clipboard;

The clipboard can only store simple data types or serializable objects. For some non-serializable objects, if they can be converted to byte streams (byte arrays ), you can also save these objects to the clipboard. In this example, the data object is not directly stored in the clipboard, but is converted to base64 encoded and stored in the clipboard as a string.

The main code of mainactivity is as follows:


case R.id.btnClipboard:intent = new Intent(this, OtherActivity3.class);//获取剪切板的对象ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);Data clipdata = new Data();clipdata.id = 6666;clipdata.name = "testclipdata";//创建字节数组输出流对象,用于将Data对象转换为字节流ByteArrayOutputStream baos = new ByteArrayOutputStream();//存储的字符串String base64Str = "";try {//对象流ObjectOutputStream oos = new ObjectOutputStream(baos);oos.writeObject(clipdata);//将字节流进行Base64编码base64Str = Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);oos.close();} catch (IOException e) {e.printStackTrace();}//获取存储文本数据的剪切板数据的对象ClipData text = ClipData.newPlainText("data", base64Str);//设置主剪切板clipboard.setPrimaryClip(text);startActivity(intent);break;

The core code has been annotated.

Activity for displaying data:

package com.example.transdata;import java.io.ByteArrayInputStream;import java.io.ObjectInputStream;import android.annotation.SuppressLint;import android.annotation.TargetApi;import android.app.Activity;import android.content.ClipboardManager;import android.content.Context;import android.os.Build;import android.os.Bundle;import android.util.Base64;import android.widget.TextView;@SuppressLint("NewApi") public class OtherActivity3 extends Activity {@TargetApi(Build.VERSION_CODES.HONEYCOMB) @SuppressLint("NewApi") @Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.activity_other3);TextView tvWord = (TextView) findViewById(R.id.tv_word);ClipboardManager manager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);//从剪切板中获取Base64编码的字符串String base64Str = manager.getPrimaryClip().getItemAt(0).getText().toString();//将Base64编码字符串解码成字节数组byte[] buffer = Base64.decode(base64Str, Base64.DEFAULT);ByteArrayInputStream bais = new ByteArrayInputStream(buffer);try {ObjectInputStream ois = new ObjectInputStream(bais);//将字节流还原为Data对象Data data = (Data) ois.readObject();tvWord.setText(base64Str+":" + data.id + ":" + data.name);} catch (Exception e) {e.printStackTrace();}}}

4. pass data through global objects;

The use of static variables has limitations (1. A large number of static variables will cause memory overflow; 2. Static variables may cause difficult code maintenance and confusion in many classes ).

The class corresponding to the global object must be inherited from Android. App. application.

Global class:

package com.example.transdata;import android.app.Application;public class MyApplication extends Application {//必须有一个无参的构造器public String country;public Data data = new Data();}

Click Event of mainactivity:

case R.id.btnApplication://必须先获取全局对象MyApplication application = (MyApplication) getApplicationContext();application.country = "china";application.data.id = 123;application.data.name = "testapplication";intent = new Intent(this, OtherActivity4.class);startActivity(intent);break;

Displayed activity:


package com.example.transdata;import android.app.Activity;import android.os.Bundle;import android.widget.TextView;public class OtherActivity4 extends Activity{@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.activity_other4);TextView tvWord = (TextView) findViewById(R.id.tv_word);MyApplication application = (MyApplication) getApplicationContext();tvWord.setText(application.country + ":" + application.data.id + ":" + application.data.name);}}






Summary:

Transmit basic type or serializable data with intent;

It is best to use global objects to pass non-serializable objects. If you want to keep some data in the memory for a long time, it is best to use global objects.

















Transmit data in different activities (four methods)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.