安卓:显示在ImageView的由SimpleAdapter图像 [英] Android: Display image in imageview by SimpleAdapter

查看:131
本文介绍了安卓:显示在ImageView的由SimpleAdapter图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的Andr​​oid现在我想从一个URL显示图像。我使用的ImageView的列表视图。我想图像列表添加到列表项的每一行。我用SimpleAdapter但ImageView的显示为空白。

这里的主要活动:

 包com.example.mysqltest;

    进口的java.util.ArrayList;
    进口的java.util.HashMap;
    进口org.json.JSONArray;
    进口org.json.JSONException;
    进口org.json.JSONObject;
    进口android.app.ListActivity;
    进口android.app.ProgressDialog;
    进口android.content.Intent;
    进口android.os.AsyncTask;
    进口android.os.Bundle;
    进口android.view.View;
    进口android.widget.AdapterView;
    进口android.widget.AdapterView.OnItemClickListener;
    进口android.widget.ListAdapter;
    进口android.widget.ListView;
    进口android.widget.SimpleAdapter;

    公共类ReadComments扩展ListActivity {

        //进度对话框
        私人ProgressDialog pDialog;

        //在模拟器中进行测试:
        私有静态最后弦乐READ_COMMENTS_URL =htt​​p://192.168.30.198/test/webservice/comments.php;


        // JSON IDS:
        私有静态最后弦乐TAG_SUCCESS =成功;
        私有静态最后弦乐TAG_TITLE =称号;
        私有静态最后弦乐TAG_POSTS =上岗;
        私有静态最后弦乐TAG_POST_ID =的post_id;
        私有静态最后弦乐TAG_USERNAME =用户名;
        私有静态最后弦乐TAG_MESSAGE =消息;
        私有静态最后弦乐TAG_IMAGE =形象;


        //我们所有的评论数组
        私人JSONArray mComments = NULL;
        //管理所有我们的看法名单。
        私人的ArrayList< HashMap的<字符串,字符串>> mCommentList;

        @覆盖
        保护无效的onCreate(包savedInstanceState){
            super.onCreate(savedInstanceState);
            //注意,使用read_comments.xml而不是我们single_post.xml
            的setContentView(R.layout.read_comments);
        }

        @覆盖
        保护无效onResume(){
            // TODO自动生成方法存根
            super.onResume();
            //加载通过AsyncTask的评论
            新LoadComments()执行();
        }

        公共无效addComment(视图v){
            意图I =新的意图(ReadComments.this,AddComment.class);
            startActivity(ⅰ);
        }

        / **
         *从服务器检索近期发布数据。
         * /
        公共无效updateJSONdata(){
            mCommentList =新的ArrayList< HashMap的<字符串,字符串>>();

            JSONParser jParser =新JSONParser();
            JSONObject的JSON = jParser.getJSONFromUrl(READ_COMMENTS_URL);

            尝试 {
                mComments = json.getJSONArray(TAG_POSTS);

                的for(int i = 0; I< mComments.length();我++){
                    JSONObject的C = mComments.getJSONObject(我);

                    //获取每个标签的内容
                    字符串标题= c.getString(TAG_TITLE);
                    字符串的内容= c.getString(TAG_MESSAGE);
                    字符串username = c.getString(TAG_USERNAME);
                    字符串图像= c.getString(TAG_IMAGE);

                    //创建新的HashMap
                    HashMap的<字符串,字符串>图=新的HashMap<字符串,字符串>();

                    map.put(TAG_TITLE,职称);
                    map.put(TAG_MESSAGE,内容);
                    map.put(TAG_USERNAME,用户名);
                    map.put(TAG_IMAGE,图像);

                    //添加HashList到ArrayList中
                    mCommentList.add(图)
                }

            }赶上(JSONException E){
                e.printStackTrace();
            }
        }

        / **
         *插入所分析的数据到列表视图。
         * /
        私人无效updateList(){
            ListAdapter适配器=新SimpleAdapter(这一点,mCommentList,
                    R.layout.single_post,新的String [] {TAG_TITLE,TAG_MESSAGE,
                            TAG_USERNAME,TAG_IMAGE},新的INT [] {R.id.title,R.id.message,
                            R.id.username,R.id.imageView1});

            //我不应该在这一个发表评论:
            setListAdapter(适配器);

            ListView的LV = getListView();
            lv.setOnItemClickListener(新OnItemClickListener(){

                @覆盖
                公共无效onItemClick(适配器视图<>母公司视图中查看,
                        INT位置,长的id){}
            });
        }

        公共类LoadComments扩展的AsyncTask<虚空,虚空,布尔> {

            @覆盖
            在preExecute保护无效(){
                super.on preExecute();
                pDialog =新ProgressDialog(ReadComments.this);
                pDialog.setMessage(加载评论...);
                pDialog.setIndeterminate(假);
                pDialog.setCancelable(真正的);
                pDialog.show();
            }

            @覆盖
            保护布尔doInBackground(虚空......为arg0){
                updateJSONdata();
                返回null;

            }

            @覆盖
            保护无效onPostExecute(布尔结果){
                super.onPostExecute(结果);
                pDialog.dismiss();
                updateList();
            }
        }
    }
 

