Deleting issue from Room Database - java

I have an issue deleting item from app. It,s Actually a notes app in which i have created a AlertDialog function that deletes notes. here is code for my function
private void showDeleteDialog(int position) {
AlertDialog.Builder alert = new AlertDialog.Builder(context)
.setTitle("Delete view")
.setMessage("Are you sure to delete")
.setIcon(R.drawable.ic_baseline_delete_24)
.setPositiveButton("yes", (dialogInterface, i) -> databaseHelper.notesDao().deleteNotes(new Notes(arrNotes.get(position).id, arrNotes.get(position).title, arrNotes.get(position).text)))
.setNegativeButton("No", (dialogInterface, i) -> {
});
alert.show();
}
Here i call it
holder.llView.setOnLongClickListener(view -> {
showDeleteDialog(position);
return true;
});
When i click yes then app crashed but it succuessfully delets notes from database.This is the error i got
java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder{a4d7d56 position=1 id=-1, oldPos=0, pLpos:0 scrap [attachedScrap] tmpDetached no parent} androidx.recyclerview.widget.RecyclerView{815f028 VFED..... ......I. 31,171-689,776 #7f090165 app:id/recycler_view}, adapter:com.example.keepnotes.RecyclerViewAdapter#773a141, layout:androidx.recyclerview.widget.StaggeredGridLayoutManager#a3a6e6, context:com.example.keepnotes.MainActivity#3065e55
All of this is in RecyclerView Adapter. The code for recyclerView adapter is following
package com.example.keepnotes;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
ArrayList<Notes> arrNotes;
DatabaseHelper databaseHelper;
private RecyclerView.RecyclerListener listener;
RecyclerViewAdapter(Context context, ArrayList<Notes> arrNotes, DatabaseHelper databaseHelper) {
this.context = context;
this.arrNotes = arrNotes;
this.databaseHelper = databaseHelper;
}
public RecyclerViewAdapter(ArrayList<Notes> arrNotes, RecyclerView.RecyclerListener listener) {
this.arrNotes = arrNotes;
this.listener = listener;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.single_view, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, #SuppressLint("RecyclerView") int position) {
holder.title.setText(arrNotes.get(position).title);
holder.body.setText(arrNotes.get(position).text);
holder.index.setText(String.valueOf(position + 1));
holder.llView.setOnClickListener(view -> {
Intent iNext = new Intent(context, ViewActivity.class);
iNext.putExtra("title", arrNotes.get(position).title);
iNext.putExtra("text", arrNotes.get(position).text);
context.startActivity(iNext);
});
holder.llView.setOnLongClickListener(view -> {
showDeleteDialog(position);
return true;
});
}
#Override
public int getItemCount() {
return arrNotes.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView title, body, index;
CardView llView;
public ViewHolder(View itemView) {
super(itemView);
title = itemView.findViewById(R.id.text_title_view);
body = itemView.findViewById(R.id.text_text_view);
index = itemView.findViewById(R.id.index);
llView = itemView.findViewById(R.id.card_View);
databaseHelper = DatabaseHelper.getDatabase(context);
}
}
private void showDeleteDialog(int position) {
AlertDialog.Builder alert = new AlertDialog.Builder(context)
.setTitle("Delete view")
.setMessage("Are you sure to delete")
.setIcon(R.drawable.ic_baseline_delete_24)
.setPositiveButton("yes", (dialogInterface, i) -> databaseHelper.notesDao().deleteNotes(new Notes(arrNotes.get(position).id, arrNotes.get(position).title, arrNotes.get(position).text)))
.setNegativeButton("No", (dialogInterface, i) -> {
});
alert.show();
}
}
How can i get rid of this error????

It is Solved, Actually, in Live Data, I was using notifyiteminserted, I changed that to notifyDataSetChnaged.

Related

List not updating after Filtering with searchView

