Data transfer and storage

A, android passed the kind of data
java syntax:
1, by construction method
2, using the get and set methods
3, the use of static static data, public static member variables
using static common errors:
ERROR / android runtime (4958): Caused by: java .lang.OutOfMemoryError: Bitmap size VM at Budget Exceeds
        4, the use of callback listener

Android Syntax:
1, using the Intent object carrying data
        2, Bundle data transfer
        2, the startActivityForResult
        . 3, custom broadcast
3, IPC communication mechanism based on
transmission and between-Service Context, and the communication between-Service Activity, defined AIDL interface file
7 , the Context based on the Application
. 8, external storage based on the transmission of
File / the Preference / Sqlite
. 9, a third party frame, EventBus
        10, RxBus
            similar EventBus. It is a subsidiary function of RxJava; if the project has been introduced RxJava package, use RxBus it easy to do.

Activity data transfer between the code example:
(. 1) basic data transfer Intent type
(2) intent pass an object
(3) Bundle delivery data
transfer objects:
the Intent the Intent Intent new new = ();
intent.setClass (Login.this, MainActivity.class) ;
the Bundle the Bundle the bundle new new = ();
bundle.putSerializable ( "User", User);
intent.putExtras (the bundle);
this.startActivity (Intent);
the Intent Intent this.getIntent = ();
User = (the User) Intent. getSerializableExtra ( "user");
delivery set:
the Intent the Intent Intent new new = ();
intent.setClass (MainActivity.this, LoginActivity.class);
the Bundle the Bundle the bundle new new = ();
bundle.putSerializable ( "List", (the Serializable) list); // serialization, to be noted that the conversion (the serializable)
intent.putExtras (the bundle); // send data
startActivity (intent); // start Intent
the Intent Intent this.getIntent = ();
list = (List <the User>) intent.getSerializableExtra ( "list"); // Get list mode

Fragment Activity and data transfer between the
first: use the Bundle
MyFragment myFragment new new MyFragment = ();
the Bundle the Bundle the bundle new new = ();
bundle.putString ( "the DATA", values); // values here that we want to pass the value
myFragment.setArguments (bundle);
second: onAttach in the Fragment (Activity Activity) the method of obtaining the value of an Activity
host activity // in getTitles () method
public String getTitles () {
return "Hello";
} // Fragment the method onAttach @Override public void onAttach (the Activity Activity) { super.onAttach (Activity); the titles = ((the MainActivity) Activity) .getTitles (); } // turn into a host by a strong activity, can be get to pass over the data extension: You can use newInstance (data) method to pass, this method is its own definition, but it is a static method as defined in 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;
}


Second, the data storage type
1, file storage (File, Cache) / Data / Data / the Package the Name / Files
2, using SharedPreferences storing data / Data / Data / the Package the Name / Shared_Pref, 
. 3, the SQLite database storing data; / data / data / the Package the Name / Database
. 4, contentPovider: based on the SQLite
5, network storage

Directory Structure

Internal exclusive:
File FILESDIR = getFilesDir ();

File filesCache=getCacheDir();

External Independent:
File sdcard Environment.getExternalStorageDirectory = ();

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

External Exclusive:
File externalFilesDir by getExternalFilesDir = (null);

File externalFilesDir = getExternalFilesDir("Caches");

 

 

A, Files
1. Context.getFilesDir (), which returns / data / data / youPackageName / files File object.
2. Context.openFileInput () and Context.openFileOutput (), can only read and write files in the files, it returns FileInputStream and FileOutputStream object. www.2cto.com
3. Context.fileList (), returns all the filenames in files, returns the String [] object.
4. Context.deleteFile (String), specifies the file name under delete files.
 
Two, Cache
1. Context.getCacheDir (), which returns / data / data / youPackageName / cache File object.
 
Three, Custom dir
the GETDIR (String name, int the MODE), specify the name of the file returns / data / data / youPackageName / folder under the File object, if the folder does not exist with the specified name to create a new folder.

