有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在onPostExecute中从另一个类调用方法导致nullPointerException

这可能对某人也有帮助:How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

我正在从onPostExecute()中的另一个类调用方法

根据文档和调试器,我假设在doInBackground(String... params)之后调用onPostExecute(),这是正确的

调用该方法:

protected void onPostExecute(String result) {
    CreateHangOut crtHO = new CreateHangOut();
    crtHO.createHangOut(result);
}

调用的方法的一部分,导致NPE(方法的第一行):

public void createHangOut(String location) {
    String city=autocompleteTV.getText().toString();
   }

自动完成TextViewautocompleteTV)在创建活动时初始化

以下是我如何称呼AsyncTask

create.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new 
HTTPRequest().execute((autocompleteTV.getText()).toString());
            }
    });

名为onCreate的方法(用于单击按钮的活动):

private void initialize() {
    gAPI= new GoogleAPIAutocomplete();
    autocompleteTV = (AutoCompleteTextView) 
    findViewById(R.id.crtHOLocOptionsTV);
    setUpAutocomplete();
    create = (Button) findViewById(R.id.crtHOCreateBtn);
    name =(EditText) findViewById(R.id.crtHONameET);
    create.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new 
    HTTPRequest().execute((autocompleteTV.getText()).toString());
            }
    });
}

共 (1) 个答案

  1. # 1 楼答案

    因为createHangOut方法在CreateHangOut活动中,所以不需要为访问方法创建新对象,只要使用方法名调用它,如果扩展AsyncTask类的类是CreateHangOut的内部类:

    protected void onPostExecute(String result) {
        CreateHangOut.this.createHangOut(result);
    }