AsyncTask onPostExecute NullPointerException

创建了两个AsyncTask,但是当把第一个AsyncTask的输出当做输入传给第二个AsyncTask时,就会出现空值异常,第一个AsyncTask 是Geopoint。

String input=EnterYourSearch.getText().toString();
Geopoint point_to_be_send;
     get_location.execute(input);       
     getplaces.execute(point_to_be_send);
        public class Getlocation extends AsyncTask<String, String, Geopoint> 
        { 
          @Override
          protected Geopoint doInBackground(String... params) {
            jsonobject=JsonRequest.getLocationInfo(params[0]);   
            point=JsonRequest.getLatLong(jsonobject);     
            return point;    
          }
          @Override
          protected void onPostExecute( Geopoint point) {
            if(point.lat !=0)
            {
              //check=false;
              point_to_be_send=point;
            }
          }
        }
    public class Getplaces extends AsyncTask<Geopoint, String, Boolean>
        {
            @Override
            protected Boolean doInBackground(Geopoint... params) {
                // TODO Auto-generated method stub
                 googleplaces=new Googleplaces();
                       try {
                        googleplaces.search(params[0].lat, params[0].lon, 1000, null);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        Log.d("Error", e.toString());
                        e.printStackTrace();
                    }
                    return true;
                    }

Geopoint 类:

public class Geopoint {
    public double lat;
    public double lon;
    public Geopoint(double i, double j) {
        // TODO Auto-generated constructor stub
        lat=i;
        lon=j;
    }
}

ChatGPT尝试为您解答
在您的代码中,您正在尝试在第一个 AsyncTask 完成后执行第二个 AsyncTask,并将第一个 AsyncTask 返回的 Geopoint 对象作为输入传递给第二个 AsyncTask。但是,您在第一个 AsyncTask 的 onPostExecute() 方法中将 Geopoint 对象赋值给 point_to_be_send 变量之前,您就在第二个 AsyncTask 中调用了 execute() 方法,并尝试使用 point_to_be_send 变量作为输入。


这意味着在第二个 AsyncTask 运行时,point_to_be_send 变量可能尚未初始化。因此,当您尝试使用 point_to_be_send 变量时,您可能会遇到空值异常。


为了解决这个问题,您可以在第一个 AsyncTask 的 onPostExecute() 方法中调用第二个 AsyncTask 的 execute() 方法,这样就可以确保 point_to_be_send 变量已经初始化。例如:

public class Getlocation extends AsyncTask<String, String, Geopoint> 
{ 
  @Override
  protected Geopoint doInBackground(String... params) {
    jsonobject=JsonRequest.getLocationInfo(params[0]);   
    point=JsonRequest.getLatLong(jsonobject);     
    return point;    
  }
  @Override
  protected void onPostExecute( Geopoint point) {
    if(point.lat !=0)
    {
      //check=false;
      point_to_be_send=point;
      getplaces.execute(point_to_be_send);
    }
  }
}

这样,当第一个 AsyncTask 完成后,就可以将 point_to_be_send 变量作为输入传递给第二个 AsyncTask。