populate ListView from my database - android

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

Related

Android - How to retrieve values from SQLite Database and post them as Checkboxes

I'm currently trying to retrieve values from my SQLite Database. Screenshot
And output the value of the subname and units on checkboxes. I'm pretty sure I just have to get the IDs so I could output the subname and units values as checkboxes, so subname + unit = 1 checkbox. Could you please provide a sample code or link me a tutorial on how to do this? I'm rather clueless on how to do this and really new to Android.
I'm also looking for a way on how to save their IDs afterwards and add them into another table, so when I retrieve the IDs it will output the values. If you know how to do this too please do help. Thank you! Your time is much appreciated
Currently I have this in my DatabaseHandler.java. I just really don't know the code or syntax on how to retrieve it in my MainActivity and output it on checkboxes.
//get all subjects
public List < Subject > getAllSubjects() {
List < Subject > subjectList = new ArrayList < Subject > ();
//select all query
String selectQuery = " SELECT * FROM " + TABLE_SUBJECTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
//loop through all rows and add it to list
if (cursor.moveToFirst()) {
do {
Subject subject = new Subject();
subject.setID(Integer.parseInt(cursor.getString(0)));
subject.setSubName(cursor.getString(1));
subject.setUnits(cursor.getString(2));
//ADD CONTACT TO LIST
subjectList.add(subject);
} while (cursor.moveToNext());
}
return subjectList;
}

Android - SQLite db keeps showing rows that should have been deleted

I'm currently creating an app that downloads lists from a server and places those lists into an SQLite database. In the Mainactivity it calls the lists from the db and places them into a custom adapter, everything works fine and such.
After this I go through several screens to proces the listdata and in the final activity it uses a query to delete the row it's been working on from the db. I use logcat to print the db after this and it shows that the row has been deleted.
Next it takes me back to the Mainactivity and in its onResume I once again load the lists from the db only to find that the row that should have been deleted is still in it. The listview is being updated correctly, it's really an issue of retrieving data from the database that should have been deleted.
So, anybody has an idea why I get rows that have been deleted in another activity?
Mainactivity:
private List<String> list = new ArrayList<>();
public void onResume() {
super.onResume();
context = getApplicationContext();
ConsLoadListDataSource cllDataSource = new ConsLoadListDataSource(context);
cllDataSource.open();
list = cllDataSource.sqliteToListIds();
cllDataSource.close();
logcat("Jadajada: " + list.toString());
}
SQLiteHelper:
public List<String> sqliteToListIds() {
List<String> conList= new ArrayList<>();
if (!db.isOpen()) {
open();
}
Cursor cursor = db.query(ConsLoadListSQLHelper.TABLE_CONS_HEADER,
allConsListColumns, null, null, "loadlist" , null, "loadlist");
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
conList.add(cursor.getString(1));
cursor.moveToNext();
}
db.close();
return conList;
}
The deleting method works, but since it's being asked for:
public void deleteList(int id) {
if (!db.isOpen()) {
open();
}
db.delete(ConsLoadListSQLHelper.TABLE_CONS_HEADER,
ConsLoadListSQLHelper.CONS_HEADER_ID + " = " + id, null);
db.close();
}
edit
I've found a workaround solution by deleting the row on my server and once again retrieving all data from the server before I go back to my MainActivity, but I still don't know how to solve the original problem and this makes my app more dependent on an internet connection, so it's not perfect, but will have to do for now.
For deleting single item you have to use
public void deleteRule(String value) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(Table_Name, Key_value + " = ?",
new String[] { value });
db.close();
}
Hope it helps.

What is going wrong in this?

