数据传递与存储

一、android中传递数据的种类
java语法:
1、通过构造方法
2、利用get和set方法
3、利用static静态数据,public static 成员变量
使用static常见错误:
ERROR/AndroidRuntime(4958): Caused by: java.lang.OutOfMemoryError: bitmap size exceeds VM budget
        4、利用回调监听

Android语法:
1、利用Intent对象携带数据
        2、Bundle 传递数据
        2、startActivityForResult
        3、自定义广播
3、基于IPC通信机制
Context 与 service之间的传输,如Activity与Service之间通信,定义AIDL接口文件
7、基于Application Context
8、基于外部存储的传输
File/Preference/Sqlite
9、第三方框架,EventBus
        10、RxBus
            类似于EventBus。它是RxJava的一个附属功能;如果项目中已经引入了RxJava包,则使用RxBus就再适合不过了。

Activity间传递数据代码示例:
(1)intent传递基本数据类型
(2)intent传递对象
(3)Bundle传递数据
传递对象:
Intent intent = new Intent();
intent.setClass(Login.this, MainActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("user", user);
intent.putExtras(bundle);
this.startActivity(intent);
Intent intent = this.getIntent();
user=(User)intent.getSerializableExtra("user");
传递集合:
Intent intent=new Intent();
intent.setClass(MainActivity.this, LoginActivity.class);
Bundle bundle=new Bundle();
bundle.putSerializable("list",(Serializable)list);//序列化,要注意转化(Serializable)
intent.putExtras(bundle);//发送数据
startActivity(intent);//启动intent
Intent intent = this.getIntent();
list = (List<User>) intent.getSerializableExtra("list");//获取list方式

Activity和Fragment间的数据传递
第一种:利用Bundle
MyFragment myFragment = new MyFragment();
Bundle bundle = new Bundle();
bundle.putString("DATA",values);//这里的values就是我们要传的值
myFragment.setArguments(bundle);
第二种:在Fragment中的onAttach(Activity activity)方法中获取Activity中的值
//宿主activity中的getTitles()方法
public String getTitles(){
return "hello";
}

//Fragment中的onAttach方法
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
titles = ((MainActivity) activity).getTitles();
}
//通过强转成宿主activity,就可以获取到传递过来的数据
扩展:可以使用newInstance(数据)方法来传递,这个方法是自己定义的,但是是定义在Fragment中的一个静态方法。
static MyFragment newInstance(String s){
MyFragment myFragment = new MyFragment();
Bundle bundle = new Bundle();
bundle.putString("DATA",s);
myFragment.setArguments(bundle);
return myFragment;
}

//同样,在onCreatView中直接获取这个值
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_fragment,container,false);
Bundle bundle = getArguments();
String data = bundle.getString("DATA");
tv = (TextView) view.findViewById(R.id.id_fm_tv);
if(data != null){
tv.setText(data);
}
return view;
}


二、数据存储类型
1、文件存储(file、cache)    /data/data/Package Name/files
2、使用SharedPreferences存储数据   /data/data/Package Name/Shared_Pref, 
3、SQLite数据库存储数据;   /data/data/Package Name/database
4、contentPovider:基于SQLite
5、网络存储

应用目录结构

内部专属:
File filesDir = getFilesDir();

File filesCache=getCacheDir();

外部独立:
File sdCard = Environment.getExternalStorageDirectory();

File directory_pictures = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

外部专属:
File externalFilesDir = getExternalFilesDir(null);

File externalFilesDir = getExternalFilesDir("Caches");

一、 files
1. Context.getFilesDir(),该方法返回/data/data/youPackageName/files的File对象。
2. Context.openFileInput()与Context.openFileOutput(),只能读取和写入files下的文件,返回的是FileInputStream和FileOutputStream对象。www.2cto.com
3. Context.fileList(),返回files下所有的文件名,返回的是String[]对象。
4. Context.deleteFile(String),删除files下指定名称的文件。
 
二、cache
1. Context.getCacheDir(),该方法返回/data/data/youPackageName/cache的File对象。
 
三、custom dir
getDir(String name, int mode),返回/data/data/youPackageName/下的指定名称的文件夹File对象,如果该文件夹不存在则用指定名称创建一个新的文件夹。

一些路径的标准写法

 Environment.getDataDirectory() = /data
 Environment.getDownloadCacheDirectory() = /cache
 Environment.getExternalStorageDirectory() = /mnt/sdcard
 Environment.getRootDirectory() = /system
 context.getCacheDir() = /data/data/com.mt.mtpp/cache
 context.getExternalCacheDir() = /mnt/sdcard/Android/data/com.mt.mtpp/cache
 context.getFilesDir() = /data/data/com.mt.mtpp/files

来源: http://blog.csdn.net/buptlzx/article/details/8773447
getFilesDir()获取你app的内部存储空间,相当于你的应用在内部存储上的根目录。
getexternalstoragedirectory:外部存储

getExternalFilesDir():

三、Intent传递数据
1、传递基本数据类型
intent.putExtra(key, value);
String value=intent.getStringExtra(key);
2、传递对象
方法一:让一个类去实现Serializable 这个接口
intent.putExtra("person_data", person);  
Person person = (Person) getIntent().getSerializableExtra("person_data"); 
方法二:让对象实现Parcelable接口(须重写describeContents()和writeToParcel()这两个方法)
intent.putExtra("person_data", person);  
Person person = (Person) getIntent().getParcelableExtra("person_data"); 

