Wednesday, July 27, 2011

complete code to load image from gallery view and store in database and retrive it into image view

code for database creation and storing

DatabaseHelper.java
package com.incept.pom;



import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View.OnClickListener;

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

public class DatabaseHelper extends SQLiteOpenHelper {

static final String dbName="imageDB";
static final String imgTable="MyImage";
static final String colID="ImageID";
static final String colName="ImageName";
static final String colbytes ="Imagebytes";
byte[] bb;
public DatabaseHelper(Context context) {
    super(context, dbName, null,33);

    // TODO Auto-generated constructor stub
}


@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    Log.i("in here", "creating database");
    db.execSQL("CREATE TABLE "+ imgTable+" ("+ colID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+ colbytes + " BLOB, "
            + colName + " TEXT)");

    //Inserts pre-defined departments

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub

    db.execSQL("DROP TABLE IF EXISTS "+ imgTable);
    onCreate(db);
}
void AddImage(MyImage img)
{
     Log.i("in here", "adding image");         
     SQLiteDatabase db= this.getWritableDatabase();

    if (db==null)
    {
        Log.i("nulll", "mnllllsg");
    }
    ContentValues cv=new ContentValues();

    cv.put(colName, img.getName());
    cv.put(colbytes, img.getImg());
    cv.put(colID, 1);
    db.insert(imgTable, null, cv);
    System.out.println("added successfully");
    db.close();


}

 int getImageCount()
 {
    SQLiteDatabase db=this.getWritableDatabase();
    Cursor cur= db.rawQuery("Select * from "+imgTable, null);
    int x= cur.getCount();
    cur.close();
    return x;
 }

 MyImage getAllImages()
 {
     SQLiteDatabase db=this.getWritableDatabase();
     MyImage results = new MyImage();
     //Cursor cur= db.rawQuery("Select "+colID+" as _id , "+colName+", "+colAge+" from "+employeeTable, new String [] {});
   // Cursor cur= db.rawQuery("SELECT * FROM "+imgTable,null);
     Cursor cur = db.rawQuery("Select "+colbytes+" from "+imgTable+" where "+colID+" = 1 ;",null);
     if (cur!= null)
        {
            //Log.d("database",database.toString());
            if (cur.moveToFirst()){
               
                Log.d("moved", "to first");
            }
           
           
                do{
                      byte[] bb = cur.getBlob(cur.getColumnIndex("Imagebytes"));
                      System.out.println(bb);

                      results.add(bb);
                    /*MySubscriberDetails pf=new MySubscriberDetails();
                    pf.country=Country;
                    Log.d("pf.country",pf.country);
                   
                    profiles.add(pf);*/
                     
                }while (cur.moveToNext());
                cur.close();
           
            db.close();
        }
       
   
   
    return results;
  
 }

 public int UpdateImg(MyImage img)
 {
     SQLiteDatabase db=this.getWritableDatabase();
     ContentValues cv=new ContentValues();
     cv.put(colName, img.getName());
     cv.put(colbytes, img.getImg());
   

     return db.update(imgTable, cv, colID+"=?", new String []{String.valueOf(img.getID())});

 }

 public void DeleteImg(MyImage img)
 {
     SQLiteDatabase db=this.getWritableDatabase();
     db.delete(imgTable,colID+"=?", new String [] {String.valueOf(img.getID())});
     db.close();



 }

 }


MyImage.java

package com.incept.pom;

import java.io.ByteArrayOutputStream;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;

public class MyImage {
    public MyImage(String _name, byte[] _img) {
        super();
        this._name = _name;
        this._img = _img;
    }
    public MyImage() {
        // TODO Auto-generated constructor stub
    }
    int _id;
    String _name;
    byte[] _img;
    protected int length;

   


    public int getID()
    {
        return this._id;
    }
    public void SetID(int ID)
    {
        this._id=ID;
    }

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

    public byte[] getImg()
    {
        return this._img;
    }

    public void setName(String Name)
    {
        this._name=Name;
    }
    public void setImg(Bitmap bitmap)
    {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.PNG, 0, outputStream);
        this._img = outputStream.toByteArray();
    }
    public void add(byte[] bb) {
        // TODO Auto-generated method stub
        this._img = bb;
    }
    }


ImageUpload.java


import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class ImageUpload extends Activity {
    private static final int PICK_IMAGE = 1;
    private ImageView imgView,imgView1;
    private Button upload,from_gal;
    private EditText caption;
    private Bitmap bitmap;
    private ProgressDialog dialog;
    ArrayList<byte[]> b=new ArrayList<byte[]>();
    public DatabaseHelper mDBHelper=new DatabaseHelper(this);
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_publicprofile);
       
        imgView = (ImageView) findViewById(R.id.upload_image);
        imgView1 = (ImageView) findViewById(R.id.upload_image1);
       
        upload = (Button) findViewById(R.id.pubprof_but2);
        from_gal = (Button) findViewById(R.id.pubprof_but1);
        caption = (EditText) findViewById(R.id.Caption);
        ((Button) findViewById(R.id.pubprof_but1))
        .setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,"Select Picture"), PICK_IMAGE);
            }
        });
         
         upload.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
            //        SQLiteDatabase database = mDBHelper.getWritableDatabase();
                 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
                 System.out.println(bitmap);
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);

                    //bm is the bitmap object

                    byte[] b = baos.toByteArray();  
                    String name;
                    name="sample_1";
                    MyImage img = new MyImage(name,b);
                   
                    mDBHelper.AddImage(img);

                    int n = mDBHelper.getImageCount();
                    Log.i("ImageCount","n == "+n);
                   
                    MyImage bb = mDBHelper.getAllImages();
                    System.out.println("outer "+ bb);
                    byte[] bs=bb.getImg();
                    long leng=bs.length;
                    System.out.println(leng);
                    
                   imgView1.setImageBitmap(BitmapFactory.decodeByteArray(bs, 0, bs.length));
                    
                    
                 
             }
         });
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
        case PICK_IMAGE:
            if (resultCode == Activity.RESULT_OK) {
                Uri selectedImageUri = data.getData();
                System.out.println(selectedImageUri);
                String filePath = null;

                try {
                    // OI FILE Manager
                    String filemanagerstring = selectedImageUri.getPath();
                    System.out.println(filemanagerstring);
                    // MEDIA GALLERY
                    String selectedImagePath = getPath(selectedImageUri);
                    System.out.println(selectedImagePath);
                   
                    if (selectedImagePath != null) {
                        filePath = selectedImagePath;
                        System.out.println(filePath);
                    } else if (filemanagerstring != null) {
                        filePath = filemanagerstring;
                        System.out.println(filePath);
                    } else {
                        Toast.makeText(getApplicationContext(), "Unknown path",
                                Toast.LENGTH_LONG).show();
                        Log.e("Bitmap", "Unknown path");
                    }

                    if (filePath != null) {
                        decodeFile(filePath);
                    } else {
                        bitmap = null;
                    }
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "Internal error",
                            Toast.LENGTH_LONG).show();
                    Log.e(e.getClass().getName(), e.getMessage(), e);
                }
            }
            break;
        default:
        }
    }
public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        if (cursor != null) {
            // HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
            // THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
            int column_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } else
            return null;
    }

    public void decodeFile(String filePath) {
        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, o);

        // The new size we want to scale to
        final int REQUIRED_SIZE = 1024;

        // Find the correct scale value. It should be the power of 2.
        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
                break;
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }

        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        bitmap = BitmapFactory.decodeFile(filePath, o2);

        imgView.setImageBitmap(bitmap);

    }
}

1 comment:

  1. I am only able to retrive one image from gallery when i try to add or replace the image it shows me the previous one can u plss help me with this I have tried all possible ways

    ReplyDelete