我已经阅读了很多STACK问题,并尝试实现所有可能的方法。但是我一直为

AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;


似乎对我没有任何帮助。长时间单击以尝试获取项目在recyclerview中的位置。

public class CheckOutstandingPayment extends AppCompatActivity {

ClsWebConnection oClsWeb = new ClsWebConnection();
DbConnection oDbCon;
private String strLeadID;
private ArrayList<String> arrayUniqueID = new ArrayList<>();
private ArrayList<String> arrayProdID = new ArrayList<>();
private ArrayList<String> arrayTotalAmt = new ArrayList<>();
private ArrayList<String> arrayOutstandAmt = new ArrayList<>();
private ArrayList<String> arrayProdName = new ArrayList<>();
private RecyclerView recyclerview;

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

    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

    oDbCon = new DbConnection(getApplicationContext());

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setTitle("Payment History");

    recyclerview = (RecyclerView) findViewById(R.id.recyclerview);
    LinearLayoutManager manager = new LinearLayoutManager(this);
    recyclerview.setLayoutManager(manager);
    recyclerview.addItemDecoration(new SimpleDividerItemDecoration(this));
    registerForContextMenu(recyclerview);

    strLeadID = getIntent().getStringExtra("LeadID");

    if (strLeadID == null) {
        strLeadID = DbConnection.strLeadID;
    }
    DisplayData();
}

@Override
protected void onResume() {
    super.onResume();
    DisplayData();
}

private void DisplayProduct() {
    SQLiteDatabase db = oDbCon.getReadableDatabase();
    for (int i = 0; i < arrayProdID.size(); i++) {
        Cursor prodCursor = db.rawQuery("SELECT PRODUCT_NAME FROM TBL_PRODUCT_MASTER WHERE PRODUCT_ID = '" + arrayProdID.get(i) + "'", null);
        if (prodCursor.getCount() > 0) {
            if (prodCursor.moveToFirst()) {
                do {
                    arrayProdName.add(prodCursor.getString(prodCursor.getColumnIndex("PRODUCT_NAME")));
                } while (prodCursor.moveToNext());
            }
        }
        prodCursor.close();
        db.close();
    }
}

private void DisplayData() {
    arrayUniqueID.clear();
    arrayProdID.clear();
    arrayTotalAmt.clear();
    arrayOutstandAmt.clear();
    arrayProdName.clear();

    if (ClsWebConnection.FunIsNetAvailable()) {
        try {
            String strGetData = oClsWeb.FunAddPayment1(DbConnection.strCustID, strLeadID);
            if (!strGetData.equalsIgnoreCase("NA")) {
                if (strGetData.contains("#")) {
                    String[] strHash = strGetData.split("#");
                    for (String Ahash : strHash) {
                        String[] strComa = Ahash.split(",");
                        arrayUniqueID.add(strComa[0]);
                        arrayProdID.add(strComa[1]);
                        arrayTotalAmt.add(strComa[2]);
                        arrayOutstandAmt.add(strComa[3]);

                        DisplayProduct();
                    }
                } else {
                    String[] strComa = strGetData.split(",");
                    arrayUniqueID.add(strComa[0]);
                    arrayProdID.add(strComa[1]);
                    arrayTotalAmt.add(strComa[2]);
                    arrayOutstandAmt.add(strComa[3]);

                    DisplayProduct();
                }
                RecyclerViewAdapter adapter = new RecyclerViewAdapter(getApplicationContext(), arrayUniqueID, arrayProdID, arrayTotalAmt, arrayOutstandAmt, arrayProdName);
                recyclerview.setAdapter(adapter);
            } else {
                Toast.makeText(getApplicationContext(), "No data available", Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "Oops! Something went wrong... Try again later", Toast.LENGTH_SHORT).show();
        }
    } else {
        Toast.makeText(getApplicationContext(), "Internet not connected", Toast.LENGTH_LONG).show();
        finish();
    }
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
    int index = info.position;
    switch (item.getItemId()) {
        case 1:
            Intent intent = new Intent(getApplicationContext(), AddPayment.class);
            DbConnection.strProdID = arrayProdID.get(info.position);
            DbConnection.strUniqueID = arrayUniqueID.get(info.position);
            startActivity(intent);
            break;
        case 2:
            Toast.makeText(getApplicationContext(), "2", Toast.LENGTH_SHORT).show();
            break;
    }
    return super.onContextItemSelected(item);
}

private class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {
    LayoutInflater inflater;
    private Context context;
    private ArrayList<String> arrayUniqueID = new ArrayList<>();
    private ArrayList<String> arrayProdID = new ArrayList<>();
    private ArrayList<String> arrayTotalAmt = new ArrayList<>();
    private ArrayList<String> arrayOutstandAmt = new ArrayList<>();
    private ArrayList<String> arrayProductName = new ArrayList<>();

    ContextMenu.ContextMenuInfo info;

    public RecyclerViewAdapter(Context context, ArrayList<String> arrayUniqueID, ArrayList<String> arrayProdID,
                               ArrayList<String> arrayTotalAmt, ArrayList<String> arrayOutstandAmt, ArrayList<String> arrayProductName) {
        this.context = context;
        this.arrayUniqueID = arrayUniqueID;
        this.arrayProdID = arrayProdID;
        this.arrayTotalAmt = arrayTotalAmt;
        this.arrayOutstandAmt = arrayOutstandAmt;
        this.arrayProductName = arrayProductName;
        inflater = LayoutInflater.from(context);
    }

    public RecyclerViewAdapter(){}

    @Override
    public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View layout = inflater.inflate(R.layout.payment_1_cell, null);
        return new RecyclerViewHolder(layout);
    }

    @Override
    public void onBindViewHolder(RecyclerViewHolder holder, int position) {
        holder.total_amt.setText("Total: Rs. " + arrayTotalAmt.get(position));
        holder.outstanding_amt.setText("Outstanding: Rs. " + arrayOutstandAmt.get(position));
        holder.prod_name.setText(arrayProductName.get(position));

    }

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

public class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener, View.OnClickListener {
    public TextView total_amt, outstanding_amt, prod_name;
    public LinearLayout linearLayout;

    public RecyclerViewHolder(View itemView) {
        super(itemView);
        itemView.setOnClickListener(this);
        itemView.setOnCreateContextMenuListener(this);
        total_amt = (TextView) itemView.findViewById(R.id.total_amt);
        outstanding_amt = (TextView) itemView.findViewById(R.id.outstanding_amt);
        prod_name = (TextView) itemView.findViewById(R.id.prod_name);
        linearLayout = (LinearLayout) itemView.findViewById(R.id.linearLayout);

    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(getApplicationContext(), AddPayment.class);
        DbConnection.strProdID = arrayProdID.get(getLayoutPosition());
        DbConnection.strUniqueID = arrayUniqueID.get(getLayoutPosition());
        startActivity(intent);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        menu.setHeaderTitle("Select option");
        menu.add(0, 1, 0, "Add Payment");
        menu.add(0, 2, 0, "View Details");
    }
  }
}


