Android之两个activity传递数据

来源:互联网 发布:淘宝关键词排列顺序 编辑:程序博客网 时间:2024/05/16 13:41
1.通过intent来传递: 
A.传字符等:activity1中设置: 
Java代码  收藏代码
  1. String text = "hello";  
  2.     Intent intent1 = new Intent(ActivityMain.this, Activity2.class);  
  3.     intent1.putExtra("activity1", text);  
  4.     startActivity(intent1 );  


B.传对象,对象要实例化,继承Serializable 
Java代码  收藏代码
  1. Bundle mbundle=new Bundle();            mbundle.putSerializable("user",userList.get(position));  
  2. Intent in =new Intent (getApplicationContext(), activity2.class);  
  3. in.putExtras(mbundle);  
  4. startActivity(in);  



activity2中接收: 
         
A:接收 
Java代码  收藏代码
  1. Bundle extras = getIntent().getExtras();  
  2.             if (extras != null) {  
  3.                 textview.setText(extras.getString("activity1"));  
  4.             }  


B.接收 
Java代码  收藏代码
  1. Bundle bundel = getIntent().getExtras();  
  2.         user= (User) bundel.get("user");   



2.SharedPreferences 

我在activity1中设置的如下: 
Java代码  收藏代码
  1. SharedPreferences sp =getSharedPreferences("textinfo",0);  
  2.     Editor editor=sp.edit();  
  3.     String text = "hello";  
  4.     editor.putString("text", text);  
  5.     editor.commit();  
  6.   
  7.     Intent i = new Intent(getApplicationContext(),activity2.class);  
  8.     startActivity(i);  


跳转到Message的activity,获取内容如下 
Java代码  收藏代码
  1. SharedPreferences share=getSharedPreferences("textinfo",0);  
  2.         String text =share.getString("text"null);  
  3.         msgtextview.setText(text);  
0 0