I implemented searchView in android which filters data. It works correctly But after filtering data, when I add new data it does not show in recyclerView when I restart the app then it shows, I am also able to view that item after again searching something and then backspace it.
Here is My Adapter Class
package com.example.keepnotes;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
ArrayList<Notes> arrNotes;
DatabaseHelper databaseHelper;
RecyclerViewAdapter(Context context, ArrayList<Notes> arrNotes, DatabaseHelper databaseHelper) {
this.context = context;
this.arrNotes = arrNotes;
this.databaseHelper = databaseHelper;
}
public void setFilteredList(ArrayList<Notes> filteredList) {
this.arrNotes = filteredList;
notifyDataSetChanged();
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.single_view, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, #SuppressLint("RecyclerView") int position) {
holder.title.setText(arrNotes.get(position).title);
holder.body.setText(arrNotes.get(position).text);
holder.index.setText(String.valueOf(position + 1));
holder.llView.setOnClickListener(view -> {
Intent iNext = new Intent(context, ViewActivity.class);
iNext.putExtra("title", arrNotes.get(position).title);
iNext.putExtra("text", arrNotes.get(position).text);
iNext.putExtra("id", arrNotes.get(position).id);
context.startActivity(iNext);
});
holder.llView.setOnLongClickListener(view -> {
showDeleteDialog(position);
return true;
});
}
#Override
public int getItemCount() {
return arrNotes.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView title, body, index;
CardView llView;
public ViewHolder(View itemView) {
super(itemView);
title = itemView.findViewById(R.id.text_title_view);
body = itemView.findViewById(R.id.text_text_view);
index = itemView.findViewById(R.id.index);
llView = itemView.findViewById(R.id.card_View);
databaseHelper = DatabaseHelper.getDatabase(context);
}
}
private void showDeleteDialog(int position) {
AlertDialog.Builder alert = new AlertDialog.Builder(context)
.setTitle("Delete view")
.setMessage("Are you sure to delete")
.setIcon(R.drawable.ic_baseline_delete_24)
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
databaseHelper.notesDao().deleteNotes(new Notes(arrNotes.get(position).getId(), arrNotes.get(position).getTitle(), arrNotes.get(position).getText()));
}
})
.setNegativeButton("No", (dialogInterface, i) -> {
});
alert.show();
}
}
Here is My filterable function
private void filterList(String text) {
ArrayList<Notes> filteredList = new ArrayList<>();
for (Notes notes : arrNotes) {
if (notes.title.toLowerCase().contains(text.toLowerCase()) || notes.text.toLowerCase().contains(text.toLowerCase())) {
filteredList.add(notes);
}
if (!(filteredList.isEmpty())) {
adapter.setFilteredList(filteredList);
}
}
}
Here I implemented SearchView
searchView = findViewById(R.id.searchView);
searchView.clearFocus();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
filterList(newText);
return false;
}
});
I updated data using live data using this
modelView = new ViewModelProvider(this).get(notesModelView.class);
modelView.getAllNotes().observe(this, new Observer<List<Notes>>() {
#Override
public void onChanged(List<Notes> notes) {
arrNotes.clear();
arrNotes.addAll(notes);
adapter.notifyDataSetChanged();
}
});
Modify your filterList() function like this -
private void filterList(String text) {
if (!text.trim().isEmpty()) {
ArrayList<Notes> filteredList = new ArrayList<>();
for (Notes notes : arrNotes) {
if (notes.title.toLowerCase().contains(text.toLowerCase()) || notes.text.toLowerCase().contains(text.toLowerCase())) {
filteredList.add(notes);
}
adapter.setFilteredList(filteredList);
}
}else{
adapter.setFilteredList(arrNotes);
}
}

How to create dialog box when click on the item of recyclerview?

