【问题标题】:How to get data from HTTP requests and add to a single ListView?如何从 HTTP 请求中获取数据并添加到单个 ListView?
【发布时间】:2016-05-06 07:14:53
【问题描述】:

例如,我正在尝试从两个不同的 HTTP 请求 获取数据并添加到单个列表视图中。

在上图中,我从不同的 HTTP REQUESTS 获取数据和来自不同 HTTP REQUESTS 的图像,我还想将图像用作 ViewPager 在这个 Listview

这是我尝试过的代码。

ArrayList<home_listview_model> restaurant_Array_list;
home_listadapter home_listadapter;

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

    restaurant_Array_list = new ArrayList<home_listview_model>();
    new get_restaurant_data().execute("http://example.com/api/restaurant");
    ListView listview = (ListView)findViewById(R.id.home_list);
    home_listadapter = new home_listadapter(getApplicationContext(), R.layout.home_list_view, restaurant_Array_list);
    listview.setAdapter(home_listadapter);
    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
       @Override
       public void onItemClick(AdapterView<?> arg0, View arg1, int position,long id) {
           Toast.makeText(getApplicationContext(), restaurant_Array_list.get(position).getRestaurant_name(), Toast.LENGTH_LONG).show();
            }
       });
}

这是我的 get_restaurant_data AsyncTask 代码

public class get_restaurant_data extends AsyncTask<String, Void, Boolean> {


        ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(home.this);
            dialog.setMessage("Loading... please wait");
            dialog.show();
            dialog.setCancelable(false);
        }


        @Override
        protected Boolean doInBackground(String... urls) {
            try {

                //------------------>>
                HttpGet httppost = new HttpGet(urls[0]);
                httppost.addHeader( "food-api-key" , "***********" );
                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response = httpclient.execute(httppost);

                // StatusLine stat = response.getStatusLine();
                int status = response.getStatusLine().getStatusCode();

                if (status == 200) {
                    HttpEntity entity = response.getEntity();
                    String data = EntityUtils.toString(entity);


                    JSONObject jsono = new JSONObject(data);
                    JSONArray jarray = jsono.getJSONArray("restaurant_list_data");

                    for (int i = 0; i < jarray.length(); i++) {
                        JSONObject jsonrealobject = jarray.getJSONObject(i);
                        home_listview_model lisviewarray = new home_listview_model();

                        lisviewarray.setRestaurant_id(jsonrealobject.getString("restaurant_id"));
                        lisviewarray.setRestaurant_name(jsonrealobject.getString("restaurant_name"));
                        lisviewarray.setRestaurant_address(jsonrealobject.getString("address"));
                        lisviewarray.setRestaurant_opping_time(jsonrealobject.getString("restaurant_opping_time"));

                        restaurant_Array_list.add(lisviewarray);
                    }
                    return true;
                }

                //------------------>>

            } catch (ParseException | IOException | JSONException e1) {
                e1.printStackTrace();
            }
            return false;
        }
        protected void onPostExecute(Boolean result) {
            dialog.cancel();
            home_listadapter.notifyDataSetChanged();
            if(result == false){
                Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
            }
        }
    }

这是我的 home_listview_model 代码

package com.example.nhp04.gqfood;

public class home_listview_model {



    private String restaurant_id;
    private String restaurant_name;
    private String restaurant_address;
    private String restaurant_opping_time;

    public home_listview_model() {

    }

    public home_listview_model(String restaurant_id, String restaurant_opping_time, String restaurant_address, String restaurant_name, String restaurant_images ) {
        super();
        this.restaurant_id = restaurant_id;
        this.restaurant_opping_time = restaurant_opping_time;
        this.restaurant_address = restaurant_address;
        this.restaurant_name = restaurant_name;
    }




    public String getRestaurant_id() {
        return restaurant_id;
    }
    public void setRestaurant_id(String restaurant_id) {
        this.restaurant_id = restaurant_id;
    }

    public String getRestaurant_opping_time() {
        return restaurant_opping_time;
    }
    public void setRestaurant_opping_time(String restaurant_opping_time) { this.restaurant_opping_time = restaurant_opping_time;}

    public String getRestaurant_address() {return restaurant_address;}
    public void setRestaurant_address(String restaurant_address) { this.restaurant_address = restaurant_address;}

    public String getRestaurant_name() { return restaurant_name; }
    public void setRestaurant_name(String restaurant_name) {this.restaurant_name = restaurant_name;}

}

这是我的 home_listadapter 代码

public class home_listadapter extends ArrayAdapter<home_listview_model> {
    String resturantid;
    ArrayList<home_listview_model> restaurant_Array_list;
    LayoutInflater vi;
    int Resource;
    ViewHolder holder;
    Context mContext;

    public home_listadapter(Context context, int resource, ArrayList<home_listview_model> objects) {
        super(context, resource, objects);
        vi = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        Resource = resource;
        restaurant_Array_list = objects;
        mContext = context;
    }
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // convert view = design
        View v = convertView;
        if (v == null) {
            holder = new ViewHolder();
            v = vi.inflate(Resource, null);
//            holder.restaurant_images = (ImageView)v.findViewById(R.id.restaurant_images);
            holder.restaurant_id = (TextView)v.findViewById(R.id.restaurant_id);
            holder.restaurant_name = (TextView)v.findViewById(R.id.restaurant_name);
            holder.restaurant_address = (TextView)v.findViewById(R.id.address);
            holder.restaurant_opping_time = (TextView)v.findViewById(R.id.opningtime);

            // view the other function for OnclickListener
            holder.bookmark = (ImageButton)v.findViewById(R.id.imgbtn_bookmark);
            holder.share = (ImageButton)v.findViewById(R.id.share_btn);
            holder.dismiss = (ImageButton)v.findViewById(R.id.dismiss_btn);
            holder.add_to_list = (ImageButton)v.findViewById(R.id.add_to_list_btn);



            v.setTag(holder);
        } else {
            holder = (ViewHolder) v.getTag();
        }
holder.restaurant_id.setText(restaurant_Array_list.get(position).getRestaurant_id());
        holder.restaurant_name.setText(restaurant_Array_list.get(position).getRestaurant_name());
        holder.restaurant_address.setText(restaurant_Array_list.get(position).getRestaurant_address());
        holder.restaurant_opping_time.setText("Opens at " + restaurant_Array_list.get(position).getRestaurant_opping_time());


return v;

    }

    static class ViewHolder {
        public TextView  restaurant_id;
        public TextView  restaurant_name;
        public TextView  restaurant_address;
        public TextView  restaurant_opping_time;

    }
}

从上面的代码我得到正确的结果

{
  "restaurant_list_data": [
    {
      "restaurant_id": "1",
      "restaurant_name": "Huynh Restaurant ",
      "categories": "",
      "address": "912 St. Emanuel St",
      "city": "Houston",
      "state": "TX",
      "zipcode": "77003",
      "subdivision": "Downtown, EaDo",
      "phone": "(713) 224-8964",
      "restaurant_opping_time": "11am",
      "crate_time_stamp": "2016-04-15 15:10:00",
      "update_time_stamp": "0000-00-00 00:00:00"
    }
  ]
}

现在我想通过 id 获取这家餐厅的图片,我的下一个 HTTP REQUEST 网址已准备好,但我不知道应该在哪里调用下一个 HTTP REQUEST要获取图像,我的下一个 HTTP REQUEST 网址是

http://example.com/api/restaurantimages/"+resturantid

【问题讨论】:

    标签: java android multithreading listview android-studio


    【解决方案1】:

    您将在第一个 asyntask 的 onPostExecute 中执行您的第二个 api 调用。

    在第二次调用的 onPostExecute 中再次执行 notifyDataSetChanged()

    【讨论】:

    • 为此我需要在我的适配器中进行哪些更改以下载图像并获取和设置。你能用代码解释一下吗?
    • 再创建一个asyntask,在第一个方法的postExecute方法中调用它的execute方法
    【解决方案2】:

    你能得到"restaurant_list_data" 中的图片吗?

    如果是这样,您可以使用像 Picasso 这样的库来加载图像。

    如果没有,我认为您必须将另一个 AsyncTask 调用到 home_listadapter 并使用 Picasso 加载图像。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-11
      • 2013-11-01
      • 1970-01-01
      • 2021-06-04
      • 1970-01-01
      • 2012-02-25
      • 2018-10-14
      • 1970-01-01
      相关资源
      最近更新 更多