How to delete recycler view item from room database - java

I am using MVVM architecture model to create an app.I have recycler view in MainActivity and on click of a delete button in recycler view item it should be removed from room database.I know item can be removed within adapter class but as I am using MVVM model I want to carry out delete operation in Repository class.
This is my code below:
UserDao.java
#Dao
public interface UserDao {
#Insert(onConflict = OnConflictStrategy.REPLACE)
void Insert(User... users);
#Query("SELECT * FROM Users")
LiveData<List<User>> getRoomUsers();
#Delete
void Delete(User... user);
}
UserAdapter.java
public class UserAdapter extends
RecyclerView.Adapter<UserAdapter.ViewHolder> {
List<User> userList;
Context context;
public UserAdapter(List<User> userList, Context context) {
this.userList = userList;
this.context = context;
}
#NonNull
#Override
public UserAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_row_layout,parent,false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull UserAdapter.ViewHolder holder, int position) {
final User users = userList.get(position);
holder.row_name.setText(users.getName());
holder.row_age.setText(users.getAge());
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
#Override
public int getItemCount() {
return userList.size();
}
public void setUserList(List<User> userList) {
this.userList = userList;
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView row_name,row_age;
ImageView delete;
public ViewHolder(#NonNull View itemView) {
super(itemView);
row_name = itemView.findViewById(R.id.row_name);
row_age = itemView.findViewById(R.id.row_age);
delete = itemView.findViewById(R.id.delete);
}
}
}
UserRepository.java
public class UserRepository {
private Context context;
private UserDb userDb;
private LiveData<List<User>> listLiveData;
public UserRepository(Context context) {
this.context = context;
userDb = UserDb.getInstance(context);
listLiveData = userDb.userDao().getRoomUsers();
}
public void getUserList(){
Retrofit retrofit = RetrofitClient.getInstance();
ApiService apiService = retrofit.create(ApiService.class);
Call<List<User>> userList = apiService.getUser();
userList.enqueue(new Callback<List<User>>() {
#Override
public void onResponse(Call<List<User>> call, final Response<List<User>> response) {
Completable.fromAction(new Action() {
#Override
public void run() throws Exception {
if(response.body() != null) {
List<User> list = response.body();
for (int i = 0; i < list.size(); i++) {
String id = list.get(i).getId();
String names = list.get(i).getName();
String age = list.get(i).getAge();
User user = new User(id,names,age);
userDb.userDao().Insert(user);
}
}
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new CompletableObserver() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onComplete() {
Toast.makeText(context,"Data inserted",Toast.LENGTH_SHORT).show();
}
#Override
public void onError(Throwable e) {
Toast.makeText(context,e.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onFailure(Call<List<User>> call, Throwable t) {
Toast.makeText(context,t.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
public LiveData<List<User>> getRoomUsers(){
return listLiveData;
}
}
UserViewModel.java
public class UserViewModel extends AndroidViewModel {
private UserRepository repo;
private LiveData<List<User>> listLiveData;
public UserViewModel(#NonNull Application application) {
super(application);
repo = new UserRepository(application);
listLiveData = repo.getRoomUsers();
}
public LiveData<List<User>> getListLiveData() {
return listLiveData;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
UserRepository userRepository;
RecyclerView recyclerView;
UserViewModel userModel;
List<User> userList;
UserAdapter adapter;
ProgressBar prg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
prg = findViewById(R.id.prg);
userRepository = new UserRepository(this);
userModel = ViewModelProviders.of(this).get(UserViewModel.class);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
userList = new ArrayList<>();
adapter = new UserAdapter(userList,this);
recyclerView.setAdapter(adapter);
userModel.getListLiveData().observe(this, new Observer<List<User>>() {
#Override
public void onChanged(List<User> users) {
prg.setVisibility(View.INVISIBLE);
adapter.setUserList(users);
}
});
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this,AddUser.class);
startActivity(i);
}
});
userRepository.getUserList();
}
Someone please let me know how do I implement delete operation. Any help would be appreciated.
THANKS

Firstly, initialize UserViewModel in your adapter class like how you did in MainActivity, then call delete function.
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
userModel.deleteItem(users);
}
});
Add this function in UserModel class.
public void deleteItem(User user) = repo.deleteItem(user);
In UserRepository class, call Delete function.
public void deleteItem(User user) {
userDb.userDao().Delete(user);
}

Try to observe changes form the database with live data, whenever you perform anything, adding or deleting(in the database), in your observer refresh that data for the recycler view
Set a click listener to your Adapter
public interface OnListInteractionListener {
// TODO: Update argument type and name
void onListInteraction(User user);
}
In Adapter class
private final OnListInteractionListener mListener;
public UserAdapter(List<User> users, OnListInteractionListener listener,Context context) {
mListener = listener;
}
and in view bind holder
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mListener.onListInteraction(userList.get(position))
}
});
Implement that listener in your activity/fragment and from that, you can access Viewmodel and repo

Related

RecyclerView crashes when I update data to Firestore

I'm showing data from a Firebase Firestore collection, the app worked fine while but when I update data to the collection from other device (I got an Arduino with sensors connected to a PC that executes a Python script to transform the serial data to JSON and then I update that data on the Firestore collection, all the back end of these functionality works perfectly. My problem it's the Java on Android.
I already search for solutions on this forum and It seems like something doesn't work with the Adapter, the RecyclerView and the "notifyDataSetChanged();" None of the current solutions worked for me or maybe I just don't know how to implement them on my project.
This is my model
public class Monitor {
String alias, placa, temp, acid;
public Monitor(){}
public Monitor(String alias, String placa, String temp, String acid) {
this.alias = alias;
this.placa = placa;
this.temp = temp;
this.acid = acid;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public String getPlaca() {
return placa;
}
public void setPlaca(String placa) {
this.placa = placa;
}
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public String getAcid() {
return acid;
}
public void setAcid(String acid) {
this.acid = acid;
}
}
The adapter
public class MonitorAdapter extends FirestoreRecyclerAdapter<Monitor, MonitorAdapter.ViewHolder> {
private FirebaseFirestore mFirestore = FirebaseFirestore.getInstance();
Activity activity;
/**
* Create a new RecyclerView adapter that listens to a Firestore Query. See {#link
* FirestoreRecyclerOptions} for configuration options.
*
* #param options
*/
public MonitorAdapter(#NonNull FirestoreRecyclerOptions<Monitor> options, Activity activity) {
super(options);
this.activity = activity;
}
#Override
protected void onBindViewHolder(#NonNull ViewHolder holder, int position, #NonNull Monitor model) {
DocumentSnapshot documentSnapshot = getSnapshots().getSnapshot(holder.getAbsoluteAdapterPosition());
final String id = documentSnapshot.getId();
holder.alias.setText(model.getAlias());
holder.temp.setText(model.getTemp());
holder.acid.setText(model.getAcid());
holder.btn_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(activity, VincularPlaca.class);
i.putExtra("id_placa",id);
activity.startActivity(i);
}
});
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_monitor_single,parent,false);
return new ViewHolder(view);
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView alias, temp, acid;
Button btn_edit;
public ViewHolder(#NonNull View itemView) {
super(itemView);
alias = itemView.findViewById(R.id.alias);
temp = itemView.findViewById(R.id.temp);
acid = itemView.findViewById(R.id.acid);
btn_edit = itemView.findViewById(R.id.btn_edit);
}
}
}
And my MainActivity
public class MainActivity extends AppCompatActivity {
Button btn_add, btn_exit;
RecyclerView mRecycler;
MonitorAdapter mAdapter;
FirebaseFirestore mFirestore;
FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFirestore = FirebaseFirestore.getInstance();
mRecycler = findViewById(R.id.recyclerViewSingle);
mRecycler.setLayoutManager(new LinearLayoutManager(this));
Query query = mFirestore.collection("dispositivos");
FirestoreRecyclerOptions<Monitor> firestoreRecyclerOptions =
new FirestoreRecyclerOptions.Builder<Monitor>().setQuery(query,Monitor.class).build();
mAdapter = new MonitorAdapter(firestoreRecyclerOptions, this);
mAdapter.notifyDataSetChanged();
mRecycler.setAdapter(mAdapter);
btn_add = findViewById(R.id.btn_add);
btn_exit = findViewById(R.id.btn_close);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,VincularPlaca.class));
}
});
btn_exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,LoginActivity.class));
mAuth.signOut();
}
});
}
#Override
protected void onStart() {
super.onStart();
mAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
mAdapter.stopListening();
}
}
class ExampleViewModel : ViewModel() {
var mFirestore : FirebaseFirestore? = null
private val _list = MutableLiveData<FirestoreRecyclerOptions<Monitor>>()
val list: LiveData<FirestoreRecyclerOptions<Monitor>> = _list
init{
mFirestore = FirebaseFirestore.getInstance()
list.value= FirestoreRecyclerOptions.Builder<Monitor>().setQuery(mFirestore!!.collection("dispositivos"),Monitor::class.java).build()
}
}
The problem has solved fixing the AndroidManifest Permissions and outside the code on the Firebase Firestore console, the attribute was supose to be an string but it recieves an int.

