显示toast会导致应用崩溃

时间:2017-03-29 06:43:04

标签: java android

我的课程延伸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();

解决了这个问题

1 个答案:

答案 0 :(得分:2)

活动为Contexts(或至少从Context继承)。因此,只需在getApplicationContext()的第一个参数中使用thisYourActivity.this,而不是Toast.makeText

另一件事:不要做Login login = new Login();。活动由Android运行时实例化,而不是我们!相反,只需直接致电getAccessCode()

(另请注意,AppCompatActivity没有任何getApplicationContext方法)

如果错误仍然存​​在,那么可能来自onSuccess回调未在UI线程中运行的事实。如果是这种情况,可能的修复方法是:

  1. 不要使用Toast,而是Log来获取调试消息:

    Log.d("your tag", "your message");
    
  2. 将您的吐司创建封闭在可运行的UI线程中:

    runOnUiThread(new Runnable() {
        public void run() {
            Toast.makeText(MyActivity.this, text, duration).show();
        }
    });