当我在recyclerview中长时间单击项目后选择任何选项时,下面将提到堆栈跟踪

03-09 01:52:00.827 24201-24201/com.syncnetic.agentdetails E/AndroidRuntime: FATAL EXCEPTION: main
                                                                        Process: com.syncnetic.agentdetails, PID: 24201
                                                                        java.lang.NullPointerException: Attempt to read from field 'int android.widget.AdapterView$AdapterContextMenuInfo.position' on a null object reference
                                                                            at com.syncnetic.agentdetails.CheckOutstandingPayment.onContextItemSelected(CheckOutstandingPayment.java:140)
                                                                            at android.app.Activity.onMenuItemSelected(Activity.java:2905)
                                                                            at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:361)
                                                                            at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:147)
                                                                            at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:100)
                                                                            at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:100)
                                                                            at com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback.onMenuItemSelected(PhoneWindow.java:4701)
                                                                            at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:761)
                                                                            at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
                                                                            at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:904)
                                                                            at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:894)
                                                                            at com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:167)
                                                                            at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:1082)
                                                                            at android.widget.AdapterView.performItemClick(AdapterView.java:305)
                                                                            at android.widget.AbsListView.performItemClick(AbsListView.java:1146)
                                                                            at android.widget.AbsListView$PerformClick.run(AbsListView.java:3053)
                                                                            at android.widget.AbsListView$3.run(AbsListView.java:3860)
                                                                            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)

最佳答案

我终于设法按您的要求获得了“选定商品ID”。

在这条线的情况下

AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;


menuinfo将始终为null,已被多次报告,但仍未解决。我很难找到所选列表项的位置,我会给你一些提示。

扩展View.OnLongClickListener

public  class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener, View.OnClickListener, View.OnLongClickListener


在ViewHolder内部分配setOnLongClickListener

 public ViewHolder(View v) {
            super(v);
            v.setOnCreateContextMenuListener(this);
            v.setOnLongClickListener(this);

        }


然后onLongClick看起来像这样

@Override
        public boolean onLongClick(View v) {
            recyclerViewClickListener.recyclerViewListClicked(this.getPosition());
            return false;
        }


其中recyclerViewClickListener是接口,recyclerViewListClicked是方法

public interface RecyclerViewClickListener
{
    public int recyclerViewListClicked(int position);
}


然后在您的Activity中创建一个globalVariable,它应该是一个类级变量,并在覆盖方法中设置其值,如下所示:

@Override
    public int recyclerViewListClicked(int position) {
        globalVariable = position;
        return position;
    }


然后,您可以将该globalVariable用作此处的选定项位置

 @Override
    public boolean onContextItemSelected(MenuItem item) {
        Log.d("mySelectedItem", ""+ globalVariable) //use the globalVariable as you need

        return super.onContextItemSelected(item);

    }

09-12 06:03