Android - 如何在asyncTask中使用JSON解析器设置gridview [Detail Fragment]的第一个显示

时间:2013-02-20 11:47:02

标签: android json arraylist android-asynctask

如何将AsquestTask中的JSON数据解析为Detail Fragment中的自定义Gridview?
我有Integer[] pictureString[] menuString[] price
在GridView中我有1 ImageView 和2 TextView

    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(mContext);
        pDialog.setMessage("Loading products. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url, "GET", params);

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

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);
            System.out.println(success);
            if (success == 1) {
                // products found
                // Getting Array of Products
                menuresto = json.getJSONArray(TAG_MENU);

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

                    // Storing each json item in variable
                    String name = c.getString(TAG_NAME);
                    String price = c.getString(TAG_PRICE);

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

                    // adding each child node to HashMap key => value
                    map.put(TAG_NAME, name);
                    map.put(TAG_PRICE, price);

                    // adding HashList to ArrayList
                    menuList.add(map);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * How to parsed JSON data into GridView
                 * */

            }
        });

    }

protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(mContext); pDialog.setMessage("Loading products. Please wait..."); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } /** * getting All products from url * */ protected String doInBackground(String... args) { // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); // getting JSON string from URL JSONObject json = jParser.makeHttpRequest(url, "GET", params); // Check your log cat for JSON reponse Log.d("All Menu: ", json.toString()); try { // Checking for SUCCESS TAG int success = json.getInt(TAG_SUCCESS); System.out.println(success); if (success == 1) { // products found // Getting Array of Products menuresto = json.getJSONArray(TAG_MENU); // looping through All Products for (int i = 0; i < menuresto.length(); i++) { JSONObject c = menuresto.getJSONObject(i); // Storing each json item in variable String name = c.getString(TAG_NAME); String price = c.getString(TAG_PRICE); // creating new HashMap HashMap<String, String> map = new HashMap<String, String>(); // adding each child node to HashMap key => value map.put(TAG_NAME, name); map.put(TAG_PRICE, price); // adding HashList to ArrayList menuList.add(map); } } } catch (JSONException e) { e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // dismiss the dialog after getting all products pDialog.dismiss(); runOnUiThread(new Runnable() { public void run() { /** * How to parsed JSON data into GridView * */ } }); }

我应该在工作吗?

修改
适配器代码完整
GetView

public class MyAdapter extends BaseAdapter {

Context mContext;
private ProgressDialog pDialog;
// creating json parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> menuList;

static final String TAG_SUCCESS = "success";
static final String TAG_MENU = "menu";
static final String TAG_MID = "mid";
static final String TAG_NAME = "name";
static final String TAG_PICT = "picture";
static final String TAG_PRICE = "price";

// url to get all menu list
private static String url = "http://10.0.2.2/menu/food/get_all_products.php";

// menu JSONArray
JSONArray menuresto = null;

public Integer[] menupict = { R.drawable.ic_launcher,
        R.drawable.ic_launcher, R.drawable.ic_launcher,
        R.drawable.ic_launcher, R.drawable.ic_launcher,
        R.drawable.ic_launcher, R.drawable.ic_launcher };

private LayoutInflater mInflater;

public MyAdapter(Context c) {

    mContext = c;
    mInflater = LayoutInflater.from(c);
    // array menu
    menuList = new ArrayList<HashMap<String, String>>();

    // Loading products in Background Thread
    new LoadAllProducts().execute();

}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return menuList.size();
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return menuList.get(position);
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    // Building Parameters
    // System.out.println("MyAdapter.getView()");
    ViewHolder holder = null;

    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.gviewfill, parent, false);
        holder = new ViewHolder();
        /*
         * holder.ImgView = new ImageView(mContext);
         * holder.ImgView.setScaleType(ImageView.ScaleType.CENTER_CROP);
         * 
         * holder.ImgView = (ImageView) convertView
         * .findViewById(R.id.iv_menu_image);
         */
        holder.txtName = (TextView) convertView
                .findViewById(R.id.tv_menu_name);
        holder.price = (TextView) convertView
                .findViewById(R.id.tv_menu_price);

        if (position == 0) {
            convertView.setTag(holder);
        }
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    // holder.ImgView.setImageResource(menupict[position]);
    holder.price.setText("Rp. " + menuList.get(position).get(TAG_PRICE));
    holder.txtName.setText(menuList.get(position).get(TAG_NAME));

    return convertView;
}

static class ViewHolder {
    ImageView ImgView;
    TextView txtName;
    TextView price;
}

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

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(mContext);
        pDialog.setMessage("Loading products. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url, "GET", params);

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

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);
            System.out.println(success);
            if (success == 1) {
                // products found
                // Getting Array of Products
                menuresto = json.getJSONArray(TAG_MENU);

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

                    // Storing each json item in variable
                    String name = c.getString(TAG_NAME);
                    String price = c.getString(TAG_PRICE);

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

                    // adding each child node to HashMap key => value
                    map.put(TAG_NAME, name);
                    map.put(TAG_PRICE, price);

                    // adding HashList to ArrayList
                    menuList.add(map);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */

            }
        });

    }

}

1 个答案:

答案 0 :(得分:0)

  

如何将JSON数据解析为GridView

=&GT;您只需要创建一个适配器来在GridView中显示数据。因为您已经在AsyncTask的doInBackground()内准备好了ArrayList(就menuList而言)。

现在,这取决于你想如何在GridView中显示数据,我想要在GridView中显示的项目布局类型。