RecyclerView не обновляется после ввода - PullRequest
0 голосов
/ 23 мая 2019

Я сохраняю данные в MySql и хочу добавить функцию обновления в мои сохраненные заметки.Я показываю список заметок в обзоре переработчиков.При обновлении я реализовал функцию щелчка на моем просмотре карты, где он передает намерение обновлению.У меня проблема при обновлении одной строки заметки.Помогите, пожалуйста!

Я пытался реализовать метод adapter.notifyDataSetChanged в моей основной операции, но он все еще не обновляет обзор реселлера.

Main Adapter.java

public class MainAdapter extends RecyclerView.Adapter<MainAdapter.CustomViewHoler>{

    private Context context;
    private ArrayList<Note> noter;
    private ItemClickListener itemClickListener;
    private int INTENT_EDIT = 200;


    class CustomViewHoler extends RecyclerView.ViewHolder implements  View.OnClickListener {
        TextView tv_title, tv_note, tv_date;
         CardView card_item;
         ItemClickListener itemClickListener;

        CustomViewHoler(View view, ItemClickListener itemClickListener) {
            super(view);
            tv_title =view.findViewById(R.id.title);
            tv_note = view.findViewById(R.id.note);
            tv_date =  view.findViewById(R.id.date);
            card_item = view.findViewById(R.id.card_item);
            this.itemClickListener = itemClickListener;
        }

        @Override
        public void onClick(View v) {
            itemClickListener.onItemOnClick(v, getAdapterPosition());
        }
    }

    public MainAdapter(Context context, ArrayList<Note> noter) {
        this.context = context;
        this.noter = noter;
        }

    public void notify(ArrayList<Note> noter){
        if (noter != null){
            noter.clear();
            noter.addAll(noter);
        } else {
            noter = noter;
        }
        notifyDataSetChanged();
    }

    @NonNull

    @Override
    public CustomViewHoler onCreateViewHolder(@NonNull ViewGroup parent, final int viewType) {
        final View view = LayoutInflater.from(context).inflate(R.layout.item_note, parent, false);
        return new CustomViewHoler(view, itemClickListener);
    }

    @Override
    public void onBindViewHolder(@NonNull final CustomViewHoler holder, final int position) {
        final Note note = noter.get(position);
        holder.tv_title.setText( noter.get(position).getTitle());
      //  holder.tv_title.setText(note.getTitle());
        holder.tv_note.setText(note.getNote());
        //holder.tv_date.setText(note.getDate());

       holder.card_item.setCardBackgroundColor(note.getColor());

       holder.tv_date.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               Intent intent = new Intent(context, UpdateActivity.class);
               intent.putExtra("note_id", note.getId());
               intent.putExtra("title", noter.get(position).getTitle());
               intent.putExtra("note", noter.get(position).getNote());
               intent.putExtra("color", noter.get(position).getColor());
                context.startActivity(intent);
           }
       });

    }


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


    public interface ItemClickListener{
        void onItemOnClick(View view, int position);

        View.OnClickListener onItemOnClick();
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

    FloatingActionButton floatingActionButton;
    RecyclerView recyclerView;
    SwipeRefreshLayout swipeRefresh;

    RecyclerView.Adapter adapter;
    AdapterView.OnItemClickListener itemClickListener;
    ArrayList <Note> noter;
    private int INTENT_ADD = 100;


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

        noter = new ArrayList <>();

//      swipeRefresh = findViewById(R.id.swipe_refresh);
        recyclerView = findViewById(R.id.recyclerview);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new MainAdapter(MainActivity.this, noter);
        recyclerView.setAdapter(adapter);
        recyclerView.notify();




        retrieveData();
//        retrieveUpdatedData();

        floatingActionButton = findViewById(R.id.add);
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.add:
                        Intent intent = new Intent(getApplicationContext(), InsertActivity.class);
                        startActivityForResult(intent, INTENT_ADD);
                }
            }
        });
    }



    private void retrieveData() {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Retrieving data....");
        progressDialog.show();


        System.out.println("!!!!!!saving!!!!!!");
        StringRequest stringRequest = new StringRequest(Request.Method.GET,
                "http://my-noter.000webhostapp.com/notes.php",
                new Response.Listener <String>() {

                    @Override
                    public void onResponse(String s) {
                        progressDialog.dismiss();

                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONArray array = jsonObject.getJSONArray("notes");

                            for (int i = 0; i < array.length(); i++) {
                                JSONObject row = array.getJSONObject(i);
                                Note note = new Note(
                                        row.getInt("note_id"),
                                        row.getString("title"),
                                        row.getString("note"),
                                        row.getInt("color")
                                );
                                noter.add(note);

                            }

                            adapter.notifyDataSetChanged();


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        System.out.println("volleyError error" + error.getMessage());
                        Toast.makeText(getApplicationContext(), "Poor network connection.", Toast.LENGTH_LONG).show();
                    }


                }) {
        };

        RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
        requestQueue.add(stringRequest);


    }


    private void retrieveUpdatedData() {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Retrieving Updateddata....");
        progressDialog.show();


        System.out.println("!!!!!!!!updating!!!!!!!");
        StringRequest stringRequest = new StringRequest(Request.Method.GET,
                "http://my-noter.000webhostapp.com/selectAll.php",
               new Response.Listener <String>() {

                    @Override
                    public void onResponse(String response) {
                        progressDialog.dismiss();

                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray array = jsonObject.getJSONArray("notes");


                            for (int i = 0; i < array.length(); i++) {

                                JSONObject object = array.getJSONObject(i);

                                Note note = new Note(
                                        object.getInt("note_id"),
                                        object.getString("title"),
                                        object.getString("note"),
                                        object.getInt("color")
                                );
                                noter.add(note);
                            }


                            adapter.notifyDataSetChanged();


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        System.out.println("volleyError error" + error.getMessage());
                        Toast.makeText(getApplicationContext(), "Poor network connection.", Toast.LENGTH_LONG).show();
                    }
                });


        RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
       requestQueue.add(stringRequest);
    }


    @Override
    public void onResume() {
        super.onResume();
        // put your code here...
        adapter.notifyItemRangeChanged(0, adapter.getItemCount());
//        retrieveData();
//        retrieveUpdatedData();
    }

}

