无法在Android中将图像从Json设置为imageView

时间:2014-04-02 06:57:56

标签: android json android-listview imageview android-lazyloading

我做了一个活动,我正在从Json webservice解析一些数据,我可以成功地解析所有数据,并且我从该数据中获取图像名称,并且我希望在ListView的imageView中进行顶部设置

activity.java

package com.epe.yehki.ui;

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

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.epe.yehki.backend.ServiceHandler;
import com.epe.yehki.uc.Header;
import com.epe.yehki.util.Const;
import com.example.yehki.R;

public class SubCategoryActivity extends ListActivity {
    // SUB CATEGORIES...
    private static final String TAG_CAT_LlIS = "categories_list";
    private static final String TAG_CAT_ID = "category_id";
    private static final String TAG_CAT_NAME = "category_name";
    int flag;
    public Header header;
    public TextView title;
    Bitmap bitmap;;
    // PRODUCTS....
    private static final String TAG_PRODUCT_ID = "product_id";
    private static final String TAG_PRODUCT_LlST = "product_list";
    private static final String TAG_PRODUCT_NAME = "product_name";
    private static final String TAG_PRODUCT_IMG = "image";
    private static final String TAG_PRODUCT_DESCRIPTION = "detail_description";
    private static final String TAG_PRODUCT_MIN_ORDER_QTY = "min_order_qty";
    private static final String TAG_PRODUCT_MIN_PRICE = "min_price";
    private static final String TAG_PRODUCT_MAX_PRICE = "max_price";

    // contacts JSONArray
    JSONArray subcategories = null;
    JSONArray products = null;
    public String catid;
    public String id;
    String name;
    JSONObject jsonObj;

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> subcategoryList;
    ArrayList<HashMap<String, String>> productList;

    private ProgressDialog pDialog;

    // URL to get contacts JSON
    private static String url = "http://yehki.epagestore.in/app_api/categories.php";

