HashMap中的simpleadapter工作,但没有工作的自定义阵列适配器 [英] hashmap working in simpleadapter but not working in custom array adapter

查看:164
本文介绍了HashMap中的simpleadapter工作,但没有工作的自定义阵列适配器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的Hashmap为code以下的工作simpleadapter数组,但不能自定义阵列适配器。为什么?如何解决呢?请Help.Unable解决.Tried一切。

我使用lazyLoading类加载图像。

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


                HashMap的<字符串,字符串> O =(HashMap的<字符串,字符串>)list.getItemAtPosition(位置);
                Toast.makeText(CustomizedListView.this,ID+ o.get(KEY_TITLE)+'被点击了。,Toast.LENGTH_SHORT).show();

            }
 

整个code被撞毁在上面的onclick所示:

 公共类CustomizedListView延伸活动{
    //所有静态变量
    静态最终字符串URL =htt​​ps://itunes.apple.com/us/rss/topalbums/limit=20/json;
    // XML节点键
    静态最后弦乐KEY_SONG =歌; //父节点
    静态最后弦乐KEY_ID =ID;
    静态最后弦乐KEY_TITLE =称号;
    静态最后弦乐KEY_ARTIST =艺术家;
    静态最后弦乐KEY_DURATION =持续时间;
    静态最后弦乐KEY_THUMB_URL =thumb_url;

    ListView控件列表;
    LazyAdapter适配器;

    HashMap的<字符串,字符串>地图;


    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.main);


        ArrayList的< HashMap的<字符串,字符串>> songsList =新的ArrayList< HashMap的<字符串,字符串>>();

        JSONObject的JSON = JSONfunctions.getJSONfromURL(URL);


        尝试 {
            JSONObject的ARR2 = json.getJSONObject(饲料);
            JSONArray ARR = arr2.getJSONArray(输入);

            的for(int i = 0; I< arr.length();我++){
                的JSONObject E1 = arr.getJSONObject(ⅰ);

                JSONArray ARR3 = e1.getJSONArray(IM:图像);

                JSONObject的arr8 = e1.getJSONObject(IM:名称);

                JSONObject的arr10 = e1.getJSONObject(IM:艺术家);

                    的JSONObject E12 = arr3.getJSONObject(0);

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

            map.put(KEY_THUMB_URL,e12.getString(标签));

            map.put(KEY_ARTIST,arr8.getString(标签));
            map.put(KEY_TITLE,arr10.getString(标签));
            //添加HashList到ArrayList中
            songsList.add(图)
            }

        }赶上(JSONException E){
            // Log.e(log_tag,错误分析数据+ e.toString());
            Toast.makeText(getBaseContext(),
                    网络通讯错误!,5).​​show();
        }


        名单=(ListView控件)findViewById(R.id.list);

        //通过传递XML数据的ArrayList获取适配器
        适配器=新LazyAdapter(这一点,songsList);
        list.setAdapter(适配器);

        // Click事件单列表行
        list.setOnItemClickListener(新OnItemClickListener(){

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

                                HashMap的<字符串,字符串> O =(HashMap的<字符串,字符串>)list.getItemAtPosition(位置);

                                Toast.makeText(CustomizedListView.this,ID+ o.get(标题)+'被点击了。,Toast.LENGTH_SHORT).show();



            }
        });
    }
}
 

这code以下工作完美:

 公共类主要扩展ListActivity {
    / **第一次创建活动时调用。 * /
    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.listplaceholder);

        ArrayList的< HashMap的<字符串,字符串>> mylist中=新的ArrayList< HashMap的<字符串,字符串>>();


        JSONObject的JSON = JSONfunctions.getJSONfromURL("http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=demo");

        尝试{

            JSONArray地震= json.getJSONArray(地震);

            的for(int i = 0; I< earthquakes.length();我++){
                HashMap的<字符串,字符串>图=新的HashMap<字符串,字符串>();
                JSONObject的E = earthquakes.getJSONObject(我);

                map.put(ID,将String.valueOf(I));
                map.put(名,地​​震的名字:+ e.getString(eqid));
                map.put(大小,幅度:+ e.getString(大小));
                mylist.add(图)
            }
        }赶上(JSONException E){
             Log.e(log_tag,错误分析数据+ e.toString());
        }

        ListAdapter适配器=新SimpleAdapter(这一点,mylist中,R.layout.main,
                        新的String [] {名,大小},
                        新的INT [] {R.id.item_title,R.id.item_subtitle});

        setListAdapter(适配器);

        最终的ListView LV = getListView();
        lv.setTextFilterEnabled(真正的);
        lv.setOnItemClickListener(新OnItemClickListener(){
            公共无效onItemClick(适配器视图<>母公司视图中查看,INT位置,长的id){
                @燮pressWarnings(未登记)
                HashMap的<字符串,字符串> O =(HashMap的<字符串,字符串>)lv.getItemAtPosition(位置);
                Toast.makeText(Main.this,ID+ o.get(ID)+'被点击了。,Toast.LENGTH_SHORT).show();

            }
        });
    }
}
 