I'm trying to create a function that once a user clicks on the recycler view, a dialog box will pop out but I am stuck on the error as mentioned below. When I try to initialize AlertDialog.build and put this as the parameter, it shows an error. I had tried with a few other parameters like context, getActivity. But the error is still the same.
The code below is my full code
package com.example.tuitioncentre;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Observable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.firestore.DocumentSnapshot;
public class myadapter_tutorlist extends FirebaseRecyclerAdapter<User,myadapter_tutorlist.myviewholder> {
AlertDialog.Builder builder;
public myadapter_tutorlist(#NonNull FirebaseRecyclerOptions<User> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull final myviewholder holder, int position, #NonNull final User model) {
holder.name.setText("Tutor's Name:" + model.getUsername());
holder.phone.setText("Phone No:" + model.getPhone());
holder.email.setText("Email:" + model.getEmail());
holder.status.setText("Status: " + model.getActive().toString());
builder = new AlertDialog.Builder(this);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
//Toast.makeText(v.getContext(),model.getUsername(),Toast.LENGTH_SHORT).show();
builder.setMessage(R.string.dialog_message) .setTitle(R.string.dialog_title);
builder.setMessage("Do you want to activate tutor account ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(v.getContext(),"you choose yes action for alertbox", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
dialog.cancel();
Toast.makeText(v.getContext(),"you choose no action for alertbox", Toast.LENGTH_SHORT).show();
}
});
//Creating dialog box
AlertDialog alert = builder.create();
//Setting the title manually
alert.setTitle("AlertDialogExample");
alert.show();
}
});
}
#NonNull
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//put singlerow xml into view holder
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.singlerow,parent,false);
return new myviewholder(view);
}
class myviewholder extends RecyclerView.ViewHolder{
TextView name,phone,email,status;
public myviewholder(#NonNull View itemView) {
super(itemView);
name=(TextView)itemView.findViewById(R.id.nametext);
phone=(TextView)itemView.findViewById(R.id.phonetext);
email=(TextView)itemView.findViewById(R.id.emailtext);
status=(TextView)itemView.findViewById(R.id.statustext);
}
}
}
Passing "this" to AlertDialog.Builder(this); won't work as you're trying to pass a reference of your Adapter.
There are two correct ways to achieve this:
Add a variable to reference your Activity like Activity mActivity; in your Adapter class. Then, in your Activity class where you're initializing the Adapter, you can pass your activity context as "this". You can achieve it either with a constructor in the Adapter class or in your Activity class use your adapter instance once it is initialized to access the mActivity variable and set it.
Alternatively, you can use a view interface and implement it in your activity, override the method to show the AlertDialog in your activity. Then add a reference variable of that interface in your Adapter like SomeInterface mInfterface; and initialize it in your Activity class the same way mentioned above. Then you can just call that method to show the AlertDialog and pass the data to that method from the Adapter to show all information like -
mInterface.showAlertDialog(model);
first create this class:
class RecyclerItemClickListener extends RecyclerView.SimpleOnItemTouchListener {
interface OnRecyclerClickListener{
void onItemClick(View view, int position);
}
private final OnRecyclerClickListener mListener;
private final GestureDetectorCompat mGestureDetector;
public RecyclerItemClickListener(Context context, final RecyclerView recyclerView,
OnRecyclerClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetectorCompat(context, new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null){
Log.d(TAG, "onSingleTapUp: calling listener.onItemClick");
mListener.onItemClick(childView, recyclerView.getChildAdapterPosition(childView));
}
return true;
}
});
}
#Override
public boolean onInterceptTouchEvent(#NonNull RecyclerView rv, #NonNull MotionEvent e) {
if (mGestureDetector != null){
boolean result = mGestureDetector.onTouchEvent(e);
return result;
} else {
return false;
}
}
}
and in MainActivity:
in onCreate method: first define recyclerView variable by findviewbyid() then:
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, recyclerView, this));
then implement onItemClick() method. you can define alert dialog here:
#Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "normal tap on position " + position, Toast.LENGTH_SHORT).show();
}
First pass the context from the Activity or Fragment:
For activity:
myadapter_tutorlist(options, this);
For Fragment:
myadapter_tutorlist(options, getActivity());
Then create a Context variable in side the Adapter class:
public class myadapter_tutorlist extends FirebaseRecyclerAdapter<User,myadapter_tutorlist.myviewholder> {
AlertDialog.Builder builder;
Context context;
public myadapter_tutorlist(#NonNull FirebaseRecyclerOptions<User> options) {
super(options);
this.context = context;
}
Now you can pass this context to your AlertDialog
builder = new AlertDialog.Builder(context);

Android alert dialog not properly functioned

I used an alert dialog box for confirmation of delete, I make a recycler view in which two methods are applied 1.swipe for delete method, 2. menu bar delete method. In swipe method when I swipe the view it removed the list and show alert dialog when clicking no then it replaces not original space but another space that creates a space between them kindly guide me what issue it is?
package com.example.framelayout;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.snackbar.BaseTransientBottomBar;
import com.google.android.material.snackbar.Snackbar;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MainActivity extends AppCompatActivity implements RecyclerClickListener, RecyclerActionClick {
private RecyclerView recyclerView;
private detailAdapt adapt;
private List<detailModel> modelList = new ArrayList<>();
detailModel modelData, swipeData;
ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
final int position = viewHolder.getAdapterPosition();
if (direction == ItemTouchHelper.LEFT) {
swipeData = modelList.get(position);
showDialogBox(position, true);
}
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_details);
populateList();
}
private void populateList() {
for (int i = 0; i < 10; i++) {
int img = R.drawable.ic_person;
String person = "Person " + i;
String name = "Person Name " + i;
String msg = "Person Last Message " + i;
detailModel model = new detailModel(person, name, msg, img);
modelList.add(model);
}
addRecycle(modelList);
}
private void addRecycle(List<detailModel> modelList) {
adapt = new detailAdapt(this, modelList, this, this);
LinearLayoutManager layout = new LinearLayoutManager(this);
layout.setSmoothScrollbarEnabled(true);
recyclerView.setAdapter(adapt);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layout);
ItemTouchHelper helper = new ItemTouchHelper(simpleCallback);
helper.attachToRecyclerView(recyclerView);
}
#Override
public void onDeleteCLick(Object obj, int position) {
showDialogBox(position, false);
}
private void showDialogBox(final int position, final boolean isSwiped) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Confirmation");
builder.setMessage("Are you sure to delete this Item");
builder.setCancelable(false);
builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
deleteItem(position);
}
});
builder.setNegativeButton("no", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (isSwiped) {
modelList.add(position, swipeData);
adapt.notifyItemInserted(position);
}
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
private void deleteItem(final int position) {
modelData = modelList.get(position);
modelList.remove(position);
adapt.notifyItemRemoved(position);
Snackbar snackbar = Snackbar.make(recyclerView, "item removed at position " + position, Snackbar.LENGTH_LONG);
snackbar.setAction("undo", new View.OnClickListener() {
#Override
public void onClick(View v) {
modelList.add(position, modelData);
adapt.notifyItemInserted(position);
}
});
snackbar.show();
}
#Override
public void onUndoCLick(Object obj, int position) {
}
#Override
public void onSingleClick(Object obj, int position) {
detailModel model = (detailModel) obj;
Toast.makeText(this, "click at " + position, Toast.LENGTH_SHORT).show();
}
}
Please remove below
modelList.add(position, swipeData);
adapt.notifyItemInserted(position);
from the cancel button of the alert dialog, as you already didn't remove the item yet, so no need to insert it again. instead replace them with notifyItemChanged(position); like below
builder.setNegativeButton("no", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (isSwiped) {
adapt.notifyItemChanged(position);
}
}
});