解决方案

好。所以,我这里假设你坚持使用 SimpleAdapter 。没有probem,问题解决了,只要按照步骤操作:

首先,让我们创建我们自定义的 row.xml 作为我们的的ListView 将仅由一个的ImageView的。(你可以添加任何你喜欢它以后,但现在我会认为你只是想加载的ImageView

 < XML版本=1.0编码=UTF-8&GT?;
< RelativeLayout的的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:layout_width =match_parent
    机器人:layout_height =WRAP_CONTENT
    机器人:方向=垂直>

    < ImageView的
        机器人:ID =@ + ID / imageView1
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_alignParentLeft =真
        机器人:layout_alignParentTop =真
        机器人:layout_marginLeft =5DP
        机器人:layout_marginTop =5DP
        机器人:SRC =@可绘制/ ic_launcher/>


< / RelativeLayout的>
 

其次,让我们创建我们的自定义 SimpleAdapter

 包com.example.helpstack;

进口的java.util.HashMap;
进口的java.util.List;
进口的java.util.Map;

进口android.content.Context;
进口android.view.LayoutInflater;
进口android.view.View;
进口android.view.ViewGroup;
进口android.widget.ImageView;
进口android.widget.SimpleAdapter;

公共类MySimpleAdapter扩展SimpleAdapter {
    私人语境mContext;
    公共LayoutInflater充气= NULL;

    公共MySimpleAdapter(上下文的背景下,
            名单,LT ;?扩展地图<字符串,>>数据,INT资源的String []而成,
            INT []键){
        超(背景下,数据,资源,从,到);
        mContext =背景;
        充气=(LayoutInflater)mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @覆盖
    公共查看getView(INT位置,查看convertView,ViewGroup中父){
        查看VI = convertView;
        如果(convertView == NULL)
            VI = inflater.inflate(R.layout.row,NULL);

        HashMap的<字符串,对象>数据=(HashMap的<字符串,对象>)的getItem(位置);

        新DownloadTask((ImageView的)vi.findViewById(R.id.imageView1))
                .execute((字符串)data.get(URI));

        返回六;
    }

}
 

三,让我们创建我们的 DownloadTask ,这个类将下载的图片:

 包com.example.helpstack;

进口java.io.IOException异常;
进口java.net.MalformedURLException;
进口的java.net.URL;

进口android.graphics.Bitmap;
进口android.graphics.BitmapFactory;
进口android.os.AsyncTask;
进口android.widget.ImageView;

公共类DownloadTask扩展的AsyncTask<字符串,太虚,布尔> {
    ImageView的伏;
    字符串URL;
    位图BM;

    公共DownloadTask(ImageView的V){
        this.v = V;
    }

    @覆盖
    保护布尔doInBackground(字符串... PARAMS){
        网址= PARAMS [0];
        BM = loadBitmap(URL);
        返回true;
    }

    @覆盖
    保护无效onPostExecute(布尔结果){
        // TODO自动生成方法存根
        super.onPostExecute(结果);
        v.setImageBitmap(BM);
    }

    公共静态位图loadBitmap(字符串URL){
        尝试 {
            URL的newURL =新的网址(URL);
            位图B = BitmapFactory.de codeStream(newurl.openConnection()
                    .getInputStream());
            返回b;
        }赶上(MalformedURLException异常E){
            // TODO自动生成的catch块
            e.printStackTrace();
        }赶上(IOException异常E){
            // TODO自动生成的catch块
            e.printStackTrace();
        }
        返回null;
    }
}
 

现在的 DownloadTask 正在从getView()内的 SimpleAdapter

使用

四,您从运行我们的神奇的小项目,我们的 MainActivity.java

 包com.example.helpstack;

进口的java.util.ArrayList;
进口的java.util.HashMap;
进口的java.util.List;
进口的java.util.Map;

进口android.app.Activity;
进口android.os.Bundle;
进口android.widget.ListView;

公共类MainActivity延伸活动{
    ListView的LV;

    @覆盖
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);
        LV =(ListView控件)findViewById(R.id.listView1);
        列表与LT;地图<字符串,对象>>数据=新的ArrayList<地图<字符串,对象>>();
        地图<字符串,对象>图=新的HashMap<字符串,对象>();
        map.put(URI,
                "http://upload.wikimedia.org/wikipedia/commons/thumb/f/f9/Wiktionary_small.svg/350px-Wiktionary_small.svg.png");
        //这里u能为u想添加尽可能多的URI
        data.add(图)
        MySimpleAdapter适配器=新MySimpleAdapter(MainActivity.this,数据,
                R.layout.row,新的String [] {},新的INT [] {});
        lv.setAdapter(适配器);
    }
}
 