3、传递List集合
方法一: 简单数据类型String、Integer
如果单纯的传递List<String> 或者List<Integer>的话 就可以直接使用 

Java代码 

intent.putStringArrayListExtra(name, value)  

intent.putIntegerArrayListExtra(name, value)  


方法二: 强转的方式
如果传递的是List<Object>,可以把list强转成Serializable类型,然后通过 
Java代码  putExtras(key, (Serializable)list)  
方法传递过去,接受的时候用 
Java代码  (List<YourObject>) getIntent().getSerializableExtra(key)  
就可以接受到List<YourObject>数据了 

但是 切记 你的YourObject类必须要实现Serializable接口 

方法三:putParcelableArrayListExtra

//传递对象集合  
intent.putParcelableArrayListExtra("persons",persons);
Person person1=new Person(1,"静静",19);
Person person2=new Person(2,"明明",19);
Person person3=new Person(3,"雷雷",19);

ArrayList<Person> persons=new ArrayList<>();
persons.add(person1);
persons.add(person2);
persons.add(person3);
//传递对象集合
intent.putParcelableArrayListExtra("persons",persons);

//接收对象集合
List<Person> persons=getIntent().getParcelableArrayListExtra("persons");
for (Person person : persons) {
tv_think_showName.setText(tv_think_showName.getText()+" "+persons.toString());//将对象集合设置到文本域
}
方法四: 利用Bundle
一种是 
Java代码  Bundle.putSerializable(Key,Object);  
另一种是 
Java代码  Bundle.putParcelable(Key, Object);  
当然这些Object是有一定的条件的,前者是实现了Serializable接口,而后者是实现了Parcelable接口 

//传递:
Intent intent = new Intent();
...
Bundle bundle = new bundle();
Bundle.putSerializable(Key,Object);
...
//接收:
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
list = (list<Object>)bundle.getSerialable("key")
//传递:(如上一样的操作)
Bundle.putParcelable(Key, Object);


方法五: 利用application全局变量
用intent传来传去 觉得不方便 我们可以写一个在application里面的全局数据 
1、创建一个属于你自己的android.app.Application的子类 
2、在manifest中申明一下这个类, 
3、这时android就为此建立一个全局可用的实例,你可以在其他任何地方使用Context.getApplicationContext()方法获取这个实例,进而获取其中的状态(变量)。 


4、传递集合嵌套类型的参数
(1)传递Map集合
/** 
* 序列化map供Bundle传递map使用 
*/

public class SerializableMap implements Serializable {

private Map<String,Object> map;

public Map<String, Object> getMap() {
return map;
}

public void setMap(Map<String, Object> map) {
this.map = map;
}
}
第二步:传递数据:

Intent intent=new Intent(ListViewActivity.this,UpdateWatchActivity.class);
//传递数据
final SerializableMap myMap=new SerializableMap();
myMap.setMap(map);//将map数据添加到封装的myMap中
Bundle bundle=new Bundle();
bundle.putSerializable("map", myMap);
intent.putExtras(bundle);
第三步:接收数据:

Bundle bundle = getIntent().getExtras();
SerializableMap serializableMap = (SerializableMap) bundle.get("map");
到此数据就能在通过map传递和使用了。


(1)传递List<Map<String, Object>>集合
//传递复杂些的参数

Map<String, Object> map1 = new HashMap<String, Object>();
map1.put("key1", "value1");
map1.put("key2", "value2");
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
list.add(map1);

Intent intent = new Intent();
intent.setClass(MainActivity.this,ComplexActivity.class);
Bundle bundle = new Bundle();
//须定义一个list用于在budnle中传递需要传递的ArrayList<Object>,这个是必须要的
ArrayList bundlelist = new ArrayList();
bundlelist.add(list);
bundle.putParcelableArrayList("list",bundlelist);
intent.putExtras(bundle);
startActivity(intent);
//接收参数

Bundle bundle = getIntent().getExtras();
ArrayList list = bundle.getParcelableArrayList("list");
//从List中将参数转回 List<Map<String, Object>>
List<Map<String, Object>> lists= (List<Map<String, Object>>)list.get(0);
String sResult = "";
for (Map<String, Object> m : lists)

{

for (String k : m.keySet())

{

sResult += "\r\n"+k + " : " + m.get(k);

}

}

四、Bundle传递数据
1、在Activity之间批量传递基本数据类型
// "com.test" is the package name of the destination class
// "com.test.Activity02" is the full class path of the destination class
Intent intent = new Intent().setClassName("com.bundletest", "com.bundletest.Bundle02");

Bundle bundle = new Bundle();
bundle.putString("name", "skywang");
bundle.putInt("height", 175);
intent.putExtras(bundle);
startActivity(intent);
// end current class
finish();
Bundle bundle = this.getIntent().getExtras();
String name = bundle.getString("name");
int height = bundle.getInt("height");
2、传递对象

3、activity和Fragment间的数据传递
public class MainActivity extends Activity {

RightFragment fragment;
FragmentManager manager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragment = new RightFragment();
manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();

//通过bundle对象向Fragment传值
Bundle bundle = new Bundle();
bundle.putString("key", "我是主人,activity");
fragment.setArguments(bundle);

transaction.add(R.id.rightLayout, fragment);
transaction.commit();


}
//获取从MainActivity传来的值
String content = getArguments().getString("key");

猜你喜欢

转载自www.cnblogs.com/mesaz/p/11141317.html