SharedPreferences Data spreads on every Fragment

I got a problem with the date of my SharedPreferences. I am using 5 Fragment wher you can dynamically add item to a RecyclerView. The Problem is that when ever I save my data on a particular fragment and reload the app the value that has been saved loads into every single Fragment of mine.It actually save the data to the Fragment it is on.I am using Gson to save my ArrayList of items
This is my Fragment (Fragment0 from 5 in total, the others are just copied and refactored)
package com.example.barryblack;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import static android.content.Context.MODE_PRIVATE;
public class FragmentPage0 extends Fragment {
private ExampleAdapter mAdapter;
private EditText editTask;
ArrayList<MyItem> items;
private Button insertbtn;
private Button stateButton;
private TextView taskText;
private String task;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable
Bundle savedInstanceState) {
CreateExampleList();
View view = inflater.inflate(R.layout.page_fragment0, container, false);
loadData();
RecyclerView recyclerView = view.findViewById(R.id.listRecyclerView);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
new ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView(recyclerView);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemViewCacheSize(500);
mAdapter = new ExampleAdapter(items);
recyclerView.setAdapter(mAdapter);
taskText = view.findViewById(R.id.tv_country);
insertbtn = view.findViewById(R.id.button_insert);
editTask = view.findViewById(R.id.editTask);
stateButton = view.findViewById(R.id.tv_button);
insertbtn.setEnabled(false);
editTask.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String taskInput = editTask.getText().toString().trim();
insertbtn.setEnabled(!taskInput.isEmpty());
}
#Override
public void afterTextChanged(Editable s) {
task = editTask.getText().toString().trim();
}
});
insertbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InsertItem();
SaveData();
editTask.setText(null);
}
});
return view;
}
private void SaveData() {
SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("shared
preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(items);
editor.putString("task list", json);
editor.apply();
}
private void loadData() {
SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("shared
preferences", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list", null);
Type type = new TypeToken<ArrayList<MyItem>>() {
}.getType();
items = gson.fromJson(json, type);
if (items == null) {
items = new ArrayList();
}
}
public void InsertItem() {
items.add(new MyItem(task, stateButton));
mAdapter.notifyItemInserted(items.size());
}
private void CreateExampleList() {
items = new ArrayList<MyItem>();
}
ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder
viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
items.remove(viewHolder.getAdapterPosition());
mAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());
SaveData();
}
};
}
This is my Adapter. I think the problem is inside the OnCreateViewHolder but im not quiet sure
package com.example.barryblack;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private ArrayList<MyItem> mExampleList;
public static class ExampleViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView;
private EditText topicName;
public Button mButton;
private int clicks = 1;
public static final String SHARED_PREFS = "sharedPrefs";
public static final String TOPIC = "topic";
public static final String CLICKS = "clicks";
public ExampleViewHolder(View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.tv_country);
mButton = itemView.findViewById(R.id.tv_button);
topicName = itemView.findViewById(R.id.editText);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicks++;
if (clicks % 2 == 0) {
mButton.setBackgroundResource(R.drawable.button_green);
}else
mButton.setBackgroundResource(R.drawable.button_red);
}
});
}
}
public ExampleAdapter(ArrayList<MyItem> exampleList) {
mExampleList = exampleList;
}
#Override
public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.example_item, parent, false);
ExampleViewHolder evh = new ExampleViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(ExampleViewHolder holder, int position) {
MyItem currentItem = mExampleList.get(position);
holder.mTextView.setText(currentItem.getTaskText());
}
#Override
public int getItemCount() {
return mExampleList.size();
}
}
Use this for your fragments. So every fragment has his own SharedPreferences
private static final String SHARED_PREFS_FRAGMENT_A = "fragmentA";
private static final String SHARED_PREFS_FRAGMENT_B = "fragmentB";
...
SharedPreferences sharedPreferences = getActivity().getSharedPreferences(SHARED_PREFS_FRAGMENT_A , MODE_PRIVATE);

