Delete and refresh items from a listview and database - android

I cannot refresh my list view after deleting the records.
String str3 = favtitle.get(position);
//position = Integer.parseInt(cur.getString(cur.getColumnIndex("id")));
db.delete("Favorites7","title= '"+str3+"'",null);
//mSchedule.notifyDataSetChanged();
cur.requery();
cur= db.query("Favorites7",
null, null, null, null, null, null);
cur.moveToFirst();
while (cur.isAfterLast() == false) {
//name.append("n" + cur.getString(1));
//mylist.addAll(cur.getString(i));
favtitle.add(cur.getString(1));
favloc.add(cur.getString(3));
favemp.add(cur.getString(2));
lat.add(cur.getString(7));
log.add(cur.getString(8));
//nextScreenData.add(cur.getString(2).toString());
cur.moveToNext();
}
cur.close();
mylist = new ArrayList<HashMap<String,Object>>();
HashMap<String,Object> map = new HashMap<String, Object>();
for(int i=0;i<favtitle.size();i++)
{
map = new HashMap<String, Object>();
map.put("train",favtitle.get(i));
map.put("value",favloc.get(i));
map.put("employer",favemp.get(i));
mylist.add(map);
}
mSchedule.notifyDataSetChanged();
mSchedule = new SimpleAdapter(Favorites.this, mylist, R.layout.listdelete,
new String[] {"train","value","employer"}, new int[] {R.id.dept,R.id.jobloc,R.id.employer});
lv.setAdapter(mSchedule);
lv.setDividerHeight(2);
lv.setCacheColorHint(Color.WHITE);
//cur.requery();
Thanx in advance.

You can just create a new Adapter, and then assign it to the ListView.

You can call notifyDataSetChanged() on your Adapter and it will reflect the changes to the ui

When the delete button is clicked do the following:
Delete the corresponding list item from the database.
Get an new cursor for your list by executing the query which fills the list again.
Bind the new cursor to the list using changeCurosr().
Call notifyDataSetChanged() on the adapter.

Related

Displaying Data in The ListView in Android

I am retrieving data from SQLite and trying to display it in the ListView. The problem is I have two columns in the database and the listview only shows data from one column. I am using following code for this purpose
public List<entry> getAllEntries() {
List<Entry> entries = new ArrayList<Entry>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_ENTRIES,
allEntries, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Entry entry = cursorToEntry(cursor);
Entry entry1 = cursorToEntry(cursor);
Log.d(TAG, "get entry = " + cursorToEntry(cursor).toString());
entries.add(entry);
cursor.moveToNext();
Log.d(TAG, "get amount = "+ cursorToEntries(cursor).toString1());
entries.add(entry1);
cursor.moveToNext();
}
cursor.close();
return entries;
}
And I have also been trying following code
while(cursor.moveToNext())
{
entries.add("Entry"+cursor.getString(1)+"Amount"+cursor.getString(2));
}
And thats how I am displaying it in the ListView
List<Entry> values = datasource.getAllEntries();
ArrayAdapter<Entry> adapter = new ArrayAdapter<Entry>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
You can either use a CursorAdapter, which lets you specify a row layout as well as how to map from columns in the cursor to views in the layout; or you can write your own adapter implementation that extends from BaseAdapter and is internally backed by a Cursor. I suggest you watch The World of ListView.

Populate Listview from List

