简体   繁体   English

不确定如何从列表的每个元素获取数据以从异步任务下载并显示其中的图像

[英]Not sure how to get data from each element of a list to download and display images in it from async task

G'day guys! G'day伙计们!

I'm trying to work out a good approach to download pictures and update a user list with the picture once it has finished downloading. 我正在尝试制定一个好的方法来下载图片,并在完成下载后用图片更新用户列表。

So I'm trying to create a list of user profiles in an android app, where it displays their username and a little picture at the side of them. 所以我正在尝试在Android应用程序中创建用户配置文件列表,在其中显示用户名和一侧的小图片。 I've been watching tutorials for the last 2 weeks and slowly getting a feel for all thing android, and I have my app pulling data down from my SQL (via PHP) server without issue, BUT I'm having trouble working out how and where I can launch an asynchronous task to download a picture for each username. 我一直在观看过去两周的教程,慢慢感受到所有东西的机器人,我的应用程序从我的SQL(通过PHP)服务器中提取数据而没有问题,但是我无法解决如何和我可以在哪里启动异步任务来下载每个用户名的图片。

I'm thinking something along the lines of flow like this 我正在思考像这样的流程

  • User clicks refresh button to 用户单击刷新按钮
  • App talks to PHP on webserver and pulls down list of users (does this correctly so far) 应用程序在Web服务器上与PHP对话并下拉用户列表(到目前为止这是正确的)
  • Parse all the data from the server that it got and turn it into a list (does this correctly so far) 解析它获得的服务器中的所有数据并将其转换为列表(到目前为止这是正确的)
  • Data in the list contains URL for profile picture (does this correctly) 列表中的数据包含个人资料图片的URL(正确执行此操作)
  • Go through each list element one by one and begin async task to download picture (don't know how to go element by element to extract URL from list) 逐个浏览每个列表元素并开始异步任务下载图片(不知道如何逐个元素地从列表中提取URL)
  • Once picture is downloaded then display it (as above, don't know how to update each element) 下载图片后再显示(如上所述,不知道如何更新每个元素)

The behavior is sort of inspired off the "Reddit is Fun" app, whereby all the articles are displayed and preview images are loaded and displayed as they are downloaded. 这种行为有点受到“Reddit is Fun”应用程序的启发,其中显示所有文章并在下载时加载和显示预览图像。 You see a little spinning circle as a placeholder until the image is seen. 在看到图像之前,您会看到一个小旋转圆圈作为占位符。

package com.example.administrator.hellopants;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class UserlistActivity extends Activity{

    private ProgressDialog pDialog;
    JSONParser jParser = new JSONParser();
    ArrayList<HashMap<String, String>> allUserList;
    private static String url_all_users = "http://myurl.com/php/db_list_all_users.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_USERLIST = "userlist";
    private static final String TAG_ID = "id";
    private static final String TAG_USERNAME = "username";

    JSONArray userlist = null;


    Button buttonRefresh;

    @Override
    public void onCreate(Bundle saveInstanceState) {
        super.onCreate(saveInstanceState);
        setContentView(R.layout.activity_userlist);

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

        buttonRefresh = (Button) findViewById(R.id.button_refresh);
        buttonRefresh.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                new PopulateUserList().execute();

            }
        });
    }

    class PopulateUserList extends AsyncTask<String, String, String> {

        ListView lvItems = (ListView) findViewById(R.id.listview_usernames);

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(UserlistActivity.this);
            pDialog.setMessage("Loading users details. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        protected String doInBackground(String... args) {

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            JSONObject json = jParser.makeHttpRequest(url_all_users, "GET", params);
            Log.d("All Usernames JSON Output: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    userlist = json.getJSONArray(TAG_USERLIST);

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

                        // Storing each json item in variable
                        String id = c.getString(TAG_ID);
                        String name = c.getString(TAG_USERNAME);

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

                        // adding each child node to HashMap key => value
                        map.put(TAG_ID, id);
                        map.put(TAG_USERNAME, name);

                        // adding HashList to ArrayList
                        allUserList.add(map);
                    }
                } else {
                    // no products found
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }


            return null;
        }

        protected void onPostExecute(String file_url) {
            pDialog.dismiss();

            runOnUiThread(new Runnable() {
                public void run() {
                    ListAdapter adapter = new SimpleAdapter(
                            UserlistActivity.this, allUserList,
                            R.layout.list_userliststyle, new String[] { TAG_ID,
                            TAG_USERNAME},
                            new int[] { R.id.list_userliststyle_id, R.id.list_userliststyle_username });
                    // updating listview
                    lvItems.setAdapter(adapter);
                }
            });



        }
    }

    public class DownloadImageBackground extends AsyncTask<String, Void, Drawable> {

        ImageView imageView;
        String myURL = null;

        @Override
        protected Drawable doInBackground(String...strings) {
            this.myURL = strings[0];
            Log.i("doInBackground", "Loading image from: "+ myURL.toString());
            //TODO: Pass the correct URL to download_image
            return download_Image(myURL);
        }

        @Override
        protected void onPostExecute(Drawable result) {
            imageView.setImageDrawable(result);
        }

        private Drawable download_Image(String url) {
            try {
                InputStream is = (InputStream) new URL(url).getContent();
                Drawable d = Drawable.createFromStream(is, url);
                return d;
            } catch (Exception e) {
                Log.e("download_Image", "Caught exception: "+e.getMessage());
                return null;
            }
        }
    }
}

Okie thanks to Nasch, that seemed to help prod me in the right direction Okie感谢Nasch,这似乎有助于我朝着正确的方向发展

        String username = allUserList.get(0).get(TAG_USERNAME);
        Log.d("And the winner is", username);

And thus the username string is printed out. 因此打印出用户名字符串。 To do that with a URL is probably similar, but my main problem was trying to work out how to pull data out from the list and that seems to have been solved now :D (finally after 3 days, phew ) 使用URL做到这一点可能类似,但我的主要问题是试图找出如何从列表中提取数据并且现在似乎已经解决了:D(最后3天后, phew

Had a feeling it would be something simple that I couldn't figure out. 有一种感觉,这是我想不通的简单事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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