0
我有一些問題從我的小部件訪問我的sharedprefereces。我正在嘗試檢查我在聯繫人列表選擇器中選擇的聯繫人數量。我在「onEnable」的方法Android小部件訪問sharedpreferences
public void onEnabled(Context context)
{
Log.i(TAG,"in onEnabled");
SharedPreferences sharedPrefs = context.getSharedPreferences("settings_category",0);
Log.i(TAG,"Total Number of Contacts: " + sharedPrefs.getInt("numContacts", 0));
if(sharedPrefs.getInt("numContacts", 0) == 0)
{
Log.i(TAG,"NO CONTACTS");
//OPEN settingsprefactivity.java
Intent con_intent = new Intent(context, ContactPrefActivity.class);
con_intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(con_intent);
Toast.makeText(context, "No Contacts Selected", Toast.LENGTH_SHORT).show();
}
}
當我跑我得到0聯繫人檢查,即使在我的偏好活動說1。我不認爲我訪問權方面的東西?
更新:添加代碼
下面是我寫入共享首選項的代碼。
private void addContact(String contactName, String contactPhone)
{
Log.i(TAG,"In Function: addContact");
SharedPreferences.Editor prefEditor = PreferenceManager.getDefaultSharedPreferences(this).edit();
if(isDuplicateContact(contactName,contactPhone)){
Log.i(TAG,"Contact Already Exists");
Toast.makeText(this,"Contact Already in List", Toast.LENGTH_SHORT).show();
}
else{
Log.i(TAG,"Add new Contact");
Log.i(TAG,"Name: " + contactName);
Log.i(TAG,"Phone: " + contactPhone);
prefEditor.putString("contact_"+contactName.replaceAll("\\s","") + contactPhone.replaceAll("[()-]",""),contactName + "|" + contactPhone);
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
int numContacts = sharedPrefs.getInt("numContacts", 0);
prefEditor.putInt("numContacts",numContacts+1);
prefEditor.commit();
}
showPreference();
}
怎麼寫共享偏好?發佈您的代碼 – Libin
我發佈了代碼。它顯示我添加共享首選項的位置。 –