2017-05-15 1 views
0

j'ai reçu des données de api lien (serveur) pour afficher les données dans recyclview, si je veux cliquer sur les articles puis il va ouvrir l'activité suivante c'est très bien, mais certains articles n'ont pas de données, si je veux cliquez geting exception class castcomment éviter ClassCast Exception

enter image description here

dans cette image ci-dessus, cliquez sur Adventure, il ouvrira l'activité suivante avec des données connexes, si je veux cliquez sur Activités pour enfants puis se classe jeté erreur d'exception en raison du serveur ne Les données sont disponibles pour les activités pour les enfants, si je veux cliquer sur Kids ACtivities puis il va ouvrir le massage toast comme plus de données sont disponibles, comment dois-je l'obtenir?

C'est un adaptateur classe

public class SubCategoryChild_Adapter extends RecyclerView.Adapter { 

private List<SubCategoryChild> subCategoryChildList; 
private Context context; 

public class MyViewHolder extends RecyclerView.ViewHolder { 
    public TextView 
      discountName, 
      subcategorychild_merchantName, 
      subcategoryChild_discountedPrice, 
      subcategoryChild_actualPrice, 
      subcategoryChild_distance, 
      staticUgx; 
    public ImageView SubcategoryChild_imageView; 
    public SubCategoryChild subCategoryChild; 

    public MyViewHolder(View view) { 
     super(view); 
     subcategoryChild_actualPrice = (TextView) view.findViewById(R.id.ScChild_actualPrice); 
     subcategoryChild_actualPrice.setPaintFlags(subcategoryChild_actualPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); 

     subcategoryChild_discountedPrice = (TextView) view.findViewById(R.id.ScChild_discountedPrice); 
     subcategorychild_merchantName = (TextView) view.findViewById(R.id.ScChild_merchantName); 

     staticUgx = (TextView) view.findViewById(R.id.ScChild_actualprice_ugx); 
     staticUgx.setPaintFlags(staticUgx.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); 

     subcategoryChild_distance = (TextView) view.findViewById(R.id.ScChild_Near_Location_text); 

     discountName = (TextView) view.findViewById(R.id.ScChild_Discount_Text); 
     SubcategoryChild_imageView = (ImageView) view.findViewById(R.id.ScChild_imageView); 
    } 
} 

public SubCategoryChild_Adapter(Context context , List<SubCategoryChild> subCategoryChildList) { 
    this.subCategoryChildList = subCategoryChildList; 
} 

@Override 
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 
    RecyclerView.ViewHolder itemView; 
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.subcategorydeal_list, parent, false); 
    itemView = new MyViewHolder(view); 
    return itemView; 
} 

@Override 
public void onBindViewHolder(RecyclerView.ViewHolder holder,int position){ 
    final SubCategoryChild subCategoryChild = subCategoryChildList.get(position); 
    ((MyViewHolder) holder).subcategorychild_merchantName.setText(subCategoryChild.getMerchantName()); 
    ((MyViewHolder) holder).discountName.setText(subCategoryChild.getName()); 
    ((MyViewHolder) holder).subcategoryChild_actualPrice.setText(subCategoryChild.getActualPrice()); 
    ((MyViewHolder) holder).subcategoryChild_discountedPrice.setText(subCategoryChild.getDiscountedPrice()); 
    ((MyViewHolder) holder).subcategoryChild_distance.setText(subCategoryChild.getDistance()); 

    context = ((MyViewHolder) holder).SubcategoryChild_imageView.getContext(); 

    Picasso.with(context).load(subCategoryChild.getLogo()).fit().into(((MyViewHolder)holder).SubcategoryChild_imageView); 
    ((MyViewHolder) holder).subCategoryChild = subCategoryChild; 
} 
@Override 
public int getItemCount() { 
    if(subCategoryChildList == null){ 
     return 0; 
    }else { 
     return subCategoryChildList.size(); 
    } 

} 
} 

cette classe est le modèle