UpdateActivity.java

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

        et_title = findViewById(R.id.title);
        et_note = findViewById(R.id.note);


        note_id = getIntent().getIntExtra("note_id", 0);
        title = getIntent().putExtra("title", title);
        note = getIntent().putExtra("note", note);
        color = getIntent().getIntExtra("color", 0);


        mSpectrumPalette = findViewById(R.id.palette);

        mSpectrumPalette.setHorizontalScrollBarEnabled(true);
        mSpectrumPalette.setFixedColumnCount(17);


        mSpectrumPalette.setOnColorSelectedListener(new SpectrumPalette.OnColorSelectedListener() {
            @Override
            public void onColorSelected(@ColorInt int color) {
                selectedColor = color;
            }
        });

        noter = new ArrayList<>();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_update, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.update:
                //Update
                final int id = this.note_id();
                final String title = et_title.getText().toString().trim();
                final String note = et_note.getText().toString().trim();
                final int color = selectedColor;

                if (title.isEmpty()) {
                    et_title.setError("Please enter a title");
                } else if (note.isEmpty()) {
                    et_note.setError("Please enter a note");
                } else {

                    final StringRequest stringRequest = new StringRequest(Request.Method.POST,
                            "http://my-noter.000webhostapp.com/update.php",
                            new Response.Listener <String>() {
                        @Override
                        public void onResponse(String response) {

                            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                            startActivity(intent);


                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                        }
                    }) {
                        @Override
                        protected Map <String, String> getParams() {
                            Map <String, String> params = new HashMap <>();
                            params.put("note_id", String.valueOf(id));
                            params.put("title", title);
                            params.put("note", note);
                            params.put("color", String.valueOf(color));
                            return params;
                        }


                    };
                    final RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
                    requestQueue.add(stringRequest);
                }
                return true;

            //Delete
            case R.id.delete:

                final StringRequest stringRequest2 = new StringRequest(Request.Method.POST, "http://my-noter.000webhostapp.com/delete.php", new Response.Listener <String>() {
                    @Override
                    public void onResponse(String response) {
                        Toast.makeText(getApplicationContext(), "Successfully Deleted!", Toast.LENGTH_LONG).show();

                        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(intent);

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

                    }
                }) {
                    @Override
                    protected Map <String, String> getParams() {
                        Map <String, String> params = new HashMap <>();
//                        params.put("note_id", String.valueOf(note_id));
                        return params;
                    }
                };
                final RequestQueue requestQueue2 = Volley.newRequestQueue(getApplicationContext());
                requestQueue2.add(stringRequest2);

                AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
                alertDialog.setTitle("Confirm !");
                alertDialog.setMessage("Are you sure?" );
                alertDialog.setNegativeButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        requestQueue2.stop();
                    }
                });
                alertDialog.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                alertDialog.show();


                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private int note_id() {
        return note_id;
    }
}
` Update.PHP``
`<?php

if($_SERVER['REQUEST_METHOD'] == 'POST'){
    $note_id = $_POST['id'];
    $title = $_POST['title'];
    $note = $_POST['note'];
    $color = $_POST['color'];


    require_once('connect.php');

    $query = "UPDATE `noter`  SET `title`='$title', `note`='$note', `color`=' $color' WHERE 'id'=$note_id ";




    if( mysqli_query($conn, $query) ) {

        $response['success'] = true;
        $response['message'] = "Successfully";

    } else {  

        $response['success'] = false;
        $response['message'] = "Failure!";

    }

} else {
        $response['success'] = false;
        $response['message'] = "Error!";
}


echo json_encode($response);

?>`

`SelectAll.PHP

<?php

header("Content-type:application/json");

     require_once('connect.php');

    $query =mysqli_query($conn, "SELECT * FROM `noter`");

    $response["notes"] = array();

while( $row = mysqli_fetch_assoc($query)){
     $notes = array();
        $notes ["note_id"] = $row["id"];
        $notes ["title"] = $row["title"];
        $notes ["note"] = $row["note"];
        $notes ["color"] = $row["color"];

array_push($response["notes"], $notes);
}


echo json_encode($response);

?>
    ``

1 Ответ

0 голосов
/ 23 мая 2019

В вашем коде вы ссылаетесь на List объект как noter только внутри метода, поэтому ваши изменения не применяются к глобальному объекту noter.попробуйте изменить, как показано ниже:

public void notify(ArrayList noter){
        if (this.noter != null){
            this.noter.clear();
            this.noter.addAll(noter);
        } else{
            this.noter = noter;
        }
        notifyDataSetChanged();
    }
...