2017-09-19 186 views
2

我第一次使用GSON進行翻新,它可以流利地使用靜態數據,但它在動態數據的情況下顯示上述錯誤。它是示出了在適配器錯誤中設置文本的值com.google.gson.internal.LinkedTreeMap無法投射

MainActivity

public class MainActivity extends AppCompatActivity { 


    String Navigation_Url = "http://www.xxxxxxxx.com"; 
    ListView listView; 
    ArrayList<ListPojo> listPojos = new ArrayList<>(); 
    ListRetrofitAndroid listRetrofitAndroid; 


    ArrayList countries = new ArrayList(); 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     listView = (ListView) findViewById(R.id.listView); 
     getRetrofitData(); 
    } 


    void getRetrofitData() { 
     Retrofit retrofit = new Retrofit.Builder().baseUrl(Navigation_Url).addConverterFactory(GsonConverterFactory.create()).build(); 
     CountryArrayAPI api = retrofit.create(CountryArrayAPI.class); 
     Call<List> call = api.getCountries(); 


     call.enqueue(new Callback<List>() { 

      @Override 
      public void onResponse(Call<List> call, Response<List> response) { 
       Gson gson = new Gson(); 
       try { 
        listPojos = (ArrayList) response.body(); 
        System.out.println("the ArrayList is" + listPojos); 


//     ArrayList<ListPojo> merchantOfferModels = gson.fromJson(response, new TypeToken<ListPojo>() {}.getType()); 









        listRetrofitAndroid = new ListRetrofitAndroid(getApplicationContext(), listPojos); 
        listView.setAdapter(listRetrofitAndroid); 


       } catch (Exception e) { 
        Log.d("onResponse", "There is an error"); 
        e.printStackTrace(); 
       } 

      } 

      @Override 
      public void onFailure(Call<List> call, Throwable t) { 
       Log.d("Failure", t.toString()); 
      } 
     }); 

    } 

} 

ListRetrofitAndroid(適配器)

public class ListRetrofitAndroid extends BaseAdapter { 

    Context mContext; 
    ArrayList<ListPojo> arrayList = new ArrayList<>(); 
    String TAG = "HomeTab_adapter"; 


    public ListRetrofitAndroid(Context context, ArrayList<ListPojo> listPojos) { 
     super(); 
     this.mContext = context; 
     this.arrayList = listPojos; 

    } 

    @Override 
    public int getCount() { 


     return arrayList.size(); 
    } 

    @Override 
    public Object getItem(int position) { 
     return arrayList.get(position); 
    } 

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

    @Override 
    public View getView(final int position, View convertView, ViewGroup parent) { 
     final Holder viewHolder; 

     if (convertView == null) { 
      LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
//   convertView = inflater.inflate(R.layout.list, parent, false); 
      convertView = inflater.inflate(R.layout.listview_item, parent, false); 

      // well set up the ViewHolder 
      // viewHolder = new ClassScheduleStudentAdapter.Holder(); 
      viewHolder = new Holder(); 
      viewHolder.textName = convertView.findViewById(R.id.list_item_main); 
      convertView.setTag(viewHolder); 


     } else { 

      viewHolder = (Holder) convertView.getTag(); 
     } 

     viewHolder.textName.setText(arrayList.get(position).getTitle()); 


     return convertView; 
    } 

    class Holder { 
     TextView textName; 
    } 


} 

模型(ListPojo)

public class ListPojo { 

    String title; 

    public ListPojo(String title) { 
     this.title = title; 
    } 

    public String getTitle() { 
     return title; 
    } 
} 

接口

public interface CountryArrayAPI { 
    @GET("/api/popular_destinations") 
    public Call<List> getCountries(); 
} 

JSON

[ 
    { 
     "id": 1, 
     "title": "Hiranya Varna Mahavihar", 
     "location": "Kwalakhu Rd, Patan 44600, Nepal", 
     "main_image": "images/popular_places/patan-durbar-square.jpg" 
    }, 
    { 
     "id": 2, 
     "title": "Yasodhar Mahavihar-Bubahal", 
     "location": "Jana Bahal Rd, Patan 44600, Nepal", 
     "main_image": "images/popular_places/patan-durbar-square.jpg" 
    }, 
    { 
     "id": 3, 
     "title": "Krishna Temple Sundhara", 
     "location": "Tyagal - Lalitpur Rd, Patan 44600, Nepal", 
     "main_image": "images/popular_places/Patan-2.jpg" 
    }, 
    { 
     "id": 4, 
     "title": "Hiranya Varna Mahavihar", 
     "location": "Kwalakhu Rd, Patan 44600, Nepal", 
     "main_image": "images/popular_places/asd.jpg" 
    } 
] 