Im trying to populate a listview from a list, this is the method that create my list:
public List<produto> buscarProdutoPorNome(String nome){
List<produto> lista = new ArrayList<produto>();
String[] columns = new String[]{
"upc", "nome", "descricao", "qtd", "nec"};
String[] args = new String[]{nome+"%"};
db = dbHelper.getWritableDatabase();
Cursor c = db.query("produto", columns,
"nome like ?", args, null, null, "nome");
c.moveToFirst();
while(!c.isAfterLast()){
produto p = fillProduto(c);
lista.add(p);
c.moveToNext();
}
c.close();
db.close();
return lista;
}
Im wanna list, but i dont know how, someone can help me?
List<produto>lista = produtosDB.buscarProdutoPorNome("");
Why not convert the List into an array as:
producto[] array = lista.toArray(new producto[lista.size()]);
and then populate to the ListView as
setListAdapter(new ArrayAdapter<producto>(this, R.layout.list_item, array));
List<String> array = new ArrayList<String>();
// Populate the array list from the database
final ListView list = (ListView) findViewById(R.id.listview);
final ArrayAdapter<String> = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, array);
list.setAdapter(adapter);
This is the simplest way to do it, but will work for a string list only. To have an adapter with your custom class list you will need to create a custom adapter class and a custom view layout in res/layout. Find more info on custom adapters here:
http://www.vogella.com/tutorials/AndroidListView/article.html#adapterown

How to get values from a spinner populated from a cursor

I've populated my spinner as this:
DatabaseConnector dbConnector = new DatabaseConnector(this);
dbConnector.open();
Cursor c = dbConnector.raw("SELECT _id, nombrecasa FROM casa");
startManagingCursor(c);
String[] from = new String[]{"nombrecasa"};
int[] to = new int[]{android.R.id.text1};
SimpleCursorAdapter adapter =
new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
casaSpinner = (Spinner) findViewById( R.id.casaspinner);
casaSpinner.setAdapter(adapter);
dbConnector.close();
}
And when I try to get the value as:
String idcasa = casaSpinner.getSelectedItem().toString();
it only returns this:
android.database.sqlite.SQLiteCursor#40539880
Your spinner has taken a SimpleCursorAdapter as an adapter, of which its dataset is a Cursor. When you select an item on the spinner, you've only moved the cursor to a specific row and when you call getSelectedItem() you're still requesting for the dataset object - which is still a cursor object. to do what you're trying you can simply call:
c.getString(1);
once your selection has been made. For something a little more fundamentary illustrative of what i said.
((Cursor) casaSpinner.getSelectedItem()).getString(1);

listview shows only one value in one block

