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
Related
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.
When I try to insert my data in my sqlite table, The inserted data is not inserting but the primary key is increasing and row count also increasing. Dont know what the exact problem is. Please some one help what the issue is. I will add my code here. Pls some one help me
here I am adding to database
mylistDataBaseModel = new MyListDataBaseModel();
mylistDataBaseModel.setItemId(0);
mylistDataBaseModel.setItemName("");
mylistDataBaseModel.setItemPrice(0.0);
mylistDataBaseModel.setItemGst(0.0);
mylistDataBaseModel.setCategoryId(0);
mylistDataBaseModel.setItemCategoryName("");
mylistDataBaseModel.setItemPicture("");
mylistDataBaseModel.setItemcount(0);
mylistDataBaseModel.setListName(createList.getText().toString().trim());
mylistDataBaseModel.setListItemcount(0);
mylistDataBaseModel.setItemisAdded(0);
// Log.d("==============", "====" + createList.getText().toString().trim());
sqLiteDatabase = sqlLiteController.getWritableDatabase();
SqliteController.addMyListNameToDataBase(sqLiteDatabase, mylistDataBaseModel);
sqlLiteController.close();
and opearation in database is
public static void addMyListNameToDataBase(SQLiteDatabase sqLiteDatabase, MyListDataBaseModel model) {
ContentValues contentValues = new ContentValues();
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN__ITEM_ID, model.getItemId());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM_NAME, model.getItemName());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM_PRICE, model.getItemPrice());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM_GST, model.getItemGst());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM__CATEGORY_ID, model.getCategoryId());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM_CATEGORY_DESCRIPTION, model.getItemCategoryName());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM_PICTURE, model.getItemPicture());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM_COUNT_ID, model.getItemcount());
Log.d("==============", "====" + model.getListName());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_MY_LIST_NAME, model.getListName());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_MY_LIST_COUNT, model.getListItemcount());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM_IS_ADDED, model.getItemisAdded());
sqLiteDatabase.insert(SqliteItemsDataBase.NewUSerInfo.MYLIST_TABLE, null, contentValues);
System.out.println("Cart Summary one row has been inserted");
UserNotification.notify(Constants.NOTIFICATION_MY_LIST_ITEM_ADDED, null);
}
this is my get data from table method
public static ArrayList<MyListDataBaseModel> getMyListData(SQLiteDatabase db) {
ArrayList<MyListDataBaseModel> allMyLists = new ArrayList<>();
Cursor cursor = db.rawQuery("select * from " + SqliteItemsDataBase.NewUSerInfo.MYLIST_TABLE, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
int localId = cursor.getInt(0);
Log.d("list","====localId====="+localId);
int itemId = cursor.getInt(1);
Log.d("list","====itemId====="+itemId);
String itemName = cursor.getString(2);
Log.d("list","====itemName====="+itemName);
Double itemPrice = cursor.getDouble(3);
Log.d("list","====itemPrice====="+itemPrice);
Double itemGst = cursor.getDouble(4);
Log.d("list","====itemGst====="+itemGst);
int categoryId = cursor.getInt(5);
Log.d("list","====categoryId====="+categoryId);
String catName = cursor.getString(6);
Log.d("list","====catName====="+catName);
String itemPicture = cursor.getString(7);
Log.d("list","====itemPicture====="+itemPicture);
int itemsCount = cursor.getInt(8);
Log.d("list","====itemsCount====="+itemsCount);
String listName = cursor.getString(9);
Log.d("list","====listName====="+listName);
int listItemCount = cursor.getInt(10);
Log.d("list","====listItemCount====="+listItemCount);
int itemIsAdded = cursor.getInt(11);
Log.d("list","====itemIsAdded====="+itemIsAdded);
allMyLists.add(new MyListDataBaseModel(localId, itemId, itemName, itemPrice,
itemGst, categoryId, catName, itemPicture, itemsCount, listName, listItemCount, itemIsAdded));
} while (cursor.moveToNext());
}
}
cursor.close();
return allMyLists;
}
I did a mistake that I got the data with some other column id instead of respected column id . That's my mistake
I want to retrieve minimum balance from table using where condition on button click.Following is my code it's not working plz give me solution.Thanks in advance..
smname = spn_mname.getSelectedItem().toString().trim();
yname = spn_yname.getSelectedItem().toString().trim();
scno = spn_count.getSelectedItem().toString().trim();
String dbsyname = null, dbsmname = null, dbsycolor = null, dbscount = null, dbsrqty = null, dbsdqty = null, dbsbaln = null;
DataBaseHelper dbh = new DataBaseHelper(StockActivity.this);
SQLiteDatabase db = dbh.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT MIN(Balance) FROM stocktable",null);
if (cursor.moveToFirst()) {
do {
dbsmname = cursor.getString(cursor.getColumnIndex("Millname"));
dbsyname = cursor.getString(cursor.getColumnIndex("Yarnname"));
dbscount = cursor.getString(cursor.getColumnIndex("Counttno"));
if (dbsmname.equals(smname)
&& bsyname.equals(syname)
&& dbscount.equals(scno)) {
dbsbaln = cursor.getString(cursor.getColumnIndex("Balance"));
}
} while (cursor.moveToNext());
edtrqty.setText(dbsbaln);
}
you have only selected MIN(Balance) only in your query and trying to access Millname,Counttno and other value on cursor it will throw the exception.
Try Below Solution
Cursor cursor = db.rawQuery("SELECT MIN(Balance) balance as FROM stocktable
where Millname=? AND bsyname=? AND dbscount=?",new String[]{smname,syname,scno});
if (cursor.moveToFirst()) {
do {
dbsbaln = cursor.getString(cursor.getColumnIndex("balance"));
}
} while (cursor.moveToNext());
edtrqty.setText(dbsbaln);
Following code works perfectly...
Cursor cursor = db.rawQuery("SELECT MIN(Balance) AS balance FROM " + DataBaseHelper.stocktable + " WHERE Millname = ? AND Yarnname = ? AND Counttno = ? ", new String[] { smname, syname, scno });
if (cursor.moveToFirst()) {
do {
dbsbaln = cursor.getString(cursor
.getColumnIndex("balance"));
} while (cursor.moveToNext());
edtrqty.setText(dbsbaln);
}
I want to read bookname field in database, but it does not work in this class.
How can I use this class?
public Person readPerson(String bookkname) {
Person person = null;
String[] columns = new String[]{"id" ,"bookname"};
String selection = "bookname=?";
String[] selectionArgs = new String[]{ bookkname};
String groupBy = null;
String having = null;
String orderBy = null;
String limit = null;
SQLiteDatabase database = null;
try {
database = sqLiteOpenHelper.getWritableDatabase();
Cursor cursor = database.query("tbl_persons", columns, selection, selectionArgs, groupBy, having, orderBy, limit);
if(cursor != null && cursor.moveToFirst()) {
int idIndex = 0;
int payIndex = 1;
int lastunitIndex = 2;
int lastlessenIndex = 3;
int booknameIndex = 4;
int maxfreeunitIndex = 5;
long personId = cursor.getLong(idIndex);
String personpay = cursor.getString(payIndex);
String personlastunit = cursor.getString(lastunitIndex);
String personlastlessen = cursor.getString(lastlessenIndex);
String personbookname = cursor.getString(booknameIndex);
String personmaxfreeunit = cursor.getString(maxfreeunitIndex);
person = new Person();
person.setId(personId);
person.setpay(personpay);
person.setlastunit(personlastunit);
person.setlastlessen(personlastlessen);
person.setbookname(personbookname);
person.setmaxfreeunit(personmaxfreeunit);
}
} catch (Exception ex) {
Log.d("Database", "Exception:" + ex.getMessage());
} finally {
if (database != null && database.isOpen()) {
database.close();
}
}
return person;
}
I try call readperson class like inner but cant give data from data base or give to me packagename
Please tell to me way of calling this class ?
PersonDatabaseAdapter databaseAdapteer = new PersonDatabaseAdapter(Main2Activity.this);
Person persoon = new Person();
databaseAdapteer = new PersonDatabaseAdapter(this);
username = databaseAdapteer.readPerson(pass.toString());
I'm trying to copy some data in a table and insert into another table. I entered the data into an ArrayList, however, is only copied a given and not all those present. What am I missing?
private void Tras() {
String numero_ricevuto = (i.getStringExtra("numero"));
SQLiteDatabase db = mHelper.getWritableDatabase();
final ArrayList<Dettaglio_i> dettaglii = new ArrayList<Dettaglio_i>();
String sql = "SELECT data, unita_di_misura FROM prev WHERE numero = '"+numero_ricevuto+"'";
Cursor c = db.rawQuery(sql, null);
while (c.moveToNext()){
Dettaglio_i e = new Dettaglio_i();
e.data_ = c.getString(0);
e.unita_di_misura = c.getString(1);
dettaglii.add(e);
}
c.close();
ContentValues cv = new ContentValues();
Dettaglio_i e = new Dettaglio_i();
cv.put(VerTable.SI_NO, "0");
cv.put(VerTable .DATA, e.data_);
cv.put(VerTable .U_M, e.unita_di_misura);
boolean inserite = false;
if (!inserite){
long result = db.insert(VerTable .TABLE_NAME, null, cv);
if (result > 0){
inserite = true;
}
}
if (inserite){
}
db.close();
}
Try replacing your code with this:
private void Tras() {
String numero_ricevuto = (i.getStringExtra("numero"));
SQLiteDatabase db = mHelper.getWritableDatabase();
String insert = String.format("INSERT INTO %s (%s, %s, %s) ",
VerTable.TABLE_NAME, VerTable.SI_NO, VerTable.DATA, VerTable .U_M);
String select = "SELECT '0', data, unita_di_misura FROM prev WHERE " +
"numero='"+numero_ricevuto+"'";
db.rawQuery(insert+select, null);
db.close();
}