StsckTrace

09-19 05:15:32.475 18949-18949/com.example.user_pc.myapplication E/AndroidRuntime: FATAL EXCEPTION: main 
                        Process: com.example.user_pc.myapplication, PID: 18949 
                        java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to com.example.user_pc.myapplication.pojo.ListPojo 
                         at com.example.user_pc.myapplication.adpater.ListRetrofitAndroid.getView(ListRetrofitAndroid.java:71) 
                         at android.widget.AbsListView.obtainView(AbsListView.java:2255) 
                         at android.widget.ListView.measureHeightOfChildren(ListView.java:1263) 
                         at android.widget.ListView.onMeasure(ListView.java:1175) 
                         at android.view.View.measure(View.java:16497) 
                         at android.support.constraint.ConstraintLayout.internalMeasureChildren(ConstraintLayout.java:934) 
                         at android.support.constraint.ConstraintLayout.onMeasure(ConstraintLayout.java:973) 
                         at android.view.View.measure(View.java:16497) 
                         at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125) 
                         at android.widget.FrameLayout.onMeasure(FrameLayout.java:310) 
                         at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139) 
                         at android.view.View.measure(View.java:16497) 
                         at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125) 
                         at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:391) 
                         at android.view.View.measure(View.java:16497) 
                         at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125) 
                         at android.widget.FrameLayout.onMeasure(FrameLayout.java:310) 
                         at android.view.View.measure(View.java:16497) 
                         at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125) 
                         at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404) 
                         at android.widget.LinearLayout.measureVertical(LinearLayout.java:695) 
                         at android.widget.LinearLayout.onMeasure(LinearLayout.java:588) 
                         at android.view.View.measure(View.java:16497) 
                         at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125) 
                         at android.widget.FrameLayout.onMeasure(FrameLayout.java:310) 
                         at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291) 
                         at android.view.View.measure(View.java:16497) 
                         at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1912) 
                         at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1109) 
                         at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1291) 
                         at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:996) 
                         at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5600) 
                         at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761) 
                         at android.view.Choreographer.doCallbacks(Choreographer.java:574) 
                         at android.view.Choreographer.doFrame(Choreographer.java:544) 
                         at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747) 
                         at android.os.Handler.handleCallback(Handler.java:733) 
                         at android.os.Handler.dispatchMessage(Handler.java:95) 
                         at android.os.Looper.loop(Looper.java:136) 
                         at android.app.ActivityThread.main(ActivityThread.java:5001) 
                         at java.lang.reflect.Method.invokeNative(Native Method) 
                         at java.lang.reflect.Method.invoke(Method.java:515) 
                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) 
                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) 
                         at dalvik.system.NativeStart.main(Native Method) 

該問題如何解決?

回答

3

您正在使用ArrayList<ListPojo>所以你需要確保解析應該發生使用權類型List<ListPojo>而不是list它沒有類型

由於缺少類型信息,gson正在恢復的List內部 創建的對象LinkedTreeMap因爲你正在使用raw類型(應該是選中蒙上了警告)與聲明的具體類型時,適配器實際上期待這將創建一個問題10但內部是另一回事。這樣的解決方案

Never use raw-types anywhere possible

這樣做

public interface CountryArrayAPI { 
    @GET("api/popular_destinations") 
    public Call<List<ListPojo>> getCountries(); 
} 

api之前還刪除/和呼叫會像

call.enqueue(new Callback<List<ListPojo>>() { 

      @Override 
      public void onResponse(Call<List<ListPojo>> call, Response<List<ListPojo>> response) { 
      listPojos = response.body(); 

始終代碼interface所以

List<ListPojo> listPojos = ...; 
+0

我會嘗試你的解決方案並更新你 – Ghimire

+0

謝謝你隊友多數民衆贊成在工作。可以詳細說明我的問題。這將是一個很大的幫助。 – Ghimire

+0

當我修改我的答案,總之你正在使用'List'沒有類型參數,所以不會解析將發生,你會得到不需要的類型對象的列表,所以不要使用原始類型'列表' –

1

我目前完全不知道如何處理使用List的json。但是你可以使用數組是這樣的:

public interface CountryArrayAPI { 
    @GET("/api/popular_destinations") 
    public Call<ListPojo[]> getCountries(); 
} 
+0

肯定nabin我會檢查這個 – Ghimire