attempt to display details in another Activity "java.lang.IndexOutOfBoundsException: Index: 0, Size: 0"

I'm trying to use OnItemClick to display details in a user profile page and I still have this error:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at fr.ousoft.suiviemedsbox.ScrollingActivity.OnItemClick(**ScrollingActivity.java:102**)
at fr.ousoft.suiviemedsbox.UsersAdapter$AdapterVH$1.onClick(**UsersAdapter.java:115**)
Here is my Activity code
public class ScrollingActivity extends AppCompatActivity implements UsersAdapter.OnItemClickListener {
public static final String EXTRA_CREATOR_NOM = "Nom";
public static final String EXTRA_CREATOR_PRENOM = "Prenom";
public static final String EXTRA_CREATOR_TEL = "Tel";
public static final String EXTRA_CREATOR_EMAIL = "Email";
public static final String EXTRA_CREATOR_ETABLISSEMENT = "Etablissement";
public static final String EXTRA_CREATOR_TYPE = "Type";
public static final String EXTRA_CREATOR_ACTIVE = "Active";
RecyclerView recyclerView;
ApiInterface apiInterface;
UsersAdapter usersAdapter;
ArrayList<User> mListe = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrolling);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
CollapsingToolbarLayout toolBarLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
toolBarLayout.setTitle(getTitle());
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ScrollingActivity.this, RegisterActivity.class);
startActivity(intent);
}
});
recyclerView = findViewById(R.id.recyclerViewList);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
usersAdapter = new UsersAdapter();
fetchUsers();
}
public void fetchUsers(){
apiInterface = ApiClient.getRetrofitInstance().create(ApiInterface.class);
Call<List<User>> call = apiInterface.getAllUsers();
call.enqueue(new Callback<List<User>>() {
#Override
public void onResponse(Call<List<User>> call, Response<List<User>> response) {
if (response.isSuccessful()){
List<User> users = response.body();
usersAdapter.setData(users);
usersAdapter.setOnItemClickListener(ScrollingActivity.this);
recyclerView.setAdapter(usersAdapter);
}
}
#Override
public void onFailure(Call<List<User>> call, Throwable t) {
Log.e("success", t.getLocalizedMessage());
}
});
}
#Override
public void OnItemClick(int position) {
Intent detailIntent = new Intent(this,DetailActivity.class);
User clickedUser = mListe.get(position);
detailIntent.putExtra(EXTRA_CREATOR_NOM, clickedUser.getNom());
detailIntent.putExtra(EXTRA_CREATOR_PRENOM, clickedUser.getPrenom());
detailIntent.putExtra(EXTRA_CREATOR_TEL, clickedUser.getTel());
detailIntent.putExtra(EXTRA_CREATOR_EMAIL, clickedUser.getEmail());
detailIntent.putExtra(EXTRA_CREATOR_ETABLISSEMENT, clickedUser.getEtablissement());
detailIntent.putExtra(EXTRA_CREATOR_TYPE, clickedUser.getType());
detailIntent.putExtra(EXTRA_CREATOR_ACTIVE, clickedUser.getActive());
startActivity(detailIntent);
}
}
Adapter:
public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.AdapterVH>{
private List<User> userList;
private Context context;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void OnItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
public UsersAdapter(){
}
public void setData(List<User> userList){
this.userList = userList;
notifyDataSetChanged();
}
#NonNull
#Override
public AdapterVH onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
context = parent.getContext();
return new UsersAdapter.AdapterVH(LayoutInflater.from(context).inflate(R.layout.item_list,parent,false));
}
#SuppressLint("ResourceAsColor")
#Override
public void onBindViewHolder(#NonNull AdapterVH holder, int position) {
User user = userList.get(position);
String nom = user.getNom();
String email = user.getEmail();
String etab = user.getEtablissement();
String active = user.getActive();
String prenom = user.getPrenom();
holder.txtNom.setText(nom);
if (nom == null) {
holder.txtNom.setText("Aucun Nom");
}
holder.txtEmail.setText(email);
if (email == null) {
holder.txtEmail.setText("Aucun Email");
}
holder.txtEttab.setText(etab);
if (etab == null) {
holder.txtEttab.setText("Aucun Etablissement");
}
holder.txtPrenom.setText(prenom);
if (prenom == null) {
holder.txtPrenom.setText("Aucun Prenom");
}
if (active == null) {
holder.ActiveDesactive.setText(R.string.desact);
}else {
holder.ActiveDesactive.setText(R.string.activ);
}
}
#Override
public int getItemCount() {
return userList.size();
}
public class AdapterVH extends RecyclerView.ViewHolder{
TextView txtNom;
TextView txtPrenom;
TextView txtEmail;
TextView txtEttab;
Button ActiveDesactive;
public AdapterVH(#NonNull View itemView) {
super(itemView);
txtNom = itemView.findViewById(R.id.NomUser);
txtPrenom = itemView.findViewById(R.id.PrenomUser);
txtEmail = itemView.findViewById(R.id.EmailUser);
txtEttab = itemView.findViewById(R.id.EtabUser);
ActiveDesactive = itemView.findViewById(R.id.ActiveDesavtive);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null){
int positions = getAdapterPosition();
if (positions != RecyclerView.NO_POSITION){
mListener.OnItemClick(positions);
}
}
}
});
}
}
}
You never fill mListe with any content. If you search for mListe. the only match you get is mListe.get. You have no invocations of mListe.add or mListe.addAll. What you do instead is set a list from a response directly into the adapter:
if (response.isSuccessful()){
// Here is the error
List<User> users = response.body();
usersAdapter.setData(users);
usersAdapter.setOnItemClickListener(ScrollingActivity.this);
recyclerView.setAdapter(usersAdapter);
}
What should be done instead is the following:
Clear mListe from any previous content;
Fill with new content;
Set new data to the adapter.
if (response.isSuccessful()){
mListe.clear();
mListe.addAll(response.body());
usersAdapter.setData(mListe);
}
I have removed a few lines from this if-statement and moved them into the onCreate. They should be called only once, there is no benefit setting the same adapter and click listener if you call fetchUsers() again.
#Override
protected void onCreate(Bundle savedInstanceState) {
...
usersAdapter = new UsersAdapter();
usersAdapter.setOnItemClickListener(this);
recyclerView.setAdapter(usersAdapter);
fetchUsers();
}
you are not adding anything in ArrayList<User> mListe = new ArrayList<>();
you should add values before implementing any action,
try this
if (response.isSuccessful()){
List<User> users = response.body();
mListe.addAll(users);
usersAdapter.setData(users);
usersAdapter.setOnItemClickListener(ScrollingActivity.this);
recyclerView.setAdapter(usersAdapter);
}

