Android应用程序中的全局变量不持久
Posted
技术标签:
【中文标题】Android应用程序中的全局变量不持久【英文标题】:Global variable in Android application not persisting 【发布时间】:2016-09-27 06:04:18 【问题描述】:我正在设计一个需要本地联系人列表的应用程序。我正在使用 cursorloader 来检索联系人并将其保存在我的应用程序类中全局的 hashmap 中
public class WoofyApp extends Application
private static WoofyApp mInstance;
private FontFactory fontFactory;
private PreferenceService preferenceService;
private RequestQueue mRequestQueue;
private VolleyService mVolley;
private Validator mValidator;
private NetworkService mNetwork;
private DaoSession daoSession;
private HashMap<String,String> persons;
private ProgressDialog pdLoading;
private UserDao userDao;
private static final String WOOFYAPP = "WOOFYAPP";
@Override
public void onCreate()
super.onCreate();
mInstance = this;
persons = new HashMap<>();
public HashMap<String, String> getPersons()
return persons;
public void setPersons(HashMap<String,String> per)
persons = per;
我正在访问相关活动和片段中的联系人列表。我在 ContactService 类中设置它:
public class ContactService implements LoaderManager.LoaderCallbacks<Cursor>
HashMap<String, String> hmContacts;
ArrayList<Person> alContacts;
private Context mContext;
private EventBus bus;
WoofyApp mApp;
private static final String[] PROJECTION =
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
;
public ContactService(AppCompatActivity context)
hmContacts = new HashMap<>();
alContacts = new ArrayList<>();
this.mContext = context;
bus = EventBus.getDefault();
mApp = WoofyApp.getApp();
Log.d(Constants.LIFE_CYCLE,"ContactService called");
if(mApp.getPersons().size()==0)
context.getLoaderManager().initLoader(0,null,this);
if(!context.getLoaderManager().getLoader(0).isReset())
context.getLoaderManager().restartLoader(0, null, this);
Log.d(Constants.LIFE_CYCLE,"ContactService loader called");
else
this.hmContacts = mApp.getPersons();
this.alContacts = hashToArray(hmContacts);
bus.post(hmContacts);
bus.post(new ContactsAdapter(mContext, R.layout.row_contact_child, alContacts));
Log.d(Constants.LIFE_CYCLE,"ContactService persons called");
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args)
Log.d(Constants.LIFE_CYCLE,"ContactService onCreateLoader called");
return new CursorLoader(
mContext,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
PROJECTION,
null,
null,
null
);
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data)
if (data.getCount() > 0)
while (data.moveToNext())
String name = data.getString(
data.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = Validator.formatNumbers(data.getString(
data.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
if (!hmContacts.containsKey(number))
alContacts.add(new Person(name, number));
hmContacts.put(number, name);
Log.d(Constants.LIFE_CYCLE,"onLoadFinished loader called "+hmContacts.size());
mApp.setPersons(hmContacts);
bus.post(hmContacts);
bus.post(new ContactsAdapter(mContext, R.layout.row_contact_child, alContacts));
@Override
public void onLoaderReset(Loader<Cursor> loader)
public static ArrayList<Person> hashToArray(HashMap<String,String> hm)
Iterator it = hm.entrySet().iterator();
ArrayList<Person> persons = new ArrayList<>();
while (it.hasNext())
Map.Entry pair = (Map.Entry)it.next();
persons.add(new Person((String)pair.getValue(),(String)pair.getKey()));
it.remove();
return persons;
奇怪的部分
当我第一次从主要活动及其片段访问它时,它正在正确加载。但是当我从不同的活动返回后尝试访问它时......即主要活动的 onResume 显示大小为 0。有什么想法会发生这种情况吗?
【问题讨论】:
【参考方案1】:添加您需要的设置模型:
public class SettingsModel
public String facebookToken;
public String twitterToken;
//... anything you need
制作设置服务并在扩展应用程序类中将其初始化为
new SettingsService();
设置服务:
public class SettingsService
private static String KEY = "yourDesiredSettingsKey";
private static Context mContext;
public static SettingsModel settings;
public SettingsService()
mContext = YourApplication.getMainContext();
//if(settings == null)
settings = getSettings();
//
public static void saveSettings()
if(settings == null)
settings = new SettingsModel();
SharedPreferences.Editor editor = mContext
.getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit();
Gson gson = new Gson();
String jsonSettings = gson.toJson(settings);
editor.putString("settings", jsonSettings );
editor.commit();
settings = getSettings();
public static SettingsModel getSettings()
SharedPreferences editor = mContext.getSharedPreferences(KEY,
Activity.MODE_PRIVATE);
try
String jsonSettings = editor.getString("settings","settings");
Gson gson = new Gson();
settings = gson.fromJson(jsonSettings, SettingsModel.class);
catch (Exception e)
settings = new SettingsModel();
return settings;
在毕业典礼中:
compile 'com.google.code.gson:gson:2.4'
就是这样,您可以从任何地方访问您的设置:
String token = SettingsService.settings.facebookToken;
或更新它们:
SettingsService.settings.facebookToken = "yourToken";
SettingsService.saveSettings();
【讨论】:
【参考方案2】:我明白了..我正在使用一种方法将 hasmap 转换为其中包含 iterator.remove() 的数组列表..它删除了联系人并将哈希图留空。很抱歉用这个愚蠢的问题打扰您。
【讨论】:
以上是关于Android应用程序中的全局变量不持久的主要内容,如果未能解决你的问题,请参考以下文章