我试图做一个简单的程序,它使用SharedPreferences保存并检索字符串。应用程序通常会加载,但如果我点击按钮,应用程序会下降我不知道什么是错的。 下面是代码:在SharedPreferences中使用字符串
Shared.java
package com.example.sharedpreferences;
import android.content.Context;
import android.content.SharedPreferences;
public class Shared {
SharedPreferences prefe;
SharedPreferences.Editor editor;
Context mycontext;
public Shared(Context context){
mycontext = context;
prefe = mycontext.getSharedPreferences("Preference", 0);
editor = prefe.edit();
}
public void setpref(String name, String value){
editor.putString(name, value);
editor.commit();
}
public String getvalue(String name){
return prefe.getString(name, "Nothing!");
}
}
MainActivity.java
package com.example.sharedpreferences;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
Shared preferences;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences = new Shared(getApplicationContext());
}
public void btn_send(View button){
TextView name = (TextView)findViewById(R.id.name2);
TextView value = (TextView)findViewById(R.id.value2);
String names = (String) name.getText();
String values = (String) value.getText();
preferences.setpref(names, values);
}
public void btn_read(View button){
TextView name = (TextView)findViewById(R.id.name2);
TextView value = (TextView)findViewById(R.id.value2);
String names = (String) name.getText();
String values = preferences.getvalue(names);
value.setText(values);
}
}
谢谢!
你能发布logcat的输出?我的猜测是有一个NullPointerException – Jared
我还没有见过这种特殊的方法(在一个类中重新使用pref对象)。我想知道在编辑器上调用“commit()”后,编辑器不再可用。你可以尝试将这个逻辑移到你的活动中,每次都得到一个新的SharedPreferernces和Editor参考吗?这至少会验证或无效重新使用对象的方法。这有意义吗? – EJK
logcat中的错误在这里[link](http://txtup.net/DCml)。 EJK,抱歉,但我不知道你的意思。 – Bullman