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

时间:2016-05-29 09:24:12

标签: android android-fragments global-variables android-contacts android-cursorloader

我正在设计一个需要原生联系人列表的应用程序。我正在使用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;
}
}

THE STRANGE PART

当我第一次从主要活动及其片段访问它时,它正在正确加载。但是当我从不同的活动返回后尝试访问它时。 onResume主要活动显示大小0.任何想法如何发生这种情况?

2 个答案:

答案 0 :(得分:0)

添加您需要的设置模型:

public class SettingsModel {
    public String facebookToken;
    public String twitterToken;
    //... anything you need 
}

制作设置服务并在扩展应用程序类中将其作为

启动
new SettingsService();

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


}

in gradle:

compile 'com.google.code.gson:gson:2.4'

这就是全部,您可以通过以下任何地方访问您的设置:

String token = SettingsService.settings.facebookToken;

或更新它们:

SettingsService.settings.facebookToken = "yourToken";
SettingsService.saveSettings();

答案 1 :(得分:0)

我得到了..我正在使用一种方法将hasmap转换为arraylist,其中包含iterator.remove()..它删除了联系人并将hashmap留空。很抱歉打扰你这个愚蠢的问题。