Java 显示toast会导致应用程序崩溃
我的类扩展了Java 显示toast会导致应用程序崩溃,java,android,Java,Android,我的类扩展了AppCompatActivity 这是我的课 public class Login extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login);
AppCompatActivity
这是我的课
public class Login extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final Button loginBtn = (Button) findViewById(R.id.login_btn);
loginBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Login login = new Login();
try {
login.getAccessCode();
}
catch (IOException e){
Log.e("LOGIN", "I got an error", e);
}
}
});
}
public void getAccessCode() throws IOException {
RequestParams params = new RequestParams();
params.put("a", "a");
QuidoRestClient.post("/login/generateCode", params, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// If the response is JSONObject instead of expected JSONArray
Log.d("LOGIN",response.toString());
String code = "";
try {
code = response.getString("code");
}
catch (JSONException e){
}
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray data) {
// If the response is JSONArray instead of expected JSONObject
}
});
}
}
这就是错误所在
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
我也试过了
Toast toast = Toast.makeText(Login.this, text, duration);
我通过直接调用我的方法而不是
Login Login=new Login()解决了这个问题代码>活动是上下文
(或者至少它们继承自上下文
)。因此,不要使用getApplicationContext()
,只需在Toast.makeText的第一个参数中使用this
或YourActivity.this
另一件事:不要做Login Login=new Login()代码>。活动由Android运行时实例化,而不是由我们实例化!相反,只需直接调用getAccessCode()
(另外,请注意,没有任何getApplicationContext
方法)
如果错误仍然存在,则可能是由于onSuccess
回调未在UI线程中运行。如果是这种情况,可能的修复方法有:
不要使用Toast
,但要获取调试消息:
Log.d("your tag", "your message");
将toast创建包含在可运行的UI线程中:
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MyActivity.this, text, duration).show();
}
});
你在代码中的什么地方使用这个?你在哪里使用这个?你能发布整个课程吗?你试过使用你的AppCompatActivity
作为上下文吗<代码>Toast.makeText(这个,文本,持续时间)代码>Login Login=new Login()代码>-你为什么这么做?这就是为什么你会得到一个NPE,不管你怎么做。只需直接调用getAccessCode()
方法。我尝试了Login.this,得到了以下错误java.lang.NullPointerException:尝试调用虚拟方法'android.content.res.Resources android.content.Context.getResources()'在一个空对象引用上更新了我的回答,并尽我所能使用了当时可用的信息。再次更新了答案。