Несколько кнопок RecycleView должны удерживать идентификатор пользователя из залпа и отправлять идентификатор пользователя в базу данных при нажатии кнопок

Я создал RecyclerView с несколькими кнопками. Обе кнопки будут удерживать user_id, используя залп с PHP и MySQL. Но я не могу отправить идентификатор пользователя при нажатии кнопки конкретного пользователя. Я много пробовал, но не смог этого сделать.

Собственно, есть 2 пользователя с картинками и по две кнопки у каждого. Каждая кнопка заполнена user_id из базы данных Mysql с использованием PHP. Функциональность заключается в том, что когда я нажимаю кнопку, user_id конкретного пользователя должен перейти в базу данных и обновить ее, чего не происходит. Подскажите, если кто знает, как решить проблему.



public class MainActivity extends AppCompatActivity  {
    //this is the JSON Data URL
    //make sure you are using the correct ip else it will not work
    private static final String URL_PRODUCTS = "http://192.168.10.119/staradmin/andcustomerrequest.php";

    //a list to store all the products
    List<CustomerRequest> productList;

    //the recyclerview
    RecyclerView recyclerView;
    CustomerRequestAdapter adapter;
    private RecyclerView mList;
    private LinearLayoutManager linearLayoutManager;
    RecyclerView.LayoutManager layoutManager;
    TextView textView;


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

        productList = new ArrayList<>();
        recyclerView = (RecyclerView) findViewById(R.id.recycleView);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
        adapter = new CustomerRequestAdapter(MainActivity.this, productList);
        recyclerView.setAdapter(adapter);

        loadProducts();

    }


    private void loadProducts(){

        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {
                            JSONArray products = new JSONArray(response);
                            for(int i=0; i<products.length();i++){
                                JSONObject productObject = products.getJSONObject(i);
                                String user_id = productObject.getString("user_id");
                                String name = productObject.getString("name");
                                String price = productObject.getString("price");
                                //  String city = productObject.getString("city");
                                String image = productObject.getString("image");
                                String outletname = productObject.getString("outletname");

                                CustomerRequest product = new CustomerRequest(user_id,name,price,image,outletname);
                                productList.add(product);

                            }

                            //   adapter = new ProductAdapter(MainActivity.this,productList);
                            recyclerView.setAdapter(adapter);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this,error.getMessage(),Toast.LENGTH_SHORT).show();

            }
        });

        Volley.newRequestQueue(this).add(stringRequest);
    }



}
----------------------------
adapterclass
public class CustomerRequestAdapter extends RecyclerView.Adapter<CustomerRequestAdapter.ProductViewHolder>  {
    private Context mCtx;
    private List<CustomerRequest> customerRequestList;
    //HashMap<String,String> modelList;

    private static final String URL_PRODUCTS = "http://192.168.10.119/staradmin/andcustomeradd.php";

    String UseridHolder;





    public CustomerRequestAdapter(Context mCtx, List<CustomerRequest> customerRequestList) {
        this.mCtx = mCtx;
        this.customerRequestList = customerRequestList;
       // this.modelList = modelList;
    }


    @NonNull
    @Override
    public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(mCtx);
        View view = inflater.inflate(R.layout.custrequest, null);
        return new ProductViewHolder(view);
    }


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

        final CustomerRequest customerRequest = customerRequestList.get(position);

        //loading the image
        Glide.with(mCtx)
                .load(customerRequest.getImage())
                .into(holder.imageView);
        holder.textViewId.setText(customerRequest.getUser_id());
        holder.textViewTitle.setText(customerRequest.getName());
        holder.textViewPrice.setText(customerRequest.getPrice());
        holder.textViewPrice.setText(customerRequest.getCity());
        holder.textViewOutlet.setText(customerRequest.getOutletname());


        holder.accept.setTag(R.id.accept);
        holder.reject.setTag(R.id.reject);

       holder.accept.setOnClickListener(new View.OnClickListener() {
           String  i = customerRequest.getUser_id();

           @Override
           public void onClick(View v) {
           final String   URL_PRODUCTS = "http://192.168.10.119/staradmin/andcustomeradd.php";

               final String i = customerRequest.getUser_id();
               UseridHolder = i.toString().trim();

              // Toast.makeText(mCtx,UseridHolder,Toast.LENGTH_LONG).show();
               //Toast.makeText(mCtx,String.valueOf(i),Toast.LENGTH_LONG).show();
               //  Intent intent = new Intent(mCtx,MainActivity.class);
               // intent.putExtra("user_id",customerRequest.getUser_id());
               //  mCtx.startActivity(intent);

               StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_PRODUCTS,
                       new Response.Listener<String>() {
                           @Override
                           public void onResponse(String response) {

                               if (response.contains("true")){
                                   Toast.makeText(mCtx,response,Toast.LENGTH_LONG).show();
                               }else{
                                   Toast.makeText(mCtx,"hello",Toast.LENGTH_LONG).show();
                               }

                           }
                       }, new Response.ErrorListener() {
                   @Override
                   public void onErrorResponse(VolleyError error) {
                       Toast.makeText(mCtx,error.getMessage(),Toast.LENGTH_LONG).show();
                   }
               }
               ){

                   @Override
                   protected Map<String, String> getParams() throws AuthFailureError {
                       Map<String, String> params = new HashMap<String, String>();
                       params.put("i",UseridHolder);
                       return params;
                   }
               };

               Volley.newRequestQueue(mCtx).add(stringRequest);
           }

       });


        holder.reject.setOnClickListener(new View.OnClickListener() {
            String k = customerRequest.getUser_id();
            @Override
            public void onClick(View v) {
                Toast.makeText(mCtx,String.valueOf(k),Toast.LENGTH_LONG).show();
            }
        });


    }

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


    class ProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        TextView textViewTitle, textViewPrice, textViewOutlet, textViewId;
        ImageView imageView;
        Button accept, reject;

        RelativeLayout parentLayout;

        public ProductViewHolder(@NonNull View itemView) {
            super(itemView);

            textViewTitle = itemView.findViewById(R.id.textViewTitle);
            textViewPrice = itemView.findViewById(R.id.textViewPrice);
            textViewOutlet = itemView.findViewById(R.id.textViewOutlet);
            textViewId = itemView.findViewById(R.id.textViewId);
            imageView = itemView.findViewById(R.id.imageView);
            accept = itemView.findViewById(R.id.accept);
            reject = itemView.findViewById(R.id.reject);


        }

        @Override
        public void onClick(View v) {

        }
    }

}
-----------------
class
public class CustomerRequest {