Deleting In Room Database

I am learning Room DataBase!!
I Know How to Insert and Retrieve Data from Room DataBase to Recycler View!! But In Delete Operation I am getting error of "No Adapter attached Skipped Layout!"
What I want when anyone click on delete button on recycler view . The Task should be deleted
That's why I also Used delete method in Interface and add Interface in Recycler View Adapter which give call back to MainActivity so that we delete and update the recycler view
All of my codes are given below
Here is my Entity Class named as Task
#Entity
public class Task implements Serializable {
#PrimaryKey(autoGenerate = true)
private int id;
#ColumnInfo(name = "task_name")
private String task_name;
#ColumnInfo
private String task_desc;
#ColumnInfo
private String comment;
#ColumnInfo
private String task_comp_date;
#ColumnInfo
private String activate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTask_name() {
return task_name;
}
public void setTask_name(String task_name) {
this.task_name = task_name;
}
public String getTask_desc() {
return task_desc;
}
public void setTask_desc(String task_desc) {
this.task_desc = task_desc;
}
public String getTask_comp_date() {
return task_comp_date;
}
public void setTask_comp_date(String task_comp_date) {
this.task_comp_date = task_comp_date;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getActivate() {
return activate;
}
public void setActivate(String activate) {
this.activate = activate;
}
}
My Data Accession Object named as TaskDao
#Dao
public interface TaskDao {
#Query("SELECT * FROM task")
List<Task> getAll();
#Insert
void insert(Task task);
#Delete
void delete(Task task);
#Update
void update(Task task);
}
My DataBase
#Database(entities = {Task.class},version = 1)
public abstract class AppDataBase extends RoomDatabase {
public abstract TaskDao taskDao();
}
My DataBaseClient named as DatabaseClient
public class DatabaseClient {
private Context context;
private static DatabaseClient mInstace;
private AppDataBase appDataBase;
public DatabaseClient(Context context) {
this.context = context;
appDataBase = Room.databaseBuilder(context,AppDataBase.class,"MyDailyTask").build();
}
public static synchronized DatabaseClient getInstance(Context context)
{
if(mInstace == null)
{
mInstace = new DatabaseClient(context);
}
return mInstace;
}
public AppDataBase getAppDataBase()
{
return appDataBase;
}
}
My RecyclerView Adapter
public class TaskAdapter extends RecyclerView.Adapter<TaskAdapter.MyViewHolder> {
private Context context;
private List<Task> taskList;
public interface OnDeleteClickListener
{
void OnDeleteClickListener(Task task);
}
private OnDeleteClickListener onDeleteClickListener;
public TaskAdapter(Context context, List<Task> taskList) {
this.context = context;
this.taskList = taskList;
}
public void setOnDeleteClickListener(OnDeleteClickListener onDeleteClickListener) {
this.onDeleteClickListener = onDeleteClickListener;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
view = LayoutInflater.from(context).inflate(R.layout.view_task_list,parent,false);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.setData(taskList.get(position).getTask_name(),taskList.get(position).getTask_desc(),taskList.get(position).getComment(),taskList.get(position).getTask_comp_date(),position);
}
#Override
public int getItemCount() {
return taskList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
private TextView t1,t2,t3,t4,t5;
private ImageView view;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
t1= itemView.findViewById(R.id.tvCommnt);
t2=itemView.findViewById(R.id.tvDesc);
t3=itemView.findViewById(R.id.tvName);
t4= itemView.findViewById(R.id.tvStart);
t5 = itemView.findViewById(R.id.tvEnd);
view =itemView.findViewById(R.id.tvdele);
}
public void setData(String t01, String t02, String t03, String t05, final int position)
{
t1.setText("Task Comment "+t03);
t2.setText("Task Description "+t02);
t3.setText("Task Name "+ t01);
t4.setText("Start ");
t5.setText("Ënd "+t05);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(onDeleteClickListener!=null)
{
onDeleteClickListener.OnDeleteClickListener(taskList.get(position));
taskList.remove(position);
notifyDataSetChanged();
}
}
});
}
}
}
MainActivity.java :
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.ivAdd);
recyclerView = findViewById(R.id.rvTask);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), AddTaskActivity.class));
}
});
new newTask().execute();
}
class newTask extends AsyncTask<Void,Void, List<Task>> implements TaskAdapter.OnDeleteClickListener {
List<Task> tasks;
#Override
protected List<Task> doInBackground(Void... voids) {
tasks = DatabaseClient.getInstance(getApplicationContext()).getAppDataBase().taskDao().getAll();
return tasks;
}
#Override
protected void onPostExecute(List<Task> tasks) {
super.onPostExecute(tasks);
TaskAdapter taskAdapter = new TaskAdapter(MainActivity.this,tasks);
LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new DividerItemDecoration(getApplicationContext(),DividerItemDecoration.VERTICAL));
recyclerView.setAdapter(taskAdapter);
taskAdapter.setOnDeleteClickListener(this);
}
#Override
public void OnDeleteClickListener(final Task task) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
DatabaseClient.getInstance(getApplicationContext()).getAppDataBase().taskDao().delete(task);
}
},1000);
}
}
welcome in stack
you interface is declared but not assign so your will throw null pointer when click on item inside your list, but good work your check null before fire method interface
first add setter for OnDeleteClickListener inside your adapter
public void setOnDeleteClickListener(OnDeleteClickListener listener){
this.onDeleteClickListener=listener;
}
and also add code that remove item from you list when user click item
so inside setData method update this code
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onDeleteClickListener != null) {
onDeleteClickListener.OnDeleteClickListener(taskList.get(position));
//remove item from list and then notify adapter data is changed
taskList.remove(position);
notifyDataSetChanged();
}
}
});
finally to Triggers onDeleteClickListener inside your AsyncTask
update your code here
#Override
protected void onPostExecute(List < Task > tasks) {
super.onPostExecute(tasks);
TaskAdapter taskAdapter = new TaskAdapter(MainActivity.this, tasks, this);
LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new DividerItemDecoration(getApplicationContext(), DividerItemDecoration.VERTICAL));
recyclerView.setAdapter(taskAdapter);
//pass this that refer to my interface
taskAdapter.setOnDeleteClickListener(this);
}
inside your OnDelete just use this code to run in another thread
AsyncTask.execute(new Runnable() {
#Override
public void run() {
DatabaseClient.getInstance(getApplicationContext()).getAppDataBase().taskDao().delete(task);
}
});
Advice : Don't name your variable or arguments like String
t01,String t02..etc ,choice name for like what this variable jop
like String taskComment,String taskName ..etc
i hope this help you

