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
http://www.androidhub4you.com/2012/09/sqlite-database-in-android.html
thankyou for the post! realli helped :)
ReplyDeleteYour Welcome!
Deletethanks for this code ..i have run that code but its not working always gives an error like:-unfortunately your app is stopped ..How can i slove this problem?pls tell me..
DeleteApp is not working when taking image from Camera. when I use putExtra(MediaStore.EXTRA_OUTPUT,fileUri) , then onActivityResult Intent data is null .And Bundle extras is also null .
DeleteAlso this project is very important for me.
ReplyDeleteCould you email me the code zip file to me ?
My email is : ufficiopierangelo@libero.it
I am studying Android, thanks for your help.
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..
DeleteFor any difficulty you can ask for help no issue..
Thanks,
Codes given here are really helpful for me .....
ReplyDeleteSuperb man.....
Nice work....... :-D
Thanks Dear.......
Delete:)
Hi,I'm having problem with your code,at ContactImageAdapter.java.
ReplyDeleteIt show error with this line
"holder.txtTitle.setText(bcard._name);" at bcard
Could you please help me with this?
Thank in advance, :D
Hi!
DeleteI 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,
First of all,thanks for replying me :D.I fixed it and it showed no error.
ReplyDeleteBut 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
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.
Delete1)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,
I check as you said but it still did not work :(
DeleteAnd 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)
Yes dear you are right, error log looks very complicated :), according log-
Deletejava.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,
Hey it worked :D,and your code isn't wrong,it'all my mistake to choose the wrong main activity :)
DeleteBy the way your code is really helpful,thanks for your sharing :)
Thanks a lot for your help Manish,appreciate it :)
your welcome & thanks for your valuable comment..
DeleteManish amazing code tnx!
ReplyDeleteI'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
Hi Nicola,
DeleteYes 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
Hey Manish,
ReplyDeleteYes yes I got you man, thank you very very much for your complete explanation :) :).
Regards,
Nicola
Your Welcome!
DeleteManish,
ReplyDeleteSorry 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");
Hi Nicola,
DeleteYou 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,
Sir i want to image update in android . so i want to save uri in database so please send me code how to save uri of image in database and find image in list type
DeleteThis comment has been removed by the author.
ReplyDeleteHi Manish,
ReplyDeleteI solved the problem with the images in the database :), once more tnx for the help.
Regards,
Nicola Lombardi
Your welcome!
Deletehow to select single list item?
ReplyDeletei want to make a toast and display name of list item
got the answer:
ReplyDeleterow.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getContext(), "test", Toast.LENGTH_LONG).show();
}
});
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-
Delete/**
* 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
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
ReplyDeleteYes 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 :);
DeletePlease check my below post it will help you-
Deletehttp://www.androidhub4you.com/2013/04/sqlite-example-in-android-add-image.html
?
ReplyDeleteThis comment has been removed by the author.
ReplyDeletepls how to insert a sound sqlite android, when I press a picture ???
ReplyDeleteHi, I think you should insert path of sound instead of .wav or other sound format. Some thing like that-
Delete/**
* 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..
thank for your help; is the sound saved in the folder raw ???
ReplyDeletehi,
ReplyDeleteyour code worked well.Thanks a lot:) My doubt is tat how can we see the stored items in the database here.?? Thanks in advance..
No no you can't see stored data in sqlite db for this you should use sqlite query browser.
Deleteor you can put it into list like I was doing.
Hello Manish
ReplyDeleteThis 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
Thank you for your nice comment!
DeleteSure I will send you zip code please check your email, hope it will help you..
Enjoy :)
Thanks,
This comment has been removed by the author.
ReplyDeleteOK... 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..
ReplyDeleteMy mail id:sunantha1831@gmail.com
Hi Please check my this post-
Deletehttp://www.androidhub4you.com/2013/04/sqlite-example-in-android-add-image.html
Thanks!
Hi manish... I worked with this .. while saving Am getting force close msg in my mobile...how can i solve it...
Deletesome thing gonna wrong in your code check your logcat and paste here so I can check it..
DeleteThanks!
Hi Manish,
ReplyDeleteIm 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);
Hi just create a class ImageLoder something like below-
Deletepublic 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....
and please tell me your email Id so I can send you ImageLoder class..
DeletePaste full class is not allow here..
Thanks,
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.
DeletePlease check your email I have sent you a idea how to implement that hope it will help you..
Deletepublic void onCreate(Bundle savedInstanceState) {
ReplyDeletesuper.onCreate(savedInstanceState);
setContentView(R.layout.main);
i have problems here in layout, it's writen to create field layout in constant R
something wrong in your package name please check your activity package name and manifest package name it should be same-
Deletepackage com.example.hellotest;
and
and if you are working in different package call it something like that-
import com.other.R;
something wrong in your package name please check your activity package name and manifest package name it should be same-
Deletepackage com.example.hellotest;
and
and if you are working in different package call it something like that-
import com.other.R;
something wrong in your package name please check your activity package name and manifest package name it should be same-
Deletein 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;
why do not put all source zip codes in you blog...
ReplyDeleteIn this case people did not going to comment for my good work.
DeleteNothing else.. I want some reward for my work thats..
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
ReplyDeleteYes sure erun you can put it in separate folder.
DeleteJust import it using something like that-
import com.util.Helper;
Hi Mainsh,
ReplyDeleteThis tutorial is very helpful. But I am not able to figure out. How to bind pre-build database with a text view?
Hi Manish
ReplyDeleteI 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();
}
});
what's error you are getting? And I am surprised with your name "manish and nidhi"?
DeleteIt displays the first record and is stuck there. Clicking on next doesn't display next record. they are 2 different names :)
ReplyDeletefirst 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 :)
DeleteOr do something like that-
Delete//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...
Hi Manish,
DeleteThanks 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
If your scope is countable means till 10 images or what you want just display one image and title at one time..
DeleteLogic-
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,
Thanks. it's working.
DeleteYour welcome Manish and Nidhi!
DeleteHi Manish,
ReplyDeleteI 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..
You can try my this artical-
Deletehttp://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..
This comment has been removed by the author.
DeleteHi Manish,
ReplyDeleteI 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?
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..
DeleteHi Manish,
ReplyDeleteI 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)
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..
DeleteTry after uninstall your app may be it work.. or try on another device or emulator may be it work..
Can you help me Manish,
Deletehow to form the database login details in the list form
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-
Delete// 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();
}
}
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.
Deletehi,i have question.
ReplyDeleteIf 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.
Hi then where you are facing problem?
Delete1)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,
nice tutorial great helpful
ReplyDeleteThanks man!
Deletehi,
ReplyDeletecan u plz send me the full source code to my mail: cvkarthikbabu@gmail.com
thanks in advance.
I will upload soon on GIT server..
DeleteHi manish, i have question.
ReplyDeleteIf 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.
Try something like that-
Delete/**
* 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
Hi manish,
ReplyDeleteHow 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.
Pass values from first page using intent or bundle and display their calculation on next page on touch full screen or any button
Delete...
Why am I getting: Unable to convert BLOB to string?
ReplyDeleteFull 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
when you are trying to get getAllProfiles data your app got crash reason
Deleteis 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
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...
ReplyDeleteHi Manish..
ReplyDeleteI 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.
Try some thing like that-
Delete// 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
}
}
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...
Deletemanish,now i m following ur code but the problem is
ReplyDeletejava.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
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
ReplyDeleteIf you are able to print your data in log then I can't say what going wrong..
DeleteI 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
hii, manish,,i got a problem. your codes i'm implement in new database, with same concept.
ReplyDeletebut 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
Hi phiko!
DeleteHave 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
hey manish , finally my project was running success..
ReplyDeletethe trouble cause i'm not write code in main activity like below ->
for (Contact cn : contacts) {
ImageArry.add(cn);
}
thanks brow.. ;)
:)
DeleteYour runs fine but nothing display what can i do.please help me
ReplyDeleteHave you copy same demo? means package name class name manifest is same?
Deleteplease give me full source code and my mail is patelsanket5657@gmail.com
ReplyDeleteI 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..
DeleteThanks!
Thanks Manish!
ReplyDeletefinally got a code which helped my project!!
Thanks and your welcome!
Deletehi,, Manish sir
ReplyDeleteHow we can get image to view using php programing (PHP My admin) in android remote server??
Use web-services and parse that web-service response. And for image use ImageLodar.
ReplyDeletePlease read first web-services Rest,soap,json,xml,GET and POST method sure it will help you.
Thanks!
thanks ... I hope it will work
ReplyDeleteGreat!
Deletecan u pls upload ur .sqlite database ??????
ReplyDeleteSure Vivek, I will inform you when upload code on git.
DeleteThanks!
Check my article again, a download link there..
DeleteThanks!
Hi Manish Sir,
ReplyDeleteI 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
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.
ReplyDeleteAnd 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!
Hi Manish Sir,
DeleteThank 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
hmmm you can't store big size image in sqlite. and 100 image never.
DeleteCreate web services and put your images on server..
thanks ! good one guy .
ReplyDeletei 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
ReplyDeleteYes 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.
Delete1)You can try another device for testing.
or 2)remove cropping code hope it will help you.
Thanks
Well Its very Nice Example Dude Please Send me zip File one my email kushaljhorar.k@gmail.com
ReplyDeletethanks
Dude please check post again, there a download link..
Deletein getView method of ContactImageAdapter class .
Deleteif (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
Hello dear, try below step hope it will help you.
Delete1)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!
hey Its working Now thanks ..:)
DeleteHi Manish,
ReplyDeleteI 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
Hi Anwar,
ReplyDeleteYou 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!
Great site for developers. Thank you so much!
ReplyDeleteThanks Sakthi!
DeleteHi Manish,
ReplyDeleteGreat 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.
please check my this post-
Deletehttp://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.
This comment has been removed by the author.
DeleteI think you are unable to get images from database. Did you check it in log-cat?
DeleteAnd 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 :)
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.
DeleteSorry for the trouble but I am not getting anything.
I am making one app in this app my screen not will show as same in all devices
ReplyDeletei 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
for best way working on UI don't fix any height, width. please follow simple way-
Delete1)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.
I totally agree with you i did all images with difference size in (ldpi,mdpi,hdpi,xhdpi)
Deletebut 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....?
Hi, Manish,
ReplyDeletei 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,
if (picture._name.equals("aNameOfPicture") ) {
Deleteholder.txtxTitle.setBackgroundColor(Color.BLACK);
}
else{
holder.txtxTitle.setBackgroundColor(Color.RED);
}
hii ,I have external sqlite database ,database contain images and text i want to display in listview.how can do this ?
ReplyDeleteexternal database means? you are talking about sqlite query browser right? please see this demo-
Deletehttp://www.androidhub4you.com/2013/08/android-sqlite-query-browser-example.html
and merge with this post..
Thanks!
i want to capture a photo/take image from gallery and save it to database and retrieve it from database
ReplyDeleteplease check this post-
Deletehttp://www.androidhub4you.com/2013/04/sqlite-example-in-android-add-image.html
This comment has been removed by the author.
ReplyDeleteHow do I add a new row from database?
ReplyDeletee.g. db.addContact(new Contact("Electronics", imageInByte ));
Should i do this?
DeleteByteArrayOutputStream stream1 = new ByteArrayOutputStream();
image1.compress(Bitmap.CompressFormat.JPEG, 100, stream1);
byte imageInByte1[] = stream1.toByteArray();
...
db.addContact(new Contact("Electronics", imageInByte1 ));
yes it will add a new row in your database.
DeleteHi 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?
ReplyDeleteYou can give a textview before submit image into database and put text there.
DeleteHi 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?
ReplyDeleteThere 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.
DeleteHi Manish. I have a question. First of all thanks for a good example.
ReplyDeleteI 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
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-
Delete1)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!
Thanks again Manish.
DeleteYou are wright.
Now everything works fine.
Andrey
Great!
Deletehey manish can u help me on how to store and retrieve contents from database and put it into a checklist?
ReplyDeleteexample
Enter Name: Manish
then ull click button
then the name manish would appear on a checkbox
Hey, have you found any solution?
Deletei ddnt have any solution yet hope u can help me
DeleteHie Manish.
ReplyDeleteCan 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?
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.!
ReplyDeletehi 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.
ReplyDeleteNo 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..
Deletehmm 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?
DeleteI 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
ReplyDeleteHi Manish, How about getting the image from contacts?
ReplyDeleteHi please check this article hope it will help you-
Deletehttp://www.androidhub4you.com/2013/06/get-phone-contacts-details-in-android_6.html
And for image please read comments..
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.
ReplyDeleteE-mail : anupnmadhva@gmail.com
Hiiee Manish sir..
ReplyDeleteI 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
HI Manish
ReplyDeleteThe 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
Hai maneesh,
ReplyDeleteI am a newcomer in android.. I want a simple program to retrieve images from database.? could you pls help me??
how to make the display into gridview?
ReplyDeletei have problem like unfortunately your app is stopped.How can i solve this problem.?
ReplyDeleteManish I want a favor from ur side my question is regarding. Db compression if we compress the sqlite db and then accesing their field value one by one and sending them to server using json/rest web services. Then my question is that is really the data will compressed which is going through webservices ?. and is it time/ network saving task or not or else pleaseeeee suggest me it is good or not n how it is possible in easy manner??
ReplyDeleteIn the picture you show 3 items in the example only 1
ReplyDelete.....
I have the same problem.
Thanks
I am not getting you, can you explain in detail? If you put 3 image it will display 3 without any issue.
Deletehie Manish im new in android but i want to get multiple images from folder and save and retrieve them database what should i do
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteHy ..
ReplyDeleteI want to save image in database when i click on tick button
i got error "Unfortunately camera has stopped working".
hi m new to android please help how and where to add click event for listview item to perform intent.. please
ReplyDeletethank you
You need to use -dataList.setOnItemClickListener(new OnItemClickListener() { }
Deletefollow below link-
http://www.androidhub4you.com/2013/09/android-call-history-example-how-to-get.html#comment-form_9010473230032386786
if i saved contacts with phone numbers in a database and the name of one contact can have several phone numbers so how can i get the names with the phone numbers in a list and post them in a toast? any help plz i put a bitton search by contact name
ReplyDeleteI think there must be two table in your sql like-
Delete1)Student
std_id(Primary key) | name(Text)
2)Student Detail
detail_id(Primary Key) | contact_num(Number) | std_id(Foreign Key)
Now you need search contact from Student detail table and get the name of contact based on foreign key, some thing like below-
SELECT name FROM Students AS C JOIN Student Detail AS R ON C.std_id=R.std_id;
Note: Above query is an assumption only, so modify it according to your need.
no i have onltable that contains names and phone numbers
ReplyDeleteat the main class i have an edit text that i can put a name on it and then press on a button to search for all names and phone numbers that have the same entered name. Can u help me to write the java code of the main class and for the databasehandler ?
I think then you can write simple query like-
Deleteselect number from student where name="xyz";
ok i know that but howe to get them on the screen in a list where many can be obtained not only the 1st name
ReplyDeletepublic void getContact(View v) {
ReplyDeleteEditText e = (EditText) findViewById(R.id.namefield);
String s = e.getText().toString();
Contact x = db.getContact_by_name(s);
if (x!= null) {
Toast.makeText(this, x.get_name() + " " + x.get_phone_number(),
Toast.LENGTH_LONG).show();
} this is used to show only one contact that i search for it by name but i need to know how to get for examples all contacts that have "xyz" name but this xyz name may have for example 3 different phone numbers so i need them all to be show
You need to return an Object from your Database Helper class and bind into listview or you can use dynamic Textview-
Delete//in your database class-
public List getAllConatct(String s) {
List contactList = new ArrayList();
db = sqlHp.getReadableDatabase();
String selectquery = " SELECT * FROM table_contact where name=s";
System.out.println("selectquery value..." + selectquery);
cursor = db.rawQuery(selectquery, null);
while (cursor.moveToNext()) {
ContactObject record = new ContactObject();
record.setName(cursor.getString(cursor.getColumnIndex(NAME)));
record.setNumber(cursor.getInt(cursor.getColumnIndex(NUMBER)));
contactList .add(record);
}
cursor.close();
db.close();
return contactList;
}
//in you activity
Database db=new Database();
ArrayListcontactList;
contactList=db.getAllContact();
for(int i=0;i<contactList.size();i++){
print(contactList.getIndex(i));
}
thank u so much.. but really thats not what am looking for anyway thank u for ur help
ReplyDeletehi manish i am using your code but i got error .
ReplyDeletei have two fragment 1 for clicking the image and another for show the image . when i click the image and click the ok for save i got this error plz help ...
12-27 10:19:06.004: E/AndroidRuntime(22053): FATAL EXCEPTION: main
12-27 10:19:06.004: E/AndroidRuntime(22053): Process: camera.project, PID: 22053
12-27 10:19:06.004: E/AndroidRuntime(22053): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65636, result=-1, data=Intent { act=inline-data (has extras) }} to activity {camera.project/camera.project.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase camera.project.DataBaseHandler.getWritableDatabase()' on a null object reference
12-27 10:19:06.004: E/AndroidRuntime(22053): at android.app.ActivityThread.deliverResults(ActivityThread.java:3539)
12-27 10:19:06.004: E/AndroidRuntime(22053): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3582)
12-27 10:19:06.004: E/AndroidRuntime(22053): at android.app.ActivityThread.access$1300(ActivityThread.java:144)
12-27 10:19:06.004: E/AndroidRuntime(22053): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1327)
12-27 10:19:06.004: E/AndroidRuntime(22053): at android.os.Handler.dispatchMessage(Handler.java:102)
12-27 10:19:06.004: E/AndroidRuntime(22053): at android.os.Looper.loop(Looper.java:135)
12-27 10:19:06.004: E/AndroidRuntime(22053): at android.app.ActivityThread.main(ActivityThread.java:5221)
12-27 10:19:06.004: E/AndroidRuntime(22053): at java.lang.reflect.Method.invoke(Native Method)
12-27 10:19:06.004: E/AndroidRuntime(22053): at java.lang.reflect.Method.invoke(Method.java:372)
12-27 10:19:06.004: E/AndroidRuntime(22053): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
12-27 10:19:06.004: E/AndroidRuntime(22053): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
12-27 10:19:06.004: E/AndroidRuntime(22053): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase camera.project.DataBaseHandler.getWritableDatabase()' on a null object reference
12-27 10:19:06.004: E/AndroidRuntime(22053): at camera.project.DataBaseHandler.addContact(DataBaseHandler.java:60)
12-27 10:19:06.004: E/AndroidRuntime(22053): at camera.project.TakePhotoFragment.onActivityResult(TakePhotoFragment.java:110)
12-27 10:19:06.004: E/AndroidRuntime(22053): at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:163)
12-27 10:19:06.004: E/AndroidRuntime(22053): at android.app.Activity.dispatchActivityResult(Activity.java:6135)
12-27 10:19:06.004: E/AndroidRuntime(22053): at android.app.ActivityThread.deliverResults(ActivityThread.java:3535)
12-27 10:19:06.004: E/AndroidRuntime(22053): ... 10 more
your code was wonderful i need a small favour from you i.e how can i get the id on clicking the listview and pass this id for deletin the entire row
ReplyDelete1)Put a delete button inside screen_list.xml
Delete2)Open your ContactImageAdapter class and call the reference of delete button, like i am doing for text and image.
3)On press delete button get the id of row like-
int rowID=picture .getID(); and follow the point number 4.
4)Open your DATABASE Class and you will see a deleteContact method inside that, now call this method from Adapter on press press delete button and pass the rowID.
5)Use the notifyDataSetChanged() every time to updated the list.
Hello! Thank you for this code, it is very helpful! This code runs good on my emulator, but it crashes when I try it on my Samsung Galaxy s5. The error says:
ReplyDeleteCaused by: java.lang.IllegalStateException: Couldn't read row 0, col 0 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
Do you know why this could be happening? The image is quite small, only 3.28K.
Smith, I think you modified something into database and you did not uninstall application from your phone before re-run. Best practice, when you working on sq-lite and modified any table just uninstall the app and reinstall it again. Hope it will help you!
Deletehiii can u tell me how to insert image to database only.
ReplyDeletein this demo we have image you can try below link too-
Deletehttp://www.androidhub4you.com/2013/04/sqlite-example-in-android-add-image.html
good day.
ReplyDeletehow do I add multiple records with different image names to the SQLite DB.
eg
db.addContact(new Contact("FaceBook", imageInByte));
db.addContact(new Contact("twitter", imageInByte));
Make a method to return byte array from bitmap-
Deletedb.addContact(new Contact("FaceBook", imageInByte(yourBitmap)));
-----------
public image[](){//do you task here}
-------------
And image name you have to write manually or take input from user using editbox.
hi..
ReplyDeleteeverytime i run your code, it will display more images of the same image..for example, if i run the code for second time, the image (for example, facebook) and text will appear two images of facebook with the text.
my question here is, how i could make the image and text just appear once only everytime i run the code?
thanks for your advice.