将图像从url添加到ListView

时间:2014-02-13 13:33:15

标签: android image listview loops

我正在使用contacts project from AndroidHive的修改版本。

它基本上只是从Joomla网站上提取文章列表及其联系方式。

我正在使用Image Plugin从网址获取图片。我可以在文章详细活动视图上成功使用它,但我不知道如何将它添加到MainAcitivity文件上的每个列表项。我是Android开发的新手,请原谅我的混乱。

添加图片的脚本是:

ImageView thumb = (ImageView) findViewById(R.id.thumb);
UrlImageViewHelper.setUrlDrawable(thumb, "https://www.site.co.za/test.png");

和我生成ListView的MainActivity:

public class MainActivity extends ListActivity {

    private ProgressDialog pDialog;

    // URL to get articles JSON
    private static String url = "http://192.168.12.21/sebastian/broadcast/index.php/blog?format=json";

    // JSON Node names
    private static final String TAG_ARTICLES = "articles";

    // Get the fields
    private static final String TAG_ID = "id";
    private static final String TAG_TITLE = "title";
    private static final String TAG_SHORTTEXT = "shorttext";
    private static final String TAG_FULLTEXT = "fulltext";
    private static final String TAG_IMAGE = "image";
    private static final String TAG_DATE = "date";

    // articles JSONArray
    JSONArray articles = null;

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> articleList;

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

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

        ListView lv = getListView();

        // Listview on item click listener
        lv.setOnItemClickListener(new OnItemClickListener() {

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

                // Starting single article activity
                Intent in = new Intent(getApplicationContext(),
                        SingleArticleActivity.class);

                in.putExtra(TAG_TITLE, title);
                in.putExtra(TAG_SHORTTEXT, shorttext);
                in.putExtra(TAG_FULLTEXT, fulltext);
                in.putExtra(TAG_IMAGE, image);
                in.putExtra(TAG_DATE, date);

                startActivity(in);

            }
        });

        // Calling async task to get json
        new GetArticles().execute();

    }

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

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Please wait...");
            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 jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    articles = jsonObj.getJSONArray(TAG_ARTICLES);

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

                        String id = c.getString(TAG_ID);
                        String title = c.getString(TAG_TITLE);
                        String shorttext = c.getString(TAG_SHORTTEXT);
                        String fulltext = c.getString(TAG_FULLTEXT);                        
                        String image = c.getString(TAG_IMAGE);
                        String date = c.getString(TAG_DATE);


                        // tmp hashmap for single article
                        HashMap<String, String> article = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        article.put(TAG_ID, id);
                        article.put(TAG_TITLE, title);
                        article.put(TAG_SHORTTEXT, shorttext);
                        article.put(TAG_FULLTEXT, fulltext);                        
                        article.put(TAG_IMAGE, image);
                        article.put(TAG_DATE, date);

                        // adding article to article list
                        articleList.add(article);
                    }
                } 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, articleList,
                    R.layout.list_item, new String[] {
                                TAG_TITLE,
                                TAG_SHORTTEXT,
                                TAG_FULLTEXT,
                                TAG_IMAGE,
                                TAG_DATE
                            },
                            new int[] {
                                R.id.title,
                                R.id.shorttext,
                                R.id.fulltext,
                                R.id.image,
                                R.id.date                               
                            });

            setListAdapter(adapter);            

        }

    }

}

**我不知道在MainActivity文件中我添加脚本以向每个列表项添加图像。

我已经让它在SingleArticleActivity上工作了,但无法让它在项目列表上工作**

感谢您的帮助

更新

我想做什么:

foreach(ListItem in the List) {

    ImageView thumb = (ImageView) findViewById(R.id.thumb);
    UrlImageViewHelper.setUrlDrawable(thumb, "https://www.site.co.za/test.png");

}

3 个答案:

答案 0 :(得分:0)

我在我的ListView适配器的getView方法中使用此方法,该方法返回一个drawable,我稍后将其设置为我的ImageView。

public Drawable LoadImageFromWebOperations(String url) {
    try {
        InputStream is = (InputStream) new URL(url).getContent();
        Drawable d = Drawable.createFromStream(is, "src name");
        return d;
    } catch (Exception e) {
        return default_image;
    }
}

希望这有帮助。

答案 1 :(得分:0)

你必须使用这个......

 ImageView thumb = (ImageView) findViewById(R.id.thumb);
 UrlImageViewHelper.setUrlDrawable(thumb, articleList.get(position).get(TAG_IMAGE));


 CustomAdapter cdp = new CustomAdapter(YourActivityName.this , articleList);
 setListAdapter(adapter);    

现在,使用 BaseAdapter 扩展 CustomAdapter

  public class CustomAdapter extends BaseAdapter {

         ArrayList<HashMap<String, String>> list;
         Context ctx;

         public CustomAdapter(Context c ,  ArrayList<HashMap<String, String>> articleList){
            this.ctx = c;

            this.list = articleList;
         }
    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        View view = convertView;
        if (view == null) {
            view = getLayoutInflater().inflate(R.layout.list_item,
                    parent, false);
            holder = new ViewHolder();
            assert view != null;
            holder.imageView = (ImageView) view.findViewById(R.id.image);

            view.setTag(holder);

        } else {
            holder = (ViewHolder) view.getTag();
        }

             UrlImageViewHelper.setUrlDrawable(thumb, articleList.get(position).get(TAG_IMAGE));



        return view;
    }

    class ViewHolder {
        ImageView imageView;

    }
}

答案 2 :(得分:0)

试用此功能强大的Android Picasso

图像下载和缓存库

图像为Android应用程序添加了急需的上下文和视觉风格。 Picasso允许在您的应用程序中轻松加载图像 - 通常只需一行代码!

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);