how to re-open or close SQLitedatabase? - android

I have gone through many pages for the same problem but i still cant find an solution for this !!
I'm getting error "attempt to re-open an already closed objectSQLiteDatabase".
public List getData(){
List list = new ArrayList();
Cursor c = db.rawQuery("SELECT * FROM Table",null );
int i = cursor.getColumnIndex(KEY1);
int ii = cursor.getColumnIndex(KEY2);
int iii = cursor.getColumnIndex(KEY3);
int inum = cursor.getColumnIndex(KEY4);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
String student = cursor.getString(inum) + "\t" +cursor.getString(i) +"\t" +cursor.getString(ii) + "\t" +cursor.getString(iii);
list.add(student);
cursor.moveToPrevious();
}
}
public List getInfo()
{
List list = new ArrayList();
Cursor c = db.rawQuery("SELECT * FROM Table where name = ?",new string[]{"android"} );
int i = cursor.getColumnIndex(KEY1);
int ii = cursor.getColumnIndex(KEY2);
int iii = cursor.getColumnIndex(KEY3);
int inum = cursor.getColumnIndex(KEY4);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
String student = cursor.getString(inum) + "\t" +cursor.getString(i) +"\t" +cursor.getString(ii) + "\t" +cursor.getString(iii);
list.add(student);
cursor.moveToPrevious();
}
Im getting this values as list and putting it in list
ListView list = (ListView) findViewById(R.id.list);
ListView list1 = (ListView) findViewById(R.id.list1);
List val = info.getData();
List val1 - info.getInfo();
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,val);
ArrayAdapter adapter1 = new ArrayAdapter(this,android.R.layout.simple_list_item_1,val1);
list.setAdapter(adapter);
list1.setAdapter(adapter1);
info.close()

First of all where are you creating database?
You should use a class that extends SQLiteOpenHelper
eg:
public class MySQLiteHelper extends SQLiteOpenHelper {
//here you create your database and tables
}
To open/close database
// Database Fields
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
More info/example here:
http://www.vogella.com/tutorials/AndroidSQLite/article.html

Related

Show all database contents in a ListView

I want to Show all database contents in a List View in Android Studio, I expect to see 3 rows that each row contains "name, family and ID" , but I see a comlex of package name and some other characters as follws:
com.google.www.hmdbtest01.Person#529e71b4
com.google.www.hmdbtest01.Person#529e7238
com.google.www.hmdbtest01.Person#529e7298
if I have more rows in my database, I will see more lines like above in the output.
my codes are as follow:
public class ListOfData extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_of_data);
ListView list = findViewById(R.id.list1);
HmDbManager01 db= new HmDbManager01(this);
ArrayList personList = db.getAll();
ArrayAdapter<ArrayList> arrayList = new ArrayAdapter<ArrayList>(this,
android.R.layout.simple_list_item_1, personList);
list.setAdapter(arrayList);
}
}
db.getAll() is as follows:
public ArrayList<Person> getAll(){
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor= sqLiteDatabase.rawQuery("SELECT * FROM tbl_person", null);
cursor.moveToFirst();
ArrayList<Person> allData = new ArrayList<>();
if(cursor.getCount() > 0){
while (!cursor.isAfterLast()){
Person p1 = new Person();
p1.pID=cursor.getString(0);
p1.pName=cursor.getString(1);
p1.pFamily=cursor.getString(2);
allData.add(p1);
cursor.moveToNext();
}
}
cursor.close();
sqLiteDatabase.close();
return allData;
}
and, this is Person:
package com.google.www.hmdbtest01;
public class Person {
public String pID;
public String pName;
public String pFamily;
}
Let me know your comments on this problem.
arrayListAdapter will convert your personList to list of string
change like it:
ArrayList<String> persons = new ArrayList<String>();
personList.forEach(personModel -> {
persons.add(personModel.name + " " + personModel.lastName + " " + personModel.id);
});
ArrayAdapter<ArrayList> arrayList = new ArrayAdapter<ArrayList>(this,
android.R.layout.simple_list_item_1, persons);

