I am building an application where the user can save some information into an sqlite database. What I now want to do is be able to get the data from the sqlite database and store each row in its own string.
Note
There is only one column in the database.
So, algoritm is not difficult, just create Cursor and in loop you will be retrieving data from it and then save them to List for example.
So try this snippet of code:
final String SELECT_QUERY = "Select column from Table";
List<String> data = new ArrayList<String>();
String member = null;
Cursor c = db.rawQuery(SELECT_QUERY, null);
if (c.getCount() > 0 && c.moveToFirst()) {
do {
member = new String(c.getString(0));
data.add(member);
}
while (c.moveToNext());
}
Related
I'm trying to fetch data from sqlite database and update a custom recycler view with these data. I've created a method in my Database helper class that returns an ArrayList of items fetched from the database.
This is how I expect the method to work:
query the database, store the result set in a Cursor object.
Loop through the result set in the Cursor object and add each item to the end of an ArrayList object.
Return the ArrayList object containing the items fetched from the database.
But this is how the method is working:
queries the database, stores the result set in a Cursor object. Correct.
On the first iteration of the result set, the first item in the result set is added at index 0 of the ArrayList object. Just as expected. But on the second iteration, the second item in the result set replaces the already added item in the ArrayList at index 0, and it's also added at index 1. Furthermore, on the third iteration, the third item in the result set replaces all the items in the ArrayList such that we now have only the third item at indices 0, 1 and 2 instead of having the first item at index 0, second at index 1 and third at index 2. I'd really appreciate all the help I can get on this.
Below is the snippet of the method that does the item fetching from the database
public ArrayList<RechargeCard> getCard(){
ArrayList<RechargeCard> list = new ArrayList<>();
RechargeCard card = new RechargeCard();
SQLiteDatabase database = getReadableDatabase();
String query = "SELECT * FROM " + RechargeEntry.TABLE_NAME;
Cursor cursor = database.rawQuery(query, null);
if (cursor.moveToFirst()){
do{
String name = cursor.getString(cursor.getColumnIndexOrThrow(RechargeEntry.NAME_COLUMN));
int price = cursor.getInt(cursor.getColumnIndexOrThrow(RechargeEntry.PRICE_COLUMN));
double quantity = cursor.getDouble(cursor.getColumnIndexOrThrow(RechargeEntry.QUANTITY_COLUMN));
double total = cursor.getDouble(cursor.getColumnIndexOrThrow(RechargeEntry.TOTAL));
card.setName(name);
card.setPrice(price);
card.setQuantity(quantity);
card.setTotal(total);
list.add(card);
} while (cursor.moveToNext());
}
cursor.close();
database.close();
return list;
}
What you code is doing is that it is only updating RechargeCard card = new RechargeCard(); for every iteration that the while loop is doing.
You should put RechargeCard card = new RechargeCard(); inside the do while loop
so it will create new instances every iteration
public ArrayList<RechargeCard> getCard(){
ArrayList<RechargeCard> list = new ArrayList<>();
SQLiteDatabase database = getReadableDatabase();
String query = "SELECT * FROM " + RechargeEntry.TABLE_NAME;
Cursor cursor = database.rawQuery(query, null);
if (cursor.moveToFirst()){
do{
RechargeCard card = new RechargeCard();
String name = cursor.getString(cursor.getColumnIndexOrThrow(RechargeEntry.NAME_COLUMN));
int price = cursor.getInt(cursor.getColumnIndexOrThrow(RechargeEntry.PRICE_COLUMN));
double quantity = cursor.getDouble(cursor.getColumnIndexOrThrow(RechargeEntry.QUANTITY_COLUMN));
double total = cursor.getDouble(cursor.getColumnIndexOrThrow(RechargeEntry.TOTAL));
card.setName(name);
card.setPrice(price);
card.setQuantity(quantity);
card.setTotal(total);
list.add(card);
}while (cursor.moveToNext());
}
cursor.close();
database.close();
return list;
}
I have a weird sqlite problem, partly Flutter partly Android... I have a database that I create in Flutter. When I insert a new row and I save it, I want to retrieve it in Android and send the values to a broadcast receiver. I am using this query: "SELECT * FROM " + TABLE_NAME + " ORDER BY " + COLUMN_ID + " DESC LIMIT 1"; This works great when creating the first row, but after that my broadcast receiver only ever receives the value of the last but one row, not the last row.
This is my code on the Java side, to get the details from the sqlite database and send them to the receiver:
public void getScheduleFromFlutter() {
String setting = "";
DatabaseHandler db = new DatabaseHandler(this);
Cursor cursor = db.getValues();
if (cursor.moveToFirst())
setting = cursor.getString(cursor.getColumnIndex(COLUMN_SETTING));
Intent intent = new Intent(this, Schedules.class);
intent.putExtra("SETTING", setting);
sendBroadcast(intent);
cursor.close();
db.close();
}
Any ideas?
You might have some issues in the query to retrieve the last row.
However if you re inserting values in table with Sqflite.
When inserting a value:
// Insert the Dog into the correct table. You might also specify the
// `conflictAlgorithm` to use in case the same dog is inserted twice.
//
// In this case, replace any previous data.
await db.insert(
'dogs',
dog.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
The method insert returns a future with the ID of new column.
// INSERT helper
Future<int> insert(String table, Map<String, dynamic> values,
{String nullColumnHack, ConflictAlgorithm conflictAlgorithm});
You can then send this ID instead or query the table with this ID to get the entry you need.
I've created an object that I need to save so the user can access the information in it later. I was using other questions, and tutorials to put it into a JSONobject, and then turn that into a string. After that, I would insert it into a table...
JSONObject json = new JSONObject();
json.put("run", run);
String runString = json.toString();
SQLiteDatabase database = openOrCreateDatabase("your runs",MODE_PRIVATE,null);
database.execSQL("CREATE TABLE IF NOT EXISTS Runs(Run BLOB);");
database.execSQL("INSERT INTO Runs VALUES('"+runString+"');");
To retrieve it I use this code...
cursor = database.rawQuery("Select * from Runs",null);
cursor.moveToFirst();
runArray = new Run[cursor.getCount()];
while(cursor.moveToNext()){
try {
object = new JSONObject(String.valueOf(cursor.getBlob(0)));
run = (Run) object.opt("run");
runArray[count] = run;
count ++;
} catch (JSONException e) {
e.printStackTrace();
}
}
This seems to work, but when I try to get a Run from the runArray, and get the name of the run it causes a null pointer exception. The runArray has a length of one, which should be correct because I only created one Run. Is this the proper way to retrieve the Runs, or should I be going about this a different way?
I figured it out. Instead of trying to put the Run object into the table. I just put all of the values from Run into the table. In the other activity that retrieved the values, I took the values and created a new Run with them.
Here's the code that inserts the values...
SQLiteDatabase database = openOrCreateDatabase("your runs",MODE_PRIVATE,null);
database.execSQL("CREATE TABLE IF NOT EXISTS Runs(name VARCHAR, units VARCHAR, runtime VARCHAR, date VARCHAR, pace FLOAT, avgSpeed FLOAT, distance FLOAT, laps BLOB, speeds BLOB, distances BLOB);");
database.execSQL("INSERT INTO Runs VALUES('"+run.getName()+"','"+run.getUnits()+"','"+run.getRunTime()+"','"+run.getDate()+"','"+run.getPace()+"','"+run.getAvgSpeed()+"','"+run.getDistance()+"','"+Arrays.toString(run.getLaps())+"','"+Arrays.toString(run.getSpeeds())+"','"+Arrays.toString(run.getDistances())+"');");
And here's the code that retrieves it...
database = openOrCreateDatabase("your runs",MODE_PRIVATE,null);
cursor = database.rawQuery("Select * from Runs",null);
cursor.moveToFirst();
runArray = new Run[cursor.getCount()];
count = 0;
while(!cursor.isAfterLast()){
run = new Run();
run.setName(cursor.getString(0));
run.setUnits(cursor.getString(1));
run.setRunTime(cursor.getString(2));
run.setDate(cursor.getString(3));
run.setPace(cursor.getFloat(4));
run.setAvgSpeed(cursor.getFloat(5));
run.setDistance(cursor.getFloat(6));
run.setLaps(toArray(new String(cursor.getBlob(7))));
run.setSpeeds(toFloatArray(new String(cursor.getBlob(8))));
run.setDistances(toFloatArray(new String(cursor.getBlob(9))));
runArray[count] = run;
count++;
cursor.moveToNext();
}
I'm not sure if this is the best way, but it works for now. I can improve it later.
This might be stupid question but this code is not working..
String sql= "SELECT field, question, choice1, choice2, choice3, choice4, answer "
+ "FROM WineQuiz ORDER BY RANDOM() LIMIT 5";
Intent i = getIntent();
String mField1 = i.getStringExtra("FIELD1");
String mField2 = i.getStringExtra("FIELD2");
String mField3 = i.getStringExtra("FIELD3");
if(mField1!="" || mField2!="" || mField3!=""){
sql = "SELECT field, question, choice1, choice2, choice3, choice4, answer "
+ "FROM WineQuiz WHERE field='"+mField1+"' or field='"+mField2+"' or field='"+mField3+"' ORDER BY RANDOM() LIMIT 5";
Cursor c =db.rawQuery(sql, null);
What I'm trying to do is simple. I'm creating quiz app, which has SelectActivity sending string data of quiz field into this class receiving it with variables of mField1,2,3.
If SelectActivity does not send any string, the first sql(variable) is put into the query.
If one of the field is chosen, mField1 or 2 or 3 receives string data, then the second sql is put into the query.
However, the first sql querying does not work while the second one works well.
When I use the first sql query independently, it works pretty well. Thus, the first and second sql seems unable to exist at the same time though those two query has no problem by themselves.
Why is that??
Replying the comments, "Not work" means cursor has no data. My continuing code is below, and the error log "Cursor has no data" shows up. It literally means those array does not store any data.
Cursor c =db.rawQuery(sql, null);
if (c.getCount() > 0) { // If cursor has at least one row
c.moveToFirst();
do { // always prefer do while loop while you deal with database
cPos = c.getPosition();
array[cPos][0] = c.getString(c.getColumnIndex("field"));
array[cPos][1] = c.getString(c.getColumnIndex("question"));
array[cPos][2] = c.getString(c.getColumnIndex("choice1"));
array[cPos][3] = c.getString(c.getColumnIndex("choice2"));
array[cPos][4] = c.getString(c.getColumnIndex("choice3"));
array[cPos][5] = c.getString(c.getColumnIndex("choice4"));
array[cPos][6] = c.getString(c.getColumnIndex("answer"));
c.moveToNext();
//Retrieves whether the cursor is after the last row in this SQLServerResultSet object.
} while (!c.isAfterLast());
} else {
Log.e("SQL Query Error", "Cursor has no data");
}
I followed this tutorial: http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/ Created db with SQLite Database Browser, put db file in "assets" folder etc..
Here my db structure created using SQLite Database Browser with instructions in tutorial link;
Then i added this method to end of DataBaseHelper class;
public ArrayList<market> getMarkets() {
String table = "markets";
ArrayList<market> markets = new ArrayList<market>();
market mrkt = new market();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + table, null);
if(cursor.moveToFirst()) {
cursor.moveToNext();
do {
mrkt.market_id = cursor.getInt(cursor.getColumnIndex("marketid"));
mrkt.market_name = cursor.getString(cursor.getColumnIndex("name"));
mrkt.market_telno = cursor.getInt(cursor.getColumnIndex("telno"));
mrkt.market_location = cursor.getString(cursor.getColumnIndex("location"));
mrkt.market_hours = cursor.getString(cursor.getColumnIndex("hours"));
markets.add(mrkt);
}while(cursor.moveToNext());
}
cursor.close();
db.close();
return markets;
}
and i try to show first market's informations on textview with these lines in activity class:
myDbHelper = new DataBaseHelper(this);
markets = new ArrayList<market>();
myDbHelper.createDataBase();
myDbHelper.openDataBase();
markets = myDbHelper.getMarkets();
id.setText(markets.get(0).getMarket_id());
name.setText(markets.get(0).getMarket_name());
telno.setText(markets.get(0).getMarket_telno());
loc.setText(markets.get(0).getMarket_location());
hours.setText(markets.get(0).getMarket_hours());
However i got logcat error:
04-12 23:40:24.477: E/SQLiteLog(30698): (1) no such table: markets
i checked data/data file and there is not my db file
i followed tutorial line by line but i dont know why i can not create table or sqlite database properly ?
i tried .db, .sqlite3 extensions.. if i'm wrong then what should be my db file extension ?
please help..
(note: i have cyanogenmod 11.0 on my phone)
I am not sure what is the problem but this code:
if(cursor.moveToFirst()) {
cursor.moveToNext();
do {
mrkt.market_id = cursor.getInt(cursor.getColumnIndex("marketid"));
mrkt.market_name = cursor.getString(cursor.getColumnIndex("name"));
mrkt.market_telno = cursor.getInt(cursor.getColumnIndex("telno"));
mrkt.market_location = cursor.getString(cursor.getColumnIndex("location"));
mrkt.market_hours = cursor.getString(cursor.getColumnIndex("hours"));
markets.add(mrkt);
}while(cursor.moveToNext());
}
skips the first row of the query. With cursor.moveToFirst() you are already pointing to the first row in the table, but you do additional cursor.moveToNext() which skips the first row, and goes to the second.
You didn't define a table. I'm assuming as it wasn't in the tutorial. This is the line and it should be after the DATABASE_NAME and DATABASE_VERSION, and before the lines to identify the columns:
public static final String TABLE_NAME = "markets";
If you fixed it with other code, please let me know! I've been working on somet