logcat的:

 主题ID = 1:螺纹退出与未捕获的异常(组= 0x40ab0228)
 致命异常:主要
 java.lang.ClassCastException:java.lang.Integer中不能转换到的java.util.HashMap
    在com.example.androidhive.CustomizedListView $ 1.onItemClick(CustomizedListView.java:94)
    在android.widget.AdapterView.performItemClick(AdapterView.java:292)
    在android.widget.AbsListView.performItemClick(AbsListView.java:1077)
    在android.widget.AbsListView $ PerformClick.run(AbsListView.java:2533)
    在android.widget.AbsListView $ 1.运行(AbsListView.java:3198)
    在android.os.Handler.handleCallback(Handler.java:605)
    在android.os.Handler.dispatchMessage(Handler.java:92)
    在android.os.Looper.loop(Looper.java:154)
    在android.app.ActivityThread.main(ActivityThread.java:4945)
    在java.lang.reflect.Method.invokeNative(本机方法)
    在java.lang.reflect.Method.invoke(Method.java:511)
    在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:784)
    在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
    在dalvik.system.NativeStart.main(本机方法)
 

LazyAdapter.java

 公共类LazyAdapter扩展了BaseAdapter {

    私人活动的活动;
    私人的ArrayList< HashMap的<字符串,字符串>>数据=新的ArrayList< HashMap的<字符串,字符串>>();
    私有静态LayoutInflater吹气= NULL;
    公共ImageLoader的ImageLoader的;


   公共静态HashMap的<字符串,字符串>歌曲;

    公共LazyAdapter(活动一,ArrayList的< HashMap的<字符串,字符串>> D){
        活性= A;
        数据= D;
        充气=(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        ImageLoader的=新ImageLoader的(activity.getApplicationContext());
    }

    公众诠释getCount将(){
        返回data.size();
    }

    公共对象的getItem(INT位置){
        返回的位置;
    }

    众长getItemId(INT位置){
        返回的位置;
    }

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

        TextView的标题=(TextView中)vi.findViewById(R.id.title); // 标题
        TextView的艺术家=(TextView中)vi.findViewById(R.id.artist); //艺术家的名字
        TextView的持续时间=(TextView中)vi.findViewById(R.id.duration); //时间
        ImageView的thumb_image =(ImageView的)vi.findViewById(R.id.list_image); //拇指图像

         歌=新的HashMap<字符串,字符串>();
        歌= data.get(位置);

        //设置列表视图中的所有值
        title.setText(song.get(CustomizedListView.KEY_TITLE));
        artist.setText(song.get(CustomizedListView.KEY_ARTIST));
        duration.setText(song.get(CustomizedListView.KEY_DURATION));
        imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL),thumb_image);
        返回六;
    }
}
 

解决方案

在您自定义适配器要返回的位置,而不是项目

 公开对象的getItem(INT位置){
            返回的位置;
        }
 

尝试使用这种

 公开对象的getItem(INT位置){
                返回data.get(位置);
            }
 

这将解决您的问题。

Hashmap for the code below is working for simpleadapter array but not for custom array adapter .Why ? and how do I fix it ? Please Help.Unable to resolve .Tried everything.

I am using lazyLoading class to load images.

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


                HashMap<String, String> o = (HashMap<String, String>) list.getItemAtPosition(position);
                Toast.makeText(CustomizedListView.this, "ID '" + o.get("KEY_TITLE") + "' was clicked.", Toast.LENGTH_SHORT).show(); 

            }        

The entire code which is crashing at onclick shown above :

public class CustomizedListView extends Activity {
    // All static variables
    static final String URL = "https://itunes.apple.com/us/rss/topalbums/limit=20/json";
    // XML node keys
    static final String KEY_SONG = "song"; // parent node
    static final String KEY_ID = "id";
    static final String KEY_TITLE = "title";
    static final String KEY_ARTIST = "artist";
    static final String KEY_DURATION = "duration";
    static final String KEY_THUMB_URL = "thumb_url";

    ListView list;
    LazyAdapter adapter;

    HashMap<String, String> map;


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


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

        JSONObject json = JSONfunctions.getJSONfromURL(URL);