Android : Put SQLite data in BaseAdapter

Currently im making a custom listview with baseadapter of(image, ressource and database). I got a problem on putting a data from sqlite inside baseadapter. my code is look like this, Database Code:
public HashMap<String, String> getResult(String year) {
HashMap<String, String> questionmap = new HashMap<String, String>();
SQLiteDatabase database = this.getReadableDatabase();
String selectQuery = "SELECT _id, COLUMN_B, COLUMN_C FROM TABLE_NAME WHERE YEAR_COLUMN='"+ year + "'";
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
questionmap.put("_id", cursor.getString(0));
questionmap.put("COLUMN_B", cursor.getString(1));
questionmap.put("COLUMN_C", cursor.getString(2));
} while (cursor.moveToNext());
}
return questionmap;
}
And Here is my BaseAdapter looks like:
class singlerow_info {
String A, B, C;
int img;
singlerow_info(String A, String B, String C,
int img) {
this.A = A;
this.B = B;
this.C = C;
this.img = img;
}
}
class resultadapter extends BaseAdapter {
//Get YEAR values from previous activity
Intent intent = getIntent();
String year = intent.getStringExtra("YEAR");
HashMap<String, String> questionmap = myDb.getResult(year);
ArrayList<singlerow_info> list;
resultadapter(Context c)
{
list = new ArrayList<singlerow_info>();
//get String A from String resource and get String []B and []C from database
Resources ress = c.getResources();
String[] A = ress.getStringArray(R.array.exam_question);
//do here get B,C from db, Here im stuck with.
String[] B=;
String[] C= ;
int[] images = {R.drawable.icon_1,R.drawable.icon_2};
for (int i =0; i<40; i++ ){
list.add(new singlerow_info(A[i],B[i],C[i],images[i]));
}
}
Please help.
class resultadapter extends BaseAdapter {
//Get YEAR values from previous activity
Intent intent = getIntent();
String year = intent.getStringExtra("YEAR");
ArrayList questionmapB,questionmapC;
ArrayList list;
resultadapter(Context c)
{
list = new ArrayList<singlerow_info>();
questionmapB = new ArrayList<String>;
questionmapC = new ArrayList<String>;
readFromDB();
//get String A from String resource and get String []B and []C from database
Resources ress = c.getResources();
String[] A = ress.getStringArray(R.array.exam_question);
//do here get B,C from db, Here im stuck with.
int[] images = {R.drawable.icon_1,R.drawable.icon_2};
for (int i =0; i<40; i++ ){
list.add(new singlerow_info(A[i],questionmapB.get(i) ,questionmapC.get(i),images[i]));
}
}
private void readFromDB()
{
SQLiteDatabase database = this.getReadableDatabase();
String selectQuery = "SELECT _id, COLUMN_B, COLUMN_C FROM TABLE_NAME WHERE YEAR_COLUMN='"+ year + "'";
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
questionmapB.put("COLUMN_B", cursor.getString(1));
questionmapC.put("COLUMN_C", cursor.getString(2));
} while (cursor.moveToNext());
}
}

Android SQLite: attempt to re-open an already-closed object

