Android: Display Image From SQLite - android

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.

Related

Fetch data from Sqlite database

I am creating app in which i register user and store user's information in database,so i have created database and storing value in databse but i don't know how to fetch data from database and show in textview?Using below query to fetch data but it has error.What is correct way?
public void insertEntry(String fname, String lname, String gen,String weight)
{
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("firstname", fname);
values.put("lastname", lname);
values.put("gender", gen);
values.put("weight",weight);
}
public Cursor fetchData()
{
SQLiteDatabase mDB = dbHelper.getWritableDatabase();
return mDB.rawQuery("SELECT * FROM Register WHERE firstname=? lastname =?" , null);
}
Using this to set fetched value on textview in different activity
Cursor name = sqliteDataBase.fetchData();
tv_name.setText((CharSequence) name);
Try this,
try {
SQLiteDatabase mDB = dbHelper.getReadableDatabase();
String selectQuery = "SELECT * FROM Register WHERE firstname= "+first+" lastname =" + last + ";";
cursor = db.rawQuery(selectQuery, null);
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
String firstName = cursor.getString(cursor.getColumnIndex("firstname")));
}
}
} catch(Exception e) {
e.printSTackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
public String fecthResults()
{
String name = null;
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
Cursor cursor = sqLiteDatabase.query(TABLE_NAME, null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
name = cursor.getString(cursor.getColumnIndex("firstname")
} while (cursor.moveToNext());
cursor.close();
}
sqLiteDatabase.close();
return name;
Get the name and then set it directly to a texView
A Cursor is an interface that provides random read-write access to the result set returned by the query. It contains multiple rows of data and this data can be easily processed by help of For loop.
Lets take an example to understand the process. Suppose, you need to access data from a column name "col_1" and show the data in TextView. The For loop for the process will be as follows.
for (cursor.moveToNext()) {
textView.setText(cursor.getString(cursor.getColumnIndex("col_1")));
}
Now, if we need only one value (from only one record or tuple) then, we can opt out the For loop and change the code as shown below.
if (cursor.moveToFirst()) {
textView.setText(cursor.getString(cursor.getColumnIndex("col_1")));
}
Always remember to close the cursor after using it.
To close the cursor, use the following line of code.
cursor.close();
For more information, please visit the following links:
https://developer.android.com/reference/android/database/Cursor.html
https://developer.android.com/training/basics/data-storage/databases.html#ReadDbRow

SQL query to sum different values from the same table for different customers [for android]

Can some one please help me with:
I have DB with 5 tables : DB diagram stat_list table is pre-populated with 5 values (Att, pass, TD, inter, pass). And I want create a table in android that will display sum of all the values from table Stat_list for every player. Thanks a lot!
String sQry = "SELECT * FROM Stat_list;";
SQLiteDatabase db = null;
int count = -1;
Cursor cursor = null;
try {
db = SQLiteOpenHelper.getReadableDatabase();
cursor = db.rawQuery(sQry, null);
if (cursor.moveToFirst()) {
do {
int playerScore = Integer.parseInt(cursor.getString(1)) +
Integer.parseInt(cursor.getString(2)) +
Integer.parseInt(cursor.getString(3)) +
Integer.parseInt(cursor.getString(4))
ContentValues playerScores = new ContentValues();
playerScores.put(THE_NAME_OF_THE_SCORE_COLUMN, playerScore);
try{
db.update(NAME_OF_TABLE_WITH_SUMMED_PLAYER_SCORES,playerScores, "PlayerName = " cursor.getString(1), null);
}catch(SQLiteException e){}
}
while (cursor.moveToNext());
}
}
catch (SQLiteException e) {
Log.d("SQL Error", e.getMessage());
}
finally {
cursor.close();
db.close();
}
The snippet above pulls the information from the db, sums up the scores and inserts it into another table. You'll have to put int he specific values though, such as the correct column and table names.

Database retrieval in android

In my application i am showing data from database in a table view.My requirement is that from database i have to retrieve the data which will fall in the current month.I Have written the query but it is coming as 0.Actually i have 1 entry in the database with today's date,so my query should return that data,but it is showing as 0.Please help me.Thanks in advance.
My query is as follows:
public String addgroupincome(String grp) throws SQLException
{
long sum=0;
Cursor cursor1 = db.rawQuery(
"SELECT SUM("+(KEY_TOTAL)+") FROM incomexpense WHERE date= Strftime('%Y-%m','now') AND category='Income' AND groups='"+grp+"'",null);
if(cursor1.moveToFirst())
{
sum = cursor1.getLong(0);
}
cursor1.close();
String housetotal=String.valueOf((long)sum);
return housetotal;
}
I am getting that total and showing in atextview in table layout..
final String houtotal=db.addgroupincome(group1);
housetotal.setText(houtotal);
Most probably nothing wrong with the query but the way you pass the query result to ListView. Can you show how you do it? Perhaps I could help.
Or you could take a look here or here
public int getCount() {
DBHelper dbHelper = DBHelper.getDBAdapterInstance(this);
int count = 0;
try {
dbHelper.openDataBase();
String query = "select count(1) from t_model where upper(brandName) = upper('"
+ selectedBrand + "') order by modelName ASC";
Cursor cursor = dbHelper.selectRecordsCursor(query, null);
if (cursor.moveToFirst()) {
count = cursor.getInt(0);
}
cursor.close();
cursor = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
dbHelper.close();
}
return count;
}
and for the TextView should be as simple as
TextView tvCount = (TextView) findViewById(R.id.tvCount);
tvCount.setText("Count : " + getCount);
If you are having trouble debugging your query. Try http://sqlitebrowser.sourceforge.net/ or http://www.sqliteexpert.com/
Why don't you try by giving column names of your table in your query..might it work out for you..specify the columns which you want to retrive..
if (cursor.moveToNext()) {
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
Log.i(ID, cursor.getInt(0) + "");
cursor.moveToNext();
}
cursor.close();
} else {
cursor.close();
return null;
}
Try This Method....

Handling Invalid SQLite Queries in Android

I have a simple code that manages to successfully query an SQLite Database and convert that result from cursor to string in order to display it on screen.
My problem now would be invalid queries that make the App Crash. Would there be a way to successfully handle invalid queries? Preferably something that would keep my app from crashing and would just redirect the user to the home page and display a toast of warning.
So far my method for searching looks like this:
public String search(DataBaseHelper myDB){
SQLiteDatabase db = myDB.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT BuildingColor, Room FROM LSBuildingsDB WHERE _id =" + newString, null);
cursor.moveToFirst();
String data = cursor.getString(cursor.getColumnIndexOrThrow("BuildingColor")) + " " +
cursor.getString(cursor.getColumnIndex("Room"));
//Toast msg = Toast.makeText(getBaseContext(),data, Toast.LENGTH_SHORT);
//msg.show();
cursor.close();
return data;
}
Cursor cursor = NULL ;
try
{
cursor = db.rawQuery("SELECT BuildingColor, Room FROM LSBuildingsDB WHERE _id =" + newString, null);
if(cursor != NULL)
{
try {
if (cursor.moveToNext()) {
String data = cursor.getString(cursor.getColumnIndexOrThrow("BuildingColor")) +
" " + cursor.getString(cursor.getColumnIndex("Room"));
} else {
// Query result was empty, deal with it here.
}
} finally {
// Cursors should be closed
cursor.close();
}
}
}
catch (SQLiteException e) // (Exception e) catch-all:s are bad mmkay.
{
//print exception
}
Cursor cursor = null;
String data = "";
try
{
cursor = db.rawQuery("SELECT BuildingColor, Room FROM LSBuildingsDB WHERE _id =" + newString, null);
}catch (Exception e) {
// TODO: handle exception
}

Android - load values from sqlite database to an arraylist

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?

Categories

Resources