将列表视图的数据从 Asynctask 传递到自定义列表适配器类 [英] Passing data for list view from Asynctask to a custom list adapter class

查看:26
本文介绍了将列表视图的数据从 Asynctask 传递到自定义列表适配器类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要有关为自定义列表视图传递数据的帮助,我似乎无法将数据从 asynctask 传递到另一个 java 类.这是我的代码:

I need help on passing data for a custom list view, I can't seem to pass the data from the asynctask to the other java class. here is my code:

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.dmo.d2d.R;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Inventory extends Activity {

    //Variables!!!!!!!!!

    // url to get all products list
    private static String url_all_products = "my server url :D";

    // Get name and email from global/application context
    final String accnt_user_name  = globalVariable.getUserName();
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "vinID";
    static final String TAG_CAR_NAME = "carName";
    static final String TAG_VIN_ID = "vinID";

    ListView list;
    CustomInventoryList adapter;


    JSONObject json;

    // Creating JSON Parser object

    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> productsList = new ArrayList<HashMap<String, String>>();

    // products JSONArray
    JSONArray products = null;
    // contacts JSONArray
    JSONArray contacts = null;
    JSONArray account = null;
    JSONArray cars = null;
    JSONArray user_names = null;
    JSONObject jsonObj;


    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);


        //Remove title bar
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);

        //Remove notification bar
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        //set content view AFTER ABOVE sequence (to avoid crash)

        this.setContentView(R.layout.inventory_list);


     new LoadAllProducts().execute();

    }
    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllProducts extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username_GET", accnt_user_name ));

            // getting JSON string from URL
            json = jParser.makeHttpRequest(url_all_products, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All Products: ", json.toString());

            runOnUiThread(new Runnable() {

                public void run() {

                    try {
                        // Checking for SUCCESS TAG
                        int success = json.getInt(TAG_SUCCESS);

                        if (success == 1) {
                            // products found
                            // Getting Array of Products
                            products = json.getJSONArray(TAG_PRODUCTS);

                            // looping through All Products
                            for (int i = 0; i < products.length(); i++) {
                                JSONObject c = products.getJSONObject(i);

                                // Storing each json item in variable
                                String vinID = c.getString("vinID");
                                String name = c.getString("carName").replaceAll("_", " ");
                                //  globalVariable.setUserComment(dealer);

                                // creating new HashMap
                                HashMap<String, String> map = new HashMap<String, String>();

                                // adding each child node to HashMap key => value
                                map.put(TAG_CAR_NAME, name);
                                map.put(TAG_VIN_ID, vinID);

                                // adding HashList to ArrayList
                                productsList.add(map);
                            }
                        } else {
                            // no products found
                            // Launch Add New product Activity

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

                }

            });


            return null;
        }


        protected void onPostExecute(String file_url) {


            list=(ListView)findViewById(R.id.list);
            adapter=new CustomInventoryList(this, productsList); << I CAN'T PASS THIS DATA!!!
            list.setAdapter(adapter);


        }


    }

}

我无法传递列表视图的数据,这里是我的 CustomInventoryList.java:

I can't pass the data for the list view here is my CustomInventoryList.java:

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.dmo.d2d.R;

import java.util.ArrayList;
import java.util.HashMap;


public class CustomInventoryList  extends BaseAdapter{


    private Activity activity;
    private ArrayList<HashMap<String, String>> data;
    private static LayoutInflater inflater=null;
  //  public ImageLoader imageLoader;

    public CustomInventoryList(Activity a, ArrayList<HashMap<String, String>> d) {
        activity = a;
        data=d;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        //imageLoader=new ImageLoader(activity.getApplicationContext());
    }

    public int getCount() {
        return data.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View vi=convertView;
        if(convertView==null)
            vi = inflater.inflate(R.layout.list_inventory, null);

        TextView title = (TextView)vi.findViewById(R.id.title);
        TextView artist = (TextView)vi.findViewById(R.id.artist);
        TextView duration = (TextView)vi.findViewById(R.id.duration);
        ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image);

        HashMap<String, String> song = new HashMap<String, String>();
        song = data.get(position);

        // Setting all values in listview
        title.setText(song.get(Inventory.TAG_VIN_ID));
        artist.setText(song.get(Inventory.TAG_VIN_ID));
      //  duration.setText(song.get(Inventory.KEY_DURATION));
      //  imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), thumb_image);
        return vi;
    }
}

我从 androidHive 获得了代码,我正在尝试修改它.所以在回顾中:

I got the code from androidHive, and I am trying to modify it. So in Recap:

  1. 我无法将数据从 Inventory.java 中的异步任务传输到 CustomInventoryList.java

  1. I can't transfer the data from the asynctask in my Inventory.java to CustomInventoryList.java

我该如何解决?

先谢谢你.:) 很抱歉这篇很长的帖子,但我真的需要帮助.:(

Thank you in advance. :) Sorry for the long post, but I really need help. :(

顺便说一句,我还没有 logcat.因为我无法从异步任务传递数据.

Oh btw, I don't have the logcat yet. since I can't pass the data from the async task.

推荐答案

首先,你真的应该考虑将 doInBackground 中的 Runnable 块移动到 onPostExecute 因为这就是它被设计的原因对于后台任务之后的 UI 线程操作.

First, you should really consider moving your Runnable block in doInBackground to onPostExecute because that's why it's designed for, UI-thread operations following a background task.

请注意,您的AsyncTask 类型已更改.

Please note that your AsyncTask type has changed.

您也可以考虑通过将 AsyncTask 设为 static 来使其独立于您的 Activity.然后,您只需在其构造函数中传递任务所需的参数,以及对活动的引用,以便它可以在 onPostExecute 中返回结果.

You may also consider making your AsyncTask independent from your Activity by making it static. Then you would just pass the arguments the task needs in its constructor, plus a reference to the activity so that it can return the result in onPostExecute.

想法:

private ListView mList;

public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);

    // ...
    mlist = ...
    new LoadAllProducts(this, username, params, ...); // PASS ALL THE PARAMTERS THE ASYNCTASK NEEDS
}

public void populateList(ArrayList<HashMap<String, String>> productsList) {
    mList.setAdapter(new CustomInventoryList(this, productsList));
}

static class LoadAllProducts extends AsyncTask<String, String, JSONObject> {
    private String username;
    private List<NameValuePair> params;
    private Activity mActivity;

    public LoadAllProducts(...) {
        username = ...;
        params = ...;
        mActivity = ...;
    }

    @Override
    protected String doInBackground(String... args) {
        ...

        // getting JSON string from URL
        json = jParser.makeHttpRequest(url_all_products, "GET", params);

        return json;
   }


   protected void onPostExecute(JSONObject json) {
        try {
           // Checking for SUCCESS TAG
           int success = json.getInt(TAG_SUCCESS);

           if (success == 1) {
               // ... handle your JSON
           }
       } catch (JSONException e) {
           e.printStackTrace();
       }

       mActivity.populateList(productsList);
   }
}

这篇关于将列表视图的数据从 Asynctask 传递到自定义列表适配器类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