使用AsyncTask从MainActivity中的my_Data类读取数据

时间:2015-03-23 09:51:33

标签: java android

如何从array list获取2 String(1 Integer,1 asynctask)并将其打印在Mainactivity ??

这是我的AsyncTask:

private class ReadJSONFeedTask extends AsyncTask<String, Void, String> {
    @Override

    protected String doInBackground(String... urls) {

        return readJSONFeed(urls[0]);
    }
    protected void onPostExecute(String result) {
        try {
            JSONArray jsonArray = new JSONArray(result);
            Log.i("JSON", "Number of surveys in feed: " +jsonArray.length());
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                Toast.makeText(getBaseContext(), jsonObject.getString("city"),Toast.LENGTH_SHORT).show();

               x.setStation_name(jsonObject.getString("city"));
               x.setStation_petrol_amount(jsonObject.getInt("amount"));

            }

            System.out.println("*******"+x.getStation_name());
            System.out.println("*******"+x.getStation_petrol_amount());



        } catch (Exception e) {
            e.printStackTrace();
        }

    }
        }

此处我的输出位于system.out.print&gt;&gt;没关系。

这是my_Data类:

 public      ArrayList<String> city = new ArrayList<>() ;
      public      ArrayList<Integer> amount = new ArrayList<>() ;


    public  void setStation_petrol_amount(int station_petrol_amount) {
        amount.add(station_petrol_amount);
    }

    public  void setStation_name(String station_name)
    {
        city.add(station_name);
    }

       public  ArrayList<String> getStation_name()
    {
        return city;
    }

  public  ArrayList<Integer> getStation_petrol_amount() {
        return amount;
    }

我的主要活动:

    new ReadJSONFeedTask().execute();
    ReadJSONFeedTask ob = new ReadJSONFeedTask();
        ob.execute("http://192.168.12.1/server/index.php");
        System.out.println(">>>>:"+x.getStation_name());
        System.out.println(">>>>:"+x.getStation_petrol_amount());

system.out.print&gt;&gt;的输出没有数据,如何获得?

1 个答案:

答案 0 :(得分:0)

How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

查看问题的答案..一旦线程完成工作,你可以将2个数组列表作为回调方法的参数传递给被调用的活动

在该示例中,接口应该像这样修改

public interface AsyncResponse {
void processFinish(List<String> firstlist,List<Integer> secondlist);}

然后在post执行中你必须将结果arraylist作为参数传递

或者您可以通过替换下面的接口

将x对象列表传递给被调用的活动
   public interface AsyncResponse {
void processFinish(List<X> firstlist);}