Android - 访问伙伴 类 的 Servlet AsyncPost 任务响应

Android - Access Servlet AsyncPost task response from fellow classes

我有一个应用程序通过 AsyncPost 任务连接到 Java Servlet backend。任务 returns 给客户端的一个字符串,表示用 Gson 序列化的 json 对象。

几乎可以正常工作,问题是我无法从 class 实例化对 ServletPostAsyncTask 的调用访问 Servlet 响应消息:ListViewPrenota.class。 项目结构如下:

我在 Servlet 和客户端中创建了两个 classes,Tour.classTours.class 来存储我的数据:

游览class:

public class Tour {
  // some simple int/string/list fields
}

游览class:

public class Tours {
  private List<Tour> tours;
  // ...
}

在客户端,在 ServletPostAsyncTask.class 中,我在 doInBackGround() 中收到上述 Gson 对象。在 onPostExecute() 我反序列化它,这样:

class ServletPostAsyncTask extends AsyncTask<Pair<Context, String>, Void,     String> {
    private Context context;
    Tours tours;

    @Override
    protected String doInBackground(Pair<Context, String>... params) {
     //connect to Servlet and get the serialized Gson object
    }

    @Override
    protected void onPostExecute(String jsonResponse) {
        tours = (new Gson().fromJson(jsonResponse, Tours.class));
    }
} 

现在,我从客户端的 ListViewPrenota.class 调用 ServletPostAsyncTask:

ServletPostAsyncTask s = new ServletPostAsyncTask();
s.execute(new Pair<Context, String>(ListViewPrenota.this, "tours"));
Tours ttours = s.tours;
Tour tour = ttours.getTours().get(0);

问题:我收到一个 java.lang.NullPointerException 指向 Tour tour = ttours.getTours().get(0);

阻止我从 ServletPostAsyncTask 以外的 class 访问新收到的 Tours 对象的原因是什么?

非常感谢

问题是你认为代码是串行运行的,如果你想使用从 AsycTask 返回的东西,你需要在 onPostExecute 中使用它,或者有一个回调在之后发送数据完成了

doInBackground(){
//do heavy work
}

onPostExecute(Data data){
//handle data
//send data via interface to activity or class that needs the data
//or just put everything that needs the data in here
}

好的,它有效。这是我能够想出的:

回调接口:

interface CallBack {
    void callBackMethod(Tours tours);//do job
}

来电者class:

class ServletPostAsyncTask extends AsyncTask<Pair<Context, String>, Tours, String>{
    private Context context;
    Tours tours;
    public ListViewPrenota listViewPrenota;
    public ServletPostAsyncTask(ListViewPrenota listView){
        this.listViewPrenota = listView;
    }
    @Override
    protected String doInBackground(Pair<Context, String>... params) {
        //communicate with Servlet and get a HttpResponse
    }

    @Override
    protected void onPostExecute(String jsonResponse) {
        tours = (new Gson().fromJson(jsonResponse, Tours.class));

        //the callback starts a thread updating the UI in ListViewPrenota
        listViewPrenota.callBackMethod(tours);
        Toast.makeText(
                context,
                "Connected. \nTours size: "+ tours.getTours().size(),
                Toast.LENGTH_LONG).show();
        }
    }

回调接口在ListViewPrenota中的实现:

public class ListViewPrenota extends FragmentActivity implements CallBack{
    private ProgressDialog m_ProgressDialog = null;
    private Runnable viewOrders;
    private TourAdapter m_adapter;
    ListView listView;
    private ArrayList<Tour> m_tours =null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_view_prenota);

    listView = (ListView) findViewById(R.id.list);
    m_tours = new ArrayList<Tour>();

    m_adapter = new TourAdapter(this, R.layout.list_row, m_tours);
    listView.setAdapter(m_adapter);

    getActionBar().setDisplayHomeAsUpEnabled(true); //pulsante drawer
    getActionBar().setHomeButtonEnabled(true);      //pulsante dietro

    ServletPostAsyncTask spat = new ServletPostAsyncTask(ListViewPrenota.this);
    String status = spat.getStatus().toString();
    spat.execute(new Pair<Context, String>(ListViewPrenota.this,"tours"));
}

public void callBackMethod(final Tours tours){
    System.out.println("I've been called back");
    viewOrders = new Runnable(){
        @Override
        public void run() {
            getOrders(tours);
        }
    };
    Thread thread =  new Thread(null, viewOrders, "MagentoBackground");
    thread.start();
    m_ProgressDialog = ProgressDialog.show(
            ListViewPrenota.this,
            "Please wait...",
            "Retrieving data ...",
            true);
}

public void getOrders(Tours tours){
    try{
        m_tours = new ArrayList<>();
        m_tours.addAll(tours.getTours());

        Thread.sleep(2000);
        Log.i("ARRAY", "" + m_tours.size());
    } catch (Exception e) {
        Log.e("BACKGROUND_PROC", e.getMessage());
    }
    //add tours to the adapter
    runOnUiThread(returnRes);
}
private Runnable returnRes = new Runnable() {
    @Override
    public void run() {

        if(m_tours != null && m_tours.size() > 0){
            m_adapter.notifyDataSetChanged();
            for(int i=0;i<m_tours.size();i++)
                m_adapter.add(m_tours.get(i));
        }
        m_ProgressDialog.dismiss();
        m_adapter.notifyDataSetChanged();
    }
};

如果有更好的方法,我接受进一步的建议。 同时,非常感谢你