我不确定如何说出来,但我在MODE_PRIVATE下访问共享首选项时遇到问题。
我实现了一个像这样的Spinner:
setSessions = (Spinner)findViewById(R.id.numSessions);
setSessions.setOnItemSelectedListener(new CustomOnItemSelectedListener());
Custom listener就是这样:
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
SharedPreferences defaultPrefs;
defaultPrefs = getSharedPreferences("Defaults", MODE_PRIVATE);
String savedSessions = defaultPrefs.getString("tcpCapSessions", "None Set");
if (savedSessions != parent.getItemAtPosition(pos).toString()) {
final Editor defaultEdit = defaultPrefs.edit();
defaultEdit.putString("tcpCapSessions", parent.getItemAtPosition(pos).toString()); // Writes the key "Default Server" along with Server Name chosen (as the value).
defaultEdit.commit();
}
Toast.makeText(parent.getContext(),
"Sessions set to: " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
我在&#34; MODE_PRIVATE &#34;上收到错误获得SharedPreferences时....
我只想根据用户选择更新首选项。我已尝试扩展活动以消除错误,但应用程序在首次启动时仍会崩溃。
我已经检查了Use sharedpreferences inside class,但它没有帮助我解决问题,可能是因为它看起来像我自己的问题一样。
答案 0 :(得分:0)
MODE_PRIVATE
是Context
的静态成员。它实际上描述得非常好here。
将其更改为Context.MODE_PRIVATE
答案 1 :(得分:0)
嗨天才尝试这个..
您必须调用getSharedPreferences()方法,该方法返回指向包含首选项值的文件的SharedPreferences实例。
SharedPreferences sharedpreferences = getSharedPreferences(YOUR_PREFERENCE_NAME, Context.MODE_PRIVATE);
第一个参数是名称,第二个参数是 MODE 。
所需的偏好文件。如果此名称的首选项文件不存在,则在检索编辑器(SharedPreferences.edit())然后提交更改(Editor.commit())时将创建该文件。
(操作模式)
示例:强>
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
//Initialize SharedPreferences.
public static SharedPreferences.Editor editUserSelection;
public static SharedPreferences prefUserSelection;
public static final String GET_USER_PREF = "get_my_user";
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
//save user selected position.
prefUserSelection = getApplicationContext().getSharedPreferences(GET_USER_PREF, 0);
editUserSelection= prefUserSelection.edit();
editUserSelection.putInt("user", pos);
editUserSelection.commit();
}
用于检索用户位置
prefUserSelection = getApplicationContext().getSharedPreferences(GET_USER_PREF, 0);
int userSelected = prefUserSelection .getInt("user", 0); //0 is the default value
Toast.makeText(getActivity(), "User Selected Position: "+userSelected ,Toast.LENGTH_SHORT).show();