【问题标题】:Android - Access Servlet AsyncPost task response from fellow classesAndroid - 从其他类访问 Servlet AsyncPost 任务响应
【发布时间】:2015-05-28 01:43:02
【问题描述】:

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

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

在 Servlet 和 Client 中我都创建了两个类,Tour.classTours.class 来存储我的数据:

旅游班:

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

旅游类:

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 以外的其他类访问新收到的 Tours 对象的原因是什么?

非常感谢

【问题讨论】:

    标签: java android json servlets android-studio


    【解决方案1】:

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

    回调接口:

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

    调用者类:

    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();
        }
    };
    

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

    【讨论】:

      【解决方案2】:

      问题是你认为代码是串行运行的,如果你想使用从 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
      }
      

      【讨论】:

      • 好的,但是,我在onPostExecute 中填充我的 Tours tours 对象,这与您的意思有何不同?回调是指吸气剂吗?我也试过了,但没有用……此外,如果代码没有串行运行,我怎么知道异步任务何时完成并可以发送数据?
      • 您的Tours ttours = s.tours; 在您的onPostExecute 命中时尚未填满。调用execute 后的所有代码都会立即运行,它不会等待
      • 他们要做的就是在 onPostExecute 中做你需要做的事情
      • 好的,但是我明白了你所说的,并且我已经完成了我在onPostExecute 中需要做的事情:它实际上填充了我的 Tours 对象,问题是它按照你的建议做得太晚了.如何同步整个过程?或者你的意思是不可能将对象从异步任务传递给其他类?
      • 更正你不能直接从异步任务传递对象,你需要使用interface在完成时创建一个回调,将对象发送到接口回调
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多