如何从ListView中的JSON对象下载AsyncTask图像?

时间:2015-04-09 08:52:05

标签: android json android-asynctask

我有一个JSON数组,其中包含几个字符串,其中包含将用于下载我的图像的链接,我是AsyncTask的新用户,字符串被正确放置在正确的位置但我在解决如何定位图像下载任务时遇到问题,我正在学习本教程http://www.mybringback.com/android-sdk/13239/android-mysql-php-json-part-6-json-parsing-and-android-design/

有人可以强调我应该如何调用AsyncTask,以便它与所有其他下载一起流入吗?以下是我的代码:

 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);
    }
}

}

1 个答案:

答案 0 :(得分:0)

要在asynctask中下载图像,我建议您使用库来处理它。因此,将缓存图像并减少可能的错误数量和数据下载。 Universal Image Download或Picasso是最常用的库。

您应该从LoadCommentsTask

中调用onPostExecute中的downloadImage

使用url将图像加载到imageview中Picasso是最佳解决方案。它非常易于使用。见Picasso

如果您想将图像保存为SD卡中的文件,那么ION可能是更好的解决方案。

Universal Image Loader在支持的功能方面更强大,但比毕加索或离子更复杂。