2016-12-30 96 views
2

我想在Android中獲取帶有動態對象的json。所以我使用Map<>來獲取json。我想使用BaseAdapter內的地圖。我收到以下錯誤Android,如何在`BaseAdapter`中使用Map?

Incompatible types.Required:com.example.EffectList. Found:java.util.Map< java.lang.String,java.util.List<com.example.EffectList>> 

這是我的BaseAdapter代碼:

public class MyContactAdapter2 extends BaseAdapter { 
    List<Map<String, List<EffectList>>> contactList; 
    Context context; 
    private LayoutInflater mInflater; 

    // Constructors 
    public MyContactAdapter2(Context context, List<Map<String, List<EffectList>>> objects) { 

     this.context = context; 
     this.mInflater = LayoutInflater.from(context); 
     contactList = objects; 
    } 

    @Override 
    public int getCount() { 
     return contactList.size(); 
    } 

    @Override 
    public Map<String, List<EffectList>> getItem(int position) { 
     return contactList.get(position); 
    } 


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


    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
    final MyContactAdapter2.ViewHolder vh; 
     if (convertView == null) { 
     View view = mInflater.inflate(R.layout.get_layout_row_view, parent, false); 
      vh = MyContactAdapter2.ViewHolder.create((RelativeLayout) view); 
      view.setTag(vh); 
     } else { 
      vh = (MyContactAdapter2.ViewHolder) convertView.getTag(); 
     } 

     EffectList item = getItem(position); // COMPILE TIME ERROR HERE 



    vh.textViewName.setText(item.getEffectsId()); 
    vh.textViewEmail.setText(item.getEffectsName()); 


     return vh.rootView; 
    } 

    private static class ViewHolder { 
     public final RelativeLayout rootView; 
     public final ImageView imageView; 
     public final TextView textViewName; 
     public final TextView textViewEmail; 

     private ViewHolder(RelativeLayout rootView, ImageView imageView, TextView textViewName, TextView textViewEmail) { 
      this.rootView = rootView; 
      this.imageView = imageView; 
      this.textViewName = textViewName; 
      this.textViewEmail = textViewEmail; 
     } 

     public static MyContactAdapter2.ViewHolder create(RelativeLayout rootView) { 
      ImageView imageView = (ImageView) rootView.findViewById(R.id.imageView); 
      TextView textViewName = (TextView) rootView.findViewById(R.id.textViewName); 
      TextView textViewEmail = (TextView) rootView.findViewById(R.id.textViewEmail); 
      return new MyContactAdapter2.ViewHolder(rootView, imageView, textViewName, textViewEmail); 
     } 
    } 
} 

什麼是錯在我的代碼?

回答

0

好吧,它很簡單,你的getItem方法返回一個Map<String, List<EffectList>>類型的對象,你不能直接將這種類型轉換爲EffectList

像這樣的事情,需要獲得EffectList項目:

EffectList item = getItem(position).get("somekey").get(0); 

解決方案

  • 得到的東西的Map,然後出來的List這是 的Map內的。
  • 修改您的BaseAdapter getItem方法返回EffectList類型的對象,並修改您的getCount方法以返回正確的項目數;

一些旁註:

  • 我建議你重新思考和重新設計你的數據結構,你真的需要一個List含有Map含有List
  • 我個人不會使用Map來支持AdapterMap中的項目順序(通常)是未定義的(除非您在定義順序時使用Map實現);
相關問題