How to Pass data from One activity to another with

2020-02-14 03:52发布

问题:

I am already using a pending intent..So if I use another intent and start that intent it goes to a new activity..I want to avoid that..So without using intents I want to pass data from one activity to another possible?

回答1:

You can use static Method to get data from one activity to another activity.Below is sample code

First Activity

public class First extends Activity {

 static First INSTANCE;
 String data="FirstActivity"; 

 @Override
  public void onCreate(Bundle savedInstanceState) {

    INSTANCE=this; 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
   }

 public static First getActivityInstance()
   {
     return INSTANCE;
   }

 public String getData()
   {
     return this.data;
   }
 }

Second Activity:

 public class Second extends Activity {

 String data; 

 @Override
  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main1);
    data=First.getActivityInstance().getData();  
    Toast.makeText(Second.this,"Data from first activity is"+data, 1).show();
   }
}

Hope it helps you.



回答2:

You can try by using Singleton

 public class Singleton{
       private static Singleton instance;

       private Singleton(){

       }

       public static Singleton getInstance(){
        if (instance == null){
            instance = new Singleton();
        }
        return instance;
    }
  // your fields, getter and setter here

 }

Then in your 1st activity

Singleton a = Singleton.getInstance();
a.setFoo("something here");

and then your 2nd activity

Singleton b = Singleton.getInstance();
b.getFoo();


回答3:

How about set up a Global Variable Class and then set it in Activity1 and access it in Activity2 as shown below:

Global variable class file: Global.java

package <your packagename>;
public class Global {   
    public static String    stringToPass = "";
}

Set the Global variable in file: Activity1.java

Global.stringToPass = "your string value to pass";
    startActivity(new Intent(Activity1.this, Activity2.class));

Read the Global variable in file: Activity2.java

String gotString = "Global.stringToPass;

Beware of memory leaks.



回答4:

You can try use the global class Application to share the datas you want to send! Just to set the datas before using them!