Category Archives: Gallery

How to store an Image from Android to a SQlite and retrieve it?

Hello all…

In today’s post I will show you how to store an image in an SQLite database and retrieve it.

Check out the output after running the program.

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

This is the layout for the MainActivity.

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <Button
            android:id="@+id/get_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/textView1"
            android:layout_alignRight="@+id/textView1"
            android:text="Get Image" />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/button1"
            android:layout_alignLeft="@+id/button1"
            android:src="@drawable/ic_action_search"
            android:visibility="gone" />

        <Button
            android:id="@+id/save_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/textView1"
            android:layout_alignRight="@+id/textView1"
            android:text="Save Image in DB" />

        <Button
            android:id="@+id/read_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/textView1"
            android:layout_alignRight="@+id/textView1"
            android:text="Read Image from DB" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            tools:context=".MainActivity" />

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/button1"
            android:layout_alignLeft="@+id/button1"
            android:layout_marginBottom="40dp"
            android:src="@drawable/ic_action_search" />
    </LinearLayout>

</ScrollView>

Now the code for the Activity.

MainActivity.java

package com.coderzheaven.saveimageindb;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
	protected static TextView textView;
	protected static ImageView image1, image2;
	protected Button get_image, save_image, read_image;
	private String selectedImagePath;
	private static final int SELECT_PICTURE = 1;
	String DB_NAME = Environment.getExternalStorageDirectory() + "/test.db";
	String TABLE_NAME = "mytable";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		image1 = (ImageView) findViewById(R.id.imageView1);
		image2 = (ImageView) findViewById(R.id.imageView2);
		textView = (TextView) findViewById(R.id.textView1);

		get_image = (Button) findViewById(R.id.get_image);
		get_image.setOnClickListener(this);

		save_image = (Button) findViewById(R.id.save_image);
		save_image.setOnClickListener(this);

		read_image = (Button) findViewById(R.id.read_image);
		read_image.setOnClickListener(this);

	}

	public void onClick(View v) {

		int id = v.getId();
		switch (id) {

		case R.id.get_image:
			Intent intent = new Intent();
			intent.setType("image/*");
			intent.setAction(Intent.ACTION_GET_CONTENT);
			startActivityForResult(
					Intent.createChooser(intent, "Select Picture"),
					SELECT_PICTURE);
			break;

		case R.id.save_image:
			createTable();
			saveInDB();
			break;

		case R.id.read_image:
			readFromDB();
			break;
		default:
			break;

		}
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == SELECT_PICTURE) {
				Uri selectedImageUri = data.getData();
				selectedImagePath = getPath(selectedImageUri);
				System.out.println("Image Path : " + selectedImagePath);
				image1.setVisibility(View.VISIBLE);
				image1.setImageURI(selectedImageUri);
			}
		}
	}

	@SuppressWarnings("deprecation")
	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	void createTable() {
		SQLiteDatabase myDb = openOrCreateDatabase(DB_NAME,
				Context.MODE_PRIVATE, null);
		String MySQL = "create table if not exists "
				+ TABLE_NAME
				+ " (_id INTEGER primary key autoincrement, name TEXT not null, image BLOB);";
		myDb.execSQL(MySQL);
		myDb.close();
	}

	void saveInDB() {
		SQLiteDatabase myDb = openOrCreateDatabase(DB_NAME,
				Context.MODE_PRIVATE, null);
		byte[] byteImage1 = null;
		String s = myDb.getPath();

		myDb.execSQL("delete from " + TABLE_NAME); 			// clearing the table
		ContentValues newValues = new ContentValues();
		String name = "CoderzHeaven";
		newValues.put("name", name);
		try {
			FileInputStream instream = new FileInputStream(selectedImagePath);
			BufferedInputStream bif = new BufferedInputStream(instream);
			byteImage1 = new byte[bif.available()];
			bif.read(byteImage1);
			newValues.put("image", byteImage1);
			long ret = myDb.insert(TABLE_NAME, null, newValues);
			if (ret < 0)
				textView.append("Error");
		} catch (IOException e) {
			textView.append("Error Exception : " + e.getMessage());
		}
		myDb.close();
		textView.append("\n Saving Details \n Name : " + name);
		textView.append("\n Image Size : " + byteImage1.length + " KB");
		textView.append("\n Saved in DB : " + s + "\n");
		Toast.makeText(this.getBaseContext(),
				"Image Saved in DB successfully.", Toast.LENGTH_SHORT).show();
	}

	void readFromDB() {
		byte[] byteImage2 = null;
		SQLiteDatabase myDb;
		myDb = openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
		Cursor cur = myDb.query(TABLE_NAME, null, null, null, null, null, null);
		cur.moveToFirst();
		while (cur.isAfterLast() == false) {
			textView.append("\n Reading Details \n Name : " + cur.getString(1));
			cur.moveToNext();
		}

		// /////Read data from blob field////////////////////
		cur.moveToFirst();
		byteImage2 = cur.getBlob(cur.getColumnIndex("image"));
		setImage(byteImage2);
		cur.close();
		myDb.close();
		Toast.makeText(this.getBaseContext(),
				"Image read from DB successfully.", Toast.LENGTH_SHORT).show();
		Toast.makeText(this.getBaseContext(),
				"If your image is big, please scrolldown to see the result.",
				Toast.LENGTH_SHORT).show();
	}

	void setImage(byte[] byteImage2) {
		image2.setImageBitmap(BitmapFactory.decodeByteArray(byteImage2, 0,
				byteImage2.length));
		textView.append("\n Image Size : " + byteImage2.length + " KB");
	}

}

Please leave your valuable comments.

How to find your Google Plus ID

This is so simple

1. Go to your Google + account (https://plus.google.com/).

2. Click on the Profile icon on the Left.

3. If you look at the URL in the address bar, it should look something like this:

https://plus.google.com/104653270154306099169/posts

4. The long numerical string in the URL is your Google+ ID. Here is CoderzHeaven’s from the URL above:

104653270154306099169/

Google + CoderzHeaven

Creating a custom Sliding GalleryView with Paging in android

This is a simple example showing A sliding Gallery in android. This example shows a sliding gallery with a paging Control and a changing page text which also indicate the page change.

Create a new project named “SlidingGallery” and copy this code into “SlidingGalleryDemo.java“.
My Activity name is “SlidingGalleryDemo.java” here.

package com.coderzheaven.pack;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class SlidingGalleryDemo extends Activity {
	
	Gallery ga;
	int width, height;
	LinearLayout linear;
	LinearLayout layout;
	Integer[] pics = {
			R.drawable.android_1,
			R.drawable.android_2,
    		R.drawable.android_3,
    		R.drawable.android_4,
    		R.drawable.android_5   
    };
	ImageView paging;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	 super.onCreate(savedInstanceState);
	     setContentView(R.layout.threemenu);
	     
	     layout = (LinearLayout) findViewById(R.id.imageLayout1);
	        
	     DisplayMetrics displaymetrics = new DisplayMetrics();
	     getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
	     width = displaymetrics.heightPixels;
	     height = displaymetrics.widthPixels;
			
	     for(int i=0; i<pics.length; i++)
         {
          	paging = new ImageView(this);
        	paging.setId(i);
        	paging.setBackgroundResource(R.drawable.unsel);
        	layout.addView(paging);
         }
	     
	     ga = (Gallery)findViewById(R.id.thisgallery);
	     ga.setAdapter(new ImageAdapter(this));
	     
	     ga.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) 
				{					
					System.out.println("SELECTED : " + arg2);
				}	        	
	        });
    }

    public class ImageAdapter extends BaseAdapter {

    	private Context ctx;
    	int imageBackground;
    	int pre=-1;
    	public ImageAdapter(Context c) {
			ctx = c;
		}

		public int getCount() {
    		
    		return pics.length;
    	}

    	public View getView(int arg0, View convertView, ViewGroup arg2) {

		     ImageView iv;
		     LinearLayout layoutnew = new LinearLayout(getApplicationContext());            
		     layoutnew.setOrientation(LinearLayout.VERTICAL);
		        
             if (convertView == null) 
             {
            	iv = new ImageView(ctx);
            	iv.setImageResource(pics[arg0]);
     			iv.setScaleType(ImageView.ScaleType.FIT_XY);
     			int temp =(int) (height/1.7f);
     			int temp_y = (int) ((3*temp)/2.0f);
     			iv.setLayoutParams(new Gallery.LayoutParams(temp,temp_y));
     			iv.setBackgroundResource(imageBackground);
             }
             else
             {
            	iv = (ImageView) convertView;
             }
             TextView tv = new TextView(ctx);
 			 tv.setText("Page " + (arg0+1));
 			 tv.setTextColor(0xFFFFFFFF);
 			 tv.setPadding(0, 15, 0, 0);
 		     tv.setTextSize(18);
 			 tv.setGravity(Gravity.CENTER); 
			 layoutnew.addView(iv);
			 layoutnew.addView(tv);
    		
    		return layoutnew;
    	}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			if(pre !=-1)
    		{
    			ImageView img = (ImageView) findViewById(pre);
    			img.setBackgroundResource(R.drawable.unsel);
    		}
    		ImageView img1 = (ImageView) findViewById(position);
    		img1.setBackgroundResource(R.drawable.sel);
    		this.pre = position;
    		return position;
		}
    }
}

Now create a new class and name it “GalleryCustom.java” which extends “Gallery” and copy this code into it.

package com.coderzheaven.pack;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Gallery;

public class GalleryCustom extends Gallery {

    public GalleryCustom(Context ctx, AttributeSet attrSet) 
    {
        super(ctx,attrSet);
    }

    @SuppressWarnings("unused")
	private boolean isScrollingLeft(MotionEvent e1, MotionEvent e2)
    { 
           return e2.getX() > e1.getX(); 
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY){
      return true;  
    }
}

Now we will create the layout for the page. Copy this code to the main.xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:keepScreenOn="true"  
    android:background="@drawable/Hotpink">
    
    <LinearLayout 
	    android:layout_width="fill_parent"
	    android:id="@+id/imageLayout1"
	    android:layout_marginBottom="5dip"
	    android:layout_alignParentBottom="true"
	    android:gravity="center_horizontal|center_vertical"
	    android:orientation="horizontal"
	    android:layout_height="wrap_content">  
	 </LinearLayout>
	 
	<LinearLayout 
	    android:layout_width="fill_parent"
	    android:id="@+id/imageLayout"
	    android:gravity="center"
	    android:layout_alignParentTop="true"
	    android:layout_above="@+id/imageLayout"
	    android:layout_height="fill_parent" >
    
		<com.coderzheaven.pack.GalleryCustom
		    android:id="@+id/thisgallery"
		    android:spacing="60dip"
		    android:layout_width="fill_parent"
		    android:layout_height="wrap_content" />
		    
    </LinearLayout>
    
</RelativeLayout>

OK Its done. Now run the project and see the result.

Gallery 1

Gallery 1

Gallery 1

Gallery 1

Gallery 1

Please comment and share this post if you like it.