I'm trying to get certain book data from my Inventory table based on the ISBN.
However, I'm getting an error: "attempt to re-open an already-closed object". The error only occurs when I click a listView object, go to a different screen, go back to this page via "finish()", and then try to click on another listView object. I moved the String searchEntries[] = InventoryAdapter.getInventoryEntriesByISBN(searchQuery, isbn[position]); from the onClickListener to the previous for loop before the onClickListener and now it works.
Why does it not work if I try to getInventoryEntriesByISBN after returning to this activity from another activity via "finish()"?
The error occurs at SearchResultsScreen:
String searchEntries[] = InventoryAdapter.getInventoryEntriesByISBN(searchQuery, isbn[position]);
and by extension, occurs at InventoryAdapter:
Cursor cursor = db.rawQuery(query, new String[] {ISBN});
SearchResultsScreen.java
// Set up search array
for(int i = 0; i < isbn.length; i++)
{
searchArray.add(new InventoryItem(isbn[i], InventoryAdapter.getTitleAndAuthorByISBN(isbn[i])));
}
Toast.makeText(getApplicationContext(), "searchArray.size()="+searchArray.size(), Toast.LENGTH_LONG).show();
// add data in custom adapter
adapter = new CustomAdapter(this, R.layout.list, searchArray);
ListView dataList = (ListView) findViewById(R.id.list);
dataList.setAdapter(adapter);
// On Click ========================================================
dataList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String searchEntries[] = InventoryAdapter.getInventoryEntriesByISBN(searchQuery, isbn[position]);
InventoryAdapter.java (Most relevant parts)
public String[] getInventoryEntriesByISBN(String search, String ISBN)
{
String[] searchEntry = new String [9];
//Query
String query = "select * from INVENTORY where ISBN = ?";
Cursor cursor = db.rawQuery(query, new String[] {ISBN});
if(cursor.getCount()<1) // title Not Exist
{
cursor.close();
for(int i = 0; i < 9; i++)
searchEntry[i] = "Not Found";
return searchEntry;
}
cursor.moveToFirst();
//put data into respective variable
int publish = cursor.getInt(cursor.getColumnIndex("PUBLISH_DATE"));
String publishdate = ((Integer)publish).toString();
String title = cursor.getString(cursor.getColumnIndex("TITLE"));
String author = cursor.getString(cursor.getColumnIndex("AUTHOR"));
String callNumber = cursor.getString(cursor.getColumnIndex("CALL_NUMBER"));
int available = cursor.getInt(cursor.getColumnIndex("AVAILABLE_COUNT"));
String availablecount = ((Integer)available).toString();
int inventory = cursor.getInt(cursor.getColumnIndex("INVENTORY_COUNT"));
String inventorycount = ((Integer)inventory).toString();
int due = cursor.getInt(cursor.getColumnIndex("DUE_PERIOD"));
String dueperiod = ((Integer)due).toString();
int checkoutcount = cursor.getInt(cursor.getColumnIndex("COUNT"));
String count = ((Integer)checkoutcount).toString();
//combine variables into one array
searchEntry[0] = ISBN;
searchEntry[1] = title;
searchEntry[2] = author;
searchEntry[3] = publishdate;
searchEntry[4] = callNumber;
searchEntry[5] = availablecount;
searchEntry[6] = inventorycount;
searchEntry[7] = dueperiod;
searchEntry[8] = count;
cursor.close();
return searchEntry;
}
public String getTitleAndAuthorByISBN(String ISBN)
{
int entriesFound = getNumSearchEntries(ISBN);
if(entriesFound==0)
entriesFound = 1;
String searchEntry;
//Query
String query = "select * from INVENTORY where ISBN = ?";
Cursor cursor = db.rawQuery(query, new String[] {ISBN});
if(cursor.getCount()<1) // title Not Exist
{
cursor.close();
searchEntry = "Not Found";
return searchEntry;
}
cursor.moveToFirst();
//put data into respective variable
String title = cursor.getString(cursor.getColumnIndex("TITLE"));
String author = cursor.getString(cursor.getColumnIndex("AUTHOR"));
//combine variables into one String
searchEntry = title + " / " + author;
//close cursor and return
cursor.close();
return searchEntry;
}
DataBaseHelper.java
public class DataBaseHelper extends SQLiteOpenHelper
{
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "database.db";
// ============================ End Variables ===========================
public DataBaseHelper(Context context, String name, CursorFactory factory, int version)
{
super(context, name, factory, version);
}
public DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Called when no database exists in disk and the helper class needs
// to create a new one.
#Override
public void onCreate(SQLiteDatabase _db)
{
_db.execSQL(LoginDataBaseAdapter.USER_TABLE_CREATE);
_db.execSQL(CheckOutDataBaseAdapter.CHECKOUT_TABLE_CREATE);
_db.execSQL(InventoryAdapter.INVENTORY_TABLE_CREATE);
_db.execSQL(StatisticsAdapter.STATISTICS_TABLE_CREATE);
}
// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
#Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new version. Multiple
// previous versions can be handled by comparing _oldVersion and _newVersion
// values.
// on upgrade drop older tables
_db.execSQL("DROP TABLE IF EXISTS " + LoginDataBaseAdapter.USER_TABLE_CREATE);
_db.execSQL("DROP TABLE IF EXISTS " + CheckOutDataBaseAdapter.CHECKOUT_TABLE_CREATE);
_db.execSQL("DROP TABLE IF EXISTS " + InventoryAdapter.INVENTORY_TABLE_CREATE);
_db.execSQL("DROP TABLE IF EXISTS " + StatisticsAdapter.STATISTICS_TABLE_CREATE);
// Create a new one.
onCreate(_db);
}
}
Check Database Connection before executing query:
if (!dbHelper.db.isOpen())
dbHelper.open();
you can also use cursor.requery(); for again same query.
and in last you have to close the cursor and database also.
cursor.close();
db.close();
Edited:
I have created DBHelper class which extends SQLiteOpenHelper, this class is inner class of DatabaseHelper class and that class have following methods.
/** For OPEN database **/
public synchronized DatabaseHelper open() throws SQLiteException {
dbHelper = new DBHelper(context);
db = dbHelper.getWritableDatabase();
return this;
}
/** For CLOSE database **/
public void close() {
dbHelper.close();
}
If you have still doubt then feel free to ping me. Thank you.
The error only occurs when I click an item, go to a different screen, go back to this page via "finish()", and then try to click on another listView object.
I moved the String searchEntries[] = InventoryAdapter.getInventoryEntriesByISBN(searchQuery, isbn[position]); from the onClickListener to the previous for loop before the onClickListener and now it works.
The correct SearchResultsScreen is below:
SearchResultsScreen.java
// Set up search array
final String Entries[][] = new String[isbn.length][9];
for(int i = 0; i < isbn.length; i++)
{
searchArray.add(new InventoryItem(isbn[i], InventoryAdapter.getTitleAndAuthorByISBN(isbn[i])));
Entries[i] = InventoryAdapter.getInventoryEntriesByISBN(searchQuery, isbn[i]);
}
Toast.makeText(getApplicationContext(), "searchArray.size()="+searchArray.size(), Toast.LENGTH_LONG).show();
// add data in custom adapter
adapter = new CustomAdapter(this, R.layout.list, searchArray);
ListView dataList = (ListView) findViewById(R.id.list);
dataList.setAdapter(adapter);
// On Click ========================================================
dataList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String searchEntries[] = Entries[position];
This is your problem
if(cursor.getCount()<1) // title Not Exist
{
cursor.close();
for(int i = 0; i < 9; i++)
searchEntry[i] = "Not Found";
return searchEntry;
}
cursor.moveToFirst();
cursor.close();
Change to
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
{
String title = cursor.getString(cursor.getColumnIndex("TITLE"));
String author = cursor.getString(cursor.getColumnIndex("AUTHOR"));
//combine variables into one String
searchEntry = title + " / " + author;
}
public String[] getInventoryEntriesByISBN(String search, String ISBN)
{
String[] searchEntry = new String [9];
//Query
String query = "select * from INVENTORY where ISBN = ?";
Cursor cursor = db.rawQuery(query, new String[] {ISBN});
Add SQLiteDatabase db = this.getWritableDatabase(); in this code before executing the raw Query

java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteQuery: SELECT * FROM pets

i have an error in my application.
I'm new in making apps for android, so i donĀ“t now what's wrong...
this is in the log:
java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteQuery: SELECT * FROM pets
i have a SQLite database in which is this method:
public List<Pet> getAllPets() {
List<Pet> petList = new ArrayList<Pet>();
String selectQuery = "SELECT * FROM " + TABLE_PETS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Pet pet = new Pet();
pet.setID(Integer.parseInt(cursor.getString(0)));
pet.setName(cursor.getString(1));
pet.setAge(cursor.getString(2));
petList.add(pet);
} while (cursor.moveToNext());
}
return petList;
}
and then i'am using this method from database in other activity to fill the ListView by the names of every pet....
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
PetListView = (ListView)findViewById(R.id.list);
MyDatabaseHelper db = new MyDatabaseHelper(this);
String [] items = new String[db.getPetsCount()];
List<Pet> pets = db.getAllPets();
for (int i = 0; i < db.getPetsCount(); i++) {
items[i] = pets.get(i).getName();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.activity_list_item, items);
PetListView.setAdapter(adapter);
}
when this activity starts the application crashes down..
Please, can you tell me what's worng? How can i fix it? Thanks a much for help.
EDIT:
getPetsCount() method:
public int getPetsCount() {
String countQuery = "SELECT * FROM " + TABLE_PETS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
i solved this by myself at the end by replace the getPetsCount method:
public int getPetsCount() {
String countQuery = "SELECT * FROM " + TABLE_PETS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
db.close();
return count;
First, you should close your cursor once you have finished to use it (that may solve your issue)
public List<Pet> getAllPets() {
List<Pet> petList = new ArrayList<Pet>();
String selectQuery = "SELECT * FROM " + TABLE_PETS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Pet pet = new Pet();
pet.setID(Integer.parseInt(cursor.getString(0)));
pet.setName(cursor.getString(1));
pet.setAge(cursor.getString(2));
petList.add(pet);
} while (cursor.moveToNext());
}
// Close cursor when finished using it
cursor.close();
return petList;
}

