20 Oct 2014

Store & Retrive hash map in shared preferences | Remember me functionality in android

Hello Friends,

It’s a very important post "Store Hash map in to Shared Preference",

Normally we are preferred database to store data but there is also alternate way to store data in case of small storage like store “Username” & “Password”

Here, in this sample code I have implemented remember me functionality using hash map with shared preference.


Functionality: Stored Username and password with its key and pair, you will able to find list of user name on Auto complete text, while selecting any username you will able to get its respective password.





Let start implementation with android application

Step : 1 User Bean

The class which have set and get username and password method


public class UserBean
{
       private String Username;
       private String Password;
       public String getUsername()
       {
              return Username;
       }
       public void setUsername(String username)
       {
              Username = username;
       }
       public String getPassword()
       {
              return Password;
       }
       public void setPassword(String password)
       {
              Password = password;
       }       
}
Step : 2 RememberMeActivity


import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; public class RememberMeActivity extends Activity { HashMap<String, String>map=new HashMap<String, String>(); SharedPreferences pref; SharedPreferences.Editor ed; EditText edtPsw; CheckBox chkUnm,chkPsw; ArrayList<UserBean>arraylistBean=new ArrayList<UserBean>(); private AutoCompleteTextView autoComplete; private ArrayAdapter<String> adapter; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); autoComplete = (AutoCompleteTextView) findViewById(R.id.autoComplete); edtPsw=(EditText) findViewById(R.id.edtPassword); chkUnm=(CheckBox) findViewById(R.id.chkUsername); chkPsw=(CheckBox) findViewById(R.id.chkPassword); Loadcredentials(); ((Button)findViewById(R.id.btnDone)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String username = autoComplete.getText().toString(); String password =edtPsw.getText().toString(); pref = getSharedPreferences("HB", MODE_PRIVATE); ed = pref.edit(); ed.putString(username, password); ed.commit(); } }); } /*Load credentials which is save in share preference Hashmap*/ @SuppressWarnings({ "rawtypes", "unchecked" }) private void Loadcredentials() { pref = this.getSharedPreferences("HB", MODE_PRIVATE); ed = pref.edit(); Map map = pref.getAll(); Set keySet = map.keySet(); Iterator iterator = keySet.iterator(); while (iterator.hasNext()) { UserBean bean=new UserBean(); String key = (String) iterator.next(); String value = (String)map.get(key); Log.i("HashMap","Username==="+ key +" Psw=== " +value); bean.setUsername(key); bean.setPassword(value); arraylistBean.add(bean); } for (int i = 0; i < arraylistBean.size(); i++) { UserBean bean=arraylistBean.get(i); Log.e("ArrayList","Username=="+ bean.getUsername() +" Psw== " +bean.getPassword()); } List countryList = getCountryList(arraylistBean); adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,countryList); autoComplete.setAdapter(adapter); autoComplete.setThreshold(1); autoComplete.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> view, View arg1, int position,long arg3) { Toast.makeText(getBaseContext(), ""+view.getItemAtPosition(position),Toast.LENGTH_LONG).show(); edtPsw.setText(arraylistBean.get(position).getPassword()); } }); } @SuppressWarnings({ "rawtypes", "unchecked" }) private List getCountryList(ArrayList<UserBean> countries) { List list = new ArrayList(); for (UserBean c : countries) { list.add(c.getUsername()); } return list; } }
Learn more about Auto complete text view visit

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

18 Oct 2014

Insert and Retrieve Image into Database android | Store and retrieve images from sqlite android

Hello Friends,

In this tutorial I am sharing the code to insert the image into database and retrieve the image from database.

I hope this article might be helpful to all learning developer.



For storing the image we are using the blob type. Blob is a Java interface representing the SQL BLOB type.An SQL BLOB type stores a large array of binary data (bytes) as the value in a column of a database.

The java.sql.Blob interface provides methods for setting and retrieving data in the Blob, for querying Blob data length, and for searching for data within the Blob. More details about Blob Here

Let start to implementation with android Project

Step 1 : Create 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:background="@android:color/darker_gray"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:cacheColorHint="@android:color/transparent" >
    </ListView>


</LinearLayout>

Step 2 : Create item_list.xml
-Here it the .xml file for inflate item on list view

<?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="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:padding="10dp" >

    <ImageView
        android:id="@+id/imgIcon"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:contentDescription="@string/app_name"
        android:gravity="center_vertical"
        android:src="@drawable/photo" />

    <TextView
        android:id="@+id/txtTitle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="7dp"
        android:layout_weight="1"
        android:gravity="center_vertical"
        android:text="@string/app_name"
        android:textColor="@android:color/black"
        android:textSize="14sp" />


</LinearLayout>

Step 3 : DatabaseHalper.java
-The class have Database operation like - insert , select ,delete , update 

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 DatabaseHalper extends SQLiteOpenHelper
{
       // All Static variables
       // Database Version
       private static final int DATABASE_VERSION = 1;

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

       // items table name
       private static final String TABLE_Items = "Items";

       // items 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 DatabaseHalper(Context context)
       {
              super(context, DATABASE_NAME, null, DATABASE_VERSION);
       }

       // Creating Tables
       @Override
       public void onCreate(SQLiteDatabase db)
       {
              String CREATE_itemS_TABLE = "CREATE TABLE " + TABLE_Items + "("
                           + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
                           + KEY_IMAGE + " BLOB" + ")";
              db.execSQL(CREATE_itemS_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_Items);

              // Create tables again
              onCreate(db);
       }

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

       public// Adding new item
       void addItem(ItemBean item)
       {
              SQLiteDatabase db = this.getWritableDatabase();

              ContentValues values = new ContentValues();
              values.put(KEY_NAME, item._name);
              values.put(KEY_IMAGE, item._image);

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

       // Getting single item
       ItemBean getitem(int id)
       {
              SQLiteDatabase db = this.getReadableDatabase();

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

              ItemBean item = new ItemBean(Integer.parseInt(cursor.getString(0)),
                           cursor.getString(1), cursor.getBlob(1));

              // return item
              return item;

       }

       // Getting All items
       public List<ItemBean> getAllItems()
       {
              List<ItemBean> itemList = new ArrayList<ItemBean>();
              String selectQuery = "SELECT  * FROM "+TABLE_Items+" 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
                     {
                           ItemBean item = new ItemBean();
                           item.setID(Integer.parseInt(cursor.getString(0)));
                           item.setName(cursor.getString(1));
                           item.setImage(cursor.getBlob(2));
                          
                           itemList.add(item);
                     }
                     while (cursor.moveToNext());
              }
              db.close();
              return itemList;

       }

       // Updating single item
       public int updateItem(ItemBean item)
       {
              SQLiteDatabase db = this.getWritableDatabase();
             
              ContentValues values = new ContentValues();
              values.put(KEY_NAME, item.getName());
              values.put(KEY_IMAGE, item.getImage());

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

       }

       // Deleting single item
       public void deleteItem(ItemBean item)
       {
              SQLiteDatabase db = this.getWritableDatabase();
              db.delete(TABLE_Items, KEY_ID + " = ?",new String[] { String.valueOf(item.getID()) });
              db.close();
       }

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

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

}

Step 3 : SQLiteDemoActivity.java

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;
import com.hb.sqlite.R;


public class SQLiteDemoActivity extends Activity
{
       ArrayList<ItemBean> imageArry = new ArrayList<ItemBean>();
       ItemImageAdapter adapter;
      
       @Override
       public void onCreate(Bundle savedInstanceState)
       {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main);

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

              // convert bitmap to byte
              ByteArrayOutputStream stream = new ByteArrayOutputStream();
              image.compress(Bitmap.CompressFormat.JPEG, 100, stream);
              byte imageInByte[] = stream.toByteArray();
             
              // Inserting Contacts
              Log.d("Insert: ", "Inserting ..");
              db.addItem(new ItemBean("Android Logo", imageInByte));

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

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

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

       }

}

Step 4 : ItemBean.java

-Class for which have set and get methods

public class ItemBean {

       int _id;
       String _name;
       byte[] _image;

       // Empty constructor
       public ItemBean() {

       }

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

       }

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

       }

       // constructor
       public ItemBean(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;
       }

}

Step 5 : ItemImageAdapter.java

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;
import com.hb.sqlite.R;

public class ItemImageAdapter extends ArrayAdapter<ItemBean>
{
       Context context;
       int layoutResourceId;

       ArrayList<ItemBean> data=new ArrayList<ItemBean>();

       public ItemImageAdapter(Context context, int layoutResourceId, ArrayList<ItemBean> 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();
              }

              ItemBean 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;
       }

}

For more reference visit this post

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)