【问题标题】:How to display an image from a url in a ListView in android?如何在android的ListView中显示来自url的图像?
【发布时间】:2014-05-20 22:08:22
【问题描述】:

我在我的应用程序中使用 json 解析。我有一个 ListView,它显示一些数据,还有一个 ImageView。这里我想在 ImageView 中显示来自另一个 url 的图像。如何做到这一点?

这是我的代码...

private ProgressDialog pDialog;
private static String url = "http://myurl/json/main.json";

// JSON Node names

private static final String TAG_NAME = "name";
private static final String TAG_VIEWERS = "viewers";

    JSONArray myarray = null;

    ArrayList<HashMap<String, String>> mylist;

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    ImageView bmImage = (ImageView) findViewById(R.id.img);


    mylist = new ArrayList<HashMap<String, String>>();
    ListView lv = getListView();
            lv.setOnItemClickListener(new OnItemClickListener() {

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


        }
    });

            new GetMyarray().execute();


    }


/**
 * Async task class to get json by making HTTP call
 * */
private class GetMyarray extends AsyncTask<Void, Void, Void> {

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

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

        Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {

                JSONObject getResponse = new JSONObject(jsonStr);
                Log.d("Response: ", "> " + jsonStr);

                JSONObject pnames=getResponse.getJSONObject("getnames");
                Log.d("Response: ", "> " + pnames);



                                    myarray = pnames.getJSONArray("pnames");
                Log.d("Listed as: ", "> " + myarray);


                for (int i = 0; i < myarray.length(); i++) {
                    JSONObject c = myarray.getJSONObject(i);


                    String name = c.getString(TAG_NAME);
                    String viewers=c.getString(TAG_VIEWERS);



                    HashMap<String, String> myarray = new HashMap<String, String>();



                    myarray.put(TAG_NAME, name);
                    myarray.put(TAG_VIEWERS, viewers);




                    mylist.add(myarray);


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

        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
         * */

        ListAdapter adapter = new SimpleAdapter(
                MainActivity.this, mylist,
                R.layout.list_item, new String[] { TAG_NAME,TAG_VIEWERS  }, new int[] { R.id.name,R.id.viewers
                        });

        setListAdapter(adapter);
    }

}

}

【问题讨论】:

  • 谷歌没有答案?
  • 我尝试了很多来自谷歌的答案。没有一个有效。
  • 你将如何获得图像? ..不同的图片有不同的网址吗?还是有一个包含所有图像的json。?
  • 但是很奇怪的是,点击ListView 你正在调用你的AsyncTask,然后为ListView 设置了相同的适配器??
  • 现在,我只想在所有 ImageViews 中显示一张图像。这就是我从 url 中获取的内容。稍后,我将使用包含图像 ID 的真实 json url

标签: android json parsing listview url


【解决方案1】:

试试这个方法

URL url = new URL("your url");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bmp);

public boolean loadImageFromURL(String url, ImageView iv){
try {

URL myUrl = new URL (url);
HttpURLConnection conn =
  (HttpURLConnection) myUrl.openConnection();
conn.setDoInput(true);
conn.connect();

InputStream is = conn.getInputStream();
iv.setImageBitmap(BitmapFactory.decodeStream(is));

return true;

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

return false;
}

*记住:在 Asyntask 中执行这两个方法,否则会崩溃

【讨论】:

  • 它抛出了哪个异常..?
  • 这么简单...这意味着您正在主线程上执行一些网络操作..只需将代码移动到异步任务中。我也在答案中添加了粗体文本,将代码放在 asyntask 中。
【解决方案2】:
【解决方案3】:

Here 展示了如何从 URL 加载列表视图中的图像

仅仅为了从 URL 加载图像,就有很多 SO 线程

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    • 2011-09-18
    • 2011-09-23
    • 1970-01-01
    • 2011-09-12
    相关资源
    最近更新 更多