I have read so many posts about how to populate the listview from a database. but i simply cant do it on my app! i dont know what im doing wrong. I´m very new to programming so there are allot of things i dont understand but im trying to learn 🙂
I add items to the database without any problems using this code in the activity:
String selectedstone = (String) stonespinner.getSelectedItem();
String weight = etaddweight.getText().toString();
db.addStone(new MyStonesDatabase(selectedstone, weight));
in the DatabaseHandler.java i have this:
// Adding new stone
void addStone(MyStonesDatabase stone) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_STONE, stone.getStone());
values.put(KEY_WEIGHT, stone.getWeight());
// Inserting Row
db.insert(TABLE_MYSTONES, null, values);
db.close(); // Closing database connection
}
I can see that my database gets populated by running this:
Log.d("Reading: ", "Reading all items..");
List<MyStonesDatabase> items = db.getAllstones();
for (MyStonesDatabase cn : items) {
String log = "Id: " + cn.getID() + ", Stone: "
+ cn.getStone() + ", Weight: " + cn.getWeight();
// Writing Items to log
Log.d("Name: ", log);
}
But when trying to have a listview to show the database my app either crashes or dont show anything. In my DatabaseHandler.java i have this:
// Getting All items from database
public List<MyStonesDatabase> getAllstones() {
List<MyStonesDatabase> stoneList = new ArrayList<MyStonesDatabase>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_MYSTONES;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
MyStonesDatabase stone = new MyStonesDatabase();
stone.setID(Integer.parseInt(cursor.getString(0)));
stone.setStone(cursor.getString(1));
stone.setWeight(cursor.getString(2));
// Adding stone to list
stoneList.add(stone);
} while (cursor.moveToNext());
}
// return stonelist
return stone;
}
I dont know what to put in my activity that should show the listview.
public class MyStones extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
Can someone please help me, im about to give up hehe 🙂
thanks!
Here is a great article/tutorial that might help you. Populating your listView isn’t as simple as just doing something in your Activity. You need to create a listAdapter and a couple other things. In the tutorial, they use hard-coded values, in an array. You might try getting that to work, then removing the hard-coded data, and using the data you are getting from your DB.
Getting this to work is a little trickier than you might think, but not overly complicated.
Hope this helps:
http://www.ezzylearning.com/tutorial.aspx?tid=1763429