How can I get a variable from RecyclerView Adapter passed to MainActivity?

I was just playing around with some code, learning new things, when I ran into this problem... I'm trying to pass a variable from my RecylcerViewAdapter to a method in MainActivity, but I just can't seem to accomplish it.
I tried a lot of different thing with interfaces and casting, but nothing did the trick. Since I'm fairly new to all of this, maybe I'm making a trivial mistake somewhere?
My Interface:
public interface AdapterCallback {
void onMethodCallback(int id);
}
This is my adapter class:
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
private List<Post> postList;
private Context context;
private AdapterCallback listener;
public PostAdapter() {
}
public PostAdapter(List<Post> postList, Context context) {
this.postList = postList;
this.context = context;
}
public void setListener(AdapterCallback listener) {
this.listener = listener;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_layout, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int position) {
viewHolder.tvTitle.setText(postList.get(position).getTitle());
viewHolder.tvBody.setText(new StringBuilder(postList.get(position).getBody().substring(0, 20)).append("..."));
viewHolder.tvId.setText(String.valueOf(postList.get(position).getUserId()));
viewHolder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = postList.get(position).getId();
if (listener != null) {
listener.onMethodCallback(id);
}
}
});
}
#Override
public int getItemCount() {
return postList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvTitle;
TextView tvBody;
TextView tvId;
LinearLayout parentLayout;
public ViewHolder(View itemView) {
super(itemView);
tvTitle = itemView.findViewById(R.id.tvTitle);
tvBody = itemView.findViewById(R.id.tvBody);
tvId = itemView.findViewById(R.id.tvId);
parentLayout = itemView.findViewById(R.id.parentLayout);
}
}
}
And my MainActivity:
public class MainActivity extends AppCompatActivity {
public static final String TAG = "MainActivityLog";
private CompositeDisposable disposable = new CompositeDisposable();
#BindView(R.id.rvPosts)
RecyclerView rvPosts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
rvPosts.setHasFixedSize(true);
rvPosts.setLayoutManager(new LinearLayoutManager(this));
populateList();
logItems();
}
private void populateList() {
MainViewModel viewModel = ViewModelProviders.of(MainActivity.this).get(MainViewModel.class);
viewModel.makeQuery().observe(MainActivity.this, new Observer<List<Post>>() {
#Override
public void onChanged(#Nullable List<Post> posts) {
PostAdapter adapter = new PostAdapter(posts, getApplicationContext());
rvPosts.setAdapter(adapter);
}
});
}
public void logItems() {
PostAdapter adapter = new PostAdapter();
adapter.setListener(new AdapterCallback() {
#Override
public void onMethodCallback(int id) {
MainViewModel viewModel = ViewModelProviders.of(MainActivity.this).get(MainViewModel.class);
viewModel.makeSingleQuery(id).observe(MainActivity.this, new Observer<Post>() {
#Override
public void onChanged(#Nullable final Post post) {
Log.d(TAG, "onChanged: data response");
Log.d(TAG, "onChanged: " + post);
}
});
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
disposable.clear();
}
}
The populateList() method works just fine, but the logItems() method is the problem.
So when i click on a view in RecyclerView I expect the log to output the title, description and ID of the post that was clicked. nut nothing happens...
So, any help would be appreciated.
Make adapter global variable i.e. a field. Use the same object to set every properties.
private PostAdapter adapter;
Replace your logItems method with this:
public void logItems() {
adapter.setListener(new AdapterCallback() {
#Override
public void onMethodCallback(int id) {
MainViewModel viewModel = ViewModelProviders.of(MainActivity.this).get(MainViewModel.class);
viewModel.makeSingleQuery(id).observe(MainActivity.this, new Observer<Post>() {
#Override
public void onChanged(#Nullable final Post post) {
Log.d(TAG, "onChanged: data response");
Log.d(TAG, "onChanged: " + post);
}
});
}
});
}
And populateList with this:
private void populateList() {
MainViewModel viewModel = ViewModelProviders.of(MainActivity.this).get(MainViewModel.class);
viewModel.makeQuery().observe(MainActivity.this, new Observer<List<Post>>() {
#Override
public void onChanged(#Nullable List<Post> posts) {
adapter = new PostAdapter(posts, getApplicationContext());
rvPosts.setAdapter(adapter);
logItems();
}
});
}
And don't call logItems() from onCreate
This is how I implement with my ListAdapters:
public class FeedbackListAdapter extends RecyclerView.Adapter<FeedbackListAdapter.ViewHolder> {
private final ArrayList<Feedback> feedbacks;
private View.OnClickListener onItemClickListener;
private View.OnLongClickListener onItemLongClickListener;
private final Context context;
public FeedbackListAdapter(ArrayList<Feedback> feedbacks, Context context) {
this.feedbacks = feedbacks;
this.context = context;
}
public void setItemClickListener(View.OnClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public void setOnItemLongClickListener(View.OnLongClickListener onItemLongClickListener){
this.onItemLongClickListener = onItemLongClickListener;
}
public class ViewHolder extends RecyclerView.ViewHolder{
final TextView feedback, created, updated;
final LinearLayout mainLayout;
ViewHolder(View iv) {
super(iv);
/*
* Associate layout elements to Java declarations
* */
mainLayout = iv.findViewById(R.id.main_layout);
feedback = iv.findViewById(R.id.feedback);
created = iv.findViewById(R.id.created_string);
updated = iv.findViewById(R.id.updated_string);
}
}
#Override
public int getItemCount() {
return feedbacks.size();
}
#Override
#NonNull
public FeedbackListAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_feedback_table_row, parent, false);
return new FeedbackListAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(final #NonNull FeedbackListAdapter.ViewHolder holder, final int position) {
/*
* Bind data to layout
* */
try{
Feedback feedback = feedbacks.get(position);
holder.feedback.setText(feedback.getContent());
holder.created.setText(feedback.getCreated());
holder.updated.setText(feedback.getUpdated());
holder.mainLayout.setOnClickListener(this.onItemClickListener);
holder.mainLayout.setOnLongClickListener(this.onItemLongClickListener);
holder.mainLayout.setTag(feedback.getDbID());
TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
holder.mainLayout.setBackgroundResource(outValue.resourceId);
}catch(IndexOutOfBoundsException e){
e.printStackTrace();
}
}
}
In onPopulateList you create an adaptor:
PostAdapter adapter = new PostAdapter(posts, getApplicationContext());
rvPosts.setAdapter(adapter);
However in public void logItems() { you used a different adapter
PostAdapter adapter = new PostAdapter();
adapter.setListener(new AdapterCallback() {
#Override
public void onMethodCallback(int id) {
...
}
});
Therefore the list is being populated with 1 adapter, but you are setting the listener on an unused second adapter.
The fix is to use the same adapter for both. If you make the adapater a field, and don't create a new one inside of logItems, but just set your listener it should work.
i.e.
// as a field in your class
private PostAdapter adapter;
then
// in `populateList()`
adapter = new PostAdapter(posts, getApplicationContext());
rvPosts.setAdapter(adapter);
and
// in `logItems()`
adapter.setListener(new AdapterCallback() {
#Override
public void onMethodCallback(int id) {
...
}
});
In Adapter
public class CustomerListAdapter extends RecyclerView.Adapter<CustomerListAdapter.OrderItemViewHolder> {
private Context mCtx;
ProgressDialog progressDialog;
//we are storing all the products in a list
private List<CustomerModel> customeritemList;
public CustomerListAdapter(Context mCtx, List<CustomerModel> orderitemList) {
this.mCtx = mCtx;
this.customeritemList = orderitemList;
progressDialog = new ProgressDialog(mCtx);
}
#NonNull
#Override
public OrderItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.activity_customer_list, null);
return new OrderItemViewHolder(view, mCtx, customeritemList);
}
#Override
public void onBindViewHolder(#NonNull OrderItemViewHolder holder, int position) {
CustomerModel customer = customeritemList.get(position);
try {
//holder.textViewPINo.setText("PINo \n"+Integer.toString( order.getPINo()));
holder.c_name.setText(customer.getCustomerName());
holder.c_address.setText(customer.getAddress());
holder.c_contact.setText(customer.getMobile());
holder.i_name.setText(customer.getInteriorName());
holder.i_contact.setText(customer.getInteriorMobile());
holder.i_address.setText(customer.getAddress());
} catch (Exception E) {
E.printStackTrace();
}
}
#Override
public int getItemCount() {
return customeritemList.size();
}
class OrderItemViewHolder extends RecyclerView.ViewHolder implements View.OnLongClickListener, View.OnClickListener {
AlertDialog.Builder alert;
private Context mCtx;
TextView c_name, c_contact, c_address, i_name, i_contact, i_address;
TextView OrderItemID, MaterialType, Price2, Qty, AQty;
//we are storing all the products in a list
private List<CustomerModel> orderitemList;
public OrderItemViewHolder(View itemView, Context mCtx, List<CustomerModel> orderitemList) {
super(itemView);
this.mCtx = mCtx;
this.orderitemList = orderitemList;
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
// CatelogOrderDetailModel catelogOrderDetailModel = new CatelogOrderDetailModel();
c_name = itemView.findViewById(R.id.customerName);
c_contact = itemView.findViewById(R.id.contact);
c_address = itemView.findViewById(R.id.address);
i_name = itemView.findViewById(R.id.interiorName);
i_address = itemView.findViewById(R.id.interiorAddress);
i_contact = itemView.findViewById(R.id.interiorContact);
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
CustomerModel orderitem = this.orderitemList.get(position);
}
#Override
public boolean onLongClick(View v) {
int position = getAdapterPosition();
CustomerModel orderitem = this.orderitemList.get(position);
if (v.getId() == itemView.getId()) {
// showUpdateDeleteDialog(order);
try {
} catch (Exception E) {
E.printStackTrace();
}
Toast.makeText(mCtx, "lc: ", Toast.LENGTH_SHORT).show();
}
return true;
}
}
}

Firebase Database not retrieving in emulator/device

Firebase database screenshot link
I Cannot retrieve the data in a device this is wallpaper app
I have updated the google play services also but nothing happens.
I have also given the internet permission.
I have also tested on the emulator and a physical device.
Firebase database screenshot link on top.
CategoryFragment.java
public class CategoryFragment extends Fragment {
FirebaseDatabase database;
DatabaseReference categoryBackground;
//Firebase UI adpter
FirebaseRecyclerOptions<CategoryItem> options;
FirebaseRecyclerAdapter<CategoryItem, CategoryViewHolder> adapter;
//View
RecyclerView recyclerView;
private static CategoryFragment INSTANCE=null;
public CategoryFragment() {
database = FirebaseDatabase.getInstance();
categoryBackground =
database.getReference(Common.STR_CATEGORY_BACKGROUND);
options = new FirebaseRecyclerOptions.Builder<CategoryItem>()
.setQuery(categoryBackground, CategoryItem.class)
.build();
adapter = new FirebaseRecyclerAdapter<CategoryItem, CategoryViewHolder>
(options) {
#Override
protected void onBindViewHolder(#NonNull final CategoryViewHolder
holder, int position, #NonNull final CategoryItem model) {
Picasso.with(getActivity())
.load(model.getImageLink())
.networkPolicy(NetworkPolicy.OFFLINE)
.into(holder.background_image, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
//Try again if cache failed to load
Picasso.with(getActivity())
.load(model.getImageLink())
.error(R.drawable.ic_terrain_black_24dp)
.into(holder.background_image, new
Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Log.e("ERROR_MSU", "Couldn't
fetch image");
}
});
}
});
holder.category_name.setText(model.getName());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position) {
//Code later for detail category
}
});
}
#Override
public CategoryViewHolder onCreateViewHolder(ViewGroup parent, int
viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.layout_category_item,parent,false);
return new CategoryViewHolder(itemView);
}
};
}
public static CategoryFragment getInstance()
{
if(INSTANCE == null)
INSTANCE = new CategoryFragment();
return INSTANCE;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_category, container,
false);
recyclerView = (RecyclerView)view.findViewById(R.id.recycler_category);
recyclerView.setHasFixedSize(true);
GridLayoutManager gridLayoutManager = new
GridLayoutManager(getActivity(),2);
recyclerView.setLayoutManager(gridLayoutManager);
setCategory();
return view;
}
private void setCategory() {
adapter.startListening();
recyclerView.setAdapter(adapter);
}
#Override
public void onStart() {
super.onStart();
if (adapter!=null)
adapter.startListening();
}
#Override
public void onStop() {
if (adapter!=null)
adapter.stopListening();
super.onStop();
}
#Override
public void onResume() {
super.onResume();
if (adapter!=null)
adapter.stopListening();
}
}
CategoryItem.java
public class CategoryItem {
public String name;
public String imageLink;
public CategoryItem() {
}
public CategoryItem(String name, String imageLink){
this.name = name;
this.imageLink = imageLink;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImageLink() {
return imageLink;
}
public void setImageLink(String imageLink) {
this.imageLink = imageLink;
}
}
CategoryViewHolder
public class CategoryViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
public TextView category_name;
public ImageView background_image;
ItemClickListener itemClickListener;
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
public CategoryViewHolder(View itemView) {
super(itemView);
background_image = (ImageView)itemView.findViewById(R.id.image);
category_name = (TextView)itemView.findViewById(R.id.name);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v){
itemClickListener.onClick(v,getAdapterPosition());
}
}

Categories

Resources