I'm using this code for Android but when I debug I'm seeing this error:
the cursor should be freed up after use with #close
This line has the error:
cursor = db.query(DATABASE_TABLECa, new String[]{ key_RoWid ,Key_GroupName}, null, null, null, null, null);
public List<ListAdapterdb> Getall() {
List<ListAdapterdb> dataList = new ArrayList<ListAdapterdb>();
db = dbhelper.getReadableDatabase();
Cursor cursor= null;
cursor = db.query(DATABASE_TABLECa, new String[]{ key_RoWid ,Key_GroupName}, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
ListAdapterdb data = new ListAdapterdb();
//data.setID(Integer.parseInt(cursor.getString(0)));
data.setItem(cursor.getString(1));
// Adding contact to list
dataList.add(data);
} while (cursor.moveToNext());
}
return dataList;
}
You need to call cursor.close() when you're done dealing with the data.
try {
ListAdapterdb data = new ListAdapterdb();
while (cursor.moveToNext()) {
// data.setID(Integer.parseInt(cursor.getString(0)));
data.setItem(cursor.getString(1));
// Adding contact to list
dataList.add(data);
}
} finally {
cursor.close()
}
You can also add this code to that line:
#SuppressLint("Recycle")
Related
public String[] getAllDescription() {
db = this.getReadableDatabase();
cursor = db.query(NOTIFICATIONTABLE, new String[]{"notification_id", "notification_title",
"notification_description", "notification_isread", "date"}, null, null, null,
null, null);
String[] result = new String[cursor.getCount()];
int i = 0;
if (cursor.moveToFirst()) {
do {
result[i] = cursor.getString(cursor.getColumnIndex("notification_description"));
i++;
} while (cursor.moveToNext());
}
if ((cursor != null) && !cursor.isClosed()) {
cursor.close();
db.close();
}
return result;
}
this is my code currently i am getting from 0 to n data in staring array i want to get in reverse array data from n to 0 so that i can Print please suggest me how i will get data
Try this method :
public ArrayList<String> getAllDescription()
{
ArrayList<String> array_list = new ArrayListString>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("SELECT * " + " FROM " + NOTIFICATIONTABLE+ " DESC;", null);
res.moveToFirst();
while (res.isAfterLast() == false)
{
array_list.add(hashmap);
res.moveToNext();
}
return array_list;
}
Or If you want to reverse arrayList then you can also do it By just a single line of code .
Collections.reverse("yourArrayList");
Hope it will help you.
i am getting from 0 to n data in staring array i want to get in
reverse array data from n to 0
Why not using ASC or DESC in db query to get result in sequence as want according to notification_description column.
do it as:
cursor = db.query(NOTIFICATIONTABLE,
new String[]{"notification_id",
"notification_title",
"notification_description",
"notification_isread",
"date"}, null, null, null,
null, "notification_description DESC");
You can insert the data from end of theString[]...
public String[] getAllDescription() {
db = this.getReadableDatabase();
cursor = db.query(NOTIFICATIONTABLE, new String[]{"notification_id", "notification_title",
"notification_description", "notification_isread", "date"}, null, null, null,
null, null);
String[] result = new String[cursor.getCount()];
int i = 0;
if (cursor.moveToFirst()) {
do {
///////////////////////
result[(cursor.getCount()-1)-i] = cursor.getString(cursor.getColumnIndex("notification_description"));
///////////////////////
i++;
} while (cursor.moveToNext());
}
if ((cursor != null) && !cursor.isClosed()) {
cursor.close();
db.close();
}
return result;
}
This is my cursor in database handler class for displaying single coloumn in a list view
public String getAllStringValues() {
ArrayList<String> yourStringValues = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor result = db.query(true, TABLE_PATIENT_GENERAL,
new String[] { KEY_PATIENT_NAME }, null, null, null, null,
null, null);
if (result.moveToFirst()) {
do {
yourStringValues.add(result.getString(result
.getColumnIndex(KEY_PATIENT_NAME)));
} while (result.moveToNext());
} else {
return null;
}
return KEY_PATIENT_NAME;
}
as I m fresher in android please tell me the exact flow and code thanks.
I use this function to get specific data from SQlite:
SearchRes getSresultByName(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_WIKIRES, new String[] { KEY_ID,
KEY_SNAME, KEY_SJSON }, KEY_SNAME + "=?",
new String[] { name }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
SearchRes searchres = new SearchRes(Integer.parseInt(cursor.getString(0)),cursor.getString(1), cursor.getString(2));
return searchres;
}
And it works just fine, I need to create similar function to test if value is exist in the table, so I tried this:
boolean checkIfExist(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_WIKIRES, new String[] { KEY_ID,
KEY_SNAME, KEY_SJSON }, KEY_SNAME + "=?",
new String[] { name }, null, null, null, null);
if (cursor == null)
return false;
else
return true;
}
But I always get TRUE. Can you help me figure out what is the problem?
you should not be checking if cursor is null you should be checking if anything exists in the cursor
if(cursor.moveToFirst()){
return true
}else{
return false;
}
You can try Cursor getCount() to check the number of rows in the result of the query.. Following is the sample code:
boolean checkIfExist(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_WIKIRES, new String[] { KEY_ID,
KEY_SNAME, KEY_SJSON }, KEY_SNAME + "=?",
new String[] { name }, null, null, null, null);
if (cursor.getCount() > 0)
return true;
else
return false;
}
answer by #tyczj is also good..
Here is a code/method to find if some name exists in the table or not..
Contact getContact(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_NAME + "=?",
new String[] { String.valueOf(name) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
db.close();
cursor.close();
// return contact
return contact;
}
I already have a function to get all names in an arrayList. I can call it before calling the above function to solve my problem. But I want to ask about is there any other (straight) way to do it
When you call cursor.moveToFirst() it will return true if there is a valid result there, or false in the case no results are found. If cursor.moveToFirst() returns false, then calling any of the getXXX() methods will fail.
Try something like this:
if( cursor.moveToFirst() )
{
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
}
cursor.close();
Note that the Cursor returned from SQLiteDatabase.query is guaranteed to be non-null.
if (cursor == null)
Toast.makeText(getApplicationContext(), "No Records Exist", Toast.LENGTH_SHORT).show();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_NAME + "=?",
new String[] { String.valueOf(name) }, null, null, null, null);
if(cursor.moveToFirst()){
do {
Double lat = cursor.getDouble(2);
Double lon = cursor.getDouble(1);
} while (trackCursor.moveToNext());
}
Here is a code for getting all the contacts in a list from the table...
/**
* Getting all the contacts in the database
*/
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return contact list
return contactList;
}
Then it is invoked in another function that returns "true" if name is present in the table "false" otherwise...
/**
* checks if name already present in the database
* #param name
* #return
*/
public boolean checkDbData(String name){
List<Contact> contactList =getAllContacts();
boolean checkName = false ;
for(Contact cn: contactList){
String dbName = cn.getName();
if(name.equals(dbName)){
checkName = true ;
}
}
return checkName;
}
And if this function returns "true", then the above given function is invoked to get the contacti.e.
Contact getContact(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_NAME + "=?",
new String[] { String.valueOf(name) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
db.close();
cursor.close();
// return contact
return contact;
}
Note: we can also get this contact from the contactList, both can be used to get the required contact (i.e. "name" in this case)
I have been trying to get all rows from the SQLite database. But I got only last row from the following codes.
FileChooser class:
public ArrayList<String> readFileFromSQLite() {
fileName = new ArrayList<String>();
fileSQLiteAdapter = new FileSQLiteAdapter(FileChooser.this);
fileSQLiteAdapter.openToRead();
cursor = fileSQLiteAdapter.queueAll();
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
fileName.add(cursor.getString(cursor.getColumnIndex(FileSQLiteAdapter.KEY_CONTENT1)));
} while (cursor.moveToNext());
}
cursor.close();
}
fileSQLiteAdapter.close();
return fileName;
}
FileSQLiteAdapter class:
public Cursor queueAll() {
String[] columns = new String[] { KEY_ID, KEY_CONTENT1 };
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns, null,
null, null, null, null);
return cursor;
}
Please tell me where is my incorrect. Appreciate.
try:
Cursor cursor = db.rawQuery("select * from table",null);
AND for List<String>:
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String name = cursor.getString(cursor.getColumnIndex(countyname));
list.add(name);
cursor.moveToNext();
}
}
Using Android's built in method
If you want every column and every row, then just pass in null for the SQLiteDatabase column and selection parameters.
Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null, null);
More details
The other answers use rawQuery, but you can use Android's built in SQLiteDatabase. The documentation for query says that you can just pass in null to the selection parameter to get all the rows.
selection Passing null will return all rows for the given table.
And while you can also pass in null for the column parameter to get all of the columns (as in the one-liner above), it is better to only return the columns that you need. The documentation says
columns Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.
Example
SQLiteDatabase db = mHelper.getReadableDatabase();
String[] columns = {
MyDatabaseHelper.COLUMN_1,
MyDatabaseHelper.COLUMN_2,
MyDatabaseHelper.COLUMN_3};
String selection = null; // this will select all rows
Cursor cursor = db.query(MyDatabaseHelper.MY_TABLE, columns, selection,
null, null, null, null, null);
This is almost the same solution as the others, but I thought it might be good to look at different ways of achieving the same result and explain a little bit:
Probably you have the table name String variable initialized at the time you called the DBHandler so it would be something like;
private static final String MYDATABASE_TABLE = "anyTableName";
Then, wherever you are trying to retrieve all table rows;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from " + MYDATABASE_TABLE, null);
List<String> fileName = new ArrayList<>();
if (cursor.moveToFirst()){
fileName.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
while(cursor.moveToNext()){
fileName.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
}
}
cursor.close();
db.close();
Honestly, there are many ways about doing this,
I have been looking into the same problem! I think your problem is related to where you identify the variable that you use to populate the ArrayList that you return. If you define it inside the loop, then it will always reference the last row in the table in the database. In order to avoid this, you have to identify it outside the loop:
String name;
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
name = cursor.getString(cursor
.getColumnIndex(countyname));
list.add(name);
cursor.moveToNext();
}
}
Update queueAll() method as below:
public Cursor queueAll() {
String selectQuery = "SELECT * FROM " + MYDATABASE_TABLE;
Cursor cursor = sqLiteDatabase.rawQuery(selectQuery, null);
return cursor;
}
Update readFileFromSQLite() method as below:
public ArrayList<String> readFileFromSQLite() {
fileName = new ArrayList<String>();
fileSQLiteAdapter = new FileSQLiteAdapter(FileChooser.this);
fileSQLiteAdapter.openToRead();
cursor = fileSQLiteAdapter.queueAll();
if (cursor != null) {
if (cursor.moveToFirst()) {
do
{
String name = cursor.getString(cursor.getColumnIndex(FileSQLiteAdapter.KEY_CONTENT1));
fileName.add(name);
} while (cursor.moveToNext());
}
cursor.close();
}
fileSQLiteAdapter.close();
return fileName;
}
Cursor cursor = myDb.viewData();
if (cursor.moveToFirst()){
do {
String itemname=cursor.getString(cursor.getColumnIndex(myDb.col_2));
String price=cursor.getString(cursor.getColumnIndex(myDb.col_3));
String quantity=cursor.getString(cursor.getColumnIndex(myDb.col_4));
String table_no=cursor.getString(cursor.getColumnIndex(myDb.col_5));
}while (cursor.moveToNext());
}
cursor.requery();
public List<String> getAllData(String email)
{
db = this.getReadableDatabase();
String[] projection={email};
List<String> list=new ArrayList<>();
Cursor cursor = db.query(TABLE_USER, //Table to query
null, //columns to return
"user_email=?", //columns for the WHERE clause
projection, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null);
// cursor.moveToFirst();
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(cursor.getColumnIndex("user_id")));
list.add(cursor.getString(cursor.getColumnIndex("user_name")));
list.add(cursor.getString(cursor.getColumnIndex("user_email")));
list.add(cursor.getString(cursor.getColumnIndex("user_password")));
// cursor.moveToNext();
} while (cursor.moveToNext());
}
return list;
}
a concise solution can be used for accessing the cursor rows.
while(cursor.isAfterLast)
{
cursor.getString(0)
cursor.getString(1)
}
These records can be manipulated with a loop