Cannot use finish() inside Adapter
Asked Answered
P

1

2

I'm always getting this error when i'm setting the finish method inside adapter.

11-28 09:46:09.661 8636-8646/? E/art: Failed sending reply to debugger: Broken pipe
11-28 09:46:17.709 8636-8636/com.juandirection E/InputEventReceiver: Exception dispatching input event.
11-28 09:46:17.709 8636-8636/com.juandirection E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
11-28 09:46:17.709 8636-8636/com.juandirection E/MessageQueue-JNI: java.lang.ClassCastException: com.juandirection.variables.Global cannot be cast to com.juandirection.ActivityCategorySelected

I tried to remove all item insde OnRatingChanged but the error remains the same.

public class AdapterPOI extends RecyclerView.Adapter<AdapterPOI.MainViewHolder> {
    private List<ModelPoi> poiDatas;
    private List<ModelImage> imageDatas;
    private List<ModelComments> commentDatas;
    private List<ModelFavorite> favoriteDatas;
    private List<ModelAccounts> accountDatas;
    private LayoutInflater inflater;
    private Context context;
    int viewType = 0;
    int add;
    int cCounter = 0;
    int[] routeImg = {R.drawable.ic_resto_route, R.drawable.ic_sights_route, R.drawable.ic_transport_route, R.drawable.ic_hotel_route,
            R.drawable.ic_gas_route, R.drawable.ic_school_route, R.drawable.ic_entertainment_route,
            R.drawable.ic_shop_route, R.drawable.ic_atm_route, R.drawable.ic_bank_route, R.drawable.ic_hospital_route,
            R.drawable.ic_pharmacy_route, R.drawable.ic_police_route, R.drawable.ic_toilet_route,};

    public AdapterPOI(Context context, List<ModelPoi> poiDatas, List<ModelFavorite> favoriteDatas, List<ModelComments> commentDatas, List<ModelImage> imageDatas) {
        inflater = LayoutInflater.from(context);
        this.poiDatas = poiDatas;
        this.context = context;
        this.favoriteDatas = favoriteDatas;
        this.imageDatas = imageDatas;
        this.commentDatas = commentDatas;
    }


