Listview doesn't update while inserting data into Database - android

My question is about Updating listview after data changed in SQLite Database.My Listview doesn't updated when i insert data into databse.On my onRestart() i want to do something like this:
onRestart(){
super.onRestart();
custom_adapter.notifyDataSetChanged();
}
It gives me NullPointerException.
But instead of this i have to write full code:
onRestart(){
super.onRestart();
cursor.requery();
listview.setadapter(custom_adapter);
listview.setonClickListener(new OnclickListener(){
......
}
)};
}
My custom listview contains Imageview and Two TextView.

Calling the notifyDataSetChanged() method from the Adapter checks changes in the list<Objects> that was received in the Adapter constructor, so changing data in sql database is not the point, you have to make sure that you changed the data in the same List<Object> that u sent to the Adapter. in that case the listView will refresh automatic

Related

Best practice for add items to adapter from LiveData.observe()

I have DAO method returned LiveData<List<Category>>:
LiveData<List<Category>> listLiveData = categoryDao.getAll();
After that I need set this data to my Adapter:
listLiveData.observe(this, categories -> {
if (categories == null || categories.isEmpty()) {
price.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.INVISIBLE);
} else {
categoryAdapter = new CategoryAdapter(categories);
categoryAdapter.setOnItemClickListener(new ClickHandler());
recyclerView.setAdapter(categoryAdapter);
}
});
if I have not data in DB I show button for update(get data from server and insert to DB).
if I have data I create adapter and set data to it.
After that if I insert some Category to DB I get this:
triggered observe method and get all categories
create new adapter with this data
I think it is very bad practice(create a new adapter for update each item) and I can some way:
Change my adapter and add method addData(List<Category> categories);
in onCreateView I create adapter: categoryAdapter = new CategoryAdapter(new ArrayList());
then when I get data in observe method I add it to adapter:
adapter.addData(categories);
and into addData method in loop check each item and if not exist add to list and notify data.
change method
LiveData> listLiveData = categoryDao.getAll();
to
LiveData<Category> category = categoryDao.getLast();
and add this item to observe method. But I have 2 problems: 1 - How can I add firstly all data? I must implement 2 methods getAll(call wen create adapter) and getLast(call for each insert in DB). 2. How can I write this getLast method?
correct way that you will advise me :)
Your first step is right, you should create adapter only once in a lifecycle of Fragment or Activity and set the value(list) to adapter whenever you need to change dataset.
You should use getAll() method and it is best practice because you have data in local database and that doesn't take longer. If you have long data set then you should use pagination where only limited no. of items are fetched at a time. That can be achieved using LIMIT clause queries in sqlite.
And then use notifyDatasetChanged() method. If you want to show a smooth animation for newly inserted items use DiffUtil class to compare list and notify adapter accordingly.
To know how to use DiffUtil, check this out https://medium.com/#iammert/using-diffutil-in-android-recyclerview-bdca8e4fbb00
Hope this helps.

How to reload listview on a activity?

I have 2 activity.
In activity 1, i have a listview show data from database and button Insert
Activity 2 use to add something to database.
When I click button ADD in activity 2, i call method finish() and return to activity 1.
So, somebody can show me how to reload listview in activity 1 please?
Recreating the adapter should help, because you need to get a new dataset as Kaaaarll said.
So for example you have something like this in your code:
MyData data = database.getData();
MyAdapter adapter = new MyAdapter(data);
ListView list = new ListView();
list.setAdapter(adapter);
and in the next run, in the onResume(), get fresh data and reapply the adapter:
MyData data = database.getData();
MyAdapter adapter = new MyAdapter(data);
list.setAdapter(adapter);
You can re-query the database to get the latest data and then repopulate your listview's adapter.
Notify the dataset in the onResume() method activity 1. It should be something like listViewAdapter.notifyDataSetChanged();. Don't forget to check whether they are null or not.
Let me know if it worked.
EDIT:
Something like this should do the work (in activity 1):
#Override
protected void onResume() {
super.onResume();
if (listViewAdapter != null) {
listViewAdapter.notifyDataSetChanged();
}
}

Android, How do i Update the selected item in my listview from my database?

Here's my code so far, but the application crashes when I press the update button.
I want to update a selected item in my list, I have already created the update activity that will allow me to load the values on my database but I can't figure out how to load the value of selected item in list.
{
ArrayAdapter<String> ard=new ArrayAdapter<String> (this,android.R.layout.simple_list_item_single_choice,list);
lv.setAdapter(ard);
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
btnupdate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
SparseBooleanArray sba = lv.getCheckedItemPositions();
Intent intent = new Intent(HomeworkInfo.this, UpdateHomework.class);
startActivity(intent);
finish();
}
});
}
When an ArrayAdapter is constructed, it holds the reference for the List that was passed in. If you were to pass in a List that was a member of an Activity, and change that Activity member later, the ArrayAdapter is still holding a reference to the original List. The Adapter does not know you changed the List in the Activity.
Your choices are:
Use the functions of the ArrayAdapter to modify the underlying List (add(), insert(), remove(), clear(), etc.)
Re-create the ArrayAdapter with the new List data. (Uses a lot of resources and garbage collection.)
Create your own class derived from BaseAdapter and ListAdapter that allows changing of the underlying List data structure.
Use the notifyDataSetChanged() every time the list is updated. To call it on the UI-Thread, use the runOnUiThread() of Activity. Then, notifyDataSetChanged() will work.
I hope this helps you ..
Happy coding !!

Android/java sqlite data to list

Im following a tutorial and i have created a database class and a activity class. Here is my activity class:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
datasource = new CommentsDataSource(this);
datasource.open();
List<Comment> values = datasource.getAllComments();
// Use the SimpleCursorAdapter to show the
// elements in a ListView
ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
My db is a bit different but most of the stuff is the same as in tutorial. Comment is just a setter/getter class.
Now the problem is that in my list i want to display comment name but i get "com.example.blabla.Comment#40dca9d0". I think it is because i am passing the whole comment class to the adapter. How would be the right way to pass the name?
Here is the link to tutorial, i must be missing something because it seems to work there but i dont know what exactly: http://www.vogella.com/articles/AndroidSQLite/article.html#sqliteoverview_sqliteopenhelper
// Will be used by the ArrayAdapter in the ListView
#Override
public String toString() {
return comment;
}
Did you make sure you added this to your Comment class?
In java the default implementation of toString() is Class#Hashcode which is what currently yours is showing, hence you need to override the default implementation by returning the comment.
You do not see toString() being called because it says in DOCS(parag2)
However the TextView is referenced, it will be filled with the
toString() of each object in the array. You can add lists or arrays of
custom objects. Override the toString() method of your objects to
determine what text will be displayed for the item in the list.

How can I refresh an adapter from an onClick event in Android

I have a ArrayAdapter onto which each row has a button which deletes the data associated to the row. So onClick for the "on row delete button" how do I delete the row from the display? I believe I need to refresh the parent view?
public void onClick(View v) {
deleteThisRowFromDB();
//ok now how do I delete this row from the ArrayAdapter display?
}
You can call notifyDataSetChanged() method for refreshing data. You might need to override the method as below,
#Override
public void notifyDataSetChanged()
{
super.notifyDataSetChanged();
}
You can use the simple cursor adapter to bind data to the listview or (parent view)... whenever you delete data from database cursor adapter will updates itself automatically
FYI
Check this example
update the database with deleting the data,
set notify to Adapter by using the method:
adapter.notifyDataSetChanged();

Categories

Resources