Android: I have to display content from the database in the listview, in which latest data comes on top

I have to implement a listview in which my current data comes on top of the listview. Right now my recent data comes at the bottom and my first data is coming on the top of the listview. I'm attaching my work so far:
SearchActivity.java
public class SearchActivity extends Activity implements OnClickListener,
OnItemClickListener {
private EditText mHistoryNameEditText;
private Button mInsertButton;
private ListView mHistoryListView;
private ListAdapter mHistoryListAdapter;
private ArrayList<SearchHistoryDetails> searchArrayList;
private ArrayList<SearchHistoryDetails> HistoryObjArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHistoryNameEditText = (EditText) findViewById(R.id.editText1);
mInsertButton = (Button) findViewById(R.id.button1);
mInsertButton.setOnClickListener(this);
mHistoryListView = (ListView) findViewById(R.id.names_lsitviews);
mHistoryListView.setOnItemClickListener(this);
searchArrayList = new ArrayList<SearchHistoryDetails>();
mHistoryListAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, populateList());
mHistoryListView.setAdapter(mHistoryListAdapter);
HistoryObjArrayList = new ArrayList<SearchHistoryDetails>();
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.button1) {
String providedUgraduateName = mHistoryNameEditText.getText()
.toString();
SearchHistoryDetails undergraduateDetailsPojoObj = new SearchHistoryDetails();
undergraduateDetailsPojoObj.setuGraduateName(providedUgraduateName);
HistoryObjArrayList.add(undergraduateDetailsPojoObj);
insertUndergraduate(undergraduateDetailsPojoObj);
finish();
}
}
public void insertUndergraduate(
SearchHistoryDetails paraUndergraduateDetailsPojoObj) {
AndroidOpenDbHelper androidOpenDbHelperObj = new AndroidOpenDbHelper(
this);
SQLiteDatabase sqliteDatabase = androidOpenDbHelperObj
.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(AndroidOpenDbHelper.COLUMN_NAME_UNDERGRADUATE_NAME,
paraUndergraduateDetailsPojoObj.getuGraduateName());
long affectedColumnId = sqliteDatabase.insert(
AndroidOpenDbHelper.TABLE_NAME_GPA, null, contentValues);
sqliteDatabase.close();
Toast.makeText(this,
"Values inserted column ID is :" + affectedColumnId,
Toast.LENGTH_SHORT).show();
}
public List<String> populateList() {
List<String> uGraduateNamesList = new ArrayList<String>();
AndroidOpenDbHelper openHelperClass = new AndroidOpenDbHelper(this);
SQLiteDatabase sqliteDatabase = openHelperClass.getReadableDatabase();
Cursor cursor = sqliteDatabase.query(
AndroidOpenDbHelper.TABLE_NAME_GPA, null, null, null, null,
null, null);
startManagingCursor(cursor);
while (cursor.moveToNext()) {
String ugName = cursor
.getString(cursor
.getColumnIndex(AndroidOpenDbHelper.COLUMN_NAME_UNDERGRADUATE_NAME));
SearchHistoryDetails ugPojoClass = new SearchHistoryDetails();
ugPojoClass.setuGraduateName(ugName);
searchArrayList.add(ugPojoClass);
uGraduateNamesList.add(ugName);
}
sqliteDatabase.close();
return uGraduateNamesList;
}
#Override
protected void onResume() {
super.onResume();
searchArrayList = new ArrayList<SearchHistoryDetails>();
mHistoryListAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, populateList());
mHistoryListView.setAdapter(mHistoryListAdapter);
}
#Override
protected void onStart() {
super.onStart();
searchArrayList = new ArrayList<SearchHistoryDetails>();
mHistoryListAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, populateList());
mHistoryListView.setAdapter(mHistoryListAdapter);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(getApplicationContext(), "Clicked on :" + arg2,
Toast.LENGTH_SHORT).show();
SearchHistoryDetails clickedObject = searchArrayList.get(arg2);
Bundle dataBundle = new Bundle();
dataBundle.putString("clickedUgraduateName",
clickedObject.getuGraduateName());
}}
This class helps me in getting the data from the database and populating it on the activity. My creating database class:
AndroidOpenDbHelper.java
public class AndroidOpenDbHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "allsearch_history_db";
public static final int DB_VERSION = 1;
public static final String TABLE_NAME_GPA = "search_table";
public static final String COLUMN_NAME_UNDERGRADUATE_NAME = "undergraduate_name_column";
public AndroidOpenDbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sqlQueryToCreateUndergraduateDetailsTable = "create table if not exists "
+ TABLE_NAME_GPA
+ " ( "
+ BaseColumns._ID
+ " integer primary key autoincrement, "
+ COLUMN_NAME_UNDERGRADUATE_NAME
+ " text not null); ";
db.execSQL(sqlQueryToCreateUndergraduateDetailsTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion == 1 && newVersion == 2) {
// Upgrade the database
}
}}
This is the class from which I create database and table.
Now, the real deal is that, when I try to populate data from the database it comes as the first one on top and the latest one on down. I want to revert it. Any help will be appreciated in overcoming this problem.
There are a few different ways to do this. I recommend using the ORDER BY clause of your query:
Cursor cursor = sqliteDatabase.query(
AndroidOpenDbHelper.TABLE_NAME_GPA, null, null, null, null, null,
AndroidOpenDbHelper.COLUMN_NAME_UNDERGRADUATE_NAME + " DESC");
Also if you are only going to read from one column, your query should only request that column. Otherwise you are wasting resources querying unused columns of information:
Cursor cursor = sqliteDatabase.query(
AndroidOpenDbHelper.TABLE_NAME_GPA,
new String[] {AndroidOpenDbHelper.COLUMN_NAME_UNDERGRADUATE_NAME},
null, null, null, null,
AndroidOpenDbHelper.COLUMN_NAME_UNDERGRADUATE_NAME + " DESC");
Lastly, you may want to look into using a SimpleCursorAdapter which allows you to bind a query to a ListView with minimal code.
Addition
I took a closer look at your code and try this:
Cursor cursor = sqliteDatabase.query(
AndroidOpenDbHelper.TABLE_NAME_GPA, null, null, null, null, null,
BaseColumns._ID + " DESC");
Well i can suggest you to get the data from the database and add the items in the reverse order in the adapter that you are setting for populating the listview.
Consider this as the sample where you can get the values from the database which returns an arraylist.
Now consider this arraylist and add each item to the arrayadapter from the last like :
for(i=arraylist.size()-1;i>0;i--)
{
adapter.add(arraylist.get(i));
}
and after setting for the first time you can call
adapter.notifyDataSetChanged()
to refresh the list automatically.
Give a try to this

Categories

Resources