问题
Android App with two solution for passing data between activities (No Intent Extras Please!)
public class A {
public static LinkedHashMap<String,String> hashStore = new LinkedHasMap<String,String>();
public void doHttp(){
//Some HTTP call and store some json value
hashStore.put("data","jsonKeyValue");
}
public void onDestroy(){
hashStore.remove(key);// remove data key
hashStore.clear();
}
}
public class B {
public void getHttp(){
//Some HTTP call
String extra = A.hashStore.get("data");
}}
// SharedPreference Call
public class A{
SharedPreference hashPref ; //declaration on onCreate
public void dohttp(){
//Some Http and Store value in SharedPreferences
hashPref.put("data","jsonkeyvalue");
hashPref.apply();
}}
public class B{
SharedPreference hashPref ; //declaration on onCreate
public void getHttp(){
//Some HTTP call
String extra = hashPref.get("data");
}}
- Which one is better option to reduce memory leaks ?
- If i store more than 30-40 keys which one would be preferrable ?
- If i use sharedpreferences won't i eat the performance while validating and updating the keys ??
- Is there any alternative that i could use instead of these two solutions ? (Don't mention Intent Extras here.)
回答1:
Using your activity as an static data source, and let your other activities depend on it (and even know that this activity exists) is a bad practice, according to many principles (high cohesion, decoupling, minimice dependency, Protected Variations...), but android team has some similar approaches that you can rely on, but for the same reason they shouldnt be the first option.
What i would prefer is:
If the data has to be persistent:
- SharedPreferences for small amount of data
- SQLite database for a bigger amount of data
if you dont need to persit the data
- A service that is always running and you bind to all your activities, where you have all common data an functions.
- A helper object where you have the data.
You can find out more in this android official faq page or in this great SO answer, that is based in that faq but with some code examples
回答2:
As stated here,
Pros and Cons of SQLite and Shared Preferences
for large groups of data > 30-40 keys I would suggest you to use SQLite. It´s more powerful than SharedPreferences and provides you the possibility to make queries based on the keys you want to search for.
In the other hand implementing SQLite it´s a little bit more complicated and longer to code than using SharedPreferences.
Having a static LinkedHashMap or any other static variable it´s never a good option for code maintenance and readability, you should use it only if there´s no other option.
Hope it helps. :)
来源:https://stackoverflow.com/questions/20904419/static-linkedhashmap-or-sharedpreference