I am fetching the list of tables from the database. I am using this code to get the list of tables:
public void showAllTable()
{
db.execSQL("select name from sqlite_master where type = 'table'");
}
This query execute successful in to the shell window.
Now I want to display that list of tables in Android. How it is possible? I am calling this function from another activity.
Edited:
Thanks to Stack Overflow, I found the answer here.
The usual way to display a list of data is to use a ListView. To do this you will need to do the following:
1: change your db query to db.query instead of db.exec and store the values in a List:
ArrayList<String> tables = new ArrayList<String>();
Cursor mCursor = db.query("sqlite_master", new String[]{"name"}, "type = table",
null,null,null,null);
if (mCursor.getCount() > 0) {
for (mCursor.moveToFirst(), !mCursor.isAfterLast(), mCursor.moveToNext()) {
tables.add(mCursor.getString(0));
}
}
/** Important! always close cursors and DB's */
mCursor.close();
db.close();
return tables;
2: Use a ListView and an ArrayAdapter to display the information. See The Android Tutorial on how to do this.

How can I attach a SQLite ID to a Spinner object in android?

I want to pull a couple columns from a database and add those to the spinner, but I want the _id of the row to be hidden in there somewhere too. Take partial sample code below for example:
public void fillProfileSpinner()
{
String query = "SELECT _id,fruit_type,weight,colour FROM fruits;";
SQLiteDatabase profileDatabase = fruitCakes.database.getReadableDatabase();
Cursor cursor = profileDatabase.rawQuery(query, null);
startManagingCursor(cursor);
try {
cursor.moveToFirst();
do
{
String fruitType = cursor.getString(cursor.getColumnIndex("fruit_type"));
double weight = cursor.getString(cursor.getColumnIndex("weight"));
String colour = cursor.getInt(cursor.getColumnIndex("colour"));
fruitAdapter.add(colour + " " + weight + " " + fruit_type);
}
while(cursor.moveToNext());
}
catch(Exception e)
{
e.printStackTrace();
}
cursor.deactivate();
cursor.close();
profileDatabase.close();
}
I believe this is what I'm looking for, however I find it very confusing:
Android Spinners, say I pull spinner selections from SQL, can I also add their SQL _id's to the spinner values?
How can I get the _id column in there somewhere, so that is accessible from some method in the spinner object?
I cannot think of a scenario where your _ID value is not already directly available to you or derivable via the position:
In onListItemClick() of a ListActivity, it is the id parameter
In onItemClick() of a OnItemClickListener, it is the id parameter
Anywhere else that you have a position (e.g., getView() of a ListAdapter), call moveToPosition() on your Cursor and retrieve your _ID that way

Sqlite error when opening a TAB and when the Database is empty Android

I have four tabs which the first one inserts data on the database, the other 2 tabs take care of displaying the data using a cursor. here is my problem though when I first start the app and there is nothing on the database if I press one of the 2 tabs it gives me this error:
ERROR/AndroidRuntime: Caused by: android.database.sqlite.SQLiteException: no such table
my question is the following how can I avoid getting this error when pressing one of 2 tabs, I would like just to display an empty tab with an empty list.
Here is a piece of code where the error happens:
void populate() {
array = new ArrayList<String>();
mydb = openOrCreateDatabase("vivo_id.db",
SQLiteDatabase.CREATE_IF_NECESSARY, null);
Cursor c = mydb.query("VIVOID", null, null, null, null, null, null);
// start the managing cursor
startManagingCursor(c);
// move to first row
c.moveToFirst();
// continue searching until it is the last row in the column
while (c.isAfterLast() == false) {
sharable = c.getString(c.getColumnIndex("isCouponSharable"));
coupon = c.getString(c.getColumnIndex("couponImageResult"));
rawImage = c.getString(c.getColumnIndex("couponThumbnailResult"));
keyword = c.getString(c.getColumnIndex("keyword"));
histDesRes = c.getString(c.getColumnIndex("couponDescription"));
history = keyword + " \n " + histDesRes + " " + "<#>" + ""
+ rawImage+""+"<#>"+""+coupon+""+"<#>"+""+sharable;
array.add(history);
c.moveToNext();
}
strings = array.toArray(new String[array.size()]);
// close everything
c.close();
mydb.close();
}
Any help or pointers would be greatly appreciated, Thank you so much in advance.
do the searching stuff only if(c.moveToFirst()) { ...search comes here...}
I was missing the most imprtant element which the following, I learned from it hopefully other people will as well.
myDbHelper.getReadableDatabase();
# the beginning of the function.

Categories

Resources