java.lang.ClassCastException:java.util.ArrayList无法强制转换为com.panaceasoft.citiesdirectory.models.PCityData

时间:2016-07-12 07:13:39

标签: android arraylist

这是我的SelectedCategoryActivity.java代码 显示错误,ArrayList无法转换为com.panaceasoft.citiesdirectory.models.PCityData,而我在其他代码中使用相同的方式

package com.panaceasoft.citiesdirectory.activities;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.TextPaint;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.panaceasoft.citiesdirectory.Config;
import com.panaceasoft.citiesdirectory.GlobalData;
import com.panaceasoft.citiesdirectory.R;
import com.panaceasoft.citiesdirectory.adapters.CategoryAdapter;
//import com.panaceasoft.citiesdirectory.adapters.CategoryAdapter1;
//import com.panaceasoft.citiesdirectory.models.CategoryRowData;
import com.panaceasoft.citiesdirectory.adapters.CityAdapter;
import com.panaceasoft.citiesdirectory.listeners.ClickListener;
import com.panaceasoft.citiesdirectory.listeners.RecyclerTouchListener;
import com.panaceasoft.citiesdirectory.models.CategoryData;

import com.panaceasoft.citiesdirectory.models.CityRowData;
import com.panaceasoft.citiesdirectory.models.PCityData;
import com.panaceasoft.citiesdirectory.models.PItemData;
import com.panaceasoft.citiesdirectory.models.PSubCategoryData;
import com.panaceasoft.citiesdirectory.utilities.Utils;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by dell on 04-Jul-16.
 */
public class SelectedCategoryActivity extends AppCompatActivity {

    private ProgressDialog prgDialog;
    private String jsonStatusSuccessString;

    private CollapsingToolbarLayout collapsingToolbar;
    private Toolbar toolbar;
    private ImageView detailImage;
    private TextView txtTitle;
    private RecyclerView mRecyclerView;
    private StaggeredGridLayoutManager mLayoutManager;
    private CityAdapter mAdapter;
    private List<PCityData> myDataset = new ArrayList<>();
    private CityRowData info;
    private int selectedCategoryID;
    private int selectedCityID;
    private CategoryData category;
    private PCityData city;
    private ArrayList<PCityData> cityArrayList ;
    //private ArrayList<PCityData> cityArrayData ;
    private ArrayList<PSubCategoryData> subCategoryArrayList ;

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

        initUI();

        initData();

        saveSelectedCategoryInfo(category);



        bindData();