    private String user_id;
    private String name,city,price,outletname;
  //  double price;
    private String image;

    public CustomerRequest(String user_id, String name, String price, String image, String outletname) {
        this.name = name;
        this.city = city;
        this.image = image;
        this.price = price;
        this.outletname = outletname;
        this.user_id = user_id;
    }

    public String getName() {
        return name;
    }

    public String getCity() {
        return city;
    }

    public String getPrice() {
        return price;
    }

    public String getImage() {
        return image;
    }

    public String getOutletname() {
        return outletname;
    }

    public String getUser_id() {
        return user_id;
    }
}
0
0
32
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Попробуйте это. Либо ваша проблема в том, что вы не можете получить идентификатор, когда пользователь нажимает кнопку, либо проблема при отправке данных.

class ProductViewHolder extends RecyclerView.ViewHolder{

    TextView textViewTitle, textViewPrice, textViewOutlet, textViewId;
    ImageView imageView;
    Button accept, reject;

    RelativeLayout parentLayout;

    public ProductViewHolder(@NonNull View itemView) {
        super(itemView);

        textViewTitle = itemView.findViewById(R.id.textViewTitle);
        textViewPrice = itemView.findViewById(R.id.textViewPrice);
        textViewOutlet = itemView.findViewById(R.id.textViewOutlet);
        textViewId = itemView.findViewById(R.id.textViewId);
        imageView = itemView.findViewById(R.id.imageView);
        accept = itemView.findViewById(R.id.accept);
        reject = itemView.findViewById(R.id.reject);


       accept.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //send the id
                customerRequest.getUser_id();
            }
        });

    }
}

Пожалуйста, дайте мне знать после того, как вы попробуете это, я сделал эту концепцию до @Sunil

Brahma Datta 22.05.2019 09:24

Здравствуйте, сэр Брахма, я получаю идентификатор пользователя. Моя проблема не может отправить этот идентификатор пользователя в базу данных. Только нулевые значения достигают php, и мой sql

Sunil Kumar Reddy 24.05.2019 14:09

сэр. Проверено, что ваш код customerrequest.getuser id не работает.

Sunil Kumar Reddy 24.05.2019 14:26

Вы четко получаете данные с сервера? @SunilKumarReddy

Brahma Datta 24.05.2019 14:28

Если getUserId не работает, проблема может быть связана с сервером или у вас возникла проблема с получением этого идентификатора с сервера @SunilKumarReddy

Brahma Datta 24.05.2019 14:35

Я получаю данные с сервера вышеholder.accept (на держателе bindview). Но я не могу передать его в базу данных, используя хэш-карту в файле адаптера.

Sunil Kumar Reddy 24.05.2019 15:08

вы не устанавливаете идентификатор в классе модели. Вы используете методы get, но не методы set. Тогда как вы можете получить идентификатор, не устанавливая идентификатор в CustomerRequest @SunilKumarReddy

Brahma Datta 24.05.2019 20:06

Спасибо за помощь. Проблема решена. Теперь это работает

Sunil Kumar Reddy 25.05.2019 08:46

Другие вопросы по теме