Word list in a RecyclerView and the favourite section of my app doesn't work properly

I developed a vocabulary app where users can select their favorite words to a favourite section. I have two problems.
First, my code looks okay but when I choose a word from the list it doesn't show in the favorite section immediately. However, when I re-open the application it appears there.
The second problem is with the words which repeat in list with any run.
Here's my code :
Adapter list
package farmani.com.essentialwordsforielts.mainPage;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import farmani.com.essentialwordsforielts.R;
import farmani.com.essentialwordsforielts.innerpage.ActivityInnerPage;
public class AdapterList extends RecyclerView.Adapter<ViewHolder> {
Context context;
LayoutInflater inflater;
TextView title;
ImageView avatar;
LinearLayout cardAdapter;
public AdapterList(Context context){
this.context = context;
inflater = LayoutInflater.from(context);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.adapter_card_view, parent, false);
title = (TextView) view.findViewById(R.id.title1);
avatar = (ImageView) view.findViewById(R.id.avatar);
cardAdapter = (LinearLayout) view.findViewById(R.id.card_adapter);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.title.setText(MainActivity.list.get(position).getWord());
String img = MainActivity.list.get(position).getImg();
int id = MainActivity.context.getResources().getIdentifier(img, "drawable", MainActivity.context.getPackageName());
holder.avatar.setImageResource(id);
holder.cardAdapter.setOnClickListener(clickListener);
holder.cardAdapter.setId(position);
}
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = view.getId();
Intent intent = new Intent (MainActivity.context, ActivityInnerPage.class);
intent.putExtra("name", "list");
intent.putExtra("id", position + "");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainActivity.context.startActivity(intent);
}
};
#Override
public int getItemCount() {
return MainActivity.list.size();
}
}
Adapter favorite
package farmani.com.essentialwordsforielts.mainPage;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import farmani.com.essentialwordsforielts.R;
import farmani.com.essentialwordsforielts.innerpage.ActivityInnerPage;
public class AdapterFav extends RecyclerView.Adapter<ViewHolder> {
Context context;
LayoutInflater inflater;
TextView title;
ImageView avatar;
LinearLayout cardAdapter;
public AdapterFav(Context context){
this.context = context;
inflater = LayoutInflater.from(context);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.adapter_card_view, parent, false);
title = (TextView) view.findViewById(R.id.title1);
avatar = (ImageView) view.findViewById(R.id.avatar);
cardAdapter = (LinearLayout) view.findViewById(R.id.card_adapter);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.title.setText(MainActivity.favorite.get(position).getWord());
String img = MainActivity.favorite.get(position).getImg();
int id = MainActivity.context.getResources().getIdentifier(img, "drawable", MainActivity.context.getPackageName());
holder.avatar.setImageResource(id);
holder.cardAdapter.setOnClickListener(clickListener);
holder.cardAdapter.setId(position);
}
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = view.getId();
Intent intent = new Intent (MainActivity.context, ActivityInnerPage.class);
intent.putExtra("name", "favorite");
intent.putExtra("id", position + "");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainActivity.context.startActivity(intent);
}
};
#Override
public int getItemCount() {
return MainActivity.favorite.size();
}
}
When you update your data set call adapater.notifyChange();

Categories