简体   繁体   中英

How to place AsyncTask image being downloaded from JSON object in ListView?

I have a JSON array which has with it several strings among which is the link that will be is being used to download my images, I am new to AsyncTask , the strings are being placed in their rightful places properly but am having issues figuring out how to position the image download task, I am following this tutorial http://www.mybringback.com/android-sdk/13239/android-mysql-php-json-part-6-json-parsing-and-android-design/

Can someone highlight me on how I should call the AsyncTask so that it goes in flow with all the other downloads? Below is my code:

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // note that use read_comments.xml instead of our single_post.xml
    setContentView(R.layout.read_comments);


    ActionBar mActionBar = getActionBar();
    mActionBar.setDisplayShowHomeEnabled(false);
    mActionBar.setDisplayShowTitleEnabled(false);
    LayoutInflater mInflater = LayoutInflater.from(this);

    View mCustomView = mInflater.inflate(R.layout.customactionbar, null);
    EditText msearch = (EditText) mCustomView.findViewById(R.id.mquerybox);
    ImageButton mstartsearch = (ImageButton) mCustomView.findViewById(R.id.msearch);
    mActionBar.setCustomView(mCustomView);
    mActionBar.setDisplayShowCustomEnabled(true);


}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    // loading the comments via AsyncTask
    new LoadComments().execute();
}

public void addComment(View v) {
    Intent i = new Intent(ReadComments.this, AddComment.class);
    startActivity(i);
}

/**
 * Retrieves recent post data from the server.
 */
public void updateJSONdata() {

    // Instantiate the arraylist to contain all the JSON data.
    // we are going to use a bunch of key-value pairs, referring
    // to the json element name, and the content, for example,
    // message it the tag, and "I'm awesome" as the content..

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

    // Bro, it's time to power up the J parser
    JSONParser jParser = new JSONParser();
    // Feed the beast our comments url, and it spits us
    // back a JSON object. Boo-yeah Jerome.
    JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);

    // when parsing JSON stuff, we should probably
    // try to catch any exceptions:
    try {

        // I know I said we would check if "Posts were Avail." (success==1)
        // before we tried to read the individual posts, but I lied...
        // mComments will tell us how many "posts" or comments are
        // available
        mComments = json.getJSONArray(TAG_POSTS);

        // looping through all posts according to the json object returned
        for (int i = 0; i < mComments.length(); i++) {
            JSONObject c = mComments.getJSONObject(i);

            // gets the content of each tag
            String title = c.getString(TAG_TITLE);
            String content = c.getString(TAG_MESSAGE);
            String username = c.getString(TAG_USERNAME);
            String downloadUrl = c.getString(TAG_IMAGE);
            new DownloadImageTask((RoundedImageView) findViewById(R.id.downloaded))
                    .execute(downloadUrl);




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

            map.put(TAG_TITLE, title);
            map.put(TAG_MESSAGE, content);
            map.put(TAG_USERNAME, username);
            map.put(TAG_IMAGE, downloadUrl);

            // adding HashList to ArrayList
            mCommentList.add(map);

            // annndddd, our JSON data is up to date same with our array
            // list
        }

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

/**
 * Inserts the parsed data into the listview.
 */
private void updateList() {
    // For a ListActivity we need to set the List Adapter, and in order to do
    //that, we need to create a ListAdapter.  This SimpleAdapter,
    //will utilize our updated Hashmapped ArrayList,
    //use our single_post xml template for each item in our list,

    ListAdapter adapter = new SimpleAdapter(this, mCommentList,
            R.layout.single_post, new String[]{TAG_TITLE, TAG_MESSAGE,
            TAG_USERNAME, TAG_IMAGE}, new int[]{R.id.title, R.id.message,
            R.id.username, R.id.downloaded});


    setListAdapter(adapter);


    ListView lv = getListView();
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {

            // This method is triggered if an item is click within our
            // list.


        }
    });
}

private class LoadComments extends AsyncTask<Void, Void, Boolean> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(ReadComments.this);
        pDialog.setMessage("Loading Comments...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected Boolean doInBackground(Void... arg0) {
        updateJSONdata();

    return null;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        pDialog.dismiss();
        updateList();
    }
}


private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {

    RoundedImageView bmImage;
    public DownloadImageTask(RoundedImageView bmImage) {
        this.bmImage = bmImage;
    }


    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }
}

}

To download images in asynctask, I recommend you to use a library to handle that. So will cache images and will reduce the possible number of errors and data downloading. Universal Image Download or Picasso are the most common libraries used for this.

You should call downloadImage in onPostExecute from LoadCommentsTask

To load the image into imageview with url Picasso is the best solution available. Its very easy to use. See yourself at Picasso

And if you want to save the image as file in sd card, then ION can be the better solution.

Universal Image Loader is more powerful in terms of supported features but is bit of complicated than picasso or ion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM