嗨,又是堆栈溢出,
我想存储会话,但我有一个问题,我跳过一个错误,我有类“会话”和另一个类称为"MainActivity“
在我的会议上,我有:
public void saveSession(Context ctx,String username, String password){
sharedpreferences = PreferenceManager.getDefaultSharedPreferences(ctx);
Editor editor = sharedpreferences.edit();
String u = username;
String p = password;
editor.putString(name, u);
editor.putString(pass, p);
editor.commit();
}我的主要观点是:
session.saveSession(getApplicationContext(), username.getText().toString(),password.getText().toString());我知道这个错误:
03-12 01:47:01.648: E/AndroidRuntime(3395): FATAL EXCEPTION: main
03-12 01:47:01.648: E/AndroidRuntime(3395): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.xx/com.example.xx.UserList}: java.lang.NullPointerException
03-12 01:47:01.648: E/AndroidRuntime(3395): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)更新: onCreate()方法
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_list);
//loadSesion(); session.loadSession(getApplicationContext());
usernameSession = session.getUsernameSession();
passwordSession = session.getPasswordSession();
inicializeBdSqlite();
inicialize();
user_list.setOnItemClickListener(this);
} 发布于 2014-03-12 12:30:05
首先,关于SharedPreferences和您使用它的方式。我有一些笔记:
1)确保字符串name和pass是最终字符串,并且已经在该方法所包含的类中初始化,因为如果您的任何sharedPreference键是null,则整个文件可能会按以下方式中断:
final string name = "name";
final string pass = "password";2)不需要将新值放入新字符串,而是直接传递
public void saveSession(Context ctx,String username, String password){
SharedPreference sharedpreferences = PreferenceManager.getDefaultSharedPreferences(ctx);
Editor editor = sharedpreferences.edit();
editor.putString(name, username);
editor.putString(pass, password);
editor.commit();
}3)使您的getter方法如下:
public String getUserName(Context ctx){
SharedPreference sharedpreferences = PreferenceManager.getDefaultSharedPreferences(ctx);
return sharedpreferences.getString(name, "");//"" is the default value
}4)关于user_list行user_list.setOnItemClickListener(this); .Make,确保您的主要活动implements类OnClickListener如下:
public class MainActivity extends Activity implements OnClickListener {在您的MainActivity中,重写它如下所示:
@Override
public void onClick(View v) {
//You action
}我希望它能帮上忙
https://stackoverflow.com/questions/22339930
复制相似问题