public class SubCategoryChild { 

@SerializedName("merchant_id") 
@Expose 
private String merchantId; 
@SerializedName("merchant_name") 
@Expose 
private String merchantName; 
@SerializedName("name") 
@Expose 
private String name; 
@SerializedName("deal_sub_title") 
@Expose 
private String dealSubTitle; 
@SerializedName("discounted_price") 
@Expose 
private String discountedPrice; 
@SerializedName("actual_price") 
@Expose 
private String actualPrice; 
@SerializedName("discounted_percentage") 
@Expose 
private String discountedPercentage; 
@SerializedName("category_id") 
@Expose 
private String categoryId; 
@SerializedName("sub_category_id") 
@Expose 
private String subCategoryId; 
@SerializedName("city_id") 
@Expose 
private String cityId; 
@SerializedName("logo") 
@Expose 
private String logo; 
@SerializedName("website") 
@Expose 
private String website; 
@SerializedName("email") 
@Expose 
private String email; 
@SerializedName("phone") 
@Expose 
private String phone; 
@SerializedName("mobile") 
@Expose 
private String mobile; 
@SerializedName("description") 
@Expose 
private String description; 
@SerializedName("Merchant_address") 
@Expose 
private String merchantAddress; 
@SerializedName("latitude") 
@Expose 
private String latitude; 
@SerializedName("longitude") 
@Expose 
private String longitude; 
@SerializedName("distance") 
@Expose 
private String distance; 
@SerializedName("deal_count") 
@Expose 
private Integer dealCount; 

public String getMerchantId() { 
    return merchantId; 
} 

public void setMerchantId(String merchantId) { 
    this.merchantId = merchantId; 
} 

public String getMerchantName() { 
    return merchantName; 
} 

public void setMerchantName(String merchantName) { 
    this.merchantName = merchantName; 
} 

public String getName() { 
    return name; 
} 

public void setName(String name) { 
    this.name = name; 
} 

public String getDealSubTitle() { 
    return dealSubTitle; 
} 

public void setDealSubTitle(String dealSubTitle) { 
    this.dealSubTitle = dealSubTitle; 
} 

public String getDiscountedPrice() { 
    return discountedPrice; 
} 

public void setDiscountedPrice(String discountedPrice) { 
    this.discountedPrice = discountedPrice; 
} 

public String getActualPrice() { 
    return actualPrice; 
} 

public void setActualPrice(String actualPrice) { 
    this.actualPrice = actualPrice; 
} 

public String getDiscountedPercentage() { 
    return discountedPercentage; 
} 

public void setDiscountedPercentage(String discountedPercentage) { 
    this.discountedPercentage = discountedPercentage; 
} 

public String getCategoryId() { 
    return categoryId; 
} 

public void setCategoryId(String categoryId) { 
    this.categoryId = categoryId; 
} 

public String getSubCategoryId() { 
    return subCategoryId; 
} 

public void setSubCategoryId(String subCategoryId) { 
    this.subCategoryId = subCategoryId; 
} 

public String getCityId() { 
    return cityId; 
} 

public void setCityId(String cityId) { 
    this.cityId = cityId; 
} 

public String getLogo() { 
    return logo; 
} 

public void setLogo(String logo) { 
    this.logo = logo; 
} 

public String getWebsite() { 
    return website; 
} 

public void setWebsite(String website) { 
    this.website = website; 
} 

public String getEmail() { 
    return email; 
} 

public void setEmail(String email) { 
    this.email = email; 
} 

public String getPhone() { 
    return phone; 
} 

public void setPhone(String phone) { 
    this.phone = phone; 
} 

public String getMobile() { 
    return mobile; 
} 

public void setMobile(String mobile) { 
    this.mobile = mobile; 
} 

public String getDescription() { 
    return description; 
} 

public void setDescription(String description) { 
    this.description = description; 
} 

public String getMerchantAddress() { 
    return merchantAddress; 
} 

public void setMerchantAddress(String merchantAddress) { 
    this.merchantAddress = merchantAddress; 
} 

public String getLatitude() { 
    return latitude; 
} 

public void setLatitude(String latitude) { 
    this.latitude = latitude; 
} 

public String getLongitude() { 
    return longitude; 
} 

public void setLongitude(String longitude) { 
    this.longitude = longitude; 
} 

public String getDistance() { 
    return distance; 
} 

public void setDistance(String distance) { 
    this.distance = distance; 
} 

public Integer getDealCount() { 
    return dealCount; 
} 

public void setDealCount(Integer dealCount) { 
    this.dealCount = dealCount; 
} 
} 

cette activité est la classe