        try {
            JSONObject arr2 = json.getJSONObject("feed");
            JSONArray arr = arr2.getJSONArray("entry");

            for (int i = 0; i < arr.length(); i++) {
                JSONObject e1 = arr.getJSONObject(i);

                JSONArray arr3 = e1.getJSONArray("im:image");

                JSONObject arr8 = e1.getJSONObject("im:name");

                JSONObject arr10 = e1.getJSONObject("im:artist");

                    JSONObject e12 = arr3.getJSONObject(0);

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

            map.put(KEY_THUMB_URL,  e12.getString("label"));

            map.put(KEY_ARTIST, arr8.getString("label"));
            map.put(KEY_TITLE, arr10.getString("label"));
            // adding HashList to ArrayList
            songsList.add(map);
            }

        } catch (JSONException e) {
            // Log.e("log_tag", "Error parsing data "+e.toString());
            Toast.makeText(getBaseContext(),
                    "Network communication error!", 5).show();
        }


        list=(ListView)findViewById(R.id.list);

        // Getting adapter by passing xml data ArrayList
        adapter=new LazyAdapter(this, songsList);        
        list.setAdapter(adapter);

        // Click event for single list row
        list.setOnItemClickListener(new OnItemClickListener() {

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

                                HashMap<String, String> o= (HashMap<String, String>) list.getItemAtPosition(position);                  

                                Toast.makeText(CustomizedListView.this, "ID '" + o.get("title") + "' was clicked.", Toast.LENGTH_SHORT).show(); 



            }
        });     
    }   
}

This Code below works perfectly:

public class Main extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listplaceholder);

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


        JSONObject json = JSONfunctions.getJSONfromURL("http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=demo");

        try{

            JSONArray  earthquakes = json.getJSONArray("earthquakes");

            for(int i=0;i<earthquakes.length();i++){                        
                HashMap<String, String> map = new HashMap<String, String>();    
                JSONObject e = earthquakes.getJSONObject(i);

                map.put("id",  String.valueOf(i));
                map.put("name", "Earthquake name:" + e.getString("eqid"));
                map.put("magnitude", "Magnitude: " +  e.getString("magnitude"));
                mylist.add(map);            
            }       
        }catch(JSONException e)        {
             Log.e("log_tag", "Error parsing data "+e.toString());
        }

        ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main, 
                        new String[] { "name", "magnitude" }, 
                        new int[] { R.id.item_title, R.id.item_subtitle });

        setListAdapter(adapter);

        final ListView lv = getListView();
        lv.setTextFilterEnabled(true);  
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              
                @SuppressWarnings("unchecked")
                HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);                   
                Toast.makeText(Main.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show(); 

            }
        });
    }
}

LogCAT:

threadid=1: thread exiting with uncaught exception (group=0x40ab0228)
 FATAL EXCEPTION: main
 java.lang.ClassCastException: java.lang.Integer cannot be cast to java.util.HashMap
    at com.example.androidhive.CustomizedListView$1.onItemClick(CustomizedListView.java:94)
    at android.widget.AdapterView.performItemClick(AdapterView.java:292)
    at android.widget.AbsListView.performItemClick(AbsListView.java:1077)
    at android.widget.AbsListView$PerformClick.run(AbsListView.java:2533)
    at android.widget.AbsListView$1.run(AbsListView.java:3198)
    at android.os.Handler.handleCallback(Handler.java:605)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:4945)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
    at dalvik.system.NativeStart.main(Native Method)

LazyAdapter.java

public class LazyAdapter extends BaseAdapter {

    private Activity activity;
    private ArrayList<HashMap<String, String>> data=new ArrayList<HashMap<String, String>>();
    private static LayoutInflater inflater=null;
    public ImageLoader imageLoader; 


   public static HashMap<String, String> song;

    public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
        activity = a;
        data=d;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        imageLoader=new ImageLoader(activity.getApplicationContext());
    }

    public int getCount() {
        return data.size();
    }

    public Object getItem(int position) {
        return position;
    }

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

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

        TextView title = (TextView)vi.findViewById(R.id.title); // title
        TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
        TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
        ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image

         song = new HashMap<String, String>();
        song = data.get(position);

        // Setting all values in listview
        title.setText(song.get(CustomizedListView.KEY_TITLE));
        artist.setText(song.get(CustomizedListView.KEY_ARTIST));
        duration.setText(song.get(CustomizedListView.KEY_DURATION));
        imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), thumb_image);
        return vi;
    }
}

解决方案

In you custom Adapter you are returning position instead of Item

public Object getItem(int position) {
            return position;
        }

Try use this

 public Object getItem(int position) {
                return data.get(position);
            }

This will fix your problem

这篇关于HashMap中的simpleadapter工作,但没有工作的自定义阵列适配器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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