Some standard wording path

 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

Source: http://blog.csdn.net/buptlzx/article/details/8773447
getFilesDir () Gets inside your app storage space, equivalent to the root directory of your application on internal storage.
getexternalstoragedirectory: external storage

getExternalFilesDir ():

Three, the Intent transmission data
1, transmission basic data types
intent.putExtra (Key, value);
String value = intent.getStringExtra (Key);
2, pass an object
method: Let a Serializable class to implement this interface
intent.putExtra ( " person_data ", the Person);  
the Person the Person = (the Person) getIntent () getSerializableExtra (." person_data "); 
method two: let Parcelable object implements the interface (and should be rewritten describeContents () and writeToParcel () two methods)
intent.putExtra ( "person_data", Person);  
the Person Person = (the Person) its getIntent () getParcelableExtra ( "person_data").; 

3, delivery List collection
method: a simple data type String, Integer
if simply pass List <String> or List <Integer> then can be used directly 

Java code 

intent.putStringArrayListExtra(name, value)  

intent.putIntegerArrayListExtra(name, value)  


Method Two: Strong turn embodiment
If passed List <Object>, can list a strong turn into Serializable type, then 
the Java code putExtras (key, (Serializable) list   )
passed past, accepted when using 
Java code (List <YourObject>) getIntent ().   getSerializableExtra (key)
can receive List <YourObject> the data 

But remember your YourObject class must implement Serializable 

 

Method three: 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);

Receiving a set of objects //
List <the Person> = persons its getIntent () getParcelableArrayListExtra ( "persons");.
For (the Person Person: persons) {
tv_think_showName.setText (tv_think_showName.getText () + "" + persons.toString ()); // collection of objects to the text field
}
four: Bundle using
one is 
Java code Bundle.putSerializable (Key, Object);  
the other is the 
Java code Bundle.putParcelable (Key, Object);  
Of course, these have certain Object condition, the former is realized Serializable interface, which interfaces are realized 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);


Method five: the use of global variables application
with intent passed around inconvenient we can write a global data inside the application 
1, create a subclass of your own android.app.Application 
2, Clarify this in the manifest class 
3, then android will create an instance of a globally available for this purpose, you can use Context.getApplicationContext in any other place () method to get this instance, then get one of the state (variables). 


4, the set of transmission parameters of the nested type
(1) transmitting a set of Map
/ ** 
* serialization Bundle for transmitting map using 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 new new = the Intent the Intent (ListViewActivity.this, UpdateWatchActivity.class);
// data transfer
Final SerializableMap new new SerializableMap myMap = ();
myMap.setMap (map); // add to the map data encapsulated in myMap
Bundle bundle = new the Bundle ();
bundle.putSerializable ( "Map", the myMap);
intent.putExtras (the bundle);
The third step: the reception data:

= The bundle its getIntent the Bundle () getExtras ();.
SerializableMap serializableMap = (SerializableMap) bundle.get ( "map");
this data can be transmitted and used by the map.


(1) passing List <Map <String, Object >> set
// complicated transmission parameters the Map <String, Object> new new MAP1 = the HashMap <String, Object> (); map1.put ( "key1", "VALUE1 "); map1.put (" key2 "," value2 "); List <the Map <String, Object >> List = new new ArrayList <the Map <String, Object >> (); list.add (map1); the Intent the Intent the Intent new new = (); intent.setClass (MainActivity.this, ComplexActivity.class); the Bundle the Bundle the bundle new new = (); // list must be defined for transmitting a need to pass ArrayList <Object> in budnle, this must be want the ArrayList = new new bundlelist the ArrayList (); bundlelist.add (List); bundle.putParcelableArrayList ( "List", bundlelist); intent.putExtras (the bundle);startActivity (Intent); // reception parameters


















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();


}
// Get the value came from MainActivity
String content = getArguments () getString ( "key").;

 

Guess you like

Origin www.cnblogs.com/mesaz/p/11141317.html