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
Related
For example; I have long listview and it has 30 lines(items). I want to show this listview but after open the screen, it will show 15. lines. That is, the middle of the listview will be shown automatically. Is it possible? (NOTE: I don't want to show 15. line as first row.)
UPDATE:
i don't want to delete rows. I have listview and it works well. I want to show the middle of list. Scrool will flow until 15. row and i will see all of them but it will show 12. or 15. row when listview opens.
Bind your ListView to ArrayAdapter
final ListView lv = (ListView) findViewById(R.id.lv);
String[] fruits = new String[] {
"Cereus peruvianus",
"Bacupari",
"Beach Plum",
"Black raspberry"};
// Create a List from String Array elements
final List fruits_list = new ArrayList(Arrays.asList(fruits));
// Create an ArrayAdapter from List
final ArrayAdapter arrayAdapter = new ArrayAdapter
(this, android.R.layout.simple_list_item_1, fruits_list);
// DataBind ListView with items from ArrayAdapter
lv.setAdapter(arrayAdapter);
Remove / Delete first item from List. You may remove multiple in a loop.
fruits_list.remove(0);
// Notify adapter
arrayAdapter.notifyDataSetChanged();
Edit:
// For scrolling to specific item in your list
lv.smoothScrollToPosition(15); // Here 15 is the position of the item
Answer is lv.setSelection(15);
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 Mainactivity which contain listview with some item and I want to add another listview in that listview as footer.How can I add this
Its not recommended to add a ListView as a footer of another ListView. You might consider making a list of objects containing both list and pass the list to your Adapter.
So if you merge two lists in a common format, you need to be tricky for the layout selection for each item in your list. Let me show you an example of a common class.
public class CommonClass {
// Set null values initially.
private ClassA mFirstListClass = null;
private ClassB mSecondListClass = null;
}
Now take an ArrayList of this object to pass it to your Adapter. In your bindView check if the item is a ClassA object or ClassB object (as you can easily determine them by checking which object is null) and then set proper action.
I think for these kinds of problems RecyclerView is better. Its very simple to implement and you can find the implementation document here.
// Create a List from String Array elements
final List<String> tests = new ArrayList<String>(Arrays.asList(test));
// Create an ArrayAdapter from List
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, tests);
// DataBind ListView with items from ArrayAdapter
lv.setAdapter(arrayAdapter);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Add new Items to List
tests.add("abc");
tests.add("def");
/*
notifyDataSetChanged ()
Notifies the attached observers that the underlying
data has been changed and any View reflecting the
data set should refresh itself.
*/
arrayAdapter.notifyDataSetChanged();
}
});
for more http://android--code.blogspot.in/2015/08/android-listview-add-items.html
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.
I'm trying to bind data do a listview on android, but I'm not able to.
I saw some code on the internet and it worked, but I just don't know why, and I don't want to create a new ListView on the fly, I want to use the one that is listed on the main.xml
Why I can do this:
ListView lv = new ListView(this);
lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,PEOPLE));
setContentView(lv);
But I can't do this:
ListView listPessoas = (ListView) findViewById(R.id.listPessoas);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.id.listPessoas, PESSOAS);
listPessoas.setAdapter(adapter);
What is R.id.pessoas??
This works fine for me:
String[] x = new String[]{"AAA","BBB","CCC"};
ListView lv = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> test = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,x);
lv.setAdapter(test);
Your error here is when you are creating the new ArrayAdapter. You are passing R.id.listPessoas as the row view to use for each row. This is the id of the ListView. The adapter is looking for a layout id containing a text view to be used for each row of the list. Change the R.id.listPessoas to android.R.layout.simple_list_item_1 and your code should work. The simple_list_item_1 layout is just a TextView that the data will be bound to.
What you have written is not correct, the second parameter in the array adapter constructor should be the simple layout for each list item not again your list view.
If your have a custom complex layout for your list item you need to write a custom adapter as well.
If you are getting error.
getApplicationContext(); will work instead of 'this'.