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.
Related
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.
I need to display in a list view some data about numbers. I get these data from a database that is sqlite.
Im using a simplecursoradapter to fill the listview. The problem is that numbers >= to one million are stored in exponential format. So for example if I insert a number like 1000 000 then it gets stored as 1+06E. The problem is that i need to display it as 1 000 000. But I can't manage to change that format inside the cursor or the simplecursoradapter.
My code for filling the listview is:
Cursor c = admin.obtenerCursorGastosVarFecha(fechaSelUs);
// The desired columns to be bound
String[] columnas = new String[] {"_id", "Descripcion", "Costo", "Fecha_Creado"};
// the XML defined views which the data will be bound to
int[] views = new int[] {R.id.IdGstVar, R.id.DescGstVar, R.id.CostoGstVar, R.id.FechaGstVar };
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(this, R.layout.lista_gastos_variables, c, columnas, views, 0);
Im getting here all as a string, but numbers higher or equal to one million show up in exponential numbers
I tried this code, but its not working at all.
It just modifies values lower than ten million and also, it rounds or changes the values, so if insert for example 8 888 888 it displays 8 888 890.
I need to display in natural numbers all the numbers stored in the database.
Also if there is a way to insert rows with numbers into the database without them being changed to exponential format, how is it done? Thank you very much for your help!
dataAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor, int column) {
if( column == 2 ){ // let's suppose that the column 0 is the date
TextView tv = (TextView) view;
// here you use SimpleDateFormat to bla blah blah
tv.setText(""+Double.parseDouble(cursor.getString(cursor.getColumnIndex("Costo"))));
return true;
}
return false;
}
});
Since you are using datatype as real , and storing it into db as real number. At the time of storing into SqliteDB, it converts it into exponential format. When you are trying to read it from database it gives you the converted exponential format into string. You just change the datatype to varchar for costo. It will solve your problem.
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();
}
I m working on an e-learning type of an application where i retrieve the data from the database on list.
It works fine on the emulator,but when i use the APK file of that app on real device,it does not show any data on list, my database is stored in the windows-file explorer-package-data-database-table_name.
I am referring to this site
http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from-a-sqlite-database-in-android/
Here's a snippet of my code using database
list_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, namelist1());
list1.setAdapter(list_adapter);
}
public List<String> namelist1()
{
// We have to return a List which contains only String values. Lets create a List first
List<String> namelist= new ArrayList<String>();
// First we need to make contact with the database we have created using the DbHelper class
Database_helper_class open_database_helper= new Database_helper_class(this);
// Then we need to get a readable database
SQLiteDatabase sqlitedatabase = open_database_helper.getReadableDatabase();
// We need a a guy to read the database query. Cursor interface will do it for us
//(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
Cursor cursor =sqlitedatabase.query(open_database_helper.TABLE_E_LEARNING,null,null,null,null,null,null);
//above query is read all the database column
// Cursor object read all the fields. So we make sure to check it will not miss any by looping through a while loop
while(cursor.moveToNext()){
String str_name = cursor.getString(cursor.getColumnIndex(Database_helper_class.QUES_COLUMN));
String str_id = cursor.getString(cursor.getColumnIndex(Database_helper_class.ANS_COLUMN));
//double str_gpa = cursor.getDouble(cursor.getColumnIndex(Database_helper_class.GPA_COLUMN));
// Finish reading one raw, now we have to pass them to the POJO
nameclass nameclassobj1=new nameclass();
nameclassobj1.setname(str_name);
nameclassobj1.setid(str_id);
//nameclassobj1.setgpa(str_gpa);
// Lets pass that POJO to our ArrayList which contains undergraduates as type
pojo_namelist.add(nameclassobj1);
// But we need a List of String to display in the ListView also.
//That is why we create "nameList"
namelist.add(str_name);
}
sqlitedatabase.close();
sqlitedatabase.query() returns a cursor which is positioned before the first record. make sure to call moveToFirst() before trying to access any data from it.
verify your database path in DBHelper.class. And after that Write below line before you call while loop.
cursor.moveToFirst();
This will point to your first record and then your while loop will work.
Try it like this:
// Cursor object read all the fields. So we make sure to check it will not miss any by looping through a while loop
cursor.moveToFirst();
while(!cursor.isAfterLast()){
String str_name = cursor.getString(cursor.getColumnIndex(Database_helper_class.QUES_COLUMN));
String str_id = cursor.getString(cursor.getColumnIndex(Database_helper_class.ANS_COLUMN));
//double str_gpa = cursor.getDouble(cursor.getColumnIndex(Database_helper_class.GPA_COLUMN));
// Finish reading one raw, now we have to pass them to the POJO
nameclass nameclassobj1=new nameclass();
nameclassobj1.setname(str_name);
nameclassobj1.setid(str_id);
//nameclassobj1.setgpa(str_gpa);
// Lets pass that POJO to our ArrayList which contains undergraduates as type
pojo_namelist.add(nameclassobj1);
// But we need a List of String to display in the ListView also.
//That is why we create "nameList"
namelist.add(str_name);
}
Use the isAfterLast()-method to check, if your reached the end of your cursor.
Sorry for late reply, got busy in other application
Actually the data was not saved in the database, that is why i was not getting it on device.
It works now.
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().