Simply populate database table names in Android ListView - android

Very new to Android development...I've been scouring the internet for answers, but I'm still finding myself stuck and hoping someone can lend me a hand. I absolutely admit I am a newbie...but trying to learn.
I have an already populated sqlite database that I am including in a package. I've copied this into the asset folder. The database has 4 tables (and some fields beneath that).
I have a simple activity with a listview that I am trying to simply query the database for the table names and have them populate, however I get no results.
my DataBaseAdapter code is essentially the code from here:
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
I modified my database name and path.
My class code to call this is here:
ON EDIT:::
public Cursor fetchAllNotes() {
return myDbHelper.rawQuery("SELECT name FROM sqlite_master WHERE type='table'",
new String[]{});
}
private void fillData() {
Cursor c = fetchAllNotes();
startManagingCursor(c);
String[] from = new String[] {"name"};
int[] to = new int[] {R.id.listview};
SimpleCursorAdapter notes =
new SimpleCursorAdapter (this, R.layout.list_view, c, from, to);
setListAdapter(notes);
}
}
The project runs, it just yields no results in the ListView (which is in an xml named lists.xml) the portion of code is here:
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
<TextView android:id="#android:id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:text="No data"
style="#style/ButtonText"/>
Any help would be great, I'm sure I am flailing hard on my sql calls...but I am stuck.

Your to and from arrays are incorrect. Your 'from' string array is currently blank. This is going to be the name of the column you are trying to display. So in your case it will be "name". Your 'to' array is going to be the id of the view you are mapping the value to...not the id of the list. You will need to create a new layout with a TextField in it to display. In the 'to' field you will then give the id of this new text field. Then in the SimpleCursorAdapter you can send in this new layout along with the 'to' and 'from' arrays.

Try this code:
private void getData() {
tb.open();
List<String> items = new ArrayList<String>();
Cursor c = tb.fetchallemployee();
c.moveToFirst();
ListAdapter adapter=new SimpleCursorAdapter(this,
R.layout.show_database, c,
new String[] {"date", "title"},
new int[] {R.id.toptext, R.id.bottomtext});
setListAdapter(adapter);
setListAdapter(entries);
tb.close();
}

Related

Can I load a SQLite column of binary data into switches?

I have SQLite Database. I've set it up using android and listview such that I can view the data in the database. Most of the columns are text. For these, I have set up several textView objects that permit me to upload the text in the SQL columns into the list view.
But I have a column of binary data. And I'd like to load this such that if there is a "0" in the column, then the switch is in the off position, and if there is a "1" in the column, the switch is in the on position?
Do I need to set up some kind of case system on the switch object?
Here's my current code for populating the ListView
// THIS UPDATES THE LIST
private void populateListViewFromDNewBMetric(){
Cursor cursor = mydbmetric.getAllRows();
// Setup mapping from cursor to view fields
String[] fromFieldNames = new String[]
{DBAdapter_Metrics.KEY_ROWID,DBAdapter_Metrics.KEY_NAME,DBAdapter_Metrics.KEY_DESCRIPTION,DBAdapter_Metrics.KEY_SWITCH};
int[] toViewIDs = new int[]
{R.id.textViewMetricID,R.id.textViewName,R.id.textViewDescription,R.id.switch1};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(),R.layout.item_metric,cursor,fromFieldNames,toViewIDs,0);
ListView mylist = (ListView) findViewById(R.id.listViewMetric);
mylist.setAdapter(myCursorAdapter);
}
}
DBAdapter_Metrics.KEY_SWITCH and R.id.switch1 are the things I don't think makes sense. It works for the other ones like DBAdapter_Metrics.KEY_DESCRIPTION because these are text. But KEY_SWITCH is an integer while switch1 is a switch not a field, so I'm not sure if I can somehow "load" a switch.

Implementing Manually Coded Auto-Incrementing RowId/Using VACUUM in SQLite

