Android: static variables for Activity data transmission

Source: Internet
Author: User

Android: static variables for Activity data transmission

Using Intent can easily transfer data between different activities. This is also officially recommended, but it also has some limitations.

That is, Intent cannot pass objects that cannot be serialized. We can use static variables to solve this problem.

Obj class

package com.example.activity;public class Obj{String name;public String getName(){return name;}public void setName(String name){this.name=name;}}


 

Declare a static variable in OtherActivity

public static Obj obj;

Add a button component to MainActivity and add a click event to it

 

Intent intent = new Intent (); intent. setClass (MainActivity. this, OtherActivity. class); startActivity (intent); Obj obj = new Obj (); obj. setName ("I am Su"); OtherActivity. obj = obj;
Then output this value in OtherActivity.
Toast.makeText(OtherActivity.this, obj.getName(), Toast.LENGTH_LONG).show();

After doing this, we also need to do one thing in OtherActivity to make obj = null when this Activity is destroyed;

This is because there is a garbage collection mechanism in java that only recycles objects with no pointing type, that is, null.

protected void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();obj=null;}

Running result:

,

 

Related Article

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.