1

Code i have use

public class DemoAsynTask extends AsyncTask{
@Override
 protected void onPreExecute(){      
     try{           

         MainActivity myActivity = new MainActivity();
         myActivity.super.onCreate(savedInstanceState);
         myActivity.setContentView(R.layout.activity_main);

         EditText txtInformation = (EditText) myActivity.findViewById(R.id.txtInformation);
     txtInformation.setText("TESTING");
     }catch(Exception ex){
        ex.printStackTrace(); 
     }
}
    @Override
    protected Object doInBackground(Object... params) {
        // TODO Auto-generated method stub
        return null;
    }
}

The DemoAsynTask class is not inside, i have seen an example is work but class inside MainActivity

public class MainActivity extends activity{
   public class DemoAsynTask extends AsyncTask{
   }
}

The DemoAsynTask class is seperate files and i want call it seperately but it have null pointer exception.

public class MainActivity extends activity{
}
public class DemoAsynTask extends AsyncTask{
}

Error Log java.lang.NullPointerException

4

1 回答 1

1

嘿,您创建了 MainActivity(无需实例化 MainActivity,让它根据活动生命周期进行实例化)并将 DemoAsyncTask 作为另一个类或作为 MainActivity 的内部类。在 onPreExecute() 中,您设置状态“TESTING”,并在 onPostExecute() 中根据您在 doInBackground() 中获得的结果更改状态。

于 2012-11-30T04:44:58.207 回答