Wednesday, September 26, 2012

Image in Sqlite Database and display in a List | SqLite demo in Android

Hello Friends,
      Today I am going to share very important example for how to save Image and text in Sq-lite database and how to display it in a List-view. Steps and code are given below please follow-

1- Create a new Project name e.g.- SQLiteImageDemo.
2- Create a DataBaseHandler class and create database.
3-Create a SQLiteDemoActivity and call DatabaseHandler class for insert and get data from database.
4- Create a Contact class.
4- Create a ContactImageAdapter class for create custom ListView.
5-Add ListView in main.xml file.
6-Create a xml file for add Image and Text.

a) Print Screen:


b)DataBaseHandler.java

package com.manish.sqlite;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseHandler extends SQLiteOpenHelper {

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "imagedb";

// Contacts table name
private static final String TABLE_CONTACTS = "contacts";

// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_IMAGE = "image";

public DataBaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_IMAGE + " BLOB" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

// Create tables again
onCreate(db);
}

/**
* All CRUD(Create, Read, Update, Delete) Operations
*/

public// Adding new contact
void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(KEY_NAME, contact._name); // Contact Name
values.put(KEY_IMAGE, contact._image); // Contact Phone

// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}

// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();

Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_IMAGE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();

Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getBlob(1));

// return contact
return contact;

}

// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM contacts ORDER BY name";

SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setImage(cursor.getBlob(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// close inserting data from database
db.close();
// return contact list
return contactList;

}

// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_IMAGE, contact.getImage());

// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });

}

// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}

// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();

// return count
return cursor.getCount();
}
}

c)SQLiteDemoActivity.java

package com.manish.sqlite;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

public class SQLiteDemoActivity extends Activity {
ArrayList<Contact> imageArry = new ArrayList<Contact>();
ContactImageAdapter adapter;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

DataBaseHandler db = new DataBaseHandler(this);
// get image from drawable
Bitmap image = BitmapFactory.decodeResource(getResources(),
R.drawable.facebook);

// convert bitmap to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte imageInByte[] = stream.toByteArray();
/**
* CRUD Operations
* */
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("FaceBook", imageInByte));
// display main List view bcard and contact name

// Reading all contacts from database
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "ID:" + cn.getID() + " Name: " + cn.getName()
+ " ,Image: " + cn.getImage();

// Writing Contacts to log
Log.d("Result: ", log);
//add contacts data in arrayList
imageArry.add(cn);

}
adapter = new ContactImageAdapter(this, R.layout.screen_list,
imageArry);
ListView dataList = (ListView) findViewById(R.id.list);
dataList.setAdapter(adapter);
}
}

d)Contact.java

package com.manish.sqlite;

public class Contact {

// private variables
int _id;
String _name;
byte[] _image;

// Empty constructor
public Contact() {

}

// constructor
public Contact(int keyId, String name, byte[] image) {
this._id = keyId;
this._name = name;
this._image = image;

}

// constructor
public Contact(String name, byte[] image) {
this._name = name;
this._image = image;
}

// getting ID
public int getID() {
return this._id;
}

// setting id
public void setID(int keyId) {
this._id = keyId;
}

// getting name
public String getName() {
return this._name;
}

// setting name
public void setName(String name) {
this._name = name;
}

// getting phone number
public byte[] getImage() {
return this._image;
}

// setting phone number
public void setImage(byte[] image) {
this._image = image;
}
}


e)ContactImageAdapter.java

package com.manish.sqlite;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ContactImageAdapter extends ArrayAdapter<Contact>{
Context context;
int layoutResourceId;
ArrayList<Contact> data=new ArrayList<Contact>();
public ContactImageAdapter(Context context, int layoutResourceId, ArrayList<Contact> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ImageHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ImageHolder();
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
row.setTag(holder);
}
else
{
holder = (ImageHolder)row.getTag();
}
Contact picture = data.get(position);
holder.txtTitle.setText(picture ._name);
//convert byte to bitmap take from contact class
byte[] outImage=picture._image;
ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
holder.imgIcon.setImageBitmap(theImage);
return row;
}
static class ImageHolder
{
ImageView imgIcon;
TextView txtTitle;
}
}



f)main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="0.55" >
</ListView>
</LinearLayout>

g)screen_list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:padding="10dp" >
<ImageView
android:id="@+id/imgIcon"
android:layout_width="0dp"
android:layout_height="100dp"
android:layout_weight="0.71"
android:gravity="center_vertical" />
<TextView
android:id="@+id/txtTitle"
android:layout_width="80dp"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:textSize="14dp"
android:layout_marginLeft="7dp" />
</LinearLayout>
For simple sqlite demo you can refer below link-
http://www.androidhub4you.com/2012/09/sqlite-database-in-android.html

170 comments :

  1. thankyou for the post! realli helped :)

    ReplyDelete
  2. Also this project is very important for me.

    Could you email me the code zip file to me ?
    My email is : ufficiopierangelo@libero.it

    I am studying Android, thanks for your help.



    ReplyDelete
    Replies
    1. Hi thanks for your comment but I don't think there is any need to send zip code everything is clear in my blog just copy paste the code..
      For any difficulty you can ask for help no issue..

      Thanks,

      Delete
  3. Codes given here are really helpful for me .....
    Superb man.....

    Nice work....... :-D

    ReplyDelete
  4. Hi,I'm having problem with your code,at ContactImageAdapter.java.
    It show error with this line
    "holder.txtTitle.setText(bcard._name);" at bcard
    Could you please help me with this?
    Thank in advance, :D

    ReplyDelete
    Replies
    1. Hi!
      I am sorry Dear its my mistake just change the code. I have also make change in my code you can check it..
      bcard=picture;

      Contact picture = data.get(position);
      holder.txtTitle.setText(picture._name);

      Thanks,

      Delete
  5. First of all,thanks for replying me :D.I fixed it and it showed no error.
    But there's another problem,it did run but it did not work :((.
    It keep on saying that the project has stopped,don't know why.
    In Log Cat window, the 1st line is "error opening trace file:No such file or directory".
    Could you help me with this,again :(
    Looking forward to hearing from you,thanks again :D

    ReplyDelete
    Replies
    1. Your most welcome and I am feeling happy to help you. Well it should work because it is working fine my side. I think therefore some very miner issue.

      1)Just do one thing uninstall application from device and then try again hope it will help you.

      2)Check your SQLiteDemoActivity.java line number 26. Do you have Image with facebook name in your drawable folder? or change image name-
      Bitmap image = BitmapFactory.decodeResource(getResources(),
      R.drawable.facebook);

      And if not work please put your log cat(at least 5 starting line) here so I can identify error in your code.

      Thanks,

      Delete
    2. I check as you said but it still did not work :(
      And there r some error from my Log Cat:
      03-27 14:23:40.887: W/dalvikvm(776): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
      03-27 14:23:40.932: E/AndroidRuntime(776): FATAL EXCEPTION: main
      03-27 14:23:40.932: E/AndroidRuntime(776): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.sqlite/com.example.sqlite.DataBaseHandler}: java.lang.InstantiationException: can't instantiate class com.example.sqlite.DataBaseHandler; no empty constructor
      03-27 14:23:40.932: E/AndroidRuntime(776): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
      03-27 14:23:40.932: E/AndroidRuntime(776): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
      03-27 14:23:40.932: E/AndroidRuntime(776): at android.app.ActivityThread.access$600(ActivityThread.java:141)
      03-27 14:23:40.932: E/AndroidRuntime(776): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
      03-27 14:23:40.932: E/AndroidRuntime(776): at android.os.Handler.dispatchMessage(Handler.java:99)

      Well that's not all but it looks so complicated so I will show you more error if you need it >""<
      Waiting to hear from you :)
      Thanks(again)

      Delete
    3. Yes dear you are right, error log looks very complicated :), according log-
      java.lang.InstantiationException: can't instantiate class com.example.sqlite.DataBaseHandler; no empty constructor

      But we have empty constructor in Contact Class-
      // Empty constructor
      public Contact() {

      }

      so its very difficult to short out problem. Do one thing send me your code at my email-id: manishsri01@gmail.com
      or give your email-id, I will send your zip code.

      Thanks,

      Delete
    4. Hey it worked :D,and your code isn't wrong,it'all my mistake to choose the wrong main activity :)
      By the way your code is really helpful,thanks for your sharing :)
      Thanks a lot for your help Manish,appreciate it :)

      Delete
    5. your welcome & thanks for your valuable comment..

      Delete
  6. Manish amazing code tnx!

    I'm a noob in android programming, I want to know why do you have 3 different constrcutors in Contact.java. Are these necessary or can I choose one that fits my implementation?

    Thank you in advance for your time

    ReplyDelete
    Replies
    1. Hi Nicola,

      Yes all constructors are needed in this application only one is extra. You can check it by yourself, just comment one by one constructor and you got red mark in your codes.
      well I am given you an idea where I am using them-

      1)public Contact(int keyId, String name, byte[] image)
      I am using it for getting single record from database see DataBaseHandler.java line number 79.

      2)public Contact(String contactID, String name, byte[] image)
      This one is extra I was using it for my other project to send image id on next page. you can remove it.And I also remove it from my code. Thanks for suggestion. :)

      3)public Contact(String name, byte[] image)
      And this one I am using for insert image and name into database see dataBaseHandler.java line number 38.

      Thanks,
      Manish

      Delete
  7. Hey Manish,

    Yes yes I got you man, thank you very very much for your complete explanation :) :).

    Regards,
    Nicola

    ReplyDelete
  8. Manish,

    Sorry for asking again, but I'm using your code the difference is that I'm building my own database in the DataBaseHelper class.
    As you can see I have all my images in the drawable folder and I declare these per row. While running the app I get an error "INTEGER data in nativeGetBlob"

    I have read that I could use BITMAP but I have no clue how to implement this in your code I have made some changes but still not working. Do you have any idea how can I fix this to load my images from the drawable?

    Thank you very very very much in advance :)



    //CREATE TABLE
    @Override
    public void onCreate(SQLiteDatabase db) {
    String CREATE_TABLE_INDICA = "CREATE TABLE" + TABLE_INDICA + "("
    + KEY_ID + "INTEGER PRIMARY KEY AUTOINCREMENT,"
    + KEY_NAME + "TEXT,"
    + KEY_IMAGE + "BLOB,"
    + KEY_GENES + "TEXT,"
    + KEY_STRAINS + "TEXT,"
    + KEY_LIFECYCLE + "TEXT,"
    + KEY_YIELD + "TEXT" +")";
    db.execSQL(CREATE_TABLE_INDICA);


    ContentValues row=new ContentValues();

    row.put(KEY_NAME, "Confidential Cheese");
    row.put(KEY_IMAGE, R.drawable.cc);
    row.put(KEY_GENES, "LA Confidential X Cheese");

    ReplyDelete
    Replies
    1. Hi Nicola,
      You are doing very good. May there a very miner issue that's why you are getting error. Above given code by you is correct. I think some issue with your this line-
      row.put(KEY_IMAGE, R.drawable.cc);

      so try something like this-

      / get image from drawable
      Bitmap image = BitmapFactory.decodeResource(getResources(),
      R.drawable.facebook);
      row.put(KEY_IMAGE, image);

      Thanks,

      Delete
  9. This comment has been removed by the author.

    ReplyDelete
  10. Hi Manish,

    I solved the problem with the images in the database :), once more tnx for the help.

    Regards,
    Nicola Lombardi

    ReplyDelete
  11. how to select single list item?
    i want to make a toast and display name of list item

    ReplyDelete
  12. got the answer:
    row.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub
    Toast.makeText(getContext(), "test", Toast.LENGTH_LONG).show();
    }
    });

    ReplyDelete
    Replies
    1. Yes dear you are right but all time its display "Test" so if you want display selected item or some thing else use blow code-

      /**
      * get on item click listener
      */
      row.setOnItemClickListener(new OnItemClickListener() {

      @Override
      public void onItemClick(AdapterView parent, View v,
      final int position, long id) {
      Log.i("List View Clicked", "**********");
      Toast.makeText(MainActivity.this,
      "List View Clicked:" + position, Toast.LENGTH_LONG)
      .show();
      }
      });


      OR you can check my below post-
      http://www.androidhub4you.com/2013/02/muftitouch-listview-multi-click.html

      Delete
  13. hii manich je veux récupérer plusieurs images depuis db Sqlite et les afficher dans la listeview et lorsque j'appuie sur l'image il apparait tt seule svp m'aider

    ReplyDelete
    Replies
    1. Yes sure! I will post a new blog soon just give me some time.. and please use English so I can understand what you want.. Well for now I have translated it into English :);

      Delete
    2. Please check my below post it will help you-
      http://www.androidhub4you.com/2013/04/sqlite-example-in-android-add-image.html

      Delete
  14. This comment has been removed by the author.

    ReplyDelete
  15. pls how to insert a sound sqlite android, when I press a picture ???

    ReplyDelete
    Replies
    1. Hi, I think you should insert path of sound instead of .wav or other sound format. Some thing like that-
      /**
      * Get Path
      */
      Uri selectedImage = data.getData();
      String[] filePathColumn = { MediaStore.Images.Media.DATA };

      Cursor cursor = getContentResolver().query(selectedImage,
      filePathColumn, null, null, null);
      cursor.moveToFirst();

      columnIndex = cursor.getColumnIndex(filePathColumn[0]);


      ==============
      and after that when you retrieve image then play that sound with your image or what you want..

      Delete
  16. thank for your help; is the sound saved in the folder raw ???

    ReplyDelete
  17. hi,

    your code worked well.Thanks a lot:) My doubt is tat how can we see the stored items in the database here.?? Thanks in advance..


    ReplyDelete
    Replies
    1. No no you can't see stored data in sqlite db for this you should use sqlite query browser.
      or you can put it into list like I was doing.

      Delete
  18. Hello Manish

    This tutorial very helpful and i'm trying to design a simple app for my degree
    but i'm finding it hard and tried everything but no luck yet. i have only untill this friday to submit it Could you please email me the code zip file to me.

    My Email:alankhad@gmail.com

    thank you

    alan Khadir

    ReplyDelete
    Replies
    1. Thank you for your nice comment!
      Sure I will send you zip code please check your email, hope it will help you..
      Enjoy :)

      Thanks,

      Delete
  19. This comment has been removed by the author.

    ReplyDelete
  20. OK... actually am doing my final year project.. i decided to do movie ticketing app with local database sqlite.. how can i fetch the data from db and pass to next next screen... can u pl help me with code..

    My mail id:sunantha1831@gmail.com

    ReplyDelete
    Replies
    1. Hi Please check my this post-
      http://www.androidhub4you.com/2013/04/sqlite-example-in-android-add-image.html

      Thanks!

      Delete
    2. Hi manish... I worked with this .. while saving Am getting force close msg in my mobile...how can i solve it...

      Delete
    3. some thing gonna wrong in your code check your logcat and paste here so I can check it..

      Thanks!

      Delete
  21. Hi Manish,

    Im new in android but not in coding:) I would like to save an image from url instead of drawable. A tought that if i will change this part of code:

    // get image from drawable
    Bitmap image = BitmapFactory.decodeResource(getResources(),
    R.drawable.facebook);

    to:
    public Drawable LoadImageFromWebOperations(String url) {
    try {
    InputStream is = (InputStream) new URL(url).getContent();
    Drawable d = Drawable.createFromStream(is, "src name");
    return d;
    } catch (Exception e) {
    return null;
    }
    }
    public static Bitmap drawableToBitmap (Drawable drawable) {
    if (drawable instanceof BitmapDrawable) {
    return ((BitmapDrawable)drawable).getBitmap();
    }

    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);

    return bitmap;
    }

    will be work, but doesnt start the application.
    Sorry for my english:) and thanks if you can help me.
    Drawable d = LoadImageFromWebOperations(urldisplay);
    image = drawableToBitmap(d);

    ReplyDelete
    Replies
    1. Hi just create a class ImageLoder something like below-
      public class ImageLoader {

      MemoryCache memoryCache=new MemoryCache();
      FileCache fileCache;
      private Map imageViews=Collections.synchronizedMap(new WeakHashMap());
      ExecutorService executorService;

      public ImageLoader(Context context){
      fileCache=new FileCache(context);
      executorService=Executors.newFixedThreadPool(5);
      }

      final int stub_id = R.drawable.user;
      public void DisplayImage(String url, ImageView imageView)
      {
      imageViews.put(imageView, url);
      Bitmap bitmap=memoryCache.get(url);
      if(bitmap!=null)
      imageView.setImageBitmap(bitmap);
      else
      {
      queuePhoto(url, imageView);
      imageView.setImageResource(stub_id);
      }
      }

      public void clearCache() {
      memoryCache.clear();
      fileCache.clear();
      }

      }

      And now in your activity-
      ImageLoader imageLoader;
      imageLoader = new ImageLoader(context);
      imageLoader.DisplayImage(url, imageView);
      Hope it will help you....

      Delete
    2. and please tell me your email Id so I can send you ImageLoder class..
      Paste full class is not allow here..

      Thanks,

      Delete
    3. Hi, thank you very much for your respons. My email address is: npisti686@gmail.com , and i would like to make an app what can store images in database from url and than to retrive from database. That is important because in offline mode the user could see the stored images and if he will be online and the app founds new pictures, will download it in database. I think that your sample is super for this but needs a little modification (saving from url not from drawable) if you can send me a sample i will realy greatfull.

      Delete
    4. Please check your email I have sent you a idea how to implement that hope it will help you..

      Delete
  22. public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    i have problems here in layout, it's writen to create field layout in constant R

    ReplyDelete
    Replies
    1. something wrong in your package name please check your activity package name and manifest package name it should be same-
      package com.example.hellotest;

      and





      and if you are working in different package call it something like that-
      import com.other.R;

      Delete
    2. something wrong in your package name please check your activity package name and manifest package name it should be same-
      package com.example.hellotest;
      and


      and if you are working in different package call it something like that-
      import com.other.R;

      Delete
    3. something wrong in your package name please check your activity package name and manifest package name it should be same-
      in your activity-
      package com.example.hellotest;
      and in manifest-
      package="com.example.hellotest"

      and if you are working in different package call it something like that-
      import com.other.R;

      Delete
  23. why do not put all source zip codes in you blog...

    ReplyDelete
    Replies
    1. In this case people did not going to comment for my good work.
      Nothing else.. I want some reward for my work thats..

      Delete
  24. thanks a lot it helped me but i m failed to understand the code for custom listview as i need same thing in my project but i m not getting how to do? and also let me know if i put database handler class in one file and want to put contact class and its all methods in separate class then how will i connect contact class from Databasehandler class? i m newbie

    ReplyDelete
    Replies
    1. Yes sure erun you can put it in separate folder.
      Just import it using something like that-
      import com.util.Helper;

      Delete
  25. Hi Mainsh,

    This tutorial is very helpful. But I am not able to figure out. How to bind pre-build database with a text view?

    ReplyDelete
  26. Hi Manish

    I want to fetch values form the SQL database and display them using Cursor's. I am not able to figure out what's wrong with this code.

    myDataBase = myDbHelper.getWritableDatabase();
    next.setOnClickListener(new OnClickListener()
    {

    public void onClick(View v)
    {

    //Cursor cursor = myDataBase.rawQuery("select * from android_metadata", null);
    Cursor cursor = myDataBase.query("android_metadata", null, null, null, null, null, null);
    cursor.moveToFirst();

    while (cursor.isAfterLast() == false) {

    textview1 = (TextView) findViewById(R.id.textView1);
    textview1.setText(cursor.getString(0));

    textview2 = (TextView) findViewById(R.id.textView2);
    textview2.setText(cursor.getString(1));
    cursor.moveToNext();
    }
    cursor.close();
    }
    });

    ReplyDelete
    Replies
    1. what's error you are getting? And I am surprised with your name "manish and nidhi"?

      Delete
  27. It displays the first record and is stuck there. Clicking on next doesn't display next record. they are 2 different names :)

    ReplyDelete
    Replies
    1. first record of database or last? and why you displaying them into textview? why not use cursorArrayAdapter and display them in a listview? And both name are nice but I think Manish is much good :)

      Delete
    2. Or do something like that-
      //Cursor cursor = myDataBase.rawQuery("select * from android_metadata", null);
      Cursor cursor = myDataBase.query("android_metadata", null, null, null, null, null, null);
      cursor.moveToFirst();
      if (cursor != null)
      cursor.moveToFirst();
      //and now put it into any object-
      Contact contact = new Contact((cursor.getString(0)),cursor.getString(1),
      cursor.getString(2), cursor.getBlob(3));
      and now display them into textview..

      hope it will help you...

      Delete
    3. Hi Manish,

      Thanks for the reply. What is the best way to show title and Image from the database? I just want to show one data row/record at a time and click on next button to show next data row/record. I don't want to show listview.
      --------------------------------
      id | title | Image

      1 Spring image1.blob
      2 summer image2.blob
      3 winter image3.blob

      Delete
    4. If your scope is countable means till 10 images or what you want just display one image and title at one time..
      Logic-
      int count=1;
      When button is pressed just call query get title,image form table name where id=count.
      now on press button count++;

      then automatic it will move to next image. don't use loop thing for small task..
      you are using-cursor.moveToFirst();
      that's why always you are getting first data..

      Thanks,

      Delete
  28. Hi Manish,

    I used your method to inset images in to my database. I have also set password for each image. now when i click on an image it will ask for the passord from user, and i need to check if the entered password is same as the one given in the database. How can i do that any suggestions!!

    Hope you reply to me soon..

    ReplyDelete
    Replies
    1. You can try my this artical-
      http://www.androidhub4you.com/2013/04/sqlite-example-in-android-add-image.html

      and when you are getting image in listview also get their id and when tab on that page open password popup and make this query-
      // Reading all contacts from database
      List guard = db.getAllGuard();
      for (final Guard cn : guard) {
      if ((imageId.equals("what you pick from db"))
      && (password.equals(cn.getPassword()))) {
      Intent intentHomepage = new Intent( LoginPage.this,AppHomePage.class);
      startActivity(intentHomepage);
      } }
      else{
      Toast.makeText(LoginPage.this,
      "usre name or password is not correct",
      Toast.LENGTH_LONG).show();
      }
      }

      Hope it will help you..

      Delete
    2. This comment has been removed by the author.

      Delete
  29. Hi Manish,

    I need to save the image in Data base in encrypted format. Also when i retreive it from DB i should use decryption technique to show it again.This is just to make sure the image is not used/changed by any one.can you assist?

    ReplyDelete
    Replies
    1. Yes Nirmal, you can use md5 or sha1 for encrypting so when you are saving image into db in byte[] just convert it into md5 or sha1 after that save it and same reverse process at the time of getting image from database..

      Delete
  30. Hi Manish,

    I am using pre-build db for this app. Not sure why I am getting this error.
    Caused by: android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database


    06-10 23:07:01.831: E/Trace(4419): error opening trace file: No such file or directory (2)
    06-10 23:07:03.611: E/SQLiteLog(4419): (14) cannot open file at line 30176 of [00bb9c9ce4]
    06-10 23:07:03.621: E/SQLiteLog(4419): (14) os_unix.c:30176: (2) open(/data/data/com.example.quotes/databasesQuotesdb) -
    06-10 23:07:03.641: E/SQLiteDatabase(4419): Failed to open database '/data/data/com.example.quotes/databasesQuotesdb'.
    06-10 23:07:03.641: E/SQLiteDatabase(4419): android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
    06-10 23:07:03.641: E/SQLiteDatabase(4419): at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
    06-10 23:07:03.641: E/SQLiteDatabase(4419): at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
    06-10 23:07:03.641: E/SQLiteDatabase(4419): at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
    06-10 23:07:03.641: E/SQLiteDatabase(4419): at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
    06-10 23:07:03.641: E/SQLiteDatabase(4419): at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
    06-10 23:07:03.641: E/SQLiteDatabase(4419): at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
    06-10 23:07:03.641: E/SQLiteDatabase(4419): at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)
    06-10 23:07:03.641: E/SQLiteDatabase(4419): at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)
    06-10 23:07:03.641: E/SQLiteDatabase(4419): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
    06-10 23:07:03.641: E/SQLiteDatabase(4419): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:669)
    06-10 23:07:03.641: E/SQLiteDatabase(4419): at com.example.quotes.DataBaseHelper.checkDataBase(DataBaseHelper.java:94)
    06-10 23:07:03.641: E/SQLiteDatabase(4419): at com.example.quotes.DataBaseHelper.createDataBase(DataBaseHelper.java:58)
    06-10 23:07:03.641: E/SQLiteDatabase(4419): at com.example.quotes.MainActivity.onCreate(MainActivity.java:34)
    06-10 23:07:03.641: E/SQLiteDatabase(4419): at android.app.Activity.performCreate(Activity.java:5104)
    06-10 23:07:03.641: E/SQLiteDatabase(4419): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
    06-10 23:07:03.641: E/SQLiteDatabase(4419): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
    06-10 23:07:03.641: E/SQLiteDatabase(4419): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
    06-10 23:07:03.641: E/SQLiteDatabase(4419): at android.app.ActivityThread.access$600(ActivityThread.java:141)
    06-10 23:07:03.641: E/SQLiteDatabase(4419): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
    06-10 23:07:03.641: E/SQLiteDatabase(4419): at android.os.Handler.dispatchMessage(Handler.java:99)
    06-10 23:07:03.641: E/SQLiteDatabase(4419): at android.os.Looper.loop(Looper.java:137)

    ReplyDelete
    Replies
    1. You have told me ones it is working fine right? then whats happen? I think you are using external database using query browser? No worry in this case its happen some time..Try after rebuild, clean your app may be it work..
      Try after uninstall your app may be it work.. or try on another device or emulator may be it work..

      Delete
    2. Can you help me Manish,
      how to form the database login details in the list form

      Delete
    3. I am not getting exactly what you want but I think you want login into application using login query so please try something like below-

      // Reading all contacts from database
      List guard = db.getAllGuard();
      for (final Guard cn : guard) {
      if ((imageId.equals("what you pick from db"))
      && (password.equals(cn.getPassword()))) {
      Intent intentHomepage = new Intent( LoginPage.this,AppHomePage.class);
      startActivity(intentHomepage);
      } }
      else{
      Toast.makeText(LoginPage.this,
      "usre name or password is not correct",
      Toast.LENGTH_LONG).show();
      }
      }

      Delete
    4. Is there a way to fix this issue? I have large database with Images and texts. I realized after sometime that using pre build database is a better way.

      Delete
  31. hi,i have question.
    If i want save image from url and change image of item listview.
    When select item listview and will show griview contains images download.
    thank you.

    ReplyDelete
    Replies
    1. Hi then where you are facing problem?
      1)just hit your server it will give you json data with image url and all detail.
      2)Use image loder and convert your image url into bitmap and add them into a custom listview.
      3)On tab an image from listview, display what you want in gridview..

      Thanks,

      Delete
  32. hi,
    can u plz send me the full source code to my mail: cvkarthikbabu@gmail.com
    thanks in advance.

    ReplyDelete
  33. Hi manish, i have question.
    If i have multiple icons in drawable, how can it display in gridview?
    If the icon stored in one of the folder in sd card how i gonna to retrieve it?

    Appreciate your help.

    Thank you.

    ReplyDelete
    Replies
    1. Try something like that-
      /**
      * Get Path
      */
      Uri selectedImage = data.getData();
      String[] filePathColumn = { MediaStore.Images.Media.DATA };

      Cursor cursor = getContentResolver().query(selectedImage,
      filePathColumn, null, null, null);
      cursor.moveToFirst();

      columnIndex = cursor.getColumnIndex(filePathColumn[0]);

      And after that add all data in any collection framework and display them into gridView..

      Thanks,
      Manish

      Delete
  34. Hi manish,
    How to implement touch event listener in android.I am having first page where the user enters a number and in next page the user should touch the screen only for the count specified in before page else a warning message must be displayed.. how can this be done???Please help me.

    ReplyDelete
    Replies
    1. Pass values from first page using intent or bundle and display their calculation on next page on touch full screen or any button
      ...

      Delete
  35. Why am I getting: Unable to convert BLOB to string?

    Full error log

    07-02 23:59:42.461: E/AndroidRuntime(24947): FATAL EXCEPTION: main
    07-02 23:59:42.461: E/AndroidRuntime(24947): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rved.profiles/com.me.myapp.MainActivity}: android.database.sqlite.SQLiteException: unknown error (code 0): Unable to convert BLOB to string
    07-02 23:59:42.461: E/AndroidRuntime(24947): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2351)
    07-02 23:59:42.461: E/AndroidRuntime(24947): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
    07-02 23:59:42.461: E/AndroidRuntime(24947): at android.app.ActivityThread.access$600(ActivityThread.java:151)
    07-02 23:59:42.461: E/AndroidRuntime(24947): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1331)
    07-02 23:59:42.461: E/AndroidRuntime(24947): at android.os.Handler.dispatchMessage(Handler.java:99)
    07-02 23:59:42.461: E/AndroidRuntime(24947): at android.os.Looper.loop(Looper.java:155)
    07-02 23:59:42.461: E/AndroidRuntime(24947): at android.app.ActivityThread.main(ActivityThread.java:5485)
    07-02 23:59:42.461: E/AndroidRuntime(24947): at java.lang.reflect.Method.invokeNative(Native Method)
    07-02 23:59:42.461: E/AndroidRuntime(24947): at java.lang.reflect.Method.invoke(Method.java:511)
    07-02 23:59:42.461: E/AndroidRuntime(24947): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
    07-02 23:59:42.461: E/AndroidRuntime(24947): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:795)
    07-02 23:59:42.461: E/AndroidRuntime(24947): at dalvik.system.NativeStart.main(Native Method)
    07-02 23:59:42.461: E/AndroidRuntime(24947): Caused by: android.database.sqlite.SQLiteException: unknown error (code 0): Unable to convert BLOB to string
    07-02 23:59:42.461: E/AndroidRuntime(24947): at android.database.CursorWindow.nativeGetString(Native Method)
    07-02 23:59:42.461: E/AndroidRuntime(24947): at android.database.CursorWindow.getString(CursorWindow.java:492)
    07-02 23:59:42.461: E/AndroidRuntime(24947): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
    07-02 23:59:42.461: E/AndroidRuntime(24947): at com.me.myapp.DatabaseHandler.getAllProfiles(DatabaseHandler.java:107)
    07-02 23:59:42.461: E/AndroidRuntime(24947): at com.me.myapp.MainActivity.onCreate(MainActivity.java:63)
    07-02 23:59:42.461: E/AndroidRuntime(24947): at android.app.Activity.performCreate(Activity.java:5066)
    07-02 23:59:42.461: E/AndroidRuntime(24947): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1101)
    07-02 23:59:42.461: E/AndroidRuntime(24947): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
    07-02 23:59:42.461: E/AndroidRuntime(24947): ... 11 more


    ReplyDelete
    Replies
    1. when you are trying to get getAllProfiles data your app got crash reason
      is sequence of column in your table.
      please check sequence of column in table, in my case BLOB type parameter
      at 3rd place so it will start from 0 to 2.

      public void onCreate(SQLiteDatabase db) {
      String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
      + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
      + KEY_IMAGE + " BLOB" + ")";
      db.execSQL(CREATE_CONTACTS_TABLE);
      }

      and when you are getting all data please check blob position-

      // Getting All Contacts
      public List getAllContacts() {
      List contactList = new ArrayList();
      // Select All Query
      String selectQuery = "SELECT * FROM contacts ORDER BY name";

      SQLiteDatabase db = this.getWritableDatabase();
      Cursor cursor = db.rawQuery(selectQuery, null);
      // looping through all rows and adding to list
      if (cursor.moveToFirst()) {
      do {
      Contact contact = new Contact();
      contact.setID(Integer.parseInt(cursor.getString(0)));
      contact.setName(cursor.getString(1));
      contact.setImage(cursor.getBlob(2));// check this line

      Delete
  36. hey man... send me the zip file plz... And also i have tried the new project with pager gallery with json parsing from server. But, i need to set that pager images as wallpaper.. I have tried and tired... can you help me...

    ReplyDelete
  37. Hi Manish..

    I have a gridview of images, I added a search widget in the action bar. I am able to produce a toast of the entered query, but when i compare the query with the data stored in the SQLite Database I'm getting a null pointer exception. This i am doing by setting OnQueryTextListener. and its methods(onQueryTextSubmit,onQueryTextChange). As a query i tried to search for the image id and image name. But for both I got null pointer exception where i am retrieving the SQLite data in the onQueryTextSubmit method of onCreateOptionMenu. Please give me a solution for this problem.

    Best Regards,
    Yamini.

    ReplyDelete
    Replies
    1. Try some thing like that-
      // Reading all contacts from database
      //guardId=type character by you in search box-
      List guard = db.getAllGuard();
      for (final Guard cn : guard) {
      if ((guardId.equals(cn.getGuardName()))
      && (guardPassword.equals(cn.getGuardPassword()))) {
      Intent intentHomepage = new Intent(
      SecurityAppLoginPage.this,
      SecurityAppHomePage.class);
      startActivity(intentHomepage);
      }
      else{
      //no matching
      }
      }

      Delete
    2. Manish I am actually trying to implement a search functionality for gridview. ie. i have many images say 100 in my grid view nd i type 59, it should get me the 59th image on the top or show just 59th image in a dialog. Hope You understand my question...

      Delete
  38. manish,now i m following ur code but the problem is
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo
    tell me solution what can i do,if u can please upload ur manifest file of this project

    ReplyDelete
    Replies
    1. Please download it from GIT server-
      https://github.com/manishsri01/SQLiteImageDemo

      Delete
  39. Hi, what is the probable problem that i am having, if only one of my image is being displayed instead of two images? I have managed to print out the second data title of the image, but not the image, why? Thanks :D

    ReplyDelete
    Replies
    1. If you are able to print your data in log then I can't say what going wrong..
      I think some issue in your Custom Adapter where you are setting data from database.
      Please download the full code from GIT Server and check-

      https://github.com/manishsri01/SQLiteImageDemo

      Delete
  40. hii, manish,,i got a problem. your codes i'm implement in new database, with same concept.
    but listview show empty list.
    the problem it seems on ...ImageAdapter.java.
    i initiative to use log for every process, all of log appear in log cat window except method "@Override public View..." on ImageAdapter.java. i don't know what the matter, could you explain to me?

    sorry my bad english :D

    ReplyDelete
    Replies
    1. Hi phiko!
      Have successfully able to save data into table? and you are able to print log of your record?
      Please try my code and modify according yours need-

      https://github.com/manishsri01/SQLiteImageDemo

      Delete
  41. hey manish , finally my project was running success..
    the trouble cause i'm not write code in main activity like below ->

    for (Contact cn : contacts) {
    ImageArry.add(cn);
    }

    thanks brow.. ;)

    ReplyDelete
  42. Your runs fine but nothing display what can i do.please help me

    ReplyDelete
    Replies
    1. Have you copy same demo? means package name class name manifest is same?

      Delete
  43. please give me full source code and my mail is patelsanket5657@gmail.com

    ReplyDelete
    Replies
    1. I am sorry dear for late reply. I think every thing is clear here just copy paste from above and if you got any problem let me know..

      Thanks!

      Delete
  44. Thanks Manish!
    finally got a code which helped my project!!

    ReplyDelete
  45. hi,, Manish sir
    How we can get image to view using php programing (PHP My admin) in android remote server??

    ReplyDelete
  46. Use web-services and parse that web-service response. And for image use ImageLodar.

    Please read first web-services Rest,soap,json,xml,GET and POST method sure it will help you.

    Thanks!

    ReplyDelete
  47. can u pls upload ur .sqlite database ??????

    ReplyDelete
    Replies
    1. Sure Vivek, I will inform you when upload code on git.

      Thanks!

      Delete
    2. Check my article again, a download link there..
      Thanks!

      Delete
  48. Hi Manish Sir,
    I am having a problen when query a single contact to display on ImageView
    When i use small image (ic_launcher) is Database operate OK
    But i use other image (size 1 024x768) is throw exeption: IllegalStateException: couldn't read row 0, col 2 from CursorWindow
    psl give a advise
    Thanks

    ReplyDelete
  49. I think because of big image size you are getting this exception. Your phone memory is low i think. Try on another phone, hope it will work.
    And see this line-
    // convert bitmap to byte
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    byte imageInByte[] = stream.toByteArray();

    And change compress size 100% to 25% hope it will help you.
    image.compress(Bitmap.CompressFormat.JPEG, 25, stream);

    Thanks!

    ReplyDelete
    Replies
    1. Hi Manish Sir,
      Thank you for quickly relying
      I tested on Xperia S. I want to use 100 image (each image about 2Mb) from Picasa to make data source when initializing and i dont want compress before using them. Currently, i try with SQLite and catch this problem.
      If SQLite can not store big size image, i need change to what is the way to store image?
      Pls give a some advice
      Thanks

      Delete
    2. hmmm you can't store big size image in sqlite. and 100 image never.
      Create web services and put your images on server..

      Delete
  50. i got an error ! once we took a picture from camera , it has a two options , one is crop and cancel . while performing the crop the image get cropping , but ! it does not save and show in list views. waiting for reply

    ReplyDelete
    Replies
    1. Yes dear in case of some devices its happen. and till date no one got solution for this problem. please try at your end may be you got any answer. This is the camera resolution issue. you can try some step hope it will you.

      1)You can try another device for testing.
      or 2)remove cropping code hope it will help you.

      Thanks

      Delete
  51. Well Its very Nice Example Dude Please Send me zip File one my email kushaljhorar.k@gmail.com

    thanks

    ReplyDelete
    Replies
    1. Dude please check post again, there a download link..

      Delete
    2. in getView method of ContactImageAdapter class .

      if (row == null) {
      LayoutInflater inflater = ((Activity) context).getLayoutInflater();
      row = inflater.inflate(layoutResourceId, parent, false);
      holder = new ImageHolder();
      holder.txtTitle = (TextView) row.findViewById(R.id.txtTitle);
      holder.imgIcon = (ImageView) row.findViewById(R.id.imgIcon);
      row.setTag(holder);
      } else {
      holder = (ImageHolder) row.getTag();

      I download full code thanks for that but i got one error
      R Cannot be resolved to a variable

      i refresh many time and clear also but still got that error
      Thanks for replay

      Delete
    3. Hello dear, try below step hope it will help you.
      1)check your activity package name, it should be same as your manifest package name.
      2)remove your gen and bin folder.
      3)tick automatic build project.
      4)and then clean your project.

      Hope it will work for you..

      Thanks!

      Delete
  52. Hi Manish,
    I have requirement in which I have to save data with images-url in SQLITE data base from server.And then I have to show it in my app that means SYNC of data.When ever user want to update then only data will upload to DB.In Async task I am loading data and inserting in DB.In DB image field is BLOB type.So I am taking url image and changing it to byte[] type and then inserting into DB.Then from DB again I am fetching this byte image and showing to ImageView I am getting null value.but If I find it's length then it's giving some number.
    So what I will do????
    Do you have any tutorial regarding this requirement...
    Help me plz

    ReplyDelete
  53. Hi Anwar,
    You can do it using two way-

    1)Get images url from server and convert it into bitmap using ImageLodaer Class and then save this bitmap into your database as a blob in from of byte[], and where you want display it just convert into bitmap and display.

    2)Get images url form server and save it into database as String field don't convert it into byte[]. Just save image URL as String. And where you want display it just use ImaeLoder class and display images from server.

    If you want use offline mode of your application then use first option else second option is more good.

    Thanks!

    ReplyDelete
  54. Great site for developers. Thank you so much!

    ReplyDelete
  55. Hi Manish,

    Great post..But I want to know that if I want to show the image in grid view in place of listview.Please give me a solution as I am new in android.

    Thanks.

    ReplyDelete
    Replies
    1. please check my this post-
      http://www.androidhub4you.com/2013/07/custom-grid-view-example-in-android.html

      here i put data from arrayList, you just get from sqlite and display in listview. i mean merge both project.

      Delete
    2. This comment has been removed by the author.

      Delete
    3. I think you are unable to get images from database. Did you check it in log-cat?
      And yes just use Async task and put all images into ArrayList then show in gridView like that-
      gridArray.add(new Item(homeIcon,"Home"));
      gridArray.add(new Item(userIcon,"User"));

      Ones you able to put here, everything in your hand :)

      Delete
    4. will you help with my code as I am trying to fetch data from database and show it in grid view but I am getting nullpointerexception and in my project I am having fragments,and I am getting stuck.
      Sorry for the trouble but I am not getting anything.

      Delete
  56. I am making one app in this app my screen not will show as same in all devices
    i used

    Samsung Galaxy Grand 5.0 screen 480x800 ~187 ppi ppi pixel density
    Google Nexus S 4.0 screen 480x800 ~233 ppi ppi pixel density
    Xolo Play 4.0 screen 720x1280 ~312 ppi ppi pixel density
    Galaxy Ace 3.5 screen 320x480 ~165 ppi ppi pixel density

    ok I run my app on these mobiles phone but i have screen problem all phone show different screen in this case i use my width and height with
    dimens in hdpi or mdpi then all mobile phone pick height from hdpi demins and mdpi

    and app work fine with only XOLO PLAY AND GLAAXY ACE but other mobile screen got problem button come front of each others
    help me out ..
    thanks

    ReplyDelete
    Replies
    1. for best way working on UI don't fix any height, width. please follow simple way-
      1)just create your layout.xml
      2)putt all 4 size images in your drawable (ldpi,mdpi,hdpi,xhdpi).
      3)your deice automatic will from there.

      suppose you have a stander size page 720x1280 and here a button size of 50x100 then ask to your Photoshop designer to create that button for other resolution i.e. 480x800 and 320x400 and put them in that related folder.

      you can create it by yourself using android assets online.

      Delete
    2. I totally agree with you i did all images with difference size in (ldpi,mdpi,hdpi,xhdpi)

      but have is problem with Lenear layout height's both device google nexus S 480-x800 or xolo play 720X1280 getting height value from hdpi - dimens both screen size same but ppi and screen resolution are dfferent....?

      Delete
  57. Hi, Manish,

    i wanna add statement into holder like this :
    if (picture._name() == "aNameOfPicture") {
    holder.txtxTitle.setBackgroundColor(Color.BLACK);
    }
    return row;

    how can i use that ? Thanks for your tutorial ! Its nice,

    ReplyDelete
    Replies
    1. if (picture._name.equals("aNameOfPicture") ) {
      holder.txtxTitle.setBackgroundColor(Color.BLACK);
      }

      else{
      holder.txtxTitle.setBackgroundColor(Color.RED);
      }

      Delete
  58. hii ,I have external sqlite database ,database contain images and text i want to display in listview.how can do this ?

    ReplyDelete
    Replies
    1. external database means? you are talking about sqlite query browser right? please see this demo-
      http://www.androidhub4you.com/2013/08/android-sqlite-query-browser-example.html

      and merge with this post..

      Thanks!

      Delete
  59. i want to capture a photo/take image from gallery and save it to database and retrieve it from database

    ReplyDelete
    Replies
    1. please check this post-
      http://www.androidhub4you.com/2013/04/sqlite-example-in-android-add-image.html

      Delete
  60. This comment has been removed by the author.

    ReplyDelete
  61. How do I add a new row from database?
    e.g. db.addContact(new Contact("Electronics", imageInByte ));

    ReplyDelete
    Replies
    1. Should i do this?
      ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
      image1.compress(Bitmap.CompressFormat.JPEG, 100, stream1);
      byte imageInByte1[] = stream1.toByteArray();
      ...
      db.addContact(new Contact("Electronics", imageInByte1 ));

      Delete
    2. yes it will add a new row in your database.

      Delete
  62. Hi Manish ,nice post but you have just inserted image in add contact.Can you please show with any random example how to insert both image and information at the same time?

    ReplyDelete
    Replies
    1. You can give a textview before submit image into database and put text there.

      Delete
  63. Hi Manish I have a question for you. Can you give me the coding for retrieving the image from the database as I'm finding some errors while retrieving the image some say that retrieving image should not be greater than 1 MB is it so?

    ReplyDelete
    Replies
    1. There is not a fix amount of data 1 MB in sq-lite but yes it is true you should not store big size data in sq-lite. Better way just create an app folder in your SD-card and put images there and save their reference in sq-lite.

      Delete
  64. Hi Manish. I have a question. First of all thanks for a good example.

    I try it in simulator and in old phone htc android 2.3 - it works propertly, but with nexus 4, android 4.4 i received following mistakes:

    - camera works not propertly
    - in getExtras() i receive null.

    Have you any ideas why it can happens?
    Thanks Andrey

    ReplyDelete
    Replies
    1. Hi Andrey, its just because of high resolution image. For this issue I can give you some idea please try it may be it will help you-
      1)Create an app folder into your phone-memory and save captured image in that folder.
      2)Before capture image create a dynamic image path for save your image like-
      mnt/myApp/xyz.png
      3)Now save this path into your database directly no need to get it from extra if you already have path of that image.
      4)Now show it from your sqlite.

      Thanks!

      Delete
    2. Thanks again Manish.
      You are wright.
      Now everything works fine.

      Andrey

      Delete
  65. hey manish can u help me on how to store and retrieve contents from database and put it into a checklist?
    example
    Enter Name: Manish
    then ull click button
    then the name manish would appear on a checkbox

    ReplyDelete
    Replies
    1. i ddnt have any solution yet hope u can help me

      Delete
  66. Hie Manish.
    Can u help me .
    I want to Store images as a grid View when User click on the image it should open in new tab.
    and all images should be received from JSON asmx web service.
    Do you have any idea?

    ReplyDelete
  67. And Just problem is that when i Display images in Grid View it doesnt Load. but when i clicked on the images it load succesfully on new activity.!

    ReplyDelete
  68. hi sir. i have a problem. it is not in the code but why is that when i export the project itself together with the filled database and when i install it in my phone the database do not have a data.

    ReplyDelete
    Replies
    1. No no in case of JAVA file storage you should run ones your app and input data then only you can get filled database. Or you can use sqlite query browser in this case you can import filled data with your project..

      Delete
    2. hmm i'm sorry i dont get what you trying to say. im sorry because im new in android development. and one more thing. after i pull out the database from the phones emulator how can i transfer the database file into my phone?

      Delete
  69. I am working on google map i make a route so the problem is when i modify route last polyLineOptions not gonna remove help how to remove polyLine thanks

    ReplyDelete
  70. Hi Manish, How about getting the image from contacts?

    ReplyDelete
    Replies
    1. Hi please check this article hope it will help you-
      http://www.androidhub4you.com/2013/06/get-phone-contacts-details-in-android_6.html

      And for image please read comments..

      Delete
  71. Hi Manish , I tried ur code but i got few errors...can u pls send me the ZIP file so tht i can check out wats wrong with my code...Please Help.
    E-mail : anupnmadhva@gmail.com

    ReplyDelete
  72. Hiiee Manish sir..
    I tried ur code it works very well bt I want to add Some more Information nd when I Add another field as price it is not working..
    Plz Tell me how to add Price which is taken as integer in Holder..
    My Fields are Mb_name ,Mb_photo,Mb_price and Mb_Dname..
    E-Mail:- darshan.shah411@gmail.com, shah.jigar003@gmail.com

    ReplyDelete
  73. HI Manish

    The example seems to be very interesting and complete , but unfortunately I am facing some problems , I am new at Android 
    I keep getting 4 errors for imgIcon cannot be resolved or is not a field & imgIcon cannot be resolved or is not a field in class ContactImageAdapter

    holder.txtTitle = (TextView) row.findViewById(R.id.txtTitle);
    holder.imgIcon = (ImageView) row.findViewById(R.id.imgIcon);


    also I am getting the same error in the mainactivity class

    public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_item);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
    }

    }

    Can u plz help me or send me the zip file my email is isapps2010@yahoo.com

    Thanks a lot man

    ReplyDelete