Hey i use a listview for demonstrate entries which are stored in a database. I also have a EditText element and a button which adds the content of the EditText into the Database. To bind the view to the database content i use the SimpleCursorAdapter and following populate function:
private void populate() {
cursor = dbAdapter.getAllItems();
startManagingCursor(cursor);
String[] from = new String[] { DBAdapter.KEY_TASK };
int[] to = new int[] { android.R.id.text1 };
// Now create an array adapter and set it to display using our row
cursorAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, from, to);
list.setAdapter(cursorAdapter);
}
If i added a new entry, by clicking on the button i want to refresh the listview but this only works with the populate function and not with the common adapter function notifyDataSetChanged();. Do i have a bug or is this the right way to refresh a listview?
Have you seen this, tried the swap cursor method, or tried just simply calling setAdapter() again?
I had a similar issue where I could not get my list to update, and what I did was just create a refreshListView() method. Now you can call this initially from your onCreate(), AND anytime a user adds something to the DB. All it does is re-bind the listview to a cursor. With all the deprecating methods (requery()), and issues with notifyDataSetChanged(), I decided this was the easiest way.
Please refer this link...it works like charm
Update SimpleCursorAdapter while maintaining scroll position in ListView
for dynamic listview on scroll i added new item from database ..
I did mistake here ..
i was assigning new adapter for each time for same simplecursoradapter .
Instead of creating new adapter.
just use
adapter.changecursor(newcursorValue);
adapter.notifydatasetChanged();
lsMedicine1.setSelectionFromTop(lsMedicine1.getLastVisiblePosition()-20, 0);
You need to call swapcursor() before notifyDataSetChanged() on the adapter.
Related
I have a custom ArrayAdapter which is set to a listview with data from database:
CustomAdapter adapter = new CustomAdapter(myview.getContext(), -1, database.getAll());
listview.setAdapter(adapter);
Now, I want when the user deletes a database item the listview should refresh.
Until now, I can successfully delete the item from the database, but it remains in the listview. In the ArrayAdapter class I call refresh() method from a new class same to adapter's parent class
public void refresh(){
ParentClass class_par = new ParentClass();
class_par.refreshfromParent();
}
And in the ParentClass I have a new method: refreshfromParent()
public void refreshfromAlarm(){
DatabaseHandler database = new DatabaseHandler(myview.getContext());
listview.setAdapter(new CustomAdapter(myview.getContext(), -1, database.getAll())); // here I change listview adapter, and populate it with new database data, but I get NullPointerException
}
So, how can I refresh listview items? Please, DO NOT mention notifyDataSetChanged(), it DOES NOT work.
here you making en error
CustomAdapter adapter = new CustomAdapter(myview.getContext(), -1, database.getAll());
listview.setAdapter(adapter);
//so first you should make an arrayList and define it globally like
// ArrayList <yourType>list = new ArrayList<>();
//then initialize your adapter like this
list.addAll(databse.getAll());
CustomAdapter adapter = new CustomAdapter(myview.getContext(), -1, list);
listview.setAdapter(adapter);
// now when you want to delete an item
// delete it from your list like list.remove(location)
// and also delete same item from your datebase
// after that just call this
notifyDataSetChanged();
I realized that notifyDataSetChanged is a big trouble, so I decided to close and reload my fragment which contains my listview. Thus, the result looks the same with DataSetChanged and there is no difference in the users' eyes. I suggest everyone who reaches in this question do the same.
I have created new ListView in my app, I have my ListView, and in an ActionBar there is a button "add new". The button's function is to make a new item in the ListView.
My question is: How can I make a new String in my ListView when the button is pushed?
This is example if you need only simple String rows.
ListView lv = (ListView) findViewById(R.id.mylist);
String[] values = new String[] { "Android", "Linux", "OSX",
"WebOS", "Windows7", "Ubuntu", "OS/2"
};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.rowlayout, R.id.restaurantname, values);
lv.setAdapter(adapter);
adapter.add("another row");
adapter.notifyDataSetChanged()
ListView are widgets that display multiple Views that are managed by an Adapter. To be specific, a ListAdapter.
You need to add an adapter to your listview widget, and use that adapter to add new items to the listview.
For example; you could add an ArrayAdapter and call the add method when a user clicks the ActionBar item.
Here is a tutorial on using ArrayAdapters.
In the most basic form. You can tell ArrayAdapter to use an existing Layout and TextView. So adding a string should be straightforward.
Basically tou have to do some like this:
your_btn.setOnClickListener(new View.OnClickListener
{
public void onClick(View v)
{
your_custom_adapter.Add('Foo');
your_custom_adapter.notifyDataSetChanged();
}
});
The implementation for method Add in your adapter is obvious,it just adds a new String to your data structure(i.e: an ArrayList).
Good Luck
If you mean: adding a new item to list with button click,
It is certainly bounded to what model you used is your list adapter. A database, a file or just a runtime List<>();
Your list is connected with an adapter; the method "getViewAt" returns every row in your listview.
If you used a database model for listview, you run an insert script in your activity for button click, database refreshes its data, your listview adapter retrieves data from DB and it's done.
Or if you're just using a simple List<> in your adapter; you will do list.add in your click & adapter does the rest.
Sample at vogella, using Map as data modeling: Listview sample
I am using ListView in android
My data is coming from database
I Have learned SimpleCursorAdapter and this is the code from official docs
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.person_name_and_number, cursor, fromColumns, toViews, 0);
ListView listView = getListView();
listView.setAdapter(adapter);
All the thing i have understand successfully created the list view also but there is one doubt
what the use of last argument 0 in the constructor they have not explained. Please tell me what this last argument is doing here.
The SimpleCursorAdapter documentation explains that these are flags used to determine the behavior of the adapter:
Flags used to determine the behavior of the adapter, as per
CursorAdapter(Context, Cursor, int).
See the CursorAdapter docs for more information.
Listview from Cursor (without Loaders)
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
this, // The Activity context
R.layout.list_item, // Points to the XML for a list item
cursor, // Cursor that contains the data to display
dataColumns, // Bind the data in column "text_column"...
viewIDs // ...to the TextView with id "R.id.text_view"
);
Listview from Cursor (Using Loaders)
To Asynchronously load data to the Containers(Listview or Fragments) Loaders are best approach.
// Initialize the adapter. Note that we pass a "null" Cursor as the
// third argument. We will pass the adapter a Cursor only when the
// data has finished loading for the first time (i.e. when the
// LoaderManager delivers the data to onLoadFinished). Also note
// that we have passed the "0" flag as the last argument. This
// prevents the adapter from registering a ContentObserver for the
// Cursor (the CursorLoader will do this for us!).
mAdapter = new SimpleCursorAdapter(this, R.layout.list_item,
null, dataColumns, viewIDs, 0);
The following URL describes above.
http://www.androiddesignpatterns.com/2012/07/understanding-loadermanager.html
I have a ListView (technically its a ListFragment, but I dont think that changes the question) which displays its results uisng a SimpleCursorAdapter.
adapter = new SimpleCursorAdapter(
getActivity(),
R.layout.item,
null,
new String[] {"Name"},
new int[] {R.id.Name}
);
setListAdapter(adapter);
(The Cursor is set/swapped in onStart).
I want to give the user the ability to toggle choice mode (which will than be used to display only the checked items). A bit like an SMS application when you put messages in "batch mode" which allows you to select multiple conversations which can the be deleted, saved etc. Do I set a new adapter or just change the existing ones properties? the ListView will need re-drawing anyway to reflect changes.
You have to do two things.
Use the ListView's setChoiceMode method to enable MULTI_SELECT on the ListView.
Create a 'Selector' to define a 'selected' or 'checked' state and set this as a style element on your R.layout.item.
Like Vikram Bodicherla answer.
setChoiceMode to enable MULTI_SELECT on the ListView.
Set in your custom item layout a background that show the selected state like:
android:background="?android:attr/activatedBackgroundIndicator"
This is a suprisingly simple answer. The problem was I was calling the method in onCreate before onCreateView had inflated the List. Stupdily this was just to test the function. Once I moved it to onStart and later into its intended location in the FragmentActivity the following worked fine:
public void toggleAdapter()
{
ListView listView = getListView();
if (listView.getChoiceMode() == ListView.CHOICE_MODE_MULTIPLE)
{
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
adapter = new SimpleCursorAdapter(
getActivity(),
R.layout.item,
dashboardCursor,
new String[] {"Name"},
new int[] {R.id.Name}
);
}
else
{
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
adapter = new SimpleCursorAdapter(
getActivity(),
R.layout.dashboard_list_item_multiple_choice,
dashboardCursor,
new String[] {"Name"},
new int[] {R.id.Name}
);
}
listView.setAdapter(adapter);
}
I have an application with a Spinner whos data is populated by a cursor from the database. Works great if there is something in the database table on startup. However, if I add something to the database after the app is running my spinner always shows that it has zero choices, even if one was there to begin with.
My code is as follows. The adapter.getCursor().requery(); did no good. I would like the Spinner to update its choices when the user clicks on it and I found a couple posts on StackOverflow that say you have to use the TextView behind the Spinner for the OnClickListener. However, for me that did nothing. Mostly likely because I'm missing one minor
c1 = myDbHelper.readCars();
startManagingCursor(c1);
// create an array to specify which fields we want to display
String[] from = new String[]{"nickname"};
// create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1};
adapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c1, from, to);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinVehicle.setAdapter(adapter);
txtVehiclePrompt.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
adapter.getCursor().requery();
}
});
Just change the underlying data and call notifyDataSetChanged()
list.clear();
//list modify
list.add("A");
list.add("B");
dataAdapter.notifyDataSetChanged();
Ok,
I got it figured out. I needed to close the adapter, stop managing the cursor, close the cursor & close the db helper in the onSuspend() method then set everything back up in the onResume method since I was using a seperate activity to add records to the table.