Android 应用程序中的全局变量未持久化



我正在设计一个需要本机联系人列表的应用程序。我正在使用光标加载器检索联系人并将其全局保存在我的应用程序类中的哈希图中

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;
}

我正在访问相关活动和片段中的联系人列表。我正在联系服务类中设置它:

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;
}
}

奇怪的部分

当我第一次从主活动及其片段访问它时,它正在正确加载。但是当我从不同的活动回来后尝试访问它时......即在主要活动的简历上,它显示大小为 0。知道这是怎么回事吗?

添加您需要的设置模型:

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

我明白了。我正在使用一种方法将hasmap转换为包含iterator.remove()的arraylist。它删除了联系人并将哈希图留空。很抱歉用这个愚蠢的问题打扰您。

相关内容

  • 没有找到相关文章

最新更新