gpt4 book ai didi

session 类上的 java.lang.NullPointerException

转载 作者:行者123 更新时间:2023-12-01 13:01:08 25 4
gpt4 key购买 nike

我正在为登录类的 session 管理创建一个 session.class,但我的 logcat 显示错误 java.lang.NullPointerException 并且应用程序无法在模拟器上运行,请帮忙

这是我的 session.java:

public class Session {

private SharedPreferences prefs;
Editor editor = prefs.edit();

public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);

}

public void setkdanggota(String kdanggota) {
editor.putString("kdanggota", kdanggota).commit();
editor.commit();
}

public String getusename() {
String kdanggota = prefs.getString("kdanggota",null);
return kdanggota;
}
}

这是我的login.java:

public class login extends Activity{
EditText kode,pw;
TextView error;
Button login;
String i;
private Session session;


public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
Context cntx = getApplicationContext();
session = new Session(cntx );
kode = (EditText) findViewById(R.id.kode);
pw = (EditText) findViewById (R.id.password);
login = (Button) findViewById (R.id.login);
error = (TextView) findViewById (R.id.error);
login.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("kode", kode.getText().toString()));
postParameters.add(new BasicNameValuePair("password", pw.getText().toString()));
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://10.0.2.2/koperasidb/login.php", postParameters);
String res = response.toString();
res = res.trim();
res = res.replaceAll("\\s+","");
error.setText(res);
if (res.equals("1")){
error.setText("Correct Username or Password");
session.setkdanggota(kode.getText().toString());
berhasil(v);
}
else {
error.setText("Sorry!! Wrong Username or Password Entered");
}
}
catch (Exception e) {
kode.setText(e.toString());
}
}
});
}

public void berhasil (View theButton)
{
Intent s = new Intent (this, Home.class);
startActivity(s);
}
}

最佳答案

当您执行此操作时,pref 未初始化/为 null,因此编辑器设置为 null。

Editor editor = prefs.edit();

因此,在初始化 prefs 后将编辑器初始化移至构造函数应该会有所帮助

更改此:

private SharedPreferences prefs;
Editor editor = prefs.edit();

public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);

}

private SharedPreferences prefs;
Editor editor;

public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
editor = prefs.edit();

}

关于 session 类上的 java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23508870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com