    @Override
    public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        int listViewItemType = getItemViewType(viewType);
        if (listViewItemType == 0) {
            return new TitleHolder(LayoutInflater.from(context).inflate(R.layout.custom_row_title, parent, false));
        }
        if (listViewItemType == 1 || listViewItemType == 4 || listViewItemType == 7) {
            return new HeaderHolder(LayoutInflater.from(context).inflate(R.layout.headerinformation, parent, false));
        }
        if (listViewItemType == 2 || listViewItemType == 3 || listViewItemType == 6) {
            return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.custom_row_pictext, parent, false));
        }
        if (listViewItemType == 5) {
            return new GalleryHolder(LayoutInflater.from(context).inflate(R.layout.custom_row_photos, parent, false));
        }
        if (listViewItemType == 8) {
            return new RatingHolder(LayoutInflater.from(context).inflate(R.layout.custom_row_rating, parent, false));
        }
        if (listViewItemType >= 9 && listViewItemType <= 8 + commentDatas.size()) {
            return new CommentsHolder(LayoutInflater.from(context).inflate(R.layout.custom_row_comments, parent, false));
        }
        if (listViewItemType == 14) {
            return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.custom_row_pictext, parent, false));
        }
        if (listViewItemType >= 9 + commentDatas.size()) {
            return new TapHolder(LayoutInflater.from(context).inflate(R.layout.custom_row_taptorate, parent, false));
        }


        return null;
    }

    @Override
    public void onBindViewHolder(MainViewHolder holder, int position) {
        try {
            if (position == 0) {
                TitleHolder tHolder = (TitleHolder) holder;
                tHolder.imgType.setBackgroundResource(routeImg[Global.getPosition]);
                tHolder.txtTitle.setText(Global.selectedPOI);
                ModelPoi poiData = (ModelPoi) getPOI(0);
                tHolder.txtType.setText(poiData.POIType);
                if (favoriteDatas.size() >= 1) {
                    tHolder.imgFavorite.setBackgroundResource(R.drawable.ic_favorite_yellow);
                    tHolder.txtID.setText("1");
                } else {
                    tHolder.imgFavorite.setBackgroundResource(R.drawable.ic_favorite_white);
                    tHolder.txtID.setText("0");
                }
                float ratingBar = 0f;
                for (int i = 0; i < commentDatas.size(); i++) {
                    ModelComments modelComments = (ModelComments) getComment(i);
                    ratingBar += Float.valueOf(modelComments.rating);
                }
                float finalRating;
                finalRating = ratingBar / commentDatas.size();
                tHolder.ratingBar.setRating(finalRating);
            }
            if (position == 1) {
                HeaderHolder hHolder = (HeaderHolder) holder;
                hHolder.txtInfo.setText("Information");
            }
            if (position == 2) {
                MyViewHolder mHolder = (MyViewHolder) holder;
                ModelPoi poiData = (ModelPoi) getPOI(0);
                mHolder.icon.setImageResource(R.drawable.ic_information);
                mHolder.title.setText(poiData.POIInfo);
                mHolder.txtID.setText("0");
            }
            if (position == 3) {
                MyViewHolder mHolder = (MyViewHolder) holder;
                ModelPoi poiData = (ModelPoi) getPOI(0);
                mHolder.icon.setImageResource(R.drawable.ic_place_black_36dp);
                mHolder.title.setText(poiData.POIAddress);
                mHolder.txtID.setText("1");
            }
            if (position == 4) {
                HeaderHolder hHolder = (HeaderHolder) holder;
                hHolder.txtInfo.setText("Photos");
            }
            if (position == 5) {
                GalleryHolder gHolder = (GalleryHolder) holder;
                AdapterGalleryViewPoi galleryViewAdapter;
                galleryViewAdapter = new AdapterGalleryViewPoi(context, imageDatas);
                gHolder.gallery.setAdapter(galleryViewAdapter);
                final WindowManager display = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

                DisplayMetrics metrics = new DisplayMetrics();
                display.getDefaultDisplay().getMetrics(metrics);
                ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) gHolder.gallery.getLayoutParams();
                mlp.setMargins(-((metrics.widthPixels * 2 + 200) / 3), mlp.topMargin,
                        mlp.rightMargin, mlp.bottomMargin);
            }
            if (position == 6) {
                MyViewHolder mHolder = (MyViewHolder) holder;
                mHolder.icon.setImageResource(R.drawable.ic_local_see_black_24dp);
                mHolder.title.setText("Add Photos");
                mHolder.txtID.setText("2");
            }
            if (position == 7) {
                HeaderHolder hHolder = (HeaderHolder) holder;
                hHolder.txtInfo.setText("Reviews");
            }
            if (position == 8) {
                RatingHolder mHolder = (RatingHolder) holder;
                float ratingBar = 0f;
                float getRate;
                int progressbarE = 0, progressbarVG = 0, progressbarAVG = 0, progressbarP = 0, progressbarT = 0;
                for (int i = 0; i < commentDatas.size(); i++) {
                    ModelComments modelComments = (ModelComments) getComment(i);
                    ratingBar += Float.valueOf(modelComments.rating);
                    getRate = Float.valueOf(modelComments.rating);
                    if (getRate >= 0 && getRate <= 1) {
                        progressbarT += getRate;
                    }
                    if (getRate > 1 && getRate <= 2) {
                        progressbarP += getRate;
                    }
                    if (getRate > 2 && getRate <= 3) {
                        progressbarAVG += getRate;
                    }
                    if (getRate > 3 && getRate <= 4) {
                        progressbarVG += getRate;
                    }
                    if (getRate > 4 && getRate <= 5) {
                        progressbarE += getRate;
                    }
                }
                mHolder.reviewTxt.setText(Global.selectedPOI);

                float finalRatingBar;
                finalRatingBar = ratingBar / commentDatas.size();
                mHolder.ratingBarReview.setRating(finalRatingBar);
                mHolder.progressbarE.setProgress(progressbarE);
                mHolder.progressbarVG.setProgress(progressbarVG);
                mHolder.progressbarAVG.setProgress(progressbarAVG);
                mHolder.progressbarP.setProgress(progressbarP);
                mHolder.progressbarT.setProgress(progressbarT);
            }
            if (position >= 9 && position <= 8 + commentDatas.size()) {
                if (position == 9) {
                    cCounter = 0;
                }
                if (position == 10) {
                    cCounter = 1;
                }
                if (position == 11) {
                    cCounter = 2;
                }
                if (position == 12) {
                    cCounter = 3;
                }
                if (position == 13) {
                    cCounter = 4;
                }
                ModelComments modelComments = (ModelComments) getComment(cCounter);
                CommentsHolder mHolder = (CommentsHolder) holder;


                accountDatas = new Select().from(ModelAccounts.class)
                        .where(Condition.column(ModelAccounts$Table.GET_ID).is(modelComments.user_id)).queryList();

                ModelAccounts modelAccounts = (ModelAccounts) getImg(0);
                byte[] dataImg;
                dataImg = Base64.decode(modelAccounts.img, Base64.DEFAULT);
                Glide.with(context)
                        .load(dataImg)
                        .fitCenter()
                        .crossFade()
                        .into(mHolder.commentPhoto);
                mHolder.commentTitle.setText(modelComments.title);
                mHolder.commentDate.setText(modelComments.date);
                mHolder.comments.setText(modelComments.comment);
                mHolder.commentRatingbar.setRating(Float.valueOf(modelComments.rating));
                mHolder.txtID.setText(modelComments.get_id);
            }
            if (commentDatas.size() == 5) {
                if (position == 14) {
                    MyViewHolder mHolder = (MyViewHolder) holder;
                    mHolder.icon.setImageResource(R.drawable.ic_comment_black_24dp);
                    mHolder.title.setText("View More Comments");
                    mHolder.txtID.setText("3");

                }
            }
        } catch (Exception e) {
            Log.e("AdapterPOI", "" + e.toString());
        }

    }


    public Object getImg(int position) {
        return accountDatas.get(position);
    }

    public Object getPOI(int position) {
        return poiDatas.get(position);
    }

    public Object getComment(int position) {
        return commentDatas.get(position);
    }

    @Override
    public int getItemCount() {
        if (commentDatas.size() == 5) {
            add = 16;
        } else if (commentDatas.size() == 4) {
            add = 14;
        } else if (commentDatas.size() == 3) {
            add = 13;
        } else if (commentDatas.size() == 2) {
            add = 12;
        } else if (commentDatas.size() == 1) {
            add = 11;
        } else if (commentDatas.size() == 0) {
            return add = 10;
        }
        return add;
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            viewType = 0;
        } else if (position == 1) {
            viewType = 1;
        } else if (position == 2) {
            viewType = 2;
        } else if (position == 3) {
            viewType = 3;
        } else if (position == 4) {
            viewType = 4;
        } else if (position == 5) {
            viewType = 5;
        } else if (position == 6) {
            viewType = 6;
        } else if (position == 7) {
            viewType = 7;
        } else if (position == 8) {
            viewType = 8;
        } else if (position == 9) {
            viewType = 9;
        } else if (position == 10) {
            viewType = 10;
        } else if (position == 11) {
            viewType = 11;
        } else if (position == 12) {
            viewType = 12;
        } else if (position == 13) {
            viewType = 13;
        } else if (position == 14) {
            viewType = 14;
        } else if (position == 15) {
            viewType = 15;
        }
        return viewType;
    }

    class MyViewHolder extends MainViewHolder {
        TextView title, txtID;
        ImageView icon;

        public MyViewHolder(View itemView) {
            super(itemView);
            title = (TextView) itemView.findViewById(R.id.poiName);
            txtID = (TextView) itemView.findViewById(R.id.txtID);
            icon = (ImageView) itemView.findViewById(R.id.poiIcon);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String getText = txtID.getText().toString();
                    String getTitle = title.getText().toString();
                    if (getText.equalsIgnoreCase("0")) {
                        Global.getInfo = getTitle;
                        Intent intent = new Intent(context, ViewInformation.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intent);
                    }
                    if (getText.equalsIgnoreCase("1")) {
                        Log.e("Info", "Map");
                    }
                    if (getText.equalsIgnoreCase("2")) {
                        Log.e("Add Photo", "Add Photo");
                    }
                    if (getText.equalsIgnoreCase("3")) {
                        Global.getID = null;
                        Intent intent = new Intent(context, ViewComment.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intent);
                    }
                }
            });

        }

    }

    public class HeaderHolder extends MainViewHolder {
        TextView txtInfo;

        public HeaderHolder(View itemView) {
            super(itemView);
            this.txtInfo = (TextView) itemView.findViewById(R.id.txtinfo);

        }
    }

    public class GalleryHolder extends MainViewHolder {
        Gallery gallery;

        public GalleryHolder(View itemView) {
            super(itemView);
            this.gallery = (Gallery) itemView.findViewById(R.id.gallery);

        }
    }

    public class TapHolder extends MainViewHolder {
        RatingBar ratingBar;

        public TapHolder(View itemView) {
            super(itemView);
            this.ratingBar = (RatingBar) itemView.findViewById(R.id.tapToRate);
            this.ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
                @Override
                public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                    Global.setRating = rating;
                    Intent intent = new Intent(context, ActivityReview.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                    //((ActivityCategorySelected)context).finish();
                }
            });

        }
    }

    public class TitleHolder extends MainViewHolder {
        ImageView imgType, imgFavorite;
        TextView txtTitle, txtID, txtType;
        RatingBar ratingBar;

        public TitleHolder(View itemView) {
            super(itemView);
            final View view;
            view = itemView;
            imgType = (ImageView) itemView.findViewById(R.id.imgType);
            imgFavorite = (ImageView) itemView.findViewById(R.id.imgFavorite);
            txtTitle = (TextView) itemView.findViewById(R.id.txtTitle);
            txtType = (TextView) itemView.findViewById(R.id.txtType);
            txtID = (TextView) itemView.findViewById(R.id.txtID);
            ratingBar = (RatingBar) itemView.findViewById(R.id.ratingBar);
            imgFavorite.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final String getID = txtID.getText().toString();
                    final String getType = txtType.getText().toString();
                    if (Global.getUserId == null) {
                        AlertDialog.Builder alertbox = new AlertDialog.Builder(v.getRootView().getContext());
                        alertbox.setTitle("Sign In");
                        alertbox.setMessage("Please Sign in your account first.");
                        alertbox.setPositiveButton("Yes",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface arg0,
                                                        int arg1) {
                                        Intent intent = new Intent(context, ActivityLogin.class);
                                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                        context.startActivity(intent);

                                    }
                                });

                        alertbox.setNegativeButton("No",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface arg0,
                                                        int arg1) {
                                    }
                                });
                        alertbox.show();
                    } else {
                        if (getID.equals("0")) {
                            AlertDialog.Builder alertbox = new AlertDialog.Builder(v.getRootView().getContext());
                            alertbox.setTitle("Add This place to your Favorites?");
                            alertbox.setPositiveButton("Yes",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface arg0,
                                                            int arg1) {

                                            if (CheckNetwork.isNetworkAvailable(context)) {
                                                txtID.setText("1");
                                                imgFavorite.setBackgroundResource(R.drawable.ic_favorite_yellow);
                                                addToFavorite(getType);
                                                Thread timerThread = new Thread() {
                                                    public void run() {
                                                        try {
                                                            new DatabaseAsyncFavorites(context).execute();
                                                            sleep(1000);
                                                        } catch (InterruptedException e) {
                                                            e.printStackTrace();
                                                        }
                                                    }
                                                };
                                                timerThread.start();
                                            } else {
                                                Snackbar.make(view, "No Internet Access. Pease Connect to the Internet.", Snackbar.LENGTH_LONG).show();
                                            }
                                        }
                                    });

                            alertbox.setNegativeButton("No",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface arg0,
                                                            int arg1) {
                                        }
                                    });
                            alertbox.show();
                        } else {
                            AlertDialog.Builder alertbox = new AlertDialog.Builder(v.getRootView().getContext());
                            alertbox.setTitle("Remove this place from your Favorites?");
                            alertbox.setPositiveButton("Yes",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface arg0,
                                                            int arg1) {

                                            if (CheckNetwork.isNetworkAvailable(context)) {
                                                addToFavorite(getType);
                                                new Delete()
                                                        .from(ModelFavorite.class)
                                                        .where(Condition.column(ModelFavorite$Table.USER_ID).is(Global.getUserId))
                                                        .and(Condition.column(ModelFavorite$Table.LATITUDE).is(Global.lat)).query();
                                                txtID.setText("0");
                                                imgFavorite.setBackgroundResource(R.drawable.ic_favorite_white_nav);
                                            } else {

                                                Snackbar.make(view, "No Internet Access. Pease Connect to the Internet.", Snackbar.LENGTH_LONG).show();
                                            }
                                        }
                                    });

                            alertbox.setNegativeButton("No",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface arg0,
                                                            int arg1) {
                                        }
                                    });
                            alertbox.show();
                        }
                    }
                }
            });
        }
    }


    public void addToFavorite(final String getType) {
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        StringRequest request = new StringRequest(Request.Method.POST, Global.INSERT_FAV_URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> parameters = new HashMap<String, String>();
                parameters.put("latitude", Global.lat);
                parameters.put("user_id", Global.getUserId);
                parameters.put("type", getType);
                return parameters;
            }
        };
        requestQueue.add(request);
    }

    public class RatingHolder extends MainViewHolder {
        TextView reviewTxt;
        RatingBar ratingBarReview;
        ProgressBar progressbarE, progressbarVG, progressbarAVG, progressbarP, progressbarT;

        public RatingHolder(View itemView) {
            super(itemView);
            this.reviewTxt = (TextView) itemView.findViewById(R.id.reviewTxt);
            this.ratingBarReview = (RatingBar) itemView.findViewById(R.id.ratingBarReview);
            this.progressbarE = (ProgressBar) itemView.findViewById(R.id.progressbarE);
            this.progressbarVG = (ProgressBar) itemView.findViewById(R.id.progressbarVG);
            this.progressbarAVG = (ProgressBar) itemView.findViewById(R.id.progressbarAVG);
            this.progressbarP = (ProgressBar) itemView.findViewById(R.id.progressbarP);
            this.progressbarT = (ProgressBar) itemView.findViewById(R.id.progressbarT);
        }
    }


    public class CommentsHolder extends MainViewHolder {
        ImageView commentPhoto;
        TextView commentTitle, commentDate, comments, txtID;
        RatingBar commentRatingbar;

        public CommentsHolder(View itemView) {
            super(itemView);
            this.commentPhoto = (ImageView) itemView.findViewById(R.id.commentPhoto);
            this.commentTitle = (TextView) itemView.findViewById(R.id.commentTitle);
            this.commentDate = (TextView) itemView.findViewById(R.id.commentDate);
            this.comments = (TextView) itemView.findViewById(R.id.comments);
            this.txtID = (TextView) itemView.findViewById(R.id.txtID);
            this.commentRatingbar = (RatingBar) itemView.findViewById(R.id.commentRatingbar);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Global.getID = txtID.getText().toString();
                    Intent intent = new Intent(context, ViewComment.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);

                }
            });

        }
    }

    public class MainViewHolder extends RecyclerView.ViewHolder {
        public MainViewHolder(View itemView) {


            super(itemView);

        }
    }
}