i have a listview and its data values is separated by blocks( Item1, Item2...) but i want to know how to show (Item 1, Sub Item 1...) ?
well here is the code that shows only the Item, so how do i show the Item and the Sub Item?
code:
//LISTVIEW database CONTATO
ListView user = (ListView) findViewById(R.id.lvShowContatos);
//String = simple value ||| String[] = multiple values/columns
String[] campos = new String[] {"nome", "telefone"};
list = new ArrayList<String>();
Cursor c = db.query( "contatos", campos, null, null, null, null, "nome" + " ASC ");
c.moveToFirst();
String lista = "";
if(c.getCount() > 0) {
while(true) {
list.add(c.getString(c.getColumnIndex("nome")).toString());
if(!c.moveToNext()) break;
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
user.setAdapter(adapter);
the code i putted there but still gives me errors and i dont see where it gets the values from yet.
//LISTVIEW database CONTATO
ListView user = (ListView) findViewById(R.id.lvShowContatos);
//String = simple value ||| String[] = multiple values/columns
String[] campos = new String[] {"nome", "telefone"};
ArrayList<HashMap<String, Object>> items = new ArrayList<HashMap<String,Object>>();
HashMap<String, Object> listItem;
Cursor c = db.query( "contatos", campos, null, null, null, null, "nome" + " ASC ");
c.moveToFirst();
listItem = new HashMap<String, Object>();
listItem.put("nome", "your_item_text");
listItem.put("telefone", "your_subitem_text");
items.add(listItem);
adapter = new SimpleAdapter(this, items, R.layout.custom_list_layout, new String[]{"item", "subitem"}, new int[]{R.id.text_item, R.id.text_subitem});
user.setAdapter(adapter);
Use SimpleAdapter, not the ArrayAdapter to populate the ListView: http://developer.android.com/reference/android/widget/SimpleAdapter.html
There you will have an array of fields to populate for each item, like:
ArrayList<HashMap<String, Object>> items = new ArrayList<HashMap<String,Object>>();
HashMap<String, Object> listItem;
listItem = new HashMap<String, Object>();
listItem.put("item", "your_item_text");
listItem.put("subitem", "your_subitem_text");
items.add(listItem);
adapter = new SimpleAdapter(this, items, R.layout.custom_list_layout, new String[]{"item", "subitem"}, new int[]{R.id.text_item, R.id.text_subitem});
listview.setAdapter(adapter);
Remember also to create custom_list_layout.xml for your ListView items, and make sure it contains textViews with proper ids:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/text_item"
... />
<TextView
android:id="#+id/text_subitem"
... />
</RelativeLayout>
Look at ExpandableListView, that is exactly for this user case.
You will have to create your own custom adapter extending either the ArrayAdapter or the BaseAdapter and you will also have to create an xml layout for your items in the list.
If you are new to ListView go through this tutorial on ListView.

Android: setListAdapter sets only last row in database

as the title states I am having a little trouble linking my data from a database to a listview, the problem being that the adapter will set only the last row returned, as opposed to each row from the database table.
An example of what I am trying to achieve:
TABLE ANIMAL:
Monkey
Cat
Dog
Tiger
will show up as only Tiger on screen.
My method returning cursor from the database:
public Cursor retrieveAnimals(){
return = DB.query(ANIMAL_TABLE, new String[] {
KEY_ROWID,
KEY_ANIMALNAME,
},
null,
null,
null,
null,
null);
}
and setting the listview
dbm = new MyDBManager(this);
dbm.open();
dbm.deleteAnimals();
dbm.populateDB();
// after populating, set the adapter..
myCursor = dbm.getAllAnimals();
String[] columns = new String[] {"animal_name"};
int[] to = new int[] {R.id.animal};
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, R.layout.row, myCursor, columns, to);
this.setListAdapter(mAdapter);
I have a feeling my problem lies in the cursor position, in that it is moving automatically to the last row when setting the adapter, I have been trying to find a solution to my problem but with no luck.
Thanks in advance for any suggestions.
EDIT: Method to populate DB
public long populateDB(){
ContentValues initialValues = new ContentValues();
for(int i = 0; i < animalName.length; i++){
initialValues.put(KEY_ANIMALNAME, animalName[i]);
}
return DB.insert(ANIMAL_TABLE, null, initialValues);
}
In your retrieveAnimals(), the line should be return DB.query(...) (note the lack of an = between return and DB.query).
Apart from that your code looks fine. You should call startManagingCursor on the cursor (after calling getAllAnimals) to avoid memory leaks.
Edit: change your populate method to:
public long[] populateDB(){
ContentValues initialValues = new ContentValues();
long[] rowIds = new long[animalName.length];
for(int i = 0; i < animalName.length; i++){
// here we are using a single ContentValues object and inserting it
// into the DB before changing the ContentValues and inserting it again
initialValues.put(KEY_ANIMALNAME, animalName[i]);
rowIds[i] = DB.insert(ANIMAL_TABLE, null, initialValues);
}
return rowIds;
}
Alternatively (more memory usage, but useful perhaps if you need to modify some of the records before inserting them):
public void populateDB(){
ContentValues[] initialValues = new ContentValues[animalName.length];
for(int i = 0; i < animalName.length; i++){
// create a new ContentValues for each object
initialValues[i] = new ContentValues();
initialValues[i].put(KEY_ANIMALNAME, animalName[i]);
}
// now our contentvalues is filled we can insert them all
for(int i = 0; i < animalName.length; i++){
DB.insert(ANIMAL_TABLE, null, initialValues[i]);
}
}
Did you try
myCursor.moveToFirst()

Categories

Resources