[英]What is the proper way to make my List be read and modified throughout my entire Android Java project?
我有以下列表:
List<Map<String, String>> items = new ArrayList<Map<String, String>>();
它填充了我應用程序負載中的數據。 我需要在整個應用程序中的大多數“活動”和“片段”上使用它,同時讀取和修改數據。
在沒有太多復雜性的情況下使這種全局性最好和最簡單的方法是什么?
注意:出於太多原因無法在Stack Overflow上進行解釋,請將該列表用作List,而不用作具有屬性的自定義對象。
我將創建一個類來保存您的數據(類似於Singleton方法),並將變量設置為靜態。
class NewClass {
public static List<Map<String, String>> items = new ArrayList<Map<String,String>>();
}
您可以根據需要將getter / setter / modifier方法添加到上述類中。
然后,在其他類中,您可以創建局部變量,您可以將其定義為其他類的列表。
class OldClass {
private List<Map<String, String>> myItems;
public OldClass() {
myItems = NewClass.items;
}
}
其他帖子都沒有講到重點。 當然,他可以將列表存儲為實例成員,並使用getter和setter訪問它,但是該成員擁有什么對象?
您可以按照建議的方式使用靜態變量,但是有更好的方法...只需將其掛在應用程序類上即可。 創建一個擴展Application
的類,並在其中添加實例,
public class MyApplication extends Application {
private List<Map<String, String>> items = new ArrayList<Map<String, String>>();
public List<Map<String, String>> getItems() {
return items;
}
public void setItems(List<Map<String, String>> items) {
this.items = items;
}
}
將應用程序類配置到清單中,
<application
android:name=".MyApplication"
...
現在,在您的活動或服務中,只需執行此操作,
List<Map<String, String>> items = ((MyApplication)getApplication()).getItems();
從你的碎片,做到這一點,
List<Map<String, String>> items = ((MyApplication)getActivity().getApplication()).getItems();
令人高興的是,該對象與您的應用程序具有相同的生命周期。 它在應用程序的任何部分處於活動狀態時都存在,並且與應用程序一起進行GC處理。
創建一個抽象幫助程序類,並將您的列表粘貼在那里,這樣您就可以從任意位置訪問它。
public abstract class HelperClass() {
public static List<Map<String, String>> items
= new ArrayList<Map<String,String>>();
static {
//populate the list with anything you need when the class is loaded.
}
}
將您的類抽象化將阻止某人實例化它。 如果在應用程序首次運行時列表中需要任何元素,則可以在靜態初始化程序塊中執行此操作,如上所示。
這將使您可以訪問應用程序中的任何位置。
private List<Map<String, String>> items = new ArrayList<Map<String, String>>();
public List<Map<String, String>> getItems() {
return items;
}
public void setItems(List<Map<String, String>> items) {
this.items = items;
}
實現此目的的首選方法是使用getter和setter。 將列表本身設為私有,並創建公共的getList和publi setList方法以從應用程序中的任何位置獲取和設置列表。
public List getList() {
return items;
}
public void addItems(String item) {
//code to add items
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.