简体   繁体   English

无法在适配器中使用意图

[英]Unable to use intent in adapter

While firing Intent finish activity i am getting this error 触发Intent finish活动时,出现此错误

03-20 11:05:16.991 8566-8566/com.example.jenya1.ebilling E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: com.example.jenya1.ebilling, PID: 8566
                                                                       java.lang.ClassCastException: droidninja.filepicker.FilePickerDelegate cannot be cast to android.app.Activity
                                                                           at com.example.jenya1.ebilling.adapter.MaterialAdapter$1$1.onClick(MaterialAdapter.java:142)
                                                                           at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                           at android.os.Looper.loop(Looper.java:164)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

This line causing error 这行导致错误

((Activity)mContext).finish();    //error

calling apapter class 调用适配器类

private void loadMaterialRequest() {

    final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
    //getting the progressbar

    //making the progressbar visible
    progressBar.setVisibility(View.VISIBLE);

    albumList.clear();

    //creating a string request to send request to the url
    StringRequest stringRequest = new StringRequest(Request.Method.GET, HttpUrl+token+"&type="+type,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    //hiding the progressbar after completion
                    progressBar.setVisibility(View.INVISIBLE);

                    try {
                        //getting the whole json object from the response
                        JSONObject obj = new JSONObject(response);

                        JSONArray heroArray = obj.getJSONArray("response");

                        //now looping through all the elements of the json array
                        for (int i = 0; i < heroArray.length(); i++) {
                            //getting the json object of the particular index inside the array
                            JSONObject heroObject = heroArray.getJSONObject(i);

                            //creating a hero object and giving them the values from json object
                            Material hero = new Material(
                                    heroObject.getInt("Request_id"),
                                    heroObject.getString("Site_name"),
                                    heroObject.getString("User_id"),
                                    heroObject.getString("Item_name"),
                                    heroObject.getString("Quantity"),
                                    heroObject.getString("Country"),
                                    heroObject.getString("Request_date"),
                                    heroObject.getString("Request_status"));

                            //adding the hero to herolist
                            albumList.add(hero);
                        }
                        //Log.e("list", String.valueOf(albumList));
                        //creating custom adapter object
                        adapter = new MaterialAdapter(getApplicationContext(),albumList);

                        //adding the adapter to listview
                        recyclerView.setAdapter(adapter);

                    } catch (JSONException e) {

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

                    Log.e("error", String.valueOf(error));

                }
            });

    //creating a request queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    //adding the string request to request queue
    requestQueue.add(stringRequest);
}

I am trying to Intent when user click on alert dialog yes button 当用户单击警报对话框的“是”按钮时,我试图显示Intent

This is my adapter class: 这是我的适配器类:

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.jenya1.ebilling.MaterialHistoryActivity;
import com.example.jenya1.ebilling.R;
import com.example.jenya1.ebilling.model.HistoryQuotation;
import com.example.jenya1.ebilling.model.Material;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Mitesh Makwana on 18/03/18.
 */
public class MaterialAdapter extends RecyclerView.Adapter<MaterialAdapter.MyViewHolder> {

    private Context mContext;
    private List<Material> albumList;
    private List lstfavquoteid;


    String quote_id;
    ArrayList<Integer> arryfavquoteid;

    Typeface tf;
    ArrayList<String> imageserver,imageList;
    int count;

    int status=0;
    private int mExpandedPosition=-1;

    public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView title,quantity,site,date,note,req_id,status;

    ImageView delete;
    LinearLayout lndetail,lnapprove,lnreject,lnoperation;
    CardView cdview;