        loadCityGrid();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_news, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_news) {
            Utils.psLog("Open News Activity");
            final Intent intent;
            intent = new Intent(this, NewsListActivity.class);
            intent.putExtra("selected_category_id", selectedCategoryID + "");
            startActivity(intent);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        finish();
        overridePendingTransition(R.anim.blank_anim, R.anim.left_to_right);
    }

    private void initUI() {
        initToolbar();
        initCollapsingToolbarLayout();
    }

    private void initCollapsingToolbarLayout(){
        try {
            collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
        } catch (Exception e) {
            Utils.psErrorLogE("Error in initCollapsingToolbarLayout.", e);
        }
    }

    private void initToolbar() {
        try {
            toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            if(Utils.isAndroid_5_0()){
                Utils.setMargins(toolbar, 0, -102, 0, 0);
            }
            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onBackPressed();
                }
            });
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            toolbar.setTitle("");
            toolbar.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
        } catch (Resources.NotFoundException e) {
            Utils.psErrorLogE("Error in initToolbar.", e);
        }

    }

    private void initData() {
              try {
                  jsonStatusSuccessString = getResources().getString(R.string.json_status_success);
                  requestData(Config.APP_API_URL + Config.GET_ALL);
                  detailImage = (ImageView) findViewById(R.id.detail_image);
                  category = GlobalData.categorydata;
            //city = GlobalData.citydata;

                  selectedCategoryID = category.id;
            //selectedCityID = city.id;
        } catch (Exception e) {
            Utils.psErrorLogE("Error in initData.", e);
        }
    }

    private void bindData() {
        try {

            if(collapsingToolbar != null){

                collapsingToolbar.setTitle(Utils.getSpannableString(category.name));
                makeCollapsingToolbarLayoutLooksGood(collapsingToolbar);

            }
            Picasso.with(getApplicationContext()).load(Config.APP_IMAGES_URL + category.cover_image_file).into(detailImage);
        } catch (Exception e) {
            Utils.psErrorLogE("Error in bindData.", e);
        }
    }

    private void requestData(String uri) {
        JsonObjectRequest request = new JsonObjectRequest(uri,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            String status = response.getString("status");
                            Utils.psLog("City Status >>>>>>>>>>>>>: " + status);
                            if (status.equals(jsonStatusSuccessString)) {
                                Gson gson = new Gson();
                                Type listType = new TypeToken<List<PCityData>>() {
                                }.getType();
                                GlobalData.citydata = (PCityData) gson.fromJson(response.getString("data"), listType);
                                //cityArrayList = gson.fromJson(response.getString("data"), listType);
                                Utils.psLog("City Count >>>>>>>>>>>>>: " + cityArrayList.size());
                                 updateGlobalCityList();
                            }





                        } catch (JSONException e) {
                            Utils.psErrorLogE("Error in loading City List.", e);

                            e.printStackTrace();
                        }
                    }
                },


                new Response.ErrorListener() {

                    public void onErrorResponse(VolleyError error) {
                        prgDialog.cancel();
                        Utils.psLog("Error: " + error.getMessage());
                    }

                    // @Override




                });




        RequestQueue queue = Volley.newRequestQueue(this.getApplicationContext());
        queue.add(request);
    }




     private void updateGlobalCityList() {
     GlobalData.cityDatas.clear();
           for (PCityData cd : cityArrayList) {
            GlobalData.cityDatas.add(cd);
        }
   }

    public void loadCityGrid() {
        try {
            mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

            mRecyclerView.setHasFixedSize(true);

            mLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
            mRecyclerView.setLayoutManager(mLayoutManager);

            mAdapter = new CityAdapter(myDataset, mRecyclerView);
            mRecyclerView.setAdapter(mAdapter);
            //cityArrayList = category.cities;
           // for (PCityData cd : cityArrayList) {
                // subCategoryArrayList = cd.sub_categories;

              //  info = new CityRowData();
                //info.setCityId(cd.id);

              //  info.setCityName(cd.name);
                //info.setCityImage(cd.cover_image_file);
               // myDataset.add(info);
           // }

            mAdapter.notifyItemInserted(myDataset.size());

            mRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(this, mRecyclerView, new ClickListener() {
                @Override
                public void onClick(View view, int position) {
                    onItemClicked(position);
                }

                @Override
                public void onLongClick(View view, int position) {

                }
            }));

            mRecyclerView.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
        } catch (Resources.NotFoundException e) {
            Utils.psErrorLogE("Error in loadCityGrid.", e);
        }
    }

    public void onItemClicked( int position){
        final Intent intent;
        intent = new Intent(this,SubCategoryActivity.class);
        GlobalData.citydata = cityArrayList.get(position);
        intent.putExtra("selected_city_index", position );
        intent.putExtra("selected_category_id", selectedCategoryID);
        intent.putExtra("selected_city_id", cityArrayList.get(0).id);

        startActivity(intent);
        overridePendingTransition(R.anim.right_to_left, R.anim.blank_anim);
    }

    private void makeCollapsingToolbarLayoutLooksGood(CollapsingToolbarLayout collapsingToolbarLayout) {
        try {
            final Field field = collapsingToolbarLayout.getClass().getDeclaredField("mCollapsingTextHelper");
            field.setAccessible(true);

            final Object object = field.get(collapsingToolbarLayout);
            final Field tpf = object.getClass().getDeclaredField("mTextPaint");
            tpf.setAccessible(true);

            ((TextPaint) tpf.get(object)).setTypeface(Utils.getTypeFace(Utils.Fonts.ROBOTO));
            ((TextPaint) tpf.get(object)).setColor(getResources().getColor(R.color.colorAccent));
        } catch (Exception ignored) {
        }
    }

    private void saveSelectedCategoryInfo(CategoryData ct) {
        try {
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putInt("_id", ct.id);
            editor.putString("_name", ct.name);
            editor.putString("_cover_image", ct.cover_image_file);
           // editor.putString("_address", ct.address);
           // editor.putString("_city_region_lat", ct.lat);
           // editor.putString("_city_region_lng", ct.lng);
            editor.commit();
        } catch (Exception e) {
            Utils.psErrorLogE("Error in saveSelectedCategoryInfo.", e);
        }
    }


}

GlobalData.java

package com.panaceasoft.citiesdirectory;

import com.panaceasoft.citiesdirectory.models.CategoryData;
import com.panaceasoft.citiesdirectory.models.PCityData;
import com.panaceasoft.citiesdirectory.models.PItemData;

import java.util.ArrayList;




public class GlobalData {
    public static PItemData itemData =  null;
    public static PCityData citydata = null;
    public static CategoryData categorydata = null;
    public static ArrayList<PCityData> cityDatas = new ArrayList<PCityData>();
    public static ArrayList<CategoryData> categoryDatas = new ArrayList<CategoryData>();
}

PCityData.java

package com.panaceasoft.citiesdirectory.models;

import android.os.Parcel;
import android.os.Parcelable;

import java.util.ArrayList;



public class PCityData implements Parcelable {

    public int id;

    public String name;

    public String description;

    public String address;

    public String lat;

    public String lng;

    public String added;

    public int status;

    public int item_count;

    public int category_count;

    public int sub_category_count;

    public int follow_count;

    public String cover_image_file;

    public int cover_image_width;

    public int cover_image_height;

    public String cover_image_description;

   // public ArrayList<PSubCategoryData> sub_categories;

    protected PCityData(Parcel in) {
        id = in.readInt();
        name = in.readString();
        description = in.readString();
        address = in.readString();
        lat = in.readString();
        lng = in.readString();
        added = in.readString();
        status = in.readInt();
        item_count = in.readInt();
        category_count = in.readInt();
        sub_category_count = in.readInt();
        follow_count = in.readInt();
        cover_image_file = in.readString();
        cover_image_width = in.readInt();
        cover_image_height = in.readInt();
        cover_image_description = in.readString();
       // if (in.readByte() == 0x01) {
        //    sub_categories = new ArrayList<PSubCategoryData>();
         //   in.readList(sub_categories, PSubCategoryData.class.getClassLoader());
       // } else {
         //   sub_categories = null;
       // }
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(id);
        dest.writeString(name);
        dest.writeString(description);
        dest.writeString(address);
        dest.writeString(lat);
        dest.writeString(lng);
        dest.writeString(added);
        dest.writeInt(status);
        dest.writeInt(item_count);
        dest.writeInt(category_count);
        dest.writeInt(sub_category_count);
        dest.writeInt(follow_count);
        dest.writeString(cover_image_file);
        dest.writeInt(cover_image_width);
        dest.writeInt(cover_image_height);
        dest.writeString(cover_image_description);
        //if (sub_categories == null) {
          //  dest.writeByte((byte) (0x00));
       // } else {
        //    dest.writeByte((byte) (0x01));
       //     dest.writeList(sub_categories);
      //  }
    }

    @SuppressWarnings("unused")
    public static final Parcelable.Creator<PCityData> CREATOR = new Parcelable.Creator<PCityData>() {
        @Override
        public PCityData createFromParcel(Parcel in) {
            return new PCityData(in);
        }

        @Override
        public PCityData[] newArray(int size) {
            return new PCityData[size];
        }
    };
}

logcat的

07-12 02:58:33.320 1797-1797/com.panaceasoft.citiesdirectory E/AndroidRuntime: FATAL EXCEPTION: main
                                                                               Process: com.panaceasoft.citiesdirectory, PID: 1797
                                                                               java.lang.ClassCastException: java.util.ArrayList cannot be cast to com.panaceasoft.citiesdirectory.models.PCityData
                                                                                   at com.panaceasoft.citiesdirectory.activities.SelectedCategoryActivity$2.onResponse(SelectedCategoryActivity.java:209)
                                                                                   at com.panaceasoft.citiesdirectory.activities.SelectedCategoryActivity$2.onResponse(SelectedCategoryActivity.java:199)
                                                                                   at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:72)
                                                                                   at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
                                                                                   at android.os.Handler.handleCallback(Handler.java:739)
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                   at android.os.Looper.loop(Looper.java:135)
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                                   at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

3 个答案:

答案 0 :(得分:0)

我认为以下行包含错误

GlobalData.citydata = (PCityData) gson.fromJson(response.getString("data"), listType);

我认为您正在尝试将gson.fromJson(response.getString(&#34; data&#34;),listType)转换为PCileData,即ArrayList

答案 1 :(得分:0)

你在这一行上收到错误:

GlobalData.citydata = (PCityData) gson.fromJson(response.getString("data"), listType);

,因为:

gson.fromJson(response.getString("data"), listType);

这会返回一个arraylist并且它不会投射到您的自定义模型中

修复此更改 GlobalData.java

public static PCityData citydata = null;

public static ArrayList<PCityData> citydata = null;

答案 2 :(得分:0)

    Gson gson = new Gson();
    Type listType = new TypeToken<List<PCityData>>() {
                                    }.getType();
    // Issue is here 
    GlobalData.citydata = (PCityData) gson.fromJson(response.getString("data"), listType);

修复1:GlobalData.citydat a应为List<PCityData>类型。
修复2:改变如此GlobalData.citydata = (List<PCityData>) gson.fromJson(response.getString("data"), listType);