I don't know what's causing the problem. I can use the same method on my fragments but in this adapter it's not working.

Patton answered 28/11, 2015 at 14:49 Comment(16)
post all of your code.Noach
As in log :Global cannot be cast to com.juandirection.ActivityCategorySelected . share Global codeResonator
Global is just Global variables.Patton
@JDev Cant post all of the codes because its too longPatton
@CharlesGalvez do you want to solve your problem or not ?Noach
@CharlesGalvez: extending any class in Global class?Resonator
@ρяσѕρєяK yes. I'm extending Application.Patton
@JDev sorry. wait, ill try to post it.Patton
@CharlesGalvez: That's why getting error. using TapHolder class in ActivityCategorySelected ?Resonator
I have posted my whole code in the adapter.Patton
@ρяσѕρєяK in my ActivityCategorySelected, The codes in tehre is just setting the adapter.(just like in normal ways.)Patton
How are you setting the adapter ?Noach
@CharlesGalvez: if using AdapterPOI in ActivityCategorySelected Activity then pass ActivityCategorySelected.this as first parameter when create object of AdapterPOI class. probably problem get resolveResonator
mRecyclerView = (RecyclerView) findViewById(R.id.rvPOI); adapter = new AdapterPOI(getApplicationContext(), poiDatas, favoriteDatas, commentDatas, imageDatas); mRecyclerView.setAdapter(adapter); mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));Patton
@CharlesGalvez: Change adapter = new AdapterPOI(getApplicationContext(), poiDatas, favoriteDatas, commentDatas, imageDatas); to adapter = new AdapterPOI(ActivityCategorySelected.this, poiDatas, favoriteDatas, commentDatas, imageDatas); Resonator
@ρяσѕρєяK Thank You! That's the problem. i just have to set the first paremeter of my adapter to ActivityCategorySelected.this. Thank You!Patton
N
3

Change

adapter = new AdapterPOI(getApplicationContext(), ....)

to

adapter = new AdapterPOI(this, ....)

in the code where you call the adapter's constructor. You get the error because getApplicationContext() cannot be casted to an ActivityCategorySelected. That's an Application context; whereas the adapter is expecting an Activity's context.

Noach answered 28/11, 2015 at 15:10 Comment(1)
Thank you! Excellent explanationSilage

© 2022 - 2024 — McMap. All rights reserved.