    public MyViewHolder(View view) {
        super(view);

        title = (TextView) view.findViewById(R.id.txttitle);
        req_id = (TextView) view.findViewById(R.id.txtreqid);
        quantity = (TextView) view.findViewById(R.id.txtquantity);
        date = (TextView) view.findViewById(R.id.txtdate);
        site = (TextView) view.findViewById(R.id.txtsite);
        note = (TextView) view.findViewById(R.id.txtnotes);
        status = (TextView) view.findViewById(R.id.txtstatus);

        delete=(ImageView)view.findViewById(R.id.imgmdelete);

        lndetail = (LinearLayout) view.findViewById(R.id.lndetails);
        lnapprove = (LinearLayout) view.findViewById(R.id.lnapprove);
        lnreject = (LinearLayout) view.findViewById(R.id.lnreject);
        lnoperation = (LinearLayout) view.findViewById(R.id.lnstatusoperation);
        cdview = (CardView) view.findViewById(R.id.card_view);
    }
    }

    public MaterialAdapter(Context mContext, List<Material> albumList) {
    this.mContext = mContext;
    this.albumList = albumList;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.raw_material_history, parent, false);

    return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int position) {

    arryfavquoteid = new ArrayList<Integer>();
    imageserver = new ArrayList<String>();

    tf = Typeface.createFromAsset(mContext.getAssets(), "fonts/HKNova-Medium.ttf");
    holder.title.setTypeface(tf);
    holder.req_id.setTypeface(tf);
    holder.quantity.setTypeface(tf);
    holder.date.setTypeface(tf);
    holder.site.setTypeface(tf);
    holder.note.setTypeface(tf);

    final Material album = albumList.get(position);

    holder.title.setText(album.getItem_name());
    holder.req_id.setText("#"+album.getId());
    holder.quantity.setText(album.getQuantity());
    holder.site.setText(album.getSite_id());

    String  input = album.getRequest_date();
    input = input.replace(" ", "\n");
    holder.date.setText(input);
    holder.note.setText("Notes : "+album.getCountry());

    holder.delete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
//                Toast.makeText(mContext, "Delete...", Toast.LENGTH_SHORT).show();
            AlertDialog.Builder alert = new AlertDialog.Builder(
                    view.getContext());
            alert.setTitle("Alert!!");
            alert.setMessage("Are you sure to delete record");
            alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    MaterialHistoryActivity.deleterequest(mContext,album.getId());

                    notifyDataSetChanged();

                    Intent i=new Intent(mContext,MaterialHistoryActivity.class);
                    mContext.startActivity(i);
                    ((Activity)mContext).finish();    //error

                    dialog.dismiss();

                }
            });
            alert.setNegativeButton("NO", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            alert.show();
        }
    });
    if (mExpandedPosition == position) {

        if(album.getRequest_status().equals("1"))
        {
            holder.status.setText("Approved");
            holder.status.setVisibility(View.VISIBLE);
            holder.status.setTextColor(Color.GREEN);
            holder.lnoperation.setVisibility(View.GONE);
        }else if(album.getRequest_status().equals("2"))
        {
            holder.status.setText("Rejected");
            holder.status.setVisibility(View.VISIBLE);
            holder.status.setTextColor(Color.RED);
            holder.lnoperation.setVisibility(View.GONE);
        }
        else
        {
            holder.status.setVisibility(View.GONE);
            holder.lnoperation.setVisibility(View.VISIBLE);
        }

        //creating an animation
        Animation slideDown = AnimationUtils.loadAnimation(mContext, R.anim.slide_down);

        //toggling visibility
        holder.lndetail.setVisibility(View.VISIBLE);

        //adding sliding effect
        holder.lndetail.startAnimation(slideDown);
    }
    else
    {
        holder.lndetail.setVisibility(View.GONE);
    }

    holder.cdview.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            //getting the position of the item to expand it
            mExpandedPosition = position;

            //reloding the list
            notifyDataSetChanged();
        }
    });


    holder.lnapprove.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
//                Toast.makeText(mContext, "Approve...", Toast.LENGTH_SHORT).show();
            MaterialHistoryActivity.materialpermission(mContext,album.getId(),1);
        }
    });

    holder.lnreject.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
//                Toast.makeText(mContext, "Reject...", Toast.LENGTH_SHORT).show();
            MaterialHistoryActivity.materialpermission(mContext,album.getId(),2);

        }
    });

    }

    @Override
    public int getItemCount() {
    return albumList.size();
    }
}

Any help would be highly appreciated. 任何帮助将不胜感激。

let see: 让我们看看:

((Activity)mContext).finish(); 

The log say mContext is kind of FilePickerDelegate. 日志中说mContext是FilePickerDelegate的一种。 So check your Adapter init function. 因此,请检查您的适配器初始化功能。 I think you pass context as "this", but "this" reference to FilePickerDelegate. 我认为您将上下文传递为“ this”,但是对FilePickerDelegate的“ this”引用。 So change it to YourActivity.this ( with activity) or getActivity( in fragment) 因此,将其更改为YourActivity.this(带有活动)或getActivity(在片段中)

You are passing the Application Context not the Activity Context in your adapter. 您正在适配器中传递应用程序上下文而不是活动上下文。

getApplicationContext(); getApplicationContext(); Wherever you are passing it pass this or ActivityName.this instead. 无论您在哪里传递它,都传递this或ActivityName.this。

Since you are trying to cast the Context you pass (Application not Activity as you thought) to an Activity with 由于您尝试投射上下文,因此您将传递(应用程序不是您想的那样的活动)传递给

(Activity) you get this exception because you can't cast the Application to Activity since Application is not a sub-class of Activity. (活动)您会收到此异常,因为您不能将应用程序强制转换为活动,因为应用程序不是活动的子类。

Instead of Context use Activity in your adapter. 在适配器中使用活动来代替上下文。 As Activity can be cast to context but context can not be cast to activity. 因为可以将活动强制转换为上下文,但是不能将上下文强制转换为活动。

Activity avtivity;

public MaterialAdapter(Activity activity, List<Material> albumList) {
this.activity = activity;
this.albumList = albumList;
}

In your calling activity when you initialize your adapter Call this adapter like below. 在初始化适配器时进行的呼叫活动中,按如下所示呼叫此适配器。

new MaterialAdapter(<your calling activity>.this, yourList);
view.getContext().startActivity(new Intent(mContext, MaterialHistoryActivity.class));               

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM