Android - load values from sqlite database to an arraylist - android

I am new to android . I have an application working with SQLite DB.
I need to push values from database to an arraylist of type object.
The code i used is given here.
private ArrayList<objectname> objectList = new ArrayList<objectname>();
//function used to get values from database
public ArrayList<objectname> getResults() {
MyDb db = new MyDb(this); //my database helper file
db.open();
Cursor c = db.getAllValues(); //function to retrieve all values from a table- written in MyDb.java file
if (c.moveToFirst())
{
do {
String date = c.getString(c.getColumnIndex("date"));
try
{
ob = new objectname();
ob.setDate(c.getString(c.getColumnIndex("date")));// setDate function is written in Class file
objectList.add(ob);
}
catch (Exception e) {
Log.e(MY_DEBUG_TAG, "Error " + e.toString());
}
} while (c.moveToNext());
}
db.close();
return objectList;
}
This is not working correctly. Not shown any errors but i didn't get values in to the arraylist objectList
Please help me..Thanks in advance..

try this:
private ArrayList<objectname> objectList = getResults();
private ArrayList<objectname> getResults() {
MyDb db = new MyDb(this); //my database helper file
db.open();
ArrayList<objectname> resultList = new ArrayList<objectname>();
Cursor c = db.getAllValues(); //function to retrieve all values from a table- written in MyDb.java file
while (c.moveToNext())
{
String date = c.getString(c.getColumnIndex("date"));
try
{
ob = new objectname();
ob.setDate(date);// setDate function is written in Class file
resultList.add(ob);
}
catch (Exception e) {
Log.e(MY_DEBUG_TAG, "Error " + e.toString());
}
}
c.close();
db.close();
return resultList;
}

I had a similar issue with retrieving values from the db using cursors and displaying on screen.. The below solution works for me..
Cursor cur = db.getAllValues();
int index = c.getColumnIndex("date");
cur.moveToFirst();
while (cur.isAfterLast() == false) {
System.out.println(cur.getString(index)); // For debug purposes
String date = cur.getString(index);
try {
ob = new objectname();
ob.setDate(date);
resultList.add(ob);
} catch (Exception e) {
Log.e(MY_DEBUG_TAG, "Error " + e.toString());
}
cur.moveToNext();
}
cur.close();

Probably your query is drawing a blank and moveToFirst is returning false.
What about logging the value of c.getCount() before your if statement?

Related

How to retrieve a single column data from a Android sugar orm database

I have created a Sugar ORM database successfully in my app, I can update, delete and also get all data from a row, but I want a single column data matched with another data...
I mean, I have a registration database with fields: username, password, first_name, last_name, email fields.
After login a user with right username and password, I want THAT User's First_Name in a Textview sent to the Next Activity...
How can I do this? Over last two days I have tried but failed, please help me...
Thanks in advance...
public static List<String> getResultWithRawQuery(String rawQuery, Context mContext) {
List<String> stringList = new ArrayList<>();
if (mContext != null) {
long startTime = System.currentTimeMillis();
SugarDb sugarDb = new SugarDb(mContext);
SQLiteDatabase database = sugarDb.getDB();
try {
Cursor cursor = database.rawQuery(rawQuery, null);
try {
if (cursor.moveToFirst()) {
do {
stringList.add(cursor.getString(0));
} while (cursor.moveToNext());
}
Timber.d(cursor.getString(0), "hi");
} finally {
try {
cursor.close();
} catch (Exception ignore) {
}
}
} catch (Exception e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println("total time query" + totalTime);
}
return stringList;
}
Another example that returns a List of values in the column. Use as such:
String rawQuery = ("SELECT feed_key FROM team_feed_key WHERE team_id = " + mTeam_id + " ORDER BY feed_key DESC");
Did you try to run a raw query like this?
List<Note> notes = Note.findWithQuery(Note.class, "Select * from Note where name = ?", "satya");
from: http://satyan.github.io/sugar/query.html
you can add function to SugarRecord.java forever
public static String Scaler(String Query) {
String Result = "";
SugarDb db = getSugarContext().getSugarDb();
SQLiteDatabase sqLiteDatabase = db.getDB();
SQLiteStatement sqLiteStatament = sqLiteDatabase
.compileStatement(Query);
try {
Result = sqLiteStatament.simpleQueryForString();
} catch (Exception e) {
e.printStackTrace();
} finally {
sqLiteStatament.close();
}
return Result;
}
or
public static String Scaler(String Query) {
String Result = "";
SQLiteDatabase sqLiteDatabase = SugarContext.getSugarContext().getSugarDb().getDB();
SQLiteStatement sqLiteStatament = sqLiteDatabase
.compileStatement(Query);
try {
Result = sqLiteStatament.simpleQueryForString();
} catch (Exception e) {
e.printStackTrace();
} finally {
sqLiteStatament.close();
}
return Result;
}
Scaler("Select First_Name from Note where name ='ali' limit 1");
I had the same problem.
I hope this helps someone:
String firstName = Select.from(User.class).where("EMAIL = "+ user.getEmail()).first().getFirstName();
Hi this must work you can not edit the libraries but you can extend them so check this out:
public class DBUtils extends SugarRecord {
public static <T> List<Object> findByColumn(Context context, String tableName,T ColumnObjectType, String columnName) {
Cursor cursor = new SugarDb(context).getDB().query(tableName, new String[]{columnName}, null, null,
null, null, null, null);
List<Object> objects = new ArrayList<>();
while (cursor.moveToNext()){
if (ColumnObjectType.equals(long.class) || ColumnObjectType.equals(Long.class)) {
objects.add(cursor.getLong(0));
}else if(ColumnObjectType.equals(float.class) || ColumnObjectType.equals(Float.class)){
objects.add(cursor.getFloat(0));
}else if(ColumnObjectType.equals(double.class) || ColumnObjectType.equals(Double.class)){
objects.add(cursor.getDouble(0));
}else if(ColumnObjectType.equals(int.class) || ColumnObjectType.equals(Integer.class)){
objects.add(cursor.getInt(0));
}else if(ColumnObjectType.equals(short.class) || ColumnObjectType.equals(Short.class)){
objects.add(cursor.getShort(0));
}else if(ColumnObjectType.equals(String.class)){
objects.add(cursor.getString(0));
}else{
Log.e("SteveMoretz","Implement other types yourself if you needed!");
}
}
if (objects.isEmpty()) return null;
return objects;
}
}
The usage is simple use DBUtils.findByColumn(...);
Any where you like and from now on you can use only this class instead of SugarRecord and add your own other functions as well.
hint:
ColumnObjectType as the name Suggest tells the type of column like you send Integer.class

Android: Display Image From SQLite

I'm learning about databases in android and have come across the following question, I would like to retrieve an image, how can I change the code below to image instead of string?
public List<String> getImage(){
List<String> listRows = new ArrayList<String>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor c;
try {
c = db.rawQuery("SELECT image FROM " + MY_TABLE + " WHERE _id = " + _id, null);
if(c == null) return null;
String row;
c.moveToFirst();
do {
row = c.getString(0);
listRows.add(row);
} while (c.moveToNext());
c.close();
}
catch (Exception e) {
Log.e("LOGmsg getDBImage", e.getMessage());
}
db.close();
return listRows;
}
store the image in the database is a bad practice, it is better to store pictures on the sd and store in the database paths to them
Treat the image as a byte array and write/retrieve it to/from your database as a Blob object.

Sqlite can i use nester cursors?

I'm trying to do a query with in a query
id = mCursor.getInt(mCursor.getColumnIndex(DatabaseHelper.COLUMN_SUBJECT_ID));
S = new Subject(id, getSubjectDescById(id));
Subjects.add(S);
the getSubjectDescById() function opens up another cursor on its own.
mCursor is opened before the code and closed after it.
Is it risky to have nested Cursors? If so what would be a better alternative to my code
I have not tested this though but i think,Yes you can use Nested cursors
Scenario:
Step-1> Open CURSOR-1
Step-2> Open CURSOR-2 and Use that cursor as a pointer for the new Cursor you care going to create
Step-3> Close CURSOR-2
Step-4> Close Cursor-1
Try this Sample::
private void DemoFunction() throws Exception {
DatabaseHandler mHelper;
SQLiteDatabase db = null;
Cursor mCursor1 = null;
Cursor mCursor2 = null;
try {
mHelper = new DatabaseHandler(getActivity());
db = mHelper.getReadableDatabase();
//make query for buffet-type
mCursor1 = db.rawQuery("<------My First Query ------>", null);
if(mCursor1.moveToFirst()){
do{
mCursor2 = db.rawQuery("<------My Second Query ------>", null);
if(mCursor2.moveToFirst()){
do{
}while(mCursor2.moveToNext());
Log.d("", "");
}
}while(mCursor1.moveToNext());
Log.d("", "");
}
} catch (Exception e) {
if(isErr==false){
errMsg=e.getLocalizedMessage();
isErr=true;
}
throw e;
}finally{
if(db!=null){
if(db.isOpen()) db.close();
}
if(mCursor1!=null||mCursor2!=null){
if(!mCursor2.isClosed())mCursor2.close();
if(!mCursor1.isClosed())mCursor1.close();
}
}
}
Note:- Make sure you close all the cursors

Trying to load an sqlite table as an ArrayList<String[]> in android

I'm trying to load an sqlite table as an arraylist so that i can use the data in it. I'm not too sure about the sqlite queries but i already have a class built to manipulate the strings as is, which is what i'm more comfortable with. I can load an individual row but i'm not sure how to get the whole table as an arraylist.
I have the following method in my main method
public void ShowCNData()
{
TestAdapter mDbHelper = new TestAdapter(this);
mDbHelper.createDatabase();
mDbHelper.open();
String allData = mDbHelper.getCYData().get(1)[1];
thing.setText(allData);
mDbHelper.close();
}
and the following method in my dbAdapter/Helper class
public ArrayList<String[]> getCYData()
{
ArrayList<String[]> CYData = new ArrayList<String[]>();
try
{
String sql ="SELECT * FROM cnYears ";
Cursor mCur = null;
do
{
mCur = mDb.rawQuery(sql, null);
CYData.add(new String[] {mCur.getString(0),mCur.getString(1),mCur.getString(2),mCur.getString(3),mCur.getString(4)});
}
while (mCur.moveToNext());
return CYData;
}
catch (SQLException mSQLException)
{
Log.e(TAG, "getTestData >>"+ mSQLException.toString());
throw mSQLException;
}
}
How do i load the data into my ArrayList?
Without actual log information, I'd guess your NullPointerException occurs when you get an empty cursor. Try it this way:
//initialize arraylist, execute query etc.
if (cursor.moveToFirst()) {
do {
String[] entry = new String[dataSize];
//pull your data here
data[0] = cursor.getInt(0);
data[1] = cursor.getString(1);
//...
list.add(entry);
} while (cursor.moveToNext());
}
// return arraylist

how to store the result of the request in table

hi
I want to store the result of request in a table. I want the result of the method is table howa to do that? My code contains error.
public array getResult_libelle(int id)
{
array tab[] = null;
try
{
Cursor c = null;
c = db.rawQuery("select libelle from favori where _id="+id, null);
c.moveToFirst();
tab = c.getString(c.getColumnIndex("libelle"));
c.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return tab;
}
public ArrayList <String> getResult_libelle(int id)
{
ArrayList <String> tab = new ArrayList <Stringr>();
try
{
Cursor c = null;
c = db.rawQuery("select libelle from favori where _id="+id, null);
c.moveToFirst();
for(int i=0;i<c.getCount();i++){
tab.add(c.getString(c.getColumnIndex("libelle")));
c.moveToNext();
}
c.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return tab;
}
First of all, your cursor will already be having only the column named libelle so I don't think there should be a need to explicitly filter it out.
I guess, you should directly use getString(i) to get data of each row out, one by one, from the cursor
give that a try.

Categories

Resources