updating recycler view items from a different activity
I am trying to update/refresh recycler view data from a different activity.
The setup I have is, I have a recycler view running in a fragment. Clicking on a recycler view item opens a new activity where user makes un update and data is saved in the database. Then going back(onBackClicked) to the fragment the recycler view is not updated. However the data is saved so if I close an app and restart the update is shown.
Can someone please guide me on how would I go on solving this issue.
Note: I'm using observer to observer items of the recycler view, but however since update is happening in a different activity recycler view is not updating. The observer works if I make update from the same fragment without opening a new activity.
Thank you in advance
3 answers
-
answered 2018-07-11 04:06
Shiva Snape
Since Fragments Doesnt have OnRestart LifeCycle ,You can use like this,
@Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { //refresh recycleradapter with notifydatasetchanged here //recyclerAdapter.notifyDataSetChanged(); } }
-
answered 2018-07-11 04:47
Jay Ryu
Fragment still has onResume method. Here you can update the data set list. don't forget to update REcyclerView.
@Override public void onResume() { super.onResume(); //update whatever your list adapter.notifyDataSetChanged(); }
-
answered 2018-07-11 04:51
Abu Mohammad Rasel
You can use LiveData for Recyclerview. It will update recyclerview automatically when data source changes.
See also questions close to this topic
-
Create view with transparent circle
I want to create a view with rounded corners and a centered round button. At the moment i am using a rectangle shape with round borders as a view-background (green part) and a white circle shape, which contains the button (green button with android logo).
This works fine as long as the background (yellow/brown at the moment, just for better visualization) has the same color as the circle shape.
But now i want to use a gradient background: What is a smart way to achieve the same look with a transparent circle?
I wasn't able to create the same look with normal android shapes (i had the idea of round corners).
-
NFC Detection in and Out of Application in Android
My application was only catch nfc tag while my app is working. I wanted to add a feature that it can catch NFC tag when my app is closed. I can do that by using intent-filter.
If my app is closed and I try to readout nfc tag, it asks me which app I should choose to open. Its normal. But now in my app (I have a button to start nfc communication), the app selector appears which I do not want.
My purpose is that: do not ask me which app I use while my app is working. it can ask when my app is closed.
Here is my intentfilter
[IntentFilter( new[] { NfcAdapter.ActionTechDiscovered }, Categories = new[] { Android.Content.Intent.CategoryDefault } )] [MetaData(NfcAdapter.ActionTechDiscovered, Resource = "@xml/rfid_type_list")]
my rfid_type_list
<?xml version="1.0" encoding="utf-8" ?> <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <!-- capture anything using NfcF --> <tech-list> <tech>android.nfc.tech.NfcA</tech> </tech-list> </resources>
How to force that nfc has to be opened by my app instead of asking when my app is working.
hope its clear.
-
Jetpack Navigation and Search Bar (Kotlin)
I have an activity with a fragment container inside. I'm using Jetpack Navigation to manage almost 100 fragments ! I'm using buttons for navigation but I want to add a searchBar. I associated keywords to each fragments so when the research is done I just want to go on the fragment I found.
The searchBar is on the activity.. So I need to be able to search from every fragment to go on every other fragments...
There are therefore 10,000 (100 * 100) combinations, I'm not going to create each of them...
Do you have an idea to do it easily ?
Thanks in advance, Sorry for my bad english, Thomas
- MS Access Multiple value from a FORM into table as a Single Line
-
Website connected to local database, how to make it remote access?
I have created a website that is hosted. The database it uses is connected locally. I created the database in MySQL workbench. How can I "host" this database remotely so that when using the website it can be accessed from any machine? Thanks
-
Merging columns with a key that tells which column should be prioritized based on suffix R
I have the following dataframe:
set.seed(123) df <- data.frame(col.dfA=rnorm(8,40,2), col.dfB=rnorm(8,20,2), colt=rnorm(8,100,20), pr.dfA=rnorm(8,20,2), pr.dfB=rnorm(8,30,2), priority=c("dfA","dfB","dfA","dfA","dfB","dfA","dfB","dfB"))
Now I would like to merge
col.dfA
&col.dfB
andpr.dfA
&pr.dfB
intodf$col
anddf$pr
respectively. Thedf$priority
column gives indication which column values should be used in each row. Ie. in the 1st, 3rd, 4th and 6th rows, columns with suffixdfA
should be prioritised. In remaining rows columns with suffixdfB
should be prioritised. The solution needs to be applicable for larger scenarios with dozens of columns and hundreds of rows.Initial dataframe:
col.dfA col.dfB colt pr.dfA pr.dfB priority 1 38.87905 18.62629 109.95701 18.74992 31.79025 dfA 2 39.53965 19.10868 60.66766 16.62661 31.75627 dfB 3 43.11742 22.44816 114.02712 21.67557 31.64316 dfA 4 40.14102 20.71963 90.54417 20.30675 31.37728 dfA 5 40.25858 20.80154 78.64353 17.72373 31.10784 dfB 6 43.43013 20.22137 95.64050 22.50763 29.87618 dfA 7 40.92183 18.88832 79.47991 20.85293 29.38807 dfB 8 37.46988 23.57383 85.42218 19.40986 29.23906 dfB
Expected result:
col colt pr priority 1 38.87905 109.95701 18.74992 dfA 2 19.10868 60.66766 31.75627 dfB 3 43.11742 114.02712 21.67557 dfA 4 40.14102 90.54417 20.30675 dfA 5 20.80154 78.64353 31.10784 dfB 6 43.43013 95.64050 22.50763 dfA 7 18.88832 79.47991 29.38807 dfB 8 23.57383 85.42218 29.23906 dfB
-
How to reach perfect list performance like whatsapp using react native?
I'm building a chat application, and I want my conversation screen to work like WhatsApp, You can scroll until infinity and will still feel smooth and fast.
My problem is that when you have a collection of 1k-10k messages when I scroll I see blanks, etc.
After some research I realized I probably need a different list than SectionList/FlatList.
I need a list that has sections (to group messages by date), can be inverted and recycle it's child items views to be able to render items fast.
I couldn't find any library that has all those 3 requirements I mentioned above, So I've come here, Have you ever encountered this kind of problem before, How did you solve it?
I'm aware WhatsApp is not built with react native.
-
Android Databinding not update UI immediately in RecyclerView
I have a recyclerView and each list item view contains two views -
- a text view to show some text from POJO using databinding lib and
- a button when that button is clicked, it calls method from viewmodel.
The viewmodel changes the text directly to the POJO. Every thing works fine except the recycler view needs to be refreshed to show changes.
My POJO
public class Post{ private String title; ...getter and setter }
Recycler Adatper is something like this.
public class MyRecyclerAdapter extends RecyclerView.Adapter<PostRecyclerAdapter.MyViewHolder> { private List<Post> posts; ... class MyViewHolder extends RecyclerView.ViewHolder { private final ViewDataBinding binding; public MyViewHolder(ViewDataBinding binding) { super(binding.getRoot()); this.binding = binding; } void bindView(int position) { Post post = posts.get(position); binding.setVariable(BR.post, post); binding.setVariable(BR.viewModel, myViewModel); binding.executePendingBindings(); } } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); ViewDataBinding binding = DataBindingUtil.inflate(inflater, R.layout.post_list_item, parent, false); return new MyViewHolder(binding); } @Override public void onBindViewHolder(MyViewHolder holder, int position) { holder.bindView(position); } ... }
post_list_item.xml
<layout xmlns:android="http://schemas.android.com/apk/res/android"> <data> <variable name="post" type="....Post" /> <variable name="viewModel" type="....MyViewModel"/> </data> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@{post.title}" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClickListener="@{()->viewModel.onButtonClicked(post)}" /> </LinearLayout>
and viewModel has this method.
public class MyViewModel extends ViewModel { public void onButtonClicked(Post post) { post.setTitle("some text"); }
I think there is a way to change the UI immediately when the data in POJO is changed. But now I need to draw the recycler view off the screen or rotate the screen.
-
Load Firebase Image as int
I have a RecyclerView with a list of Card Views as usual. This time tho, I'd like to set an Image in the CardView from my Firebase storage, but I cannot understand the error.
Here is the influenced Code:
From the main Fragment:
StorageReference mStorage= FirebaseStorage.getInstance().getReference().child("SliderGames/SlideCover2.jpg"); ArrayList<GameItem> GameList = new ArrayList<>(); GameList.add(new GameItem(Glide.with(this).load(mStorage).into(Cover), "SomeText"));
The Item:
package com.reogen.gametime.Items; public class GameItem { private int Cover; private String Title; private String Description; public GameItem(int CoverImage, String TextTitle, String TextDescription) { Cover = CoverImage; Title = TextTitle; Description = TextDescription; } public int getCover() { return Cover; } public String getTitle() { return Title; } public String getDescription() { return Description; } }
and last the Adapter:
public void onBindViewHolder(@NonNull GameViewHolder gameViewHolder, int position) { GameItem currentItem = mGameList.get(position); gameViewHolder.Cover.setImageResource(currentItem.getCover()); gameViewHolder.Title.setText(currentItem.getTitle()); gameViewHolder.Description.setText(currentItem.getDescription()); }
If using images from the drawable, everything goes fine, now that I have used glide in my Main fragment I get this error:
GameItem() in GameItem cannot be applied to: Expected Parameters: Actual Arguments: CoverImage: int Glide...this).load(oStorage).into(Cover) (com...android.graphics.drawable.Drawa ble>)
Since copy&pasting Android Studio error does'nt really make them understandable, here's a screen:
-
Create single adapter for any type of List Android
I am trying to create Generic Adapter in Android.
I am succeeded in creating to the given level where I have to extend RecyclerBaseAdapter
import kotlinx.android.synthetic.main.activity_animal_list.* class AnimalListActivity : AppCompatActivity() { private lateinit var animalAdapter: AnimalNewAdapter private val animalList = listOf( Animal("Monkey"), Animal("Dog"), Animal("Cat"), Animal("Chimpanzee"), Animal("Frog"), Animal("Elephant"), Animal("Cat"), Animal("Chimpanzee") ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_animal_list) animalAdapter = AnimalNewAdapter(R.layout.item_animal,true,animalList, { position, view -> Toast.makeText(this@AnimalListActivity, "Clicked at :" + position, Toast.LENGTH_LONG).show() }) recycler_view.apply { layoutManager = LinearLayoutManager(this@AnimalListActivity) adapter = animalAdapter } } }
AnimalNewAdapter.kt
import kotlinx.android.synthetic.main.item_animal.view.* class AnimalNewAdapter( layoutID: Int, clickable: Boolean, itemList: List<Animal>, onRecyclerItemClick: (position: Int, view: View) -> Unit ) : RecyclerBaseAdapter<Animal>(layoutID, clickable, itemList, onRecyclerItemClick) { override fun onBindViewHolder(holder: RecyclerBaseViewHolder, pos: Int) { holder.itemView.tv_animal.text = itemList.get(pos).title } }
RecyclerBaseAdapter.kt
abstract class RecyclerBaseAdapter<BO>(val layoutID: Int,val clickable:Boolean,val itemList: List<BO>, val onRecyclerItemClick: ((position: Int, view: View) -> Unit) ) : RecyclerView.Adapter<RecyclerBaseViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, position: Int): RecyclerBaseViewHolder { return RecyclerBaseViewHolder(parent,layoutID,clickable,onRecyclerItemClick) } override fun getItemCount(): Int { return itemList.size } }
Is it possible to create an adapter without need of AnimalNewAdapter. like below
animalAdapter = RecyclerBaseAdapter<Animal>(R.layout.item_animal,true,animalList, { position, view -> Toast.makeText(this@AnimalListActivity, "Clicked at :" + position, Toast.LENGTH_LONG).show() override fun onBindViewHolder(holder: RecyclerBaseViewHolder, pos: Int) { holder.itemView.tv_animal.text = itemList.get(pos).title } })
I want to remove this overhead to create a seperate adapter for each..
-
Data Deleted From Recycler List But Not From Sqlite Database
I am working on android application I which I am using Recycler Adapter and Sqlite database to delete and update the sqlite database.
My Problem is when I Click on Item in Recycler view to delete It Deletes the data from list, But When I Click Back and open List Again The deleted data is still there.
I have checked my database From device File Explorer That The Data does not deleted from database.
Same thing happens with the Update
Here is My Recycler Adapter Class
public class UserRecyclerAdapterSavedUsers extends RecyclerView.Adapter<UserRecyclerAdapterSavedUsers.UserViewHolder> { private List<User> listUsers; Context mContext; RecyclerView mRecyclerView; ItemClickListenerLongPressed itemClickListenerLongPressed; UserRecyclerAdapterSavedUsers userRecyclerAdapterSavedUsers; View itemView; public UserRecyclerAdapterSavedUsers(List<User> listUsers,RecyclerView recyclerView) { this.listUsers = listUsers; mRecyclerView=recyclerView; } @Override public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { mContext= parent.getContext(); itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_user_recycler_second, parent, false); return new UserViewHolder(itemView); } /** * ViewHolder class */ public class UserViewHolder extends RecyclerView.ViewHolder { //public AppCompatTextView ID; public AppCompatTextView textViewID; public AppCompatTextView textViewName; public AppCompatTextView textViewPassword; public AppCompatTextView textViewRole; LinearLayout layout; public UserViewHolder(View view) { super(view); textViewID = (AppCompatTextView) view.findViewById(R.id.textViewID); textViewName = (AppCompatTextView) view.findViewById(R.id.textViewName); textViewPassword = (AppCompatTextView) view.findViewById(R.id.textViewPassword); textViewRole = (AppCompatTextView) view.findViewById(R.id.textViewRole); layout = (LinearLayout) view.findViewById(R.id.list_view); } } @Override public void onBindViewHolder(UserViewHolder holder, final int position) { holder.textViewID.setText(listUsers.get(position).getUserid()); holder.textViewName.setText(listUsers.get(position).getName()); holder.textViewPassword.setText(listUsers.get(position).getPassword()); holder.textViewRole.setText(listUsers.get(position).getRole()); holder.layout.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { displayingAlertDialog(position); return false; } }); } public void setItemClickListenerLongPressed(ItemClickListenerLongPressed itemClickListenerLongPressed) { this.itemClickListenerLongPressed = itemClickListenerLongPressed; } @Override public int getItemCount() { Log.v(UsersRecyclerAdapter.class.getSimpleName(),""+listUsers.size()); return listUsers.size(); } private void displayingAlertDialog(final int position) { final User user= new User(); //displaying alert dialog box AlertDialog.Builder builder = new AlertDialog.Builder(itemView.getContext()); builder.setTitle("Choose Option"); builder.setMessage("Update or Delete?"); builder.setPositiveButton("Update", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //go to update activity gotupdateuserActivity(user.getUserid()); // dialog.cancel(); } }); builder.setNeutralButton("Delete", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //go to Remove Item DatabaseHelper dbHelper = new DatabaseHelper(mContext); dbHelper.deletePersonRecord(user.getUserid(), mContext); listUsers.remove( position); notifyItemRemoved(position); mRecyclerView.removeViewAt(position); notifyItemRangeChanged(position, listUsers.size()); notifyDataSetChanged(); dialog.cancel(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alert11 = builder.create(); alert11.show(); } public void remove(int position) { listUsers.remove(position); notifyItemRemoved(position); } private void gotupdateuserActivity(String userid) { Intent goToUpdate = new Intent(mContext, UpdateUserRec.class); goToUpdate.putExtra("USER_ID", userid); Toast.makeText(mContext, "USER REC", Toast.LENGTH_SHORT).show(); mContext.startActivity(goToUpdate); }
}
Here is Sqlite Database Helper Class
public class DatabaseHelper extends SQLiteOpenHelper { // Database Version private static final int DATABASE_VERSION = 2; Context context; // Database Name private static final String DATABASE_NAME = "DynamicERP.db"; public static final String table_imei = "IMEITABLE"; public static final String table_login= "USERLOGIN"; // User Table Columns names public static final String imeiid = "IMEIID"; public static final String imei = "IMEI"; public static final String userid = "USERID"; public static final String username = "USERNAME"; public static final String password = "PASSWORD"; public static final String userrole = "USERROLE"; // create table sql query private static final String DATABASE_CIMEI = "CREATE TABLE " + table_imei + "(" + imeiid + " INTEGER, " + imei + " VARCHAR );" ; private static final String DATABASE_CUSER = "CREATE TABLE " + table_login + "(" + userid + " INTEGER, " + username + " VARCHAR, " + password + " INTEGER, " + userrole + " VARCHAR );" ; // drop table sql query private String DROP_IMEI_TABLE = "DROP TABLE IF EXISTS " + table_imei; private String DROP_USER_TABLE = "DROP TABLE IF EXISTS " + table_login; /** * Constructor * * @param context */ public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CIMEI); db.execSQL(DATABASE_CUSER); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { //Drop User Table if exist db.execSQL(DROP_USER_TABLE); // Create tables again onCreate(db); } /** * This method is to create user record * * @param user */ public void addUser(User user) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(userid,user.getUserid()); values.put(username, user.getName()); values.put(password, user.getPassword()); values.put(userrole, user.getRole()); // Inserting Row db.insert(table_login, null, values); db.close(); } public void addIMEI(User user) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(imei,user.getImei()); values.put(imeiid, user.getImeiid()); // Inserting Row db.insert(table_imei, null, values); db.close(); } /** * This method is to fetch all user and return the list of user records * * @return list */ public List<User> getAllUser() { // array of columns to fetch String[] columns = { userid, username, password, userrole }; // sorting orders String sortOrder = userid + " ASC"; List<User> userList = new ArrayList<User>(); SQLiteDatabase db = this.getReadableDatabase(); // query the user table /** * Here query function is used to fetch records from user table this function works like we use sql query. * SQL query equivalent to this query function is * SELECT user_id,user_name,user_email,user_password FROM user ORDER BY user_name; */ Cursor cursor = db.query(table_login, //Table to query columns, //columns to return null, //columns for the WHERE clause null, //The values for the WHERE clause null, //group the rows null, //filter by row groups sortOrder); //The sort order // Traversing through all rows and adding to list if (cursor.moveToFirst()) { do { User user = new User(); //user.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(userid)))); user.setUserid(cursor.getString(cursor.getColumnIndex(userid))); user.setName(cursor.getString(cursor.getColumnIndex(username))); user.setPassword(cursor.getString(cursor.getColumnIndex(password))); user.setRole(cursor.getString(cursor.getColumnIndex(userrole))); // Adding user record to list userList.add(user); } while (cursor.moveToNext()); } cursor.close(); db.close(); // return user list return userList; } /** * This method is to fetch all user and return the list of user records * * @return list */ public List<User> getAllImei() { // array of columns to fetch String[] columns = { imeiid, imei, }; // sorting orders String sortOrder = imeiid + " ASC"; List<User> userList = new ArrayList<User>(); SQLiteDatabase db = this.getReadableDatabase(); // query the user table /** * Here query function is used to fetch records from user table this function works like we use sql query. * SQL query equivalent to this query function is * SELECT user_id,user_name,user_email,user_password FROM user ORDER BY user_name; */ Cursor cursor = db.query(table_imei, //Table to query columns, //columns to return null, //columns for the WHERE clause null, //The values for the WHERE clause null, //group the rows null, //filter by row groups sortOrder); //The sort order // Traversing through all rows and adding to list if (cursor.moveToFirst()) { do { User user = new User(); //user.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(userid)))); user.setImei(cursor.getString(cursor.getColumnIndex(imei))); user.setImeiid(cursor.getString(cursor.getColumnIndex(imeiid))); // Adding user record to list userList.add(user); } while (cursor.moveToNext()); } cursor.close(); db.close(); // return user list return userList; } /** * This method to update user record * * @param receivedUSERId * @param updateUserRec * @param user */ public void updateUser(String receivedUSERId, UpdateUserRec updateUserRec, User user) { SQLiteDatabase db = this.getWritableDatabase(); String strSQL = "UPDATE "+table_login+ " SET "+username+" = "+user.getName()+"," + " "+password+" = "+user.getPassword()+","+userrole+" = "+user.getRole()+"" + " WHERE "+userid+" = "+receivedUSERId; db.execSQL(strSQL); db.close(); } /** * This method is to delete user record * * @param user */ public void deleteUser(User user) { SQLiteDatabase db = this.getWritableDatabase(); // delete user record by id db.delete(table_login, userid + " = ?", new String[]{String.valueOf(user.getUserid())}); db.close(); } /** * This method to check user exist or not * @param userid * @return true/false */ public boolean checkUser(String userid) { // array of columns to fetch String[] columns = { userid }; SQLiteDatabase db = this.getReadableDatabase(); // selection criteria String selection = userid + " = ?"; // selection argument String[] selectionArgs = {userid}; // query user table with condition /** * Here query function is used to fetch records from user table this function works like we use sql query. * SQL query equivalent to this query function is * SELECT user_id FROM user WHERE imei = 'dynamic@imei.com'; */ Cursor cursor = db.query(table_login, //Table to query columns, //columns to return selection, //columns for the WHERE clause selectionArgs, //The values for the WHERE clause null, //group the rows null, //filter by row groups null); //The sort order int cursorCount = cursor.getCount(); cursor.close(); db.close(); if (cursorCount > 0) { return true; } return false; } /** * This method to check user exist or not * * @param email * @param password * @return true/false */ public boolean checkUser(String email, String password) { // array of columns to fetch String[] columns = { userid }; SQLiteDatabase db = this.getReadableDatabase(); // selection criteria String selection = userid + " = ?" + " AND " + password + " = ?"; // selection arguments String[] selectionArgs = {email, password}; // query user table with conditions /** * Here query function is used to fetch records from user table this function works like we use sql query. * SQL query equivalent to this query function is * SELECT user_id FROM user WHERE user_email = 'jack@androidtutorialshub.com' AND user_password = 'qwerty'; */ Cursor cursor = db.query(table_login, //Table to query columns, //columns to return selection, //columns for the WHERE clause selectionArgs, //The values for the WHERE clause null, //group the rows null, //filter by row groups null); //The sort order int cursorCount = cursor.getCount(); cursor.close(); db.close(); if (cursorCount > 0) { return true; } return false; } /** * This method to check user exist or not * * @param userid * @param username * @return true/false */ public boolean checkUserData(String userid, String username) { // array of columns to fetch String[] columns = { userid }; SQLiteDatabase db = this.getReadableDatabase(); // selection criteria String selection = userid + " = ?" + " AND " + username + " = ?"; // selection arguments String[] selectionArgs = {userid, username}; // query user table with conditions /** * Here query function is used to fetch records from user table this function works like we use sql query. * SQL query equivalent to this query function is * SELECT user_id FROM user WHERE user_email = 'jack@androidtutorialshub.com' AND user_password = 'qwerty'; */ Cursor cursor = db.query(table_login, //Table to query columns, //columns to return selection, //columns for the WHERE clause selectionArgs, //The values for the WHERE clause null, //group the rows null, //filter by row groups null); //The sort order int cursorCount = cursor.getCount(); cursor.close(); db.close(); if (cursorCount > 0) { return true; } return false; } public boolean checkUserData(String userid) { // array of columns to fetch String[] columns = { userid }; SQLiteDatabase db = this.getReadableDatabase(); // selection criteria String selection = userid + " = ?"; // selection argument String[] selectionArgs = {userid}; // query user table with condition /** * Here query function is used to fetch records from user table this function works like we use sql query. * SQL query equivalent to this query function is * SELECT user_id FROM user WHERE user_email = 'dynamic@data.com'; */ Cursor cursor = db.query(table_login, //Table to query columns, //columns to return selection, //columns for the WHERE clause selectionArgs, //The values for the WHERE clause null, //group the rows null, //filter by row groups null); //The sort order int cursorCount = cursor.getCount(); cursor.close(); db.close(); if (cursorCount > 0) { return true; } return false; } public User getUser(String id){ SQLiteDatabase db = this.getWritableDatabase(); String query= "SELECT * FROM "+table_login; Cursor cursor = db.rawQuery(query, null); User user = new User(); if(cursor.getCount() > 0) { cursor.moveToFirst(); user.setUserid(cursor.getString(cursor.getColumnIndex(userid))); user.setName(cursor.getString(cursor.getColumnIndex(username))); user.setPassword(cursor.getString(cursor.getColumnIndex(password))); user.setRole(cursor.getString(cursor.getColumnIndex(userrole))); } return user; } public void deletePersonRecord(String useridValue, Context mContext) { SQLiteDatabase db = this.getWritableDatabase(); db.execSQL("DELETE FROM "+table_login+" WHERE "+userid +"='"+useridValue+"'"); Toast.makeText(mContext, "Deleted successfully.", Toast.LENGTH_SHORT).show(); db.close(); } public void deleteIMEIRecord(String imeiidValue, Context mContext) { SQLiteDatabase db = this.getWritableDatabase(); db.execSQL("DELETE FROM "+table_imei+" WHERE "+imeiid +"='"+imeiidValue+"'"); Toast.makeText(mContext, "Deleted successfully.", Toast.LENGTH_SHORT).show(); } public void updateIMEI(String receivedIMEIId, UpdateIMEIRec updateIMEIRec, User user) { SQLiteDatabase db = this.getWritableDatabase(); String strSQL = "UPDATE "+table_imei+ " SET "+imei+" = "+user.getImei()+"," + " "+imeiid+" = "+user.getImeiid()+ " WHERE "+imeiid+" = "+receivedIMEIId; db.execSQL(strSQL); db.close(); } public User getIMEI(String receivedIMEIId) { SQLiteDatabase db = this.getWritableDatabase(); String query = "SELECT * FROM " + table_imei ; Cursor cursor = db.rawQuery(query, null); User user = new User(); if(cursor.getCount() > 0) { cursor.moveToFirst(); user.setImeiid(cursor.getString(cursor.getColumnIndex(imeiid))); user.setImei(cursor.getString(cursor.getColumnIndex(imei))); } return user; }
}
And Here is my Recycler List Activity Class
public class UserUpdateListActivity extends AppCompatActivity { AppCompatActivity activity = UserUpdateListActivity.this; AppCompatTextView textViewName; RecyclerView recyclerViewUsers; AppCompatButton textViewButtonNewUser; List<User> listUsers; UserRecyclerAdapterSavedUsers userRecyclerAdapterSavedUsers; DatabaseHelper databaseHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_record_updated_list); //getSupportActionBar().setTitle(""); initViews(); initObjects(); } @Override public void onBackPressed() { super.onBackPressed(); startActivity(new Intent(UserUpdateListActivity.this,AdminMain.class)); finish(); } @Override protected void onRestart() { super.onRestart(); } /** * This method is to initialize views */ private void initViews() { textViewName = (AppCompatTextView) findViewById(R.id.textViewName); textViewButtonNewUser = (AppCompatButton) findViewById(R.id.btnaddnew); recyclerViewUsers = (RecyclerView) findViewById(R.id.recyclerViewUsers); textViewButtonNewUser.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(UserUpdateListActivity.this,UserRecordSaveActivity.class)); } }); } /** * This method is to initialize objects to be used */ private void initObjects() { listUsers = new ArrayList<>(); userRecyclerAdapterSavedUsers = new UserRecyclerAdapterSavedUsers(listUsers,recyclerViewUsers); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext()); recyclerViewUsers.setLayoutManager(mLayoutManager); recyclerViewUsers.setItemAnimator(new DefaultItemAnimator()); recyclerViewUsers.setHasFixedSize(true); recyclerViewUsers.setAdapter(userRecyclerAdapterSavedUsers); databaseHelper = new DatabaseHelper(activity); String emailFromIntent = getIntent().getStringExtra("USERS"); textViewName.setText(emailFromIntent); getDataFromSQLite(); } /** * This method is to fetch all user records from SQLite */ private void getDataFromSQLite() { // AsyncTask is used that SQLite operation not blocks the UI Thread. new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { listUsers.clear(); listUsers.addAll(databaseHelper.getAllUser()); return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); userRecyclerAdapterSavedUsers.notifyDataSetChanged(); } }.execute(); }
}
This is the Query I am using to delete the data
public void deletePersonRecord(String useridValue, Context mContext) { SQLiteDatabase db = this.getWritableDatabase(); db.execSQL("DELETE FROM "+table_login+" WHERE "+userid +"='"+useridValue+"'"); Toast.makeText(mContext, "Deleted successfully.", Toast.LENGTH_SHORT).show(); db.close(); }
Here is image of my recycler list
As I click on an Item It open me a Dialog like this Dialog
When I click on delete this shows me this Clicking on Delete
After that As I pressed back and again open the Data I deleted again open Logcat has no Errors
Here is my update activity
public class UpdateUserRec extends AppCompatActivity { EditText UserIDUpdate,UserNameUpdate,UserPasswordUpdate,UserRoleUpdate; Button BtnUserRecUpdate; DatabaseHelper dbHelper; String receivedUSERId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update_record); UserIDUpdate= (EditText) findViewById(R.id.useridupdate); UserNameUpdate= (EditText) findViewById(R.id.usernameupdate); UserPasswordUpdate= (EditText) findViewById(R.id.userpasswordupdate); UserRoleUpdate= (EditText) findViewById(R.id.userroleupdate); BtnUserRecUpdate= (Button) findViewById(R.id.userbtnupdate); dbHelper = new DatabaseHelper(this); try { //get intent to get person id receivedUSERId= getIntent().getStringExtra("USER_ID"); } catch (Exception e) { e.printStackTrace(); } User user= dbHelper.getUser(receivedUSERId); UserIDUpdate.setText(user.getUserid()); UserNameUpdate.setText(user.getName()); UserPasswordUpdate.setText(user.getPassword()); UserRoleUpdate.setText(user.getRole()); BtnUserRecUpdate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { updateUserFunction(); } }); } private void updateUserFunction() { String useridupdate = UserIDUpdate.getText().toString().trim(); String usernameupdate = UserNameUpdate.getText().toString().trim(); String userpasswordupdate = UserRoleUpdate.getText().toString().trim(); String userroleupdate = UserRoleUpdate.getText().toString().trim(); if(useridupdate.isEmpty()){ //error name is empty Toast.makeText(this, "Enter User ID", Toast.LENGTH_LONG).show(); } if(usernameupdate.isEmpty()){ //error name is empty Toast.makeText(this, "Enter User Name", Toast.LENGTH_LONG).show(); } if(userpasswordupdate.isEmpty()){ //error name is empty Toast.makeText(this, "Enter the password", Toast.LENGTH_LONG).show(); } if(userroleupdate.isEmpty()){ //error name is empty Toast.makeText(this, "Enter User Role", Toast.LENGTH_LONG).show(); } //create updated person User user = new User(); //call dbhelper update dbHelper.updateUser(receivedUSERId, this, user); //finally redirect back home // NOTE you can implement an sqlite callback then redirect on success delete goBackHome(); } private void goBackHome() { startActivity(new Intent(UpdateUserRec.this,UsersListActivity.class)); }
}