hashmap 在 simpleadapter 中工作,但在自定义数组适配器中不工作 [英] hashmap working in simpleadapter but not working in custom array adapter

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

问题描述

下面代码的 Hashmap 适用于 simpleadapter 数组,但不适用于自定义数组适配器.为什么?我该如何解决?请帮助.无法解决.尝试了一切.

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.

我正在使用lazyLoading 类来加载图像.

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

            }        

上面显示的 onclick 崩溃的整个代码:

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



            }
        });     
    }   
}

以下代码完美运行:

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

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

推荐答案

在您的自定义适配器中,您返回的是位置而不是 Item

In you custom Adapter you are returning position instead of Item

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

试试这个

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

这将解决您的问题

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

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