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();
}
Related
Hey as I was running tests on my application I began to delete database values from my database. Once I did I began getting this error
Caused by: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
It is for this line of code.
PasswordResults passwordResults = password.get(0); which I am confused on as .get(0) would always get the selected row on my recyclerView prior to me deleting some data in the database.
Here is my code for my PasswordManager where I am getting the error at.
I am passing a checker integer and a String that has the selectedID of the row the user clicked. I have tried using PasswordResults passwordResults = password.get(Integer.parseInt(id)) thinking that would work but it does not.
// method to load correct screen based on user input.
public void loadScreen(int c, String id){
// checking if it is a previous entry.
if(c == 1) {
// Since there already is a password set button to "Show Password"
password_btn.setText("Show");
// getting selected passwords data.
password = db.getSelectedPassword(id);
// GETTING ERROR HERE
PasswordResults passwordResults = password.get(0);
idSelected = id;
entryName_et.setText(passwordResults.entryName);
website_et.setText(passwordResults.website);
username_et.setText(passwordResults.username);
realPassword = passwordResults.password;
// dont show real password yet.
if(showPW == 1)
password_et.setText(realPassword);
else
password_et.setText("***********");
desc_et.setText(passwordResults.description);
// make delete button visible since user could want to delete entry.
delete_btn.setVisibility(View.VISIBLE);
} else {
// since user is creating a new entry dont show delete button.
delete_btn.setVisibility(View.GONE);
}
}
Here is my code for my Database class which handles the retrieval of information in my database.
public void addPassword(String n, String w, String u, String p, String d) {
// get database.
SQLiteDatabase db = getWritableDatabase();
try {
// add scores.
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, n);
values.put(COLUMN_WEBSITE, w);
values.put(COLUMN_USERNAME, u);
values.put(COLUMN_PASSWORD, p);
values.put(COLUMN_DESC, d);
// insert will handle null values. closing.
db.insert(TABLE_NAME, "", values);
db.close();
} catch (Exception e) {
e.getLocalizedMessage();
}
}
public void removePassword(String id){
// get database.
SQLiteDatabase db = getWritableDatabase();
// delete database then close or print error.
try {
db.delete(TABLE_NAME, "_id="+id, null);
db.close();
} catch(Exception e) {
e.getLocalizedMessage();
}
}
public void updatePassword(String id, String n, String w, String u, String p, String d) {
// get database.
SQLiteDatabase db = getWritableDatabase();
//update database then close or print error.
try {
ContentValues values = new ContentValues();
values.put(COLUMN_ID, id);
values.put(COLUMN_NAME, n);
values.put(COLUMN_WEBSITE, w);
values.put(COLUMN_USERNAME, u);
values.put(COLUMN_PASSWORD, p);
values.put(COLUMN_DESC, d);
db.update(TABLE_NAME, values, "_id="+id, null);
db.close();
} catch (Exception e) {
e.getLocalizedMessage();
}
}
public ArrayList<PasswordResults> getPasswords() {
// get database, password array, and select statement.
passwords = new ArrayList<>();
String refQuery = "Select "+COLUMN_NAME+", "+COLUMN_WEBSITE+", "+COLUMN_USERNAME+", "+COLUMN_PASSWORD+", "+COLUMN_DESC+" FROM "+TABLE_NAME;
SQLiteDatabase db = getWritableDatabase();
// link to database
Cursor cursor = db.rawQuery(refQuery, null);
if(cursor.moveToFirst()) {
do {
PasswordResults passwordResults = new PasswordResults();
passwordResults.entryName = cursor.getString(0);
passwordResults.website = cursor.getString(1);
passwordResults.username = cursor.getString(2);
passwordResults.password = cursor.getString(3);
passwordResults.description = cursor.getString(4);
passwords.add(passwordResults);
} while(cursor.moveToNext());
}
db.close();
return passwords;
}
public ArrayList<PasswordResults> getSelectedPassword(String id) {
// get database, password array, and select statement.
passwords = new ArrayList<>();
String refQuery = "Select "+COLUMN_NAME+", "+COLUMN_WEBSITE+", "+COLUMN_USERNAME+", "+COLUMN_PASSWORD+", "+COLUMN_DESC+" FROM "+TABLE_NAME+" WHERE "+COLUMN_ID+" = "+id;
SQLiteDatabase db = getWritableDatabase();
// link to database
Cursor cursor = db.rawQuery(refQuery, null);
if(cursor.moveToFirst()) {
do {
PasswordResults passwordResults = new PasswordResults();
passwordResults.id = Integer.parseInt(id);
passwordResults.entryName = cursor.getString(0);
passwordResults.website = cursor.getString(1);
passwordResults.username = cursor.getString(2);
passwordResults.password = cursor.getString(3);
passwordResults.description = cursor.getString(4);
passwords.add(passwordResults);
} while(cursor.moveToNext());
}
db.close();
return passwords;
}
And here is my code for PasswordResults class.
public class PasswordResults {
public int id;
public String entryName;
public String website;
public String username;
public String password;
public String description;
}
Could be an easy fix like half the things I put on here but thanks for your help in advance.
If your id is a String, you have to change +id inside your query to + '"' + id + '"', so it will be treat as a String.
String refQuery = "Select "+COLUMN_NAME+", "+COLUMN_WEBSITE+", "+COLUMN_USERNAME+", "+COLUMN_PASSWORD+", "+COLUMN_DESC+" FROM "+TABLE_NAME+" WHERE "+COLUMN_ID+" = "+ '"' + id + '"';
Odds on no rows are being selected by the getSelectedPassword. The do...while construct won't be entered (i.e. cursor.moveToFirst() returns false) and thus the result an empty ArrayList being returned that has no elements and thus index 0 is out of bounds.
Check the ArrayList's size and only attempt to get the password if the size is greater than 0. Perhaps Toast or something to indicate the error.
Obviously you then need to ascertain why the id being passed is not found, which will be the root cause.
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
I am using the following method to query my SQLite database with LIKE statement.
public List<Bean> getWords(String englishWord) {
if(englishWord.equals(""))
return new ArrayList<Bean>();
String sql = "SELECT * FROM " + TABLE_NAME +
" WHERE " + ENGLISH + " LIKE ? ORDER BY LENGTH(" + ENGLISH + ") LIMIT 100";
SQLiteDatabase db = initializer.getReadableDatabase();
Cursor cursor = null;
try {
cursor = db.rawQuery(sql, new String[]{"%" + englishWord.trim() + "%"});
List<Bean> wordList = new ArrayList<Bean>();
while(cursor.moveToNext()) {
String english = cursor.getString(1);
String mal = cursor.getString(2);
wordList.add(new Bean(english, bangla));
}
return wordList;
} catch (SQLiteException exception) {
exception.printStackTrace();
return null;
} finally {
if (cursor != null)
cursor.close();
}
}
I would like to change the above code for that it will query for exact match. I tried to modify the code as below but I do not how to get the mal string.
public void getoneWords(String englishWord) {
String sql = "SELECT * FROM " + TABLE_NAME +
" WHERE " + ENGLISH + " =?";
SQLiteDatabase db = initializer.getReadableDatabase();
Cursor cursor = null;
try {
cursor = db.rawQuery(sql, new String[]{englishWord});
while(cursor.moveToNext()) {
String english = cursor.getString(1);
String mal = cursor.getString(2);
}
} finally {
if (cursor != null)
cursor.close();
}
}
Method getoneWords for what. You should return mal and english in this function.
return new Bean(english, mal);
If you need first word, just cursor.moveToFirst and delete while loop:
String english = cursor.getString(1);
String mal = cursor.getString(2);
return new Bean(english, mal);
I finally solved this problem myself.
public String getoneWords(String englishWord) {
String sql = "SELECT * FROM " + TABLE_NAME +
" WHERE " + ENGLISH + " =?";
SQLiteDatabase db = initializer.getReadableDatabase();
Cursor cursor = null;
String meaning = "";
try {
cursor = db.rawQuery(sql, new String[] {englishWord});
if(cursor.getCount() > 0) {
cursor.moveToFirst();
meaning = cursor.getString(2);
}
return meaning;
}finally {
cursor.close();
}
}
In your getoneWords() you are not returning the queried values.
As you have two return values you would either need to wrap them in a Pair or create a "holder" Object (e.g. class Words(String english, String mal)) for the return values.
If your Query returns multiple matches you would need to return a list of those Objects. Otherwise, your above Code would just return the last match.
So you need to alter your function to return the queried
public Pair<String,String> getoneWords(String englishWord) {
Pair<String,String> result = null;
...
if(cursor.moveToNext()) {
String english = cursor.getString(1);
String mal = cursor.getString(2);
result = new Pair<String,String>(english, mal);
}
...
return result;
}
Experts,
As-Is
I am having application in which textview is displaying the database table count.Which keep change upon inserting the data in to the database table
And issue is changed data is appearing whenever i closed and reopen again only.
To-Be
Textview should show the count the moment data is inserted in to the table. Like auto refresh something like that. Could you assist.
my code is
String strData1 = "";
Cursor c = dbhndlr.getAllEntries();
if (c!= null) {
if (c.moveToFirst()) {
do {
strData1 += c.getString(0);
} while (c.moveToNext());
}
}
tex.setText(strData1);
String strData2 = "";
Cursor c1 = dbhndlr.getAllEntries1();
if (c1!= null) {
if (c1.moveToFirst()) {
do {
strData2 += c1.getString(0);
} while (c1.moveToNext());
}
}
tex1.setText(strData2);
DB
public Cursor getAllEntries(){
String selectQuery = "SELECT count (*) FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cur = db.rawQuery(selectQuery, null);
return cur;
}
public Cursor getAllEntries1(){
String selectQuery = "SELECT count (*) FROM " + TABLE_LABELS2;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cur1 = db.rawQuery(selectQuery, null);
return cur1;
}
public List<String> getAllLabels1(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT count (*) FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor1 = db.rawQuery(selectQuery, null);
final ArrayList<String> row1 = new ArrayList<String>();
// looping through all rows and adding to list
if (cursor1.moveToFirst()) {
do {
labels.add(cursor1.getString(1));
} while (cursor1.moveToNext());
}
// closing connection
cursor1.close();
db.close();
// returning lables
return labels;
}
I am having problem while retrieving data from sqlite database what I need is to retrieve all data on console. But I am getting only one rows data on console
Here is the code to insert and retrieve data from Sqlite. Please specify what I am missing or doing wrong. Thanks for any help.
public long InsertContacts(Contacts contacts) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_IMAGE, DbUtility.getBytes(contacts.getBmp()));
contentValues.put(KEY_BABY_NAME, contacts.getBaby_name());
contentValues.put(KEY_GENDER, contacts.getBaby_gender());
contentValues.put(KEY_SET_DATE, contacts.getDate());
contentValues.put(KEY_SET_TIME, contacts.getTime());
return db.insert(TABLE_NAME, null, contentValues);
}
public Contacts retriveContactsDetails() {
SQLiteDatabase db = this.getReadableDatabase();
String[] columns = new String[]{KEY_IMAGE, KEY_BABY_NAME, KEY_GENDER, KEY_SET_DATE, KEY_SET_TIME};
Cursor cursor = db.query(TABLE_NAME, columns, null, null, null, null, null);
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
byte[] blob = cursor.getBlob(cursor.getColumnIndex(KEY_IMAGE));
String name = cursor.getString(cursor.getColumnIndex(KEY_BABY_NAME));
String gender = cursor.getString(cursor.getColumnIndex(KEY_GENDER));
String date = cursor.getString(cursor.getColumnIndex(KEY_SET_DATE));
String time = cursor.getString(cursor.getColumnIndex(KEY_SET_TIME));
Log.d(TAG, DbUtility.getImage(blob) + name + "-" + gender + "-" + date + "- " + time); // I need to get all date here that have been inserted but i am getting only first rows data every time i insert.
cursor.moveToNext();
return new Contacts(DbUtility.getImage(blob), name, gender, date, time);
}
cursor.close();
return null;
}
}
Contacts.java
public class Contacts {
private Bitmap bmp;
private String baby_name;
private String baby_gender;
private String date;
private String time;
public Contacts(Bitmap b, String n, String g, String d, String t) {
bmp = b;
baby_name = n;
baby_gender = g;
date = d;
time = t;
}
public Bitmap getBmp() {
return bmp;
}
public String getBaby_name() {
return baby_name;
}
public String getBaby_gender() {
return baby_gender;
}
public String getDate() {
return date;
}
public String getTime() {
return time;
}
}
You should change your retriveContactsDetails() to this:
public List<Contacts> retriveContactsDetails() {
SQLiteDatabase db = this.getReadableDatabase();
String[] columns = new String[]{KEY_IMAGE, KEY_BABY_NAME, KEY_GENDER, KEY_SET_DATE, KEY_SET_TIME};
List<Contacts> contactsList = new ArrayList<>();
Cursor cursor;
try {
cursor = db.query(TABLE_NAME, columns, null, null, null, null, null);
while(cursor.moveToNext()) {
byte[] blob = cursor.getBlob(cursor.getColumnIndex(KEY_IMAGE));
String name = cursor.getString(cursor.getColumnIndex(KEY_BABY_NAME));
String gender = cursor.getString(cursor.getColumnIndex(KEY_GENDER));
String date = cursor.getString(cursor.getColumnIndex(KEY_SET_DATE));
String time = cursor.getString(cursor.getColumnIndex(KEY_SET_TIME));
contactsList.add(new Contacts(DbUtility.getImage(blob), name, gender, date, time));
Log.d(TAG, DbUtility.getImage(blob) + name + "-" + gender + "-" + date + "- " + time);
}
} catch (Exception ex) {
// Handle exception
} finally {
if(cursor != null) cursor.close();
}
return contactsList;
}
Also, your Contacts class should be named Contact as it contains only a single instance of your object.
public Contacts retriveContactsDetails() {
...
while (cursor.isAfterLast() == false) {
...
cursor.moveToNext();
return new Contacts(...);
}
Your Contacts class is named wrong because it contains only a single contact. It should be named Contact.
The return statement does what it says, it returns from the function. So the loop body cannot be executed more than once.
What you actually want to do is to construct a list of contacts, add one contact object to the list in each loop iteration, and return that list at the end.