How to Pass data from One activity to another with

2020-02-14 03:20发布

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?

4条回答
女痞
2楼-- · 2020-02-14 03:57

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.

查看更多
爷的心禁止访问
3楼-- · 2020-02-14 04:03

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.

查看更多
Lonely孤独者°
4楼-- · 2020-02-14 04:05

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();
查看更多
Emotional °昔
5楼-- · 2020-02-14 04:20

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

查看更多
登录 后发表回答