I am new android now I want to display image from an url. I am using imageview in listview. I want to add the list of images into the each row of the list item. I used SimpleAdapter but the imageview shows blank.

Here's the main activity:

package com.example.mysqltest;

    import java.util.ArrayList;
    import java.util.HashMap;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    import android.app.ListActivity;
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;

    public class ReadComments extends ListActivity {

        // Progress Dialog
        private ProgressDialog pDialog;

        // testing on Emulator:
        private static final String READ_COMMENTS_URL = "http://192.168.30.198/test/webservice/comments.php";


        // JSON IDS:
        private static final String TAG_SUCCESS = "success";
        private static final String TAG_TITLE = "title";
        private static final String TAG_POSTS = "posts";
        private static final String TAG_POST_ID = "post_id";
        private static final String TAG_USERNAME = "username";
        private static final String TAG_MESSAGE = "message";
        private static final String TAG_IMAGE = "image";


        // An array of all of our comments
        private JSONArray mComments = null;
        // manages all of our comments in a list.
        private ArrayList<HashMap<String, String>> mCommentList;

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

        @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() {
            mCommentList = new ArrayList<HashMap<String, String>>();

            JSONParser jParser = new JSONParser();      
            JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);

            try {
                mComments = json.getJSONArray(TAG_POSTS);

                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 image = c.getString(TAG_IMAGE);

                    // 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, image);

                    // adding HashList to ArrayList
                    mCommentList.add(map);
                }

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

        /**
         * Inserts the parsed data into the listview.
         */
        private void updateList() { 
            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.imageView1 });

            // I shouldn't have to comment on this one:
            setListAdapter(adapter);    

            ListView lv = getListView();    
            lv.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {}
            });
        }

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

解决方案

Okay. So I assume here that you insist on using SimpleAdapter. No probem, problem solved, just follow the steps:

First lets create our custom row.xml for our ListView which will consist of only one ImageView.(You can add whatever you like to it later on but now i'll assume that you only wanna load the ImageView)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="5dp"
        android:layout_marginTop="5dp"
        android:src="@drawable/ic_launcher" />


</RelativeLayout>

Second lets create our custom SimpleAdapter

package com.example.helpstack;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SimpleAdapter;

public class MySimpleAdapter extends SimpleAdapter {
    private Context mContext;
    public LayoutInflater inflater = null;

    public MySimpleAdapter(Context context,
            List<? extends Map<String, ?>> data, int resource, String[] from,
            int[] to) {
        super(context, data, resource, from, to);
        mContext = context;
        inflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View vi = convertView;
        if (convertView == null)
            vi = inflater.inflate(R.layout.row, null);

        HashMap<String, Object> data = (HashMap<String, Object>) getItem(position);

        new DownloadTask((ImageView) vi.findViewById(R.id.imageView1))
                .execute((String) data.get("uri"));

        return vi;
    }

}

Third lets create our DownloadTask, this class will download the image:

package com.example.helpstack;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

public class DownloadTask extends AsyncTask<String, Void, Boolean> {
    ImageView v;
    String url;
    Bitmap bm;

    public DownloadTask(ImageView v) {
        this.v = v;
    }

    @Override
    protected Boolean doInBackground(String... params) {
        url = params[0];
        bm = loadBitmap(url);
        return true;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        v.setImageBitmap(bm);
    }

    public static Bitmap loadBitmap(String url) {
        try {
            URL newurl = new URL(url);
            Bitmap b = BitmapFactory.decodeStream(newurl.openConnection()
                    .getInputStream());
            return b;
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}

Now the DownloadTask is being used from inside the getView() in SimpleAdapter

Fourth lets run our amazing small project from our MainActivity.java

package com.example.helpstack;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

public class MainActivity extends Activity {
    ListView lv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv = (ListView) findViewById(R.id.listView1);
        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("uri",
                "http://upload.wikimedia.org/wikipedia/commons/thumb/f/f9/Wiktionary_small.svg/350px-Wiktionary_small.svg.png");
        //here u can add as many uri as u want
        data.add(map);
        MySimpleAdapter adapter = new MySimpleAdapter(MainActivity.this, data,
                R.layout.row, new String[] {}, new int[] {});
        lv.setAdapter(adapter);
    }
}

这篇关于安卓:显示在ImageView的由SimpleAdapter图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