如何在AsyncTask中设置ImageView

时间:2015-03-08 15:56:48

标签: android android-asynctask imageview

据我所知,我们无法在AsyncTask中设置ImageView。但我需要将ImageView添加到HashMap中,并且HashMap需要添加到for循环内的ArrayList中。我不能在onPostExecute()中这样做。有谁知道该怎么做?

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

import org.apache.http.NameValuePair;
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.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class AllProductsActivity extends ListActivity {

    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> productsList;

    // url to get all products list
    private static String url_all_products = "http://192.168.1.132/retEqp.php";
    ImageView iv; 


    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "equipments";
    private static final String TAG_PID = "item_ID";
    private static final String TAG_NAME = "item_Name";
    private static final String TAG_DESC = "item_Desc";
    private static final String TAG_LOC = "item_Location";
    private static final String TAG_STATUS = "item_Status";
    private static final String TAG_IMAGE = "item_Image";

    // products JSONArray
    JSONArray equipments = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_products);

        iv = (ImageView)findViewById(R.id.img2);


        // Hashmap for ListView
        productsList = new ArrayList<HashMap<String, String>>();

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



        // Get listview
        ListView lv = getListView();

        // on seleting single product
        // launching Edit Product Screen
        lv.setOnItemClickListener(new OnItemClickListener() {

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

                // Starting new intent
                Intent previousScreen = new Intent(getApplicationContext(), NewProductActivity.class);
                 //Sending the data to NewProductActivity
                 previousScreen.putExtra("id",pid); 
                 setResult(1000, previousScreen);

                finish();   

                // starting new activity and expecting some response back

            }
        });

    }

    // Response from Edit Product Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            // if result code 100 is received
            // means user edited/deleted product
            // reload this screen again
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }

    }

    /**
     * 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(AllProductsActivity.this);
            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_all_products, "GET", params);

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

            try {

                    equipments = json.getJSONArray(TAG_PRODUCTS);

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

                        // Storing each json item in variable
                        String id = "ID: "+c.getString(TAG_PID);
                        String name = "Name: "+c.getString(TAG_NAME);
                        String desc = "Description: "+c.getString(TAG_DESC);
                        String loc = "Location: "+c.getString(TAG_LOC);
                        String status = "Status: "+c.getString(TAG_STATUS);
                        String image = c.getString(TAG_IMAGE);



                        byte[] rawImage = Base64.decode(image, Base64.DEFAULT);
                        Bitmap bmp12 = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length);
                        iv.setImageBitmap(bmp12);


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


                        // adding each child node to HashMap key => value
                       // map.put(TAG_IMAGE, rawImage.length);

                        map.put(TAG_PID, id);
                        map.put(TAG_NAME, name);
                        map.put(TAG_DESC, desc);
                        map.put(TAG_LOC, loc);
                        map.put(TAG_STATUS, status);
                        map.put(TAG_IMAGE, iv.toString());



                        // adding HashList to ArrayList

                        productsList.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();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            AllProductsActivity.this, productsList,
                            R.layout.list_item, new String[] { TAG_IMAGE,TAG_PID,
                                    TAG_NAME,TAG_DESC,TAG_LOC,TAG_STATUS},
                            new int[] {R.id.img,R.id.pid, R.id.name,R.id.desc,R.id.loc,R.id.status});
                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }

    }
}

1 个答案:

答案 0 :(得分:1)

您无法在后台线程中访问用户界面。

AsyncTask背后的想法是doInBackground后台工作,然后你可以返回一些将作为参数传递给onPostExecute的东西,它在主线程中执行。

在这种情况下,你必须从doInBackground返回解析后的模型对象(我会创建一个自定义类),在onPostExecute中接收。此外,创建一个自定义适配器,它将负责创建视图。你应该在那里生成位图(可能你必须在另一个异步任务中将解析放到位图中)。