public class SubCategoryChild_Activity extends AppCompatActivity { 
RecyclerView subCategoryDeal_RecyclerView; 
public Context context; 
ProgressBar progress_bar; 
SubCategoryChild_Adapter subCategoryChild_adapter; 
List<SubCategoryChild> subCategoryChildList; 
SubCategoryChild subCategoryChild; 
public String catId,subCatId,ActionBar_Name; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_sub_category_child_); 

    Bundle extras = getIntent().getExtras(); 
    catId = extras.getString("cat_Id"); 
    subCatId = extras.getString("Sub_CatId"); 
    ActionBar_Name = extras.getString("actionBar_Name"); 

    getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
    getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true); 
    getSupportActionBar().setTitle(ActionBar_Name); 

    subCategoryDeal_RecyclerView = (RecyclerView) findViewById(R.id.subCategoryDeal_RecyclerView); 
    final ProgressBar progress_bar = (ProgressBar) findViewById(R.id.ScChild_progress_bar); 
    subCategoryDeal_RecyclerView.setLayoutManager(new LinearLayoutManager(this)); 

    subCategoryDeal_RecyclerView.setHasFixedSize(true); 

    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this); 
    subCategoryDeal_RecyclerView.setLayoutManager(layoutManager); 

    subCategoryDeal_RecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST)); 
    subCategoryDeal_RecyclerView.setItemAnimator(new DefaultItemAnimator()); 
    subCategoryChild_adapter = new SubCategoryChild_Adapter(context, subCategoryChildList); 
    subCategoryDeal_RecyclerView.setAdapter(subCategoryChild_adapter); 

    progress_bar.setVisibility(View.VISIBLE); 
    if(new SubCategoryChild_Response().getStatus() == null){ 

     RestClient.get(this).diskCacheEnable(true).new NetworkTask<Void, SubCategoryChild_Response>(SubCategoryChild_Response.class, Http.GET) { 

      @Override 
      protected void onPostExecute(SubCategoryChild_Response subCategoryChild_response) { 
       super.onPostExecute(subCategoryChild_response); 
       progress_bar.setVisibility(View.GONE); 
       if (subCategoryChild_response != null && subCategoryChild_response.getSubCategoryChild() != null & subCategoryChild_response.getSubCategoryChild().size() > 0) { 
        subCategoryChildList = subCategoryChild_response.getSubCategoryChild(); 
        subCategoryChild_adapter = new SubCategoryChild_Adapter(SubCategoryChild_Activity.this, subCategoryChildList); 
        subCategoryDeal_RecyclerView.setAdapter(subCategoryChild_adapter); 
       } 
      } 
     }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "https://api.bargaincry.com/apurl/deal/get_merchantBy_subcat/41187/" + catId + "/" + subCatId + "/latitude~longitude"); 

    }else { 
     if(new SubCategoryChild_Response().getStatus().isEmpty()) 
     Toast.makeText(SubCategoryChild_Activity.this,"error",Toast.LENGTH_LONG).show(); 
       } 

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

    // Associate searchable configuration with the SearchView 

    SearchManager searchManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE); 
    SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView(); 
    ComponentName cn = new ComponentName(this, SearchResultsActivity.class); 
    searchView.setSearchableInfo(searchManager.getSearchableInfo(cn)); 
    //searchView.setSubmitButtonEnabled(true); 
    //searchView.setOnQueryTextListener(MainActivity.this); 
    searchView.setIconifiedByDefault(false); 
    return super.onCreateOptionsMenu(menu); 
} 
@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    switch (item.getItemId()) { 
     case android.R.id.home: 
      // app icon in action bar clicked; goto parent activity. 
      this.finish(); 
      return true; 
     default: 
      return super.onOptionsItemSelected(item); 
    } 
} 
} 

cette classe est la réponse

public class SubCategoryChild_Response { 
@SerializedName("status") 
@Expose 
private String status; 
@SerializedName("merchant") 
@Expose 
private List<SubCategoryChild> subCategoryChildList = null; 

public String getStatus() { 
    return status; 
} 

public void setStatus(String status) { 
    this.status = status; 
} 

public List<SubCategoryChild> getSubCategoryChild() { 
    return subCategoryChildList; 
} 

public void setSubCategoryChildList(List<SubCategoryChild> subCategoryChildList) { 
    this.subCategoryChildList = subCategoryChildList; 
} 
} 

c'est CatLog ici

FATAL EXCEPTION: principal processus: app.com.BargainCryApp, PID: 28129
java.lang.ClassCastException: java.lang.String ne peut pas être jeté à models.SubCategoryChild_Response à app.com.BargainCryApp.SubCategoryChild_Activity $ 1.onPostExecute (SubCategoryChild_Activity.java:69) à android.os.AsyncTask.finish (AsyncTask.java:665) à android.os.AsyncTask.-wrap1 (AsyncTask.java) à android.os.AsyncTask $ InternalHandler.handleMessage (AsyncTask.java:682) à l'adresse android.os.Handler.dispatchMessage (Handl er.java:111) à android.os.Looper.loop (Looper.java:207) à android.app.ActivityThread.main (ActivityThread.java:5769) à java.lang.reflect.Method.invoke (Méthode native) à com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run (ZygoteInit.java:861) à com.android.internal.os.ZygoteInit.main (ZygoteInit.java:751)

+0

s'il vous plaît fournir CatLog –

+0

i posté CatLog, vérifier une fois –

+0

ce qui est à l'intérieur subCategoryChild_response? –

Répondre

0

Pour votre question comment éviter ClassCastException, la réponse est l'utilisation 'instanceof' opérateur et instanceof renvoie vrai puis poursuivre vos actions.

if (subCategoryChild_response != null && 
    subCategoryChild_response.getSubCategoryChild() != null && 
    subCategoryChild_response.getSubCategoryChild() instanceof 'Your Child Class should be here' 
    subCategoryChild_response.getSubCategoryChild().size() > 0) 

Hope this vous aide

+0

bro me donner le code, je veux essayer –

+0

où puis-je mettre ce code dans l'adaptateur ou d'une réponse –

+0

mettre ceci dans votre méthode 'onPostExecute' –

0

Avant de couler objet, vérifier instanceOf

if (holder instanceof MyViewHolder) { 
    MyViewHolder mHolder = (MyViewHolder) holder; 
    mHolder.subcategorychild_merchantName.setText(subCategoryChild.getMerchantName()); 
//.......... 
    } 
+0

bro !!! obtenir la même erreur. –