Android 将图像从url添加到列表视图

Android 将图像从url添加到列表视图,android,image,listview,loops,Android,Image,Listview,Loops,我正在使用的是的修改版本 它基本上只是从一个Joomla网站上提取n个文章列表和他们的联系人 我使用的是从url获取图像的。我可以在article detail activity视图中成功地使用它,但我不知道如何将它添加到MainActivity文件的每个列表项中。我是Android开发新手,请原谅我的困惑 要添加图像的脚本是: ImageView thumb = (ImageView) findViewById(R.id.thumb); UrlImageViewHelper.setUrlDra

我正在使用的是的修改版本

它基本上只是从一个Joomla网站上提取n个文章列表和他们的联系人

我使用的是从url获取图像的。我可以在article detail activity视图中成功地使用它,但我不知道如何将它添加到MainActivity文件的每个列表项中。我是Android开发新手,请原谅我的困惑

要添加图像的脚本是:

ImageView thumb = (ImageView) findViewById(R.id.thumb);
UrlImageViewHelper.setUrlDrawable(thumb, "https://www.site.co.za/test.png");
以及生成ListView的my 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);            

        }

    }

}

我在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;
    }
}

希望这有帮助。

你只需使用这一个

 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的类

公共类CustomAdapter扩展了BaseAdapter{
数组列表;
上下文ctx;
公共CustomAdapter(上下文c、ArrayList articleList){
这个.ctx=c;
this.list=articleList;
}
@凌驾
public int getCount(){
返回list.size();
}
@凌驾
公共对象getItem(int位置){
返回null;
}
@凌驾
公共长getItemId(int位置){
返回位置;
}
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图){
最终持票人;
视图=转换视图;
如果(视图==null){
视图=GetLayoutFlater()。充气(R.layout.list_项,
父母,假);
holder=新的ViewHolder();
断言视图!=null;
holder.imageView=(imageView)view.findViewById(R.id.image);
视图.设置标签(支架);
}否则{
holder=(ViewHolder)view.getTag();
}
UrlImageViewHelper.setUrlDrawable(thumb,articleList.get(position.get(TAG_IMAGE));
返回视图;
}
类视图持有者{
图像视图图像视图;
}
}

试试这个功能强大的Android图像下载和缓存库

图像为Android应用程序添加了急需的上下文和视觉天赋。毕加索允许在一行代码中轻松加载应用程序中的图像

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

表示您想在SingleArticleActivity中显示图像?我已设法使其在那里工作,但不在列表项中表示您没有在ListView中显示图像。不是吗?不,图像的url是我检索的JSON的一部分,从该url添加图像的脚本是我必须使用的脚本,但我不知道在哪里添加它。哪里会有类似“foreach ListItem{}”,但在MainActivity.java中我应该在哪里添加它?为此,您可以使用自定义适配器Hanks Piyush作为帮助我可以将SimpleAdapter转换为一个吗?thumb imagview在您的list\u item.xml文件中??
  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;

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