I have run into that timeless issue of wanting to have an auto-incrementing column (in SQLITE) that remains intact after a record is deleted. I have run into a number of posts about this problem, but none of them explain exactly how to code your own column for this purpose. I need the numbers to be consecutive because I want to be able to display a record number for each item in a ListView which will also serve as a running total of how many records are in the db.
So far, I have been trying to use the VACUUM function because it's my understanding that it will reset the numbers once it's complete, and I thought I would run it every time a record is deleted, but nothing seems to happen when the code is run. I'm not getting any errors, but the VACUUM isn't happening as far as I can tell. Here's the code:
String sql = "VACUUM;" ;
db.execSQL(sql,new String [] {sql});
Maybe nothing is happening because the coding is off? So I guess what I am getting at here is am I on the right track with trying to use VACUUM or should I go with manually setting up an auto-incrementing column? Either way, any advice is greatly appreciated!
Here's the fetch and display portion of the code:
populateListViewFromDB();
}
#SuppressWarnings("deprecation")
private void populateListViewFromDB() {
Cursor cursor = db.getAllRecords();
//Allow activity to manage cursor lifetime
startManagingCursor(cursor);
//Setup mapping from cursor to view fields:
String [] fromFieldNames = new String []
{DBAdapter.KEY_ROWID, DBAdapter.KEY_GENRE, DBAdapter.KEY_TITLE, DBAdapter.KEY_PLATFORM, DBAdapter.KEY_DATE, DBAdapter.KEY_PRICE, DBAdapter.KEY_WHEREBOUGHT};
int [] toViewIDs = new int []
{R.id.RecordNumberEdit, R.id.textView1, R.id.textView2, R.id.textView3, R.id.textView4, R.id.textView5, R.id.textView6};
//Create mapping from cursor to view fields
SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(
this,
R.layout.database_view_layout,
cursor, //Set of DB records
fromFieldNames, //DB field Names
toViewIDs //View IDs in which to put info
);
//Set the adapter for the list view
ListView listViewFromDB = (ListView) findViewById(R.id. listViewFromDB);
listViewFromDB.setAdapter(myCursorAdapter);
I changed the VACCUUM code to the following since the original code was actually passing the query twice :
String sql = "VACUUM;" ;
db.execSQL(sql);
Still, though, nothing seems to be happening.

SQLite changing layout of list

Im working on the notepad tutorial from the android website. I have created a database with 2 entries: name and address. When the application is run only the Name is displayed. I want to display both Name and address. I have edited my filldata method but it doesnt work. See my code below. Any suggestions?
private void fillData() {
Cursor notesCursor = mDbHelper.fetchAllNotes();
startManagingCursor(notesCursor);
// Create an array to specify the fields we want to display in the list (TITLE + BODY)
String[] from = new String[]{NotesDbAdapter.KEY_TITLE,NotesDbAdapter.KEY_BODY};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.text1};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.notes_row, notesCursor, from, to);
setListAdapter(notes);
}
In your R.layout.notes_row file you should have two TextViews one for the title and one for the address and then you will write:
String[] from = new String[]{NotesDbAdapter.KEY_TITLE,NotesDbAdapter.KEY_BODY};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.text1, R.id.id_of_the_second_text};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.notes_row, notesCursor, from, to);
setListAdapter(notes);
Edit:
R.layout.notes_row could be something like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
<TextView android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView android:id="#+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

Populating a spinner with a db query

I recently started programming for android and java development in general. Currently I train by writing a timetable app.
I want to get a list with all subjects from the db (the table also contains teacher and rooms) and put them into a spinner.
Thats the code I wrote
Cursor c = dba.fetchAllSubjects();
if (c.getCount() != 0) {
Spinner subjectSpinner = (Spinner) findViewById(R.id.newlesson_subject);
startManagingCursor(c);
String[] from = new String[]{DbAdapter.KEY_SUBJECT};
int[] to = new int[] {android.R.layout.simple_spinner_item};
SimpleCursorAdapter subjectAdapter =
new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to);
subjectSpinner.setAdapter(subjectAdapter);
}
The problem is that when clicking on the spinner it shows a list with as much items as the db has entries, but the list doesn't show the names (you can say it's empty). So I probably messed something up with the simple cursor adapter, but I don't know what.
Thanks for your help
You're error lies in specifying the wrong Resource ID in your to integer array.
int[] to = new int[] {android.R.layout.simple_spinner_item};
You need to specify the ID of a TextView (or similarly typed view) and not the layout itself. Replace the line above with:
int[] to = new int[] { android.R.id.text1 };

Fetch all notes returns zero rows from Android notepad example

Well this is probably a stupid question with a simple answer but when using simple cursor adapter from the notepad example, I get a list of names from my database.
When I try to do it "manually" by moving the cursor over the rows and extracting the names the cursor says there is zero rows returned...
This works as per the example:
Cursor notesCursor = mDbHelper.fetchAllNotes();
startManagingCursor(notesCursor);
// Create an array to specify the fields we want to display in the list (only NAME)
String[] from = new String[]{WeightsDatabase.KEY_NAME};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.weightrows};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.weights_row, notesCursor, from, to);
setListAdapter(notes);
Now i'm trying to do this but it's not quite working. Is the simple cursor adapter doing something special i'm not?
//check # of rows, returns 0
int mOne = notesCursor.getCount();
//initial random string array
String[] temp = new String[100];
int i = 0;
notesCursor.moveToFirst();
do{
temp[i]=notesCursor.getString(notesCursor.getColumnIndex(WeightsDatabase.KEY_ROWID)); //crashes here
//index out of bounds
i++;
}while(notesCursor.moveToNext());
I have gotten this to work, but with returning a specific query like return all row with the name "_". What is different about returning all notes?
moveToFirst() actually returns a boolean, so you can prevent the exception from being thrown by checking the value before you attempt to read from the Cursor:
if (notesCursor.moveToFirst()) {
// do loop
}
As for why there are 0 rows, are you attempting to re-use the same cursor that you passed into the SimpleCursorAdapter, or is the code that is failing stand-alone? If you are attempting to re-use it, I would try it using a new Cursor after performing a fresh fetchAllNotes().

Categories

Resources