    private static String mainurl = "http://yehki.epagestore.in/";
    public String suburl = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sub);
        this.header = (Header) findViewById(R.id.headersubcat);
        title = (TextView) findViewById(R.id.title);
        // getting intent data
        Intent in = getIntent();

        // Get JSON values from previous intent

        try {
            catid = in.getStringExtra(TAG_CAT_ID);
            name = in.getStringExtra(TAG_CAT_NAME);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("::::::::::::::MY CATEGORY ID::::::::::::::IN SUB "
                + catid);
        subcategoryList = new ArrayList<HashMap<String, String>>();
        productList = new ArrayList<HashMap<String, String>>();

        suburl = "http://yehki.epagestore.in/app_api/categories.php?"
                + TAG_CAT_ID + "=" + catid;
        System.out.println("::::::::::::::::MY SUBCATEGORY URL::::::::::::"
                + suburl);
        title.setText(name);

        // Displaying all values on the screen

        ListView lv = getListView();
        new GetSubCategories().execute();

        // Listview on item click listener
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String catname = ((TextView) view.findViewById(R.id.name))
                        .getText().toString();

                Intent in = new Intent(getApplicationContext(),
                        SubCategoryTwoActivity.class);
                in.putExtra(TAG_CAT_NAME, catname);
                in.putExtra(TAG_CAT_ID, catid);

                startActivity(in);

            }
        });

    }

    private class GetSubCategories extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(SubCategoryActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();
            System.out.println(":::::::::::::::::::SUB URL:::::::::::::::::"
                    + suburl);
            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(suburl, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);
            try {
                if (jsonStr != null) {

                    jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    if (jsonObj.has(TAG_CAT_LlIS)) {

                        System.out
                                .println("::::::::::::::::true::::::::::::::::"
                                        + jsonObj.has(TAG_CAT_LlIS));
                        subcategories = jsonObj.getJSONArray(TAG_CAT_LlIS);
                        if (subcategories != null
                                && subcategories.length() != 0) {
                            // looping through All Contacts
                            flag = 0;
                            System.out
                                    .println(":::::::::::FLAG IN SUB:::::::::::"
                                            + subcategories.length());
                            for (int i = 0; i < subcategories.length(); i++) {
                                JSONObject c = subcategories.getJSONObject(i);

                                id = c.getString(TAG_CAT_ID);
                                String name = c.getString(TAG_CAT_NAME);

                                // tmp hashmap for single category
                                HashMap<String, String> subcategory = new HashMap<String, String>();

                                // adding each child node to HashMap key =>
                                // value
                                subcategory.put(TAG_CAT_ID, id);
                                subcategory.put(TAG_CAT_NAME, name);

                                // adding contact to contact list
                                subcategoryList.add(subcategory);
                            }
                        }
                    } else if (jsonObj.has(TAG_PRODUCT_LlST)) {
                        flag = 1;
                        System.out
                                .println("::::::::::::::::true::::::::::::::::"
                                        + jsonObj.has(TAG_PRODUCT_LlST));
                        products = jsonObj.getJSONArray(TAG_PRODUCT_LlST);
                        if (products != null && products.length() != 0) {
                            // looping through All Contacts

                            System.out
                                    .println(":::::::::::FLAG IN SUB:::::::::::"
                                            + flag);
                            for (int i = 0; i < products.length(); i++) {
                                JSONObject c = products.getJSONObject(i);

                                id = c.getString(TAG_PRODUCT_ID);
                                String name = c.getString(TAG_PRODUCT_NAME);
                                String desc = c
                                        .getString(TAG_PRODUCT_DESCRIPTION);
                                String img = Const.API_HOST + "/"
                                        + c.getString(TAG_PRODUCT_IMG);
                                System.out
                                        .println(":::::::::::::::My Image Url:::::::::::::"
                                                + img);
                                String minOrderQty = c
                                        .getString(TAG_PRODUCT_MIN_ORDER_QTY);
                                String minPrice = c
                                        .getString(TAG_PRODUCT_MIN_PRICE);
                                String maxPrice = c
                                        .getString(TAG_PRODUCT_MAX_PRICE);
                                bitmap = BitmapFactory.decodeFile(img);
                                System.out
                                        .println(":::::::::::::My prododuct name+++++++:::::::::::::"
                                                + name);
                                System.out
                                        .println(":::::::::::::My prododuct image+++++++:::::::::::::"
                                                + img);
                                System.out
                                        .println(":::::::::::::My prododuct min order qty+++++++:::::::::::::"
                                                + minOrderQty);

                                // tmp hashmap for single category
                                HashMap<String, String> product = new HashMap<String, String>();

                                // adding each child node to HashMap key =>
                                // value
                                product.put(TAG_PRODUCT_ID, id);
                                product.put(TAG_PRODUCT_NAME, name);
                                product.put(TAG_PRODUCT_IMG, img);
                                product.put(TAG_PRODUCT_MIN_ORDER_QTY,
                                        minOrderQty);
                                product.put(TAG_PRODUCT_DESCRIPTION, desc);

                                // adding contact to contact list
                                productList.add(product);
                            }
                        }
                    }

                } else {
                    Log.e("ServiceHandler",
                            "Couldn't get any data from the url");
                }

            } catch (JSONException e) {
                e.printStackTrace();
                System.out
                        .println("::::::::::::::::::got an error::::::::::::");
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * 
             * */

            if (flag == 0) {

                ListAdapter adapter = new SimpleAdapter(
                        SubCategoryActivity.this, subcategoryList,
                        R.layout.list_item, new String[] { TAG_CAT_NAME },
                        new int[] { R.id.name });
                setListAdapter(adapter);
            } else {
                ListAdapter adapter = new SimpleAdapter(
                        SubCategoryActivity.this, productList,
                        R.layout.activity_single_produt, new String[] {
                                TAG_PRODUCT_NAME, TAG_PRODUCT_IMG,
                                TAG_PRODUCT_MIN_ORDER_QTY,
                                TAG_PRODUCT_DESCRIPTION }, new int[] {
                                R.id.product_label, R.id.iv_product_img,
                                R.id.min_qty, R.id.pro_desc });
                setListAdapter(adapter);
            }

        }

    }
}

2 个答案:

答案 0 :(得分:0)

如果您想在ListView中显示图片,则必须创建自定义ListView,然后您无需展开ListActivity。为此,请遵循此Link

答案 1 :(得分:0)

您必须从网址加载图片,并为此创建自定义适配器。

这是一篇非常好的文章。

http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/

您可以使用某些库,例如 AQuery 等。