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

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.

Related

How to navigate through data via Sqllite and ListActivity

I'm displaying data from SQLite using
ListAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2,
employees,
new String[] {"FirstName","LastName"},
new int[] {android.R.id.text1,android.R.id.text2},0);
getListView().setAdapter(adapter);
empoyees - my Cursor.
Data is showing correctly, but how to get what row I used from SQLite duaring OnClick on my item from List?
For example I have 2 tables
1)Category
_id Integer
Name Text
2)Articles
_id Integer
Name text
CategoryId (foreing key)
So on first screen I'm displaying all Categorys, then on list item click I want to display Articles that are from specified category, how to do that?
Don't use your cursor in your adapter. Build up an array and send in the array instead. In that array, typically something like List<MyDataRecordHolder> (where MyDataRecordHolder is an object you've created and filled with data from the database), you will have to set a reference to a row id.
UPDATE:
Create your MyDataRecordHolder: (Pseudo code)
List<MyDataRecordHolder> list = new List<MyDataRecordHolder>();
in your loop where you fetch data:
MyDataRecordHolder record = new MyDataRecordHolder();
record.setId(cursor.get("rowid"))
//set any other pertinent data
list.add(record);
For your adapter:
ListAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2,
list,
new String[] {"FirstName","LastName"},
new int[] {android.R.id.text1,android.R.id.text2},0);
Note, you are now supplying the List (list) to the adapter.
In your OnClick for your row, in the adapter, you will get the current MyDataRecordHolder:
final MyRecordHolder record = getItem(position);
String id = record.getId();
//make new db query based on your id

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.

How to present cursor from two columns of the same table to SimpleCursorAdapter Android

I a developing an app whereby i retrieve data from an sqlite database and the data is displayed on a listview I am retrieving data from two columns of a specific table and it is added to a SimpleCursorAdapter which is then set to the listview i would like to display each record in the different columns to be displayed on its own row currently data from both columns is displayed in one row any help will be appreciated especially a link to a working example
i have deicded to add my code maybe this will help you help me even better
mDicCursor=managedQuery(DictionaryProvider.CONTENT_URI, null, null,
new String[] {query}, null);
if (mDicCursor == null ) {
mTextView.setText(getString(R.string.no_results, new Object[] {query}));
/* final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("WORD MISSING");*/
showDialog(DIALOG_WORDMISSING);
//new AlertDialog.Builder(this).setTitle("Argh").setMessage("Watch out!").setNeutralButton("Close", null).show();
} else {
int count = mDicCursor.getCount();
String countString = getResources().getQuantityString(R.plurals.search_results,
count, new Object[] {count, query});
mTextView.setText(countString);
/* int iWord = mDicCursor.getColumnIndexOrThrow(DictDatabase.REC_DESCRIPTION);
mTextView.setText(mDicCursor.getString(iWord));*/
// Specify the columns we want to display in the result
String[] from = new String[]{ DictDatabase.REC_WORD,
DictDatabase.REC_DESCRIPTION };
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{ R.id.text2,
R.id.text3};
SimpleCursorAdapter words =
new SimpleCursorAdapter(this, R.layout.dictwords, mDicCursor, from, to);
mListView.setAdapter(words);
In your cursor adapter, you can detail how the data is set up and presented on the screen. You need to ensure that every 2nd row comes from the second column. This can be done using modulus on the current row index
boolean isEvenRow = (currentRow % 2==0); // will give 0 for even rows, 1 for odd rows
And then you can use this boolean result to choose whether the data comes from Column A or Column B.
String data;
if (isEvenRow){
data = mCursor.getString(COLUMN_A);
}else{
data = mCursor.getString(COLUMN_B);
}
And then you also need to ensure that the count of total rows is going to be double the size of the cursor, so when you are returning the count, make sure you return the correct value:
return mCursor.getCount()*2;
This will allow you to scroll double the length of the cursor.
Create an another layout which is containi ng 2 textviews and place them next to each other. In your activity "R.layout.new_layout" and use this in your simplecursoradapter's constructor with your new 2 textviews id.m
Example :
SimpleCursorAdapter simple=new SimpleCursorAdapter(this, R.layout.new_layout,cursor, new String[]{column1,column2} , new int[] {textview1,textview2});

Fill each spinner row with two values from database

I have a spinner currently being filled with one column (name) from a database. I would like to change this to have each spinner row displaying the name, a space and an Id from the same table. This is the code I am using at the moment, I am not sure how to map multiple rows in the "from" array into the same textview in the "to" array.
Cursor c = db.fetchAllUsers();
startManagingCursor(c);
// create an array to specify which fields we want to display
String[] from = new String[]{"name"};
// create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1};
// create simple cursor adapter
SimpleCursorAdapter adapter =
new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
// get reference to our spinner
spinner.setAdapter(adapter);
Thanks!
Use SimpleCursorAdapter.setViewBinder with a custom ViewBinder that does what you wish. To elaborate, you can simply ignore columnIndex in your implementation of setViewValue and use the given Cursor to populate the given View however you wish.
See: http://developer.android.com/reference/android/widget/SimpleCursorAdapter.html#setViewBinder(android.widget.SimpleCursorAdapter.ViewBinder)

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