How to retrieve data from SQLite? - android

I am working on an sqlite database in which I am sure that I have inserted in sqlite correctly.
Now i am fetching data from sqlite using cursor but when I set the data to Texview, my application crashes. Here is my table:
here is my db code:
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM " + PRODUCT_TABLE + " WHERE ID = 23";
Cursor cursor = db.rawQuery(query,null);
return cursor;
Here is my cursor code:
Cursor cursor = dbHelper.getCheckOutProduct(Id);
if (cursor != null && cursor.getCount() > 0) {
do {
int proId = cursor.getInt(cursor.getColumnIndex("ID"));
int addressId = cursor.getInt(cursor.getColumnIndex("Price"));
int paymentTypeID = cursor.getInt(cursor.getColumnIndex("Quantity"));
int customerID = cursor.getInt(cursor.getColumnIndex("ProductID"));
Log.e("ProductId",String.valueOf(proId));
}while (cursor.moveToNext());
}
Where am I making a mistake?

if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
do {
int proId = cursor.getInt(cursor.getColumnIndex("ID"));
int addressId = cursor.getInt(cursor.getColumnIndex("Price"));
int paymentTypeID = cursor.getInt(cursor.getColumnIndex("Quantity"));
int customerID = cursor.getInt(cursor.getColumnIndex("ProductID"));
Log.e("ProductId",String.valueOf(proId));
}while (cursor.moveToNext());
}

SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM " + PRODUCT_TABLE + " where id = 23";
Cursor cursor = db.rawQuery(query,null);
return cursor;
this is right query i guess

Where are you storing the values retrieved form cursor? For easiness, you can create a model with required attributes and set it one by one, and return a list like this:
Cursor cursor = dbHelper.getCheckOutProduct(Id);
List<Model> values = new ArrayList<>();
if (cursor != null && cursor.getCount() > 0) {
do {
int proId = cursor.getInt(cursor.getColumnIndex("ID"));
int addressId = cursor.getInt(cursor.getColumnIndex("Price"));
int paymentTypeID = cursor.getInt(cursor.getColumnIndex("Quantity"));
int customerID = cursor.getInt(cursor.getColumnIndex("ProductID"));
Model model = new Model();
model.setProdId(prodId);
//just like above line set other desired values.
values.add(model);
Log.e("ProductId",String.valueOf(proId));
}while (cursor.moveToNext());
}
return values;
Hope this helps to debug the problem.

Related

how to retrieve data from sqlite in android

I am working on an sqlite database in which I am sure that I have inserted in sqlite correctly.
Now i am fetching data from sqlite using cursor but when I set the data to Texview, my application crashes. Here is my table:
Here is my cursor code:
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM " + PRODUCT_TABLE + " where id = 23";
Cursor cursor = db.rawQuery(query,null);
return cursor;
And here is my code in activity from where i am fetching data from database
dbHelper = new DBHelper(context);
Cursor c = dbHelper.getCheckOutProduct();
if (c != null){
while (c.moveToNext()) {
int Id = c.getInt(0);
int paymentTypeID = c.getInt(1);
int customerID = c.getInt(2);
}
}
Where am I making a mistake? Thank-you in advance
here is my exception
Your Isuue is that you have selected all column by
String query = "SELECT * FROM " + ORDER_TABLE + " ORDER BY ID DESC LIMIT 1 ";
But you didnt get column index for AddressId column
Change
dbHelper = new DBHelper(context);
Cursor c = dbHelper.getCheckOutRequest();
if (c != null){
while (c.moveToNext()) {
int Id = c.getInt(0);
int paymentTypeID = c.getInt(1);
int customerID = c.getInt(2);
}
}
To
dbHelper = new DBHelper(context);
Cursor c = dbHelper.getCheckOutRequest();
if (c != null){
while (c.moveToNext()) {
int Id = c.getInt(0);
int AddressID = c.getInt(1);
int paymentTypeID = c.getInt(2);
int customerID = c.getInt(3);
}
}
Probably because you are casting a String to int, try this -
int Id = 0;
int paymentTypeID = 0;
int customerID = 0;
dbHelper = new DBHelper(context);
Cursor c = dbHelper.getCheckOutRequest();
if (c != null){
while (c.moveToNext()) {
Id = c.getInt(0);
paymentTypeID = c.getInt(1);
customerID = c.getInt(2);
}
}
Then in Textview,
textView.setText(String.valueOf(Id));
let's change your cursor way and take it in some othe code way
you have this tabel and you wanna set and get the data from it hmm lets try harder code
but it gonna be easy with use it up next
||========================================||
|| ORDER_TABLE ||
||========================================||
|| ID ||
|| AddressID ||
|| PaymentTypeID ||
|| CustomerID ||
||========================================||
put this function in DBHelper class
public ArrayList<Map<String, String>> getorder()
{
ArrayList<Map<String, String>> array_list = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select * from " + ORDER_TABLE + " ORDER BY ID DESC LIMIT 1 " , null);
res.moveToFirst();
while(res.isAfterLast() == false){
Map<String, String> datanum = new HashMap<String, String>();
datanum.put("ID", res.getString(res.getColumnIndex("ID")));
datanum.put("AddressID", res.getString(res.getColumnIndex("AddressID")));
datanum.put("PaymentTypeID", res.getString(res.getColumnIndex("PaymentTypeID")));
datanum.put("CustomerID", res.getString(res.getColumnIndex("CustomerID")));
array_list.add(datanum);
res.moveToNext();
}
return array_list;
}
and this code to fetching data from DBHelper
DB = new DBHelper(this);
ArrayList<Map<String, String>> order = DB.getorder();
String ID;
String AddressID;
String PaymentTypeID;
String CustomerID;
try {
if(order.size() = 0){
//database is empty
} else {
ID = order.get(0).get("ID");
AddressID = order.get(0).get("AddressID");
PaymentTypeID = order.get(0).get("PaymentTypeID");
CustomerID = order.get(0).get("CustomerID");
}
}catch (IndexOutOfBoundsException e){
Toast.makeText(this,"ERROR IndexOutOfBoundsException :. "+ e ,Toast.LENGTH_LONG).show();
}
and if you have alot of orders
you can for loop
for (int i= 0 ; i< order.size();i++){
ID_list = order.get(i).get("ID");
AddressID_list = order.get(i).get("AddressID");
PaymentTypeID_list = order.get(i).get("PaymentTypeID");
CustomerID_list = order.get(i).get("CustomerID");
}
i think you know the rest of the part
i hope that help you

CursorIndexOutOfBoundException: Index -1 requested, with a size of 1

How do i do a select statement which retrieves 2 String and 1 integer value. I am receiving this error. My app keep crashing at cursor.getString(0); In my log, i do get this message Log.d("TAG","Row found");
Login.java
private void getQRCodeInformation(){
//database helper object
DatabaseHelper db;
//initializing views and objects
db = new DatabaseHelper(this);
Cursor cursor = db.getQRCodeInformation();
if(cursor.getCount() == 0) {
Log.d("TAG","Nothing found");
}
else{
Log.d("TAG","Row found");
if(cursor != null && cursor.moveToFirst()){
//cursor.getString(0);
//cursor.getString(1);
//cursor.getInt(1);
Log.d("TAG","Data found");
}
}
}
DatabaseHelper.java
public Cursor getQRCodeInformation(){
SQLiteDatabase db = this.getReadableDatabase();
String sql = "SELECT "+COLUMN_0_UserDetail+" , "+COLUMN_4_UserDetail+" , "+COLUMN_5_UserDetail+ " FROM "+ TABLE_NAME_UserDetail;
Cursor c = db.rawQuery(sql, null);
return c;
}
you just need to get index of column
int index = cursor.getColumnIndex(COLUMN_NAME);
then
String columnValue = cursor.getString(index);
Good luck :)

android.database.CursorIndexOutOfBoundsException:Index -1 requested, with a size of 0

I'm trying to use a cursor to return the most recently added entry into a database. I get the error in the title when I send the following code:
SQLiteDatabase db =getReadableDatabase();
String sql = "SELECT * FROM "+SPORTS_TABLE_NAME+" ORDER BY Sport_id DESC LIMIT 1;";
Cursor cursor = db.rawQuery(sql, null);
db.close();
return cursor.getInt(0);
Any ideas?
Your code have to be like the following:
int id = 0;
SQLiteDatabase db =getReadableDatabase();
String sql = "SELECT * FROM "+SPORTS_TABLE_NAME+" ORDER BY Sport_id DESC LIMIT 1";
Cursor cursor = db.rawQuery(sql, null);
if(cursor != null && cursor.moveToFirst()) {
id = cursor.getInt(0);
}
if(cursor != null)
db.close();
return id;

Cursor Index Out Of Bounds Exception - Android SQLite

I'm attempting to query my SQLite database but I'm getting the error "Cursor Index Out Of Bounds Exception: Index 0 requested, with a size of 0". When I run the same query in SQLite Man, I get the result I'm looking for.
public int getHighScore () {
String query = "SELECT score FROM " + SCORE_TABLE + ";";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
cursor.moveToFirst();
int score = cursor.getInt(0);
cursor.close();
return score;
}
Please check if cursor is not null then you want to fetch record from cursor.Use this line to fetch record:
cursor.getInt(cursor.getColumnIndex("score")))
use this code :
public int getHighScore () {
int score=0;
String query = "SELECT score FROM " + SCORE_TABLE + ";";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor != null && cursor.moveToFirst()) {
score = cursor.getInt(cursor.getColumnIndex("score")));
}
cursor.close();
return score;
}

cant access data in sqlite database

I wrote this function which takes in a post id and finds the last name for that post id.When I run this I get error :
database.cursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
What is wrong?
public Person_Obj GetPerson_Obj(int post_id)
{
Person_Obj obj = new Person_Obj();
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_Persons + " WHERE "
+ Post_Id + " = " + post_id;
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null)
cursor.moveToFirst();
obj.set_last_name(cursor.getString(cursor.getColumnIndex("LastName")));
return obj;
}
Try this,
SQLiteDatabase db = database.getReadableDatabase();
Cursor cursor = db.rawQuery("query", null);
// looping through all rows and adding to list
if (cursor.moveToFirst())
{
do
{
// write your code
} while (cursor.moveToNext());
}
database.close();

Categories

Resources