Wednesday, July 25, 2012

How to display sqlite data into a listview in android

In this session, i am going to explain how to display sqlite data into a listview in android.
This is bit tricky...You should neatly build the xml file accordingly.
We directly enter into the code:


Firstly database Class:

package com.mahesh.listlat;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class newdb extends SQLiteOpenHelper
{
 private static final String DATABASE_NAME = "sample.db";
 private static final int DATABASE_VERSION = 1;
 private Context context;

 public newdb(Context context)
 {
  super(context, DATABASE_NAME, null, DATABASE_VERSION);
  this.context = context;
 }
 @Override
 public void onCreate(SQLiteDatabase db) {
  // TODO Auto-generated method stub
  db.execSQL("CREATE TABLE gallery (id integer primary key autoincrement, image BLOB,Name varchar(160),phonenumber integer,state varchar(40),city varchar(40),pincode integer)");
 }
 private void versionUpdation(SQLiteDatabase db) {
 }
 /**
  * Check if the database already exist to avoid re-copying the file each
  * time you open the application.
  *
  * @return true if it exists, false if it doesn't
  */
 public boolean checkDataBase(String db)
 {
  SQLiteDatabase checkDB = null;
  try
  {
   String myPath = "data/data/com.mahesh.listlat/databases/" + db;
   checkDB = SQLiteDatabase.openDatabase(myPath, null,
     SQLiteDatabase.OPEN_READONLY);
  }
  catch (SQLiteException e)
  {
   // database does't exist yet.
  }
  catch (Exception e)
  {
  }
  if (checkDB != null)
  {
   checkDB.close();
  }
  return checkDB != null ? true : false;
 }
 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  if (oldVersion >= newVersion)
   return;
  if (oldVersion == 1) {
   Log.d("New Version", "Datas can be upgraded");
  }
  Log.d("Sample Data", "onUpgrade : " + newVersion);
 }
}

/////////////////////////////////////////////////////////////////////////////////////////////////
 now we go to activity Class:

package com.mahesh.listlat;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
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 Detailsdisplay extends Activity
{
 TextView name;
 TextView Phonenumber;
 TextView city;
 TextView state;
 TextView Pincode;
 Button takephoto;
 Button Done;
 private final int IMAGE_CAPTURE = 100;
 private SQLiteDatabase newDB;
 private String tableName = TestsDBManager.TABLE_NAME;
 private ArrayList<String> results = new ArrayList<String>();
 //TestsDBManager Databaserecord;
 private static newdb placeData;

 public void onCreate(Bundle savedInstanceState)
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.detaildisplay);
  //Databaserecord = new TestsDBManager(this);
  name = (TextView)findViewById(R.id.Name);
  Phonenumber = (TextView)findViewById(R.id.Phonenumber);
  city = (TextView)findViewById(R.id.City);
  state = (TextView)findViewById(R.id.State);
  Pincode = (TextView)findViewById(R.id.editText1);
  Done = (Button)findViewById(R.id.Done);  
        placeData = new newdb(this);
       
        SQLiteDatabase db = placeData.getWritableDatabase();

  Done.setOnClickListener(new OnClickListener() {
  
   public void onClick(View v)
   {
    // TODO Auto-generated method stub   
    String nametoinsert = name.getText().toString();
    String Phonenumbertoinsert = Phonenumber.getText().toString();
    String citynametoinsert = city.getText().toString();
    String statenumbertoinsert = state.getText().toString();
    String Pincodenumbertoinsert = Pincode.getText().toString();
   
    if(nametoinsert.equals("") || Phonenumbertoinsert.equals("") || citynametoinsert.equals("") || statenumbertoinsert.equals("") || Pincodenumbertoinsert.equals(""))
    {     
     Toast.makeText(getApplicationContext(), "Please enter all the details", Toast.LENGTH_LONG).show();     
     //openAndQueryDatabase();
     Intent i=new Intent("com.mahesh.listlat.dbdisplay");
     startActivity(i);
     Toast.makeText(getApplicationContext(), "Please enter all the details", Toast.LENGTH_LONG).show();
          }   
    else
    { 
     //openAndQueryDatabase();
     Intent i1=new Intent("com.mahesh.listlat.dbdisplay");
     startActivity(i1);
     Toast.makeText(getApplicationContext(), "went into ", Toast.LENGTH_LONG).show();
     insertData(nametoinsert,Phonenumbertoinsert,citynametoinsert,statenumbertoinsert,Pincodenumbertoinsert);
     //placeData.insert();   
    }
   }
  });
 }


 private void insertData( String Name, String phonenumber, String state, String city, String pincode) {
     SQLiteDatabase db = placeData.getWritableDatabase();
     ContentValues values;
  values = new ContentValues();

  //values.put("image", image);
  values.put("Name" , Name);
  values.put("phonenumber", phonenumber);
  values.put("state", state);
  values.put("city", city);
  values.put("pincode", pincode);


  db.insert("gallery", null, values);
    }



 public void onDestroy()
 {
  super.onDestroy();
  //Databaserecord.close();
  placeData.close();
 }
 public void callCamera(View v)
 {
  Intent photointent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  startActivityForResult(photointent,250);
 }

 protected void onActivityResult(int RequestCode, int ResultCode, Intent data)
 {
  if(RequestCode == 250)
  {
   if(ResultCode == RESULT_OK)
   {
    Bitmap image = (Bitmap) data.getExtras().get("data");
   
    ImageView imageview = (ImageView)findViewById(R.id.imageView1);
    imageview.setImageBitmap(image);
    sendImageData(image);
   }  
   else if(ResultCode == RESULT_CANCELED)
   {
    Toast.makeText(Detailsdisplay.this, "Launch Cancelled", Toast.LENGTH_SHORT).show();
   }
  }

 }
 public void sendImageData(Bitmap image)
 { 
  ByteArrayOutputStream stream = new ByteArrayOutputStream();
  image.compress(Bitmap.CompressFormat.PNG, 100, stream);
  byte[] byteArray = stream.toByteArray();

  String data=Base64.encodeToString(byteArray, Base64.DEFAULT); 

  /*byte im[]=Base64.decode("dsfdsfsd", Base64.DEFAULT);
  Bitmap dd=BitmapFactory.decodeByteArray(im, 1, im.length);
  */
  System.out.println("Decode String"+data); 
 } 
}
//////////////////////////////////////////////////////////////////////////////////////////////
Now list activity class:

package com.mahesh.listlat;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class dbdisplay extends ListActivity
{
 private static newdb placeData;
 private ArrayList<String> id = new ArrayList<String>();
 private ArrayList<byte[]> imagetoshow = new ArrayList<byte[]>();
 private ArrayList<String> Nametoshow = new ArrayList<String>();
 private ArrayList<String> phonenumbertoshow = new ArrayList<String>();
 private ArrayList<String> statetoshow = new ArrayList<String>();
 private ArrayList<String> citytoshow = new ArrayList<String>();
 private ArrayList<String> pincodetoshow = new ArrayList<String>();

  public void onCreate(Bundle savedInstanceState)
  {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.dbdisplay);
         placeData = new newdb(this);        
         SQLiteDatabase db = placeData.getWritableDatabase();        
         // Cursor cursors = getRawEvents("select * from gallery");
          Cursor cursors = getRawEvents("select * from gallery");
    if (cursors.moveToNext())
    {
     //Done.setVisibility(View.GONE);
     getDataAndPopulate();
    }
    else
    {
     //Done.setVisibility(View.VISIBLE);
    }     
          db.delete("gallery", "id=?", new String[] {"12"});   
  } 
  private Cursor getRawEvents(String sql)
  {
  SQLiteDatabase db = (placeData).getReadableDatabase();
  Cursor cursor = db.rawQuery(sql, null);
  startManagingCursor(cursor);
  return cursor;
  }
  private Cursor getEvents(String table) {
   SQLiteDatabase db = (placeData).getReadableDatabase();
   Cursor cursor = db.query(table, null, null, null, null, null, null);
   startManagingCursor(cursor);
   return cursor;
  }

  private void getDataAndPopulate()
     {
      id = new ArrayList<String>();
      imagetoshow = new ArrayList<byte[]>();
      Nametoshow = new ArrayList<String>();
      phonenumbertoshow = new ArrayList<String>();
      statetoshow = new ArrayList<String>();
      citytoshow = new ArrayList<String>();
      pincodetoshow = new ArrayList<String>();    
    
      Cursor cursor = getEvents("gallery");
   while (cursor.moveToNext())
   {
    String temp_id = cursor.getString(0);
    byte[] temp_image = cursor.getBlob(1);
    String temp_name = cursor.getString(2);
    String temp_phonenumber = cursor.getString(3);
    String temp_state = cursor.getString(4);
    String temp_city = cursor.getString(5);
    String temp_pincode = cursor.getString(6);
   
    id.add(temp_id);
    imagetoshow.add(temp_image);
    Nametoshow.add(temp_name);
    phonenumbertoshow.add(temp_phonenumber);
    statetoshow.add(temp_state);
    citytoshow.add(temp_city);
    pincodetoshow.add(temp_pincode);   
   }
   String[] NametoshowArray = (String[]) Nametoshow.toArray(new String[Nametoshow.size()]); 
   ItemsAdapter itemsAdapter = new ItemsAdapter(dbdisplay.this, R.layout.item,NametoshowArray);
   setListAdapter(itemsAdapter);
   //Done.setVisibility(View.GONE);
     }
    
    
     private class ItemsAdapter extends BaseAdapter
     {
   String[] items;
   public ItemsAdapter(Context context, int textViewResourceId,String[] items)
   {
    this.items = items;
   }  
   public View getView(final int POSITION, View convertView,ViewGroup parent)
   {
    TextView Name;
    TextView phonenumber;
    TextView state;
    TextView city;
    TextView pincode;   
    View view = convertView;
    ImageView img;
    if (view == null)
    {
     LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
     view = vi.inflate(R.layout.item, null);   
    }
    img = (ImageView) view.findViewById(R.id.image);
    Name = (TextView) view.findViewById(R.id.Name);  
    phonenumber = (TextView) view.findViewById(R.id.phonenumber);
    state = (TextView) view.findViewById(R.id.state);
    city  = (TextView) view.findViewById(R.id.city);
    //pincode = (Textview) view.findViewById(R.id.pincode);    
    Name.setText(Nametoshow.get(POSITION));
    phonenumber.setText(phonenumbertoshow.get(POSITION));
    state.setText(statetoshow.get(POSITION));
    city.setText(citytoshow.get(POSITION));   
    //img.setImageBitmap(BitmapFactory.decodeByteArray(imagetoshow.get(POSITION), 0, imagetoshow.get(POSITION).length));
    return view;
   }
   public int getCount() {
    return items.length;
   }
   public Object getItem(int position)
   {
    return position;
   }
   public long getItemId(int position)
   {
    return position;
   }
  }
 public void onDestroy()
 {
  super.onDestroy();
  //Databaserecord.close();
  placeData.close();
 }
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
Now let see the xml files:
First is dbdisplay.xml


<?
xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical" >
<ListView android:id="@android:id/list" android:background="@android:color/transparent"
android:layout_width="fill_parent" android:layout_height="fill_parent"></ListView>
</LinearLayout>
///////////////////////////////////////////////////////////////////////////////////////////////////////////////


Our second file is item.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView android:layout_width="50dp" android:layout_height="50dp"
android:id="@+id/image" />
<TextView android:id="@+id/Name" android:layout_toRightOf="@id/image"
android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="18sp"/>

<TextView android:id="@+id/phonenumber"
android:layout_toRightOf="@id/image" android:layout_below="@id/Name"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
<TextView android:id="@+id/state"
android:layout_below="@id/phonenumber"
android:layout_width="wrap_content" android:layout_height="wrap_content" />


<TextView android:id="@+id/city"

android:layout_below="@id/state"
android:layout_width="wrap_content" android:layout_height="wrap_content" />

<TextView android:id="@+id/pincode"
android:layout_below="@id/city"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
</RelativeLayout>





CHEERS....