Friday 14 November 2014

SQLiteDBExample

First create main_activity.xml

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

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

            <EditText
                android:id="@+id/edtname"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:hint="@string/name" />

            <EditText
                android:id="@+id/edtadd"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:hint="@string/address" />

            <EditText
                android:id="@+id/edtcity"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:hint="@string/city" />

            <EditText
                android:id="@+id/edtstate"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:hint="@string/state" />

            <EditText
                android:id="@+id/edtcountry"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:hint="@string/country" />
            
            <ImageView 
                android:id="@+id/imageviewsetphoto"
                android:layout_height="100dp"
                android:layout_width="100dp"/>
            
            <Button 
                android:id="@+id/btnuploadimage"
                android:layout_height="wrap_content"
                android:layout_width="fill_parent"
                android:text="Upload image"/>

            <Button
                android:id="@+id/btnsave"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:onClick="saveClick"
                android:text="@string/save" />

            <Button
                android:id="@+id/btnlist"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:onClick="listClick"
                android:text="@string/list" />

        </LinearLayout>
    </ScrollView>


</RelativeLayout>

then , create displaylist.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" 
    android:background="@android:color/black">

    <Button
        android:id="@+id/backbtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/back" 
        android:onClick="backClick"/>

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>


</LinearLayout>

then ,create editrecord.xml

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

     <Button
        android:id="@+id/backbtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/back" 
        android:onClick="backClick"/>
    
     <ImageView  android:id="@+id/usrimg"
         android:layout_height="wrap_content"
         android:layout_width="wrap_content"
         android:layout_below="@+id/backbtn"
         android:contentDescription="useimg"/>
     
    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/usrimg" >

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

            <EditText
                android:id="@+id/edtname"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:hint="@string/name" />

            <EditText
                android:id="@+id/edtadd"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:hint="@string/address" />

            <EditText
                android:id="@+id/edtcity"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:hint="@string/city" />

            <EditText
                android:id="@+id/edtstate"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:hint="@string/state" />

            <EditText
                android:id="@+id/edtcountry"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:hint="@string/country" />

            <Button
                android:id="@+id/btnsave"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:onClick="updateClick"
                android:text="@string/save" />

            <Button
                android:id="@+id/btndel"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:onClick="deleteClick"
                android:text="@string/delete" />

        </LinearLayout>
    </ScrollView>

</RelativeLayout>

then ,create myraw.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" >

    <TextView
        android:id="@+id/textViewname"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="name" />
    <TextView
        android:id="@+id/textViewadd"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="add" />
    <TextView
        android:id="@+id/textViewcity"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="city" />
    <TextView
        android:id="@+id/textViewstate"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="state" />
    <TextView
        android:id="@+id/textViewcountry"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="country" />

</LinearLayout>

then ,create photouploaddialog1.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/dialog_style"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="bottom"
    android:gravity="bottom"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="2dp"
        android:paddingRight="2dp"
        android:paddingTop="15dp"
        android:background="@drawable/transperet_bg"
        android:orientation="vertical" >

        <Button
            android:id="@+id/btn_take_photo"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="take_photo"
            android:textStyle="bold"
            android:textColor="@android:color/black"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginBottom="10dp"
            android:background="@drawable/photoselector" />

        <Button
            android:id="@+id/btn_choose_from_library"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="choose_from_library"
            android:textStyle="bold" 
            android:textColor="@android:color/black"
           android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:background="@drawable/photoselector"/>

        <Button
            android:id="@+id/photo_cancel"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:text="photo_cancel"
            android:textStyle="bold"
            android:padding="5dp"
               android:textColor="@android:color/white"
               android:layout_marginBottom="10dp"
                 android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:background="@drawable/photocancelselectoe" />
    </LinearLayout>

</LinearLayout>

then create crop_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:gravity="center_vertical">
<ImageView
android:id="@+id/iv_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""/>
</LinearLayout>

then create amin sub folder in res folder and create slide_out_down.xml

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@android:integer/config_longAnimTime"
    android:fromYDelta="0%p"
    android:toYDelta="100%p" />

then create slide_up_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromYDelta="50%p" android:toYDelta="0%p"
    android:duration="@android:integer/config_longAnimTime"/>

then create drawable folder and create photocancelselectoe.xml 

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/take_photo_hover"
          android:state_pressed="true" />
    <item android:drawable="@drawable/cancel_btn"
          android:state_focused="true" />
    <item android:drawable="@drawable/cancel_btn" />
</selector>

then create photoselector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/take_photo_hover"
          android:state_pressed="true" />
    <item android:drawable="@drawable/take_photo"
          android:state_focused="true" />
    <item android:drawable="@drawable/take_photo" />
</selector>

then use this images in drawable-hdpi folder







then below is my menifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.sqlitedbexample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.sqlitedbexample.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Displaylist"></activity>
        <activity android:name=".UpdateRecord"></activity>
    </application>

</manifest>


then below is my string.xml file

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">SQLiteDBExample</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
<string name="address">Address</string>
<string name="name">Name</string>
<string name="city">City</string>
<string name="state">State</string>
<string name="country">Country</string>
<string name="back">Back</string>
<string name="save">Save</string>
<string name="list">List</string>
<string name="update">Update</string>
<string name="delete">Delete</string>
</resources>

then below is style.xml file

 <style name="dialog_style" parent="android:Theme.Dialog">
<item name="android:windowNoTitle">true</item>
<item name="android:windowFrame">@null</item>
<item name="android:windowTitleStyle">@null</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
<item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
<item name="android:height">100dp</item>
</style>
<style name="DialogAnimation" parent="android:Theme.Dialog">
        <item name="android:windowEnterAnimation">@anim/slide_up_dialog</item>
        <item name="android:windowExitAnimation">@anim/slide_out_down</item>
    </style>
    

then start java code from below ,first one is MainActivity.java

package com.example.sqlitedbexample;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.example.sqlitedbexample.sqlite.TaskData;

public class MainActivity extends Activity {

private static final String tag = MainActivity.class.getSimpleName();
EditText edtname,edtadd,edtcity,edtstate,edtcountry;
String strname,stradd,strcity,strstate,strcountry,currentDateandTime;
TaskData taskdata;
Button btnuploadimage;
Bitmap photo;
ImageView imgphoto;
View popUpView;
private PopupWindow mpopup;
private Uri mImageCaptureUri;
private static final int RESULT_LOAD_IMAGE = 101;
private static final int CAMERA_RESULT = 102;
private static final int CROP_FROM_CAMERA = 103;
String selectedImagePath;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = MainActivity.this;
edtname = (EditText)findViewById(R.id.edtname);
edtadd = (EditText)findViewById(R.id.edtadd);
edtcity = (EditText)findViewById(R.id.edtcity);
edtstate = (EditText)findViewById(R.id.edtstate);
edtcountry = (EditText)findViewById(R.id.edtcountry);
btnuploadimage = (Button)findViewById(R.id.btnuploadimage);
imgphoto = (ImageView)findViewById(R.id.imageviewsetphoto);
btnuploadimage.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
PopupMenu();
}
});
}
public void saveClick(View v){
strname = edtname.getText().toString();
stradd = edtadd.getText().toString();
strcity = edtcity.getText().toString();
strstate = edtstate.getText().toString();
strcountry = edtcountry.getText().toString();
// this code is for adding image from drawable folder
Bitmap b=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream bos=new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 100, bos);
byte[] photo=bos.toByteArray();
Log.i("MainActivity","insert image photo...."+photo);
// this code is for adding image from drawable folder
 
 
//coding to add image using camera or sdcard
Log.i(tag, "selectedImagePath..."+selectedImagePath);
Bitmap bMap = BitmapFactory.decodeFile(selectedImagePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bMap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//this will convert image to byte[] 
byte[] byteArrayImage = baos.toByteArray(); 
//coding to add image using camera or sdcard
 
 
 
taskdata = new TaskData(getApplicationContext());
taskdata.open();
//belwo this line is for adding image from drawable folder 
//taskdata.createTask(strname, stradd, strcity, strstate, strcountry,photo);
//below line is for adding image from camera or sdcard
taskdata.createTask(strname, stradd, strcity, strstate, strcountry,byteArrayImage);
taskdata.close();
Toast.makeText(getApplicationContext(), "Inserted successfully completd", Toast.LENGTH_LONG).show();
}
public void listClick(View v){
Intent ilist = new Intent(MainActivity.this,Displaylist.class);
startActivity(ilist);
}

public void PopupMenu() {
 popUpView = getLayoutInflater().inflate(R.layout.photouploaddialog1, null); // inflating popup layout
 mpopup = new PopupWindow(popUpView, LayoutParams.FILL_PARENT,
   LayoutParams.WRAP_CONTENT, true); // Creation of popup
 mpopup.setAnimationStyle(R.style.DialogAnimation);
 mpopup.showAtLocation(popUpView, Gravity.BOTTOM, 0, 0); // Displaying
               // popup

 Button btnOk = (Button) popUpView.findViewById(R.id.btn_take_photo);
 btnOk.setOnClickListener(new OnClickListener() {
  public void onClick(View v) {
  mpopup.dismiss();
  Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
  "Tixe_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, CAMERA_RESULT);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
  }
  
 });

 Button btnchooselibrary = (Button) popUpView
   .findViewById(R.id.btn_choose_from_library);
 btnchooselibrary.setOnClickListener(new OnClickListener() {

  public void onClick(View v) {
   try {
    Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Complete action using"), RESULT_LOAD_IMAGE);
   } catch (Exception ex) {
   }
  }
 });

 Button btnCancel = (Button) popUpView.findViewById(R.id.photo_cancel);
 btnCancel.setOnClickListener(new OnClickListener() {
  public void onClick(View v) {
   mpopup.dismiss();
  }
 });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
try{
mpopup.dismiss();
}catch(Exception e){
e.printStackTrace();
}
switch (requestCode) {
case CAMERA_RESULT:
    doCrop();
    break;

   case RESULT_LOAD_IMAGE: 
    try{
    mImageCaptureUri = data.getData();
    doCrop();
    }catch(Exception e){
    e.printStackTrace();
    }
    break;    

   case CROP_FROM_CAMERA:    
   
    try{
   
       Bundle extras = data.getExtras();

       if (extras != null) {        
            photo = extras.getParcelable("data");

           imgphoto.setImageBitmap(photo);
           imgphoto.setBackgroundColor(getResources().getColor(android.R.color.transparent));
       }

       File f = new File(mImageCaptureUri.getPath());    
       selectedImagePath = f.getAbsolutePath();
       if (f.exists()) f.delete();
       
       boolean success = false;
if(photo != null){
try {
byte[] bitmapdata;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 90, stream);
bitmapdata = stream.toByteArray();

if (bitmapdata != null) {
MyWrite(bitmapdata);
success = true;
}

} catch (Exception e) {
e.printStackTrace();
success = false;
}
}
if (success) {
Log.i(tag, "Image Saved Successfully");
   } else {
    Log.i(tag, "Error during image saving");
   } }catch(Exception e){
    e.printStackTrace();
    }
       break;
}
}
public void MyWrite(byte[] buffer) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
currentDateandTime = sdf.format(new Date());
System.gc();
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath() + "/MyTixeCropImage");
directory.mkdirs();
// Now create the file in the above directory and write the contents
// into it
System.out.println("Image path=" + selectedImagePath);
File file;
file = new File(directory, currentDateandTime + ".jpg");

// File file = new File(directory, "sample.jpg");
selectedImagePath = file.getAbsolutePath();
System.out.println("Path=" + selectedImagePath);

try {
if (!file.exists())
file.createNewFile();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}

FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

BufferedOutputStream osw = new BufferedOutputStream(fOut);
try {
// osw.write(path);
osw.write(buffer);
// osw.write(buffer, offset, length);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
osw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
osw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
int cropsize = cropOptions.size();
Intent intent = new Intent("com.android.camera.action.CROP");
       intent.setType("image/*");
       
       List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );
       
       int size = list.size();
       
       if (size == 0) {   
        //Utility.showDialogwithTitle(context, "Can not find image crop app");
        Toast.makeText(getApplicationContext(),"Can not find image crop app" , 11).show();
           return;
       } else {
        intent.setData(mImageCaptureUri);
           
           intent.putExtra("outputX", 200);
           intent.putExtra("outputY", 200);
           intent.putExtra("aspectX", 1);
           intent.putExtra("aspectY", 1);
           intent.putExtra("scale", true);
           intent.putExtra("return-data", true);
           
        if (size == 1) {
        Intent i = new Intent(intent);
        ResolveInfo res = list.get(0);

        i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));

        startActivityForResult(i, CROP_FROM_CAMERA);
        } else {
       for (ResolveInfo res : list) {
        final CropOption co = new CropOption();

        co.title = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
        co.icon = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
        co.appIntent= new Intent(intent);

        co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));

           cropOptions.add(co);
       }

       CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);

       AlertDialog.Builder builder = new AlertDialog.Builder(this);
       builder.setTitle("Choose Crop App");
       builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
           public void onClick( DialogInterface dialog, int item ) {
               startActivityForResult( cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
           }
       });

       builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
           @Override
           public void onCancel( DialogInterface dialog ) {

               if (mImageCaptureUri != null ) {
                   getContentResolver().delete(mImageCaptureUri, null, null );
                   mImageCaptureUri = null;
               }
           }
       } );

       AlertDialog alert = builder.create();

       alert.show();
        }
        }
}
}

then create FormClass.java

package com.example.sqlitedbexample;

import android.graphics.Bitmap;

public class FormClass {
private Integer id;
private String name;
private String address;
private String city;
private String state;
private String country;
private byte[] bmp;


public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getState() {
return state;
}

public void setState(String state) {
this.state = state;
}

public String getCountry() {
return country;
}

public void setCountry(String country) {
this.country = country;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public byte[] getBmp() {
return bmp;
}

public void setBmp(byte[] bmp) {
this.bmp = bmp;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

then create Displaylist.java

package com.example.sqlitedbexample;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.example.sqlitedbexample.sqlite.TaskData;

public class Displaylist extends Activity{
private static final String tag = Displaylist.class.getSimpleName();
ListView lst;
List<FormClass> lsttask;
TaskData taskdataobj;
FormClass task;
String strname,stradd,strcity,strstate,strcountry;
ArrayList<String> myname;
ArrayAdapter<String> adp;
Integer myid;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.displaylist);
lst = (ListView)findViewById(R.id.listView1);
taskdataobj = new TaskData(Displaylist.this);
taskdataobj.open();
Log.i(tag, tag + "get Single id");

myname = new ArrayList<String>();
lsttask = taskdataobj.getAllTask();

for(int i=0;i<lsttask.size();i++){
task = lsttask.get(i);
strname = task.getName();
if(!TextUtils.isEmpty(strname)){
myname.add(strname);
}
}
taskdataobj.close();
adp = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,myname);
lst.setAdapter(adp);
lst.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int pos,
long arg3) {
// TODO Auto-generated method stub
myid = (int) parent.getItemIdAtPosition(pos);
Log.i(tag, "get my selected item id...."+myid);
task = lsttask.get(pos);
Integer mylistid = task.getId();
Log.i(tag, "get my selected item id from mylist...."+mylistid);
Intent i = new Intent(Displaylist.this,UpdateRecord.class);
i.putExtra("myid", mylistid);
startActivity(i);
}
});
}
public void backClick(View v){
Intent i = new Intent(Displaylist.this,MainActivity.class);
startActivity(i);
}
}


then create UpdateRecord.java

package com.example.sqlitedbexample;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.example.sqlitedbexample.sqlite.TaskData;

public class UpdateRecord extends Activity{
private static final String tag = UpdateRecord.class.getSimpleName();
EditText edtname,edtadd,edtcity,edtstate,edtcountry;
String strname,stradd,strcity,strstate,strcountry,currentDateandTime;
byte[] usrimg;
TaskData taskdataobj;
FormClass task;
List<FormClass> lsttask;
Integer myid;
ImageView imgphoto;
Bitmap photo;
View popUpView;
private PopupWindow mpopup;
private Uri mImageCaptureUri;
private static final int RESULT_LOAD_IMAGE = 101;
private static final int CAMERA_RESULT = 102;
private static final int CROP_FROM_CAMERA = 103;
String selectedImagePath;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.editrecord);
edtname = (EditText)findViewById(R.id.edtname);
edtadd = (EditText)findViewById(R.id.edtadd);
edtcity = (EditText)findViewById(R.id.edtcity);
edtstate = (EditText)findViewById(R.id.edtstate);
edtcountry = (EditText)findViewById(R.id.edtcountry);
imgphoto = (ImageView)findViewById(R.id.usrimg);
Intent i = getIntent();
if(null != i.getExtras()){
myid = i.getExtras().getInt("myid");
}
taskdataobj = new TaskData(UpdateRecord.this);
taskdataobj.open();
Log.i(tag, tag + "get Single id");
lsttask = taskdataobj.GetRecord(myid);

for(int j=0;j<lsttask.size();j++){
task = lsttask.get(j);
strname = task.getName();
stradd = task.getAddress();
strcity = task.getCity();
strstate = task.getState();
strcountry = task.getCountry();
usrimg = task.getBmp();
Log.i(tag,"usrimg...."+usrimg);
}
taskdataobj.close();
if(!TextUtils.isEmpty(strname)){
edtname.setText(strname);
}
if(!TextUtils.isEmpty(stradd)){
edtadd.setText(stradd);
}
if(!TextUtils.isEmpty(strcity)){
edtcity.setText(strcity);
}
if(!TextUtils.isEmpty(strstate)){
edtstate.setText(strstate);
}
if(!TextUtils.isEmpty(strcountry)){
edtcountry.setText(strcountry);
}
ByteArrayInputStream imageStream = new ByteArrayInputStream(usrimg);
Bitmap theImage= BitmapFactory.decodeStream(imageStream);
imgphoto.setImageBitmap(theImage);
imgphoto.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
PopupMenu();
}
});
}
public void updateClick(View v){
strname = edtname.getText().toString();
stradd = edtadd.getText().toString();
strcity = edtcity.getText().toString();
strstate = edtstate.getText().toString();
strcountry = edtcountry.getText().toString();
// this code is for adding image from drawable folder
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
Bitmap bitmap = ((BitmapDrawable)getResources().getDrawable(R.drawable.android_icon)).getBitmap();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);   
byte[] photo = baos.toByteArray(); 
// this code is for adding image from drawable folder
//coding to add image using camera or sdcard
Log.i(tag, "selectedImagePath..."+selectedImagePath);
Bitmap bMap = BitmapFactory.decodeFile(selectedImagePath);
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();  
bMap.compress(Bitmap.CompressFormat.JPEG, 100, baos1);
//this will convert image to byte[] 
byte[] byteArrayImage = baos1.toByteArray(); 
//coding to add image using camera or sdcard
taskdataobj = new TaskData(UpdateRecord.this);
taskdataobj.open();
//belwo this line is for adding image from drawable folder 
//taskdataobj.update(myid, strname, stradd, strcity, strstate, strcountry,photo);
//below line is for adding image from camera or sdcard
taskdataobj.update(myid, strname, stradd, strcity, strstate, strcountry,byteArrayImage);
taskdataobj.close();
Toast.makeText(getApplicationContext(), "Update successfully...", Toast.LENGTH_LONG).show();
}
public void deleteClick(View v){
taskdataobj = new TaskData(UpdateRecord.this);
taskdataobj.open();
taskdataobj.deleteTask(myid.toString());
taskdataobj.close();
Toast.makeText(getApplicationContext(), "Delete successfully...", Toast.LENGTH_LONG).show();
Intent i = new Intent(UpdateRecord.this,MainActivity.class);
startActivity(i);
}
public void backClick(View v){
Intent i = new Intent(UpdateRecord.this,MainActivity.class);
startActivity(i);
}


public void PopupMenu() {
 popUpView = getLayoutInflater().inflate(R.layout.photouploaddialog1, null); // inflating popup layout
 mpopup = new PopupWindow(popUpView, LayoutParams.FILL_PARENT,
   LayoutParams.WRAP_CONTENT, true); // Creation of popup
 mpopup.setAnimationStyle(R.style.DialogAnimation);
 mpopup.showAtLocation(popUpView, Gravity.BOTTOM, 0, 0); // Displaying
               // popup

 Button btnOk = (Button) popUpView.findViewById(R.id.btn_take_photo);
 btnOk.setOnClickListener(new OnClickListener() {
  public void onClick(View v) {
  mpopup.dismiss();
  Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
  "Tixe_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, CAMERA_RESULT);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
  }
  
 });

 Button btnchooselibrary = (Button) popUpView
   .findViewById(R.id.btn_choose_from_library);
 btnchooselibrary.setOnClickListener(new OnClickListener() {

  public void onClick(View v) {
   try {
    Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Complete action using"), RESULT_LOAD_IMAGE);
   } catch (Exception ex) {
   }
  }
 });

 Button btnCancel = (Button) popUpView.findViewById(R.id.photo_cancel);
 btnCancel.setOnClickListener(new OnClickListener() {
  public void onClick(View v) {
   mpopup.dismiss();
  }
 });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
try{
mpopup.dismiss();
}catch(Exception e){
e.printStackTrace();
}
switch (requestCode) {
case CAMERA_RESULT:
    doCrop();
    break;

   case RESULT_LOAD_IMAGE: 
    try{
    mImageCaptureUri = data.getData();
    doCrop();
    }catch(Exception e){
    e.printStackTrace();
    }
    break;    

   case CROP_FROM_CAMERA:    
   
    try{
   
       Bundle extras = data.getExtras();

       if (extras != null) {        
            photo = extras.getParcelable("data");

           imgphoto.setImageBitmap(photo);
           imgphoto.setBackgroundColor(getResources().getColor(android.R.color.transparent));
       }

       File f = new File(mImageCaptureUri.getPath());    
       selectedImagePath = f.getAbsolutePath();
       if (f.exists()) f.delete();
       
       boolean success = false;
if(photo != null){
try {
byte[] bitmapdata;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 90, stream);
bitmapdata = stream.toByteArray();

if (bitmapdata != null) {
MyWrite(bitmapdata);
success = true;
}

} catch (Exception e) {
e.printStackTrace();
success = false;
}
}
if (success) {
Log.i(tag, "Image Saved Successfully");
   } else {
    Log.i(tag, "Error during image saving");
   } }catch(Exception e){
    e.printStackTrace();
    }
       break;
}
}
public void MyWrite(byte[] buffer) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
currentDateandTime = sdf.format(new Date());
System.gc();
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath() + "/MyTixeCropImage");
directory.mkdirs();
// Now create the file in the above directory and write the contents
// into it
System.out.println("Image path=" + selectedImagePath);
File file;
file = new File(directory, currentDateandTime + ".jpg");

// File file = new File(directory, "sample.jpg");
selectedImagePath = file.getAbsolutePath();
System.out.println("Path=" + selectedImagePath);

try {
if (!file.exists())
file.createNewFile();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}

FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

BufferedOutputStream osw = new BufferedOutputStream(fOut);
try {
// osw.write(path);
osw.write(buffer);
// osw.write(buffer, offset, length);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
osw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
osw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
int cropsize = cropOptions.size();
Intent intent = new Intent("com.android.camera.action.CROP");
       intent.setType("image/*");
       
       List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );
       
       int size = list.size();
       
       if (size == 0) {   
        //Utility.showDialogwithTitle(context, "Can not find image crop app");
        Toast.makeText(getApplicationContext(),"Can not find image crop app" , 11).show();
           return;
       } else {
        intent.setData(mImageCaptureUri);
           
           intent.putExtra("outputX", 200);
           intent.putExtra("outputY", 200);
           intent.putExtra("aspectX", 1);
           intent.putExtra("aspectY", 1);
           intent.putExtra("scale", true);
           intent.putExtra("return-data", true);
           
        if (size == 1) {
        Intent i = new Intent(intent);
        ResolveInfo res = list.get(0);

        i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));

        startActivityForResult(i, CROP_FROM_CAMERA);
        } else {
       for (ResolveInfo res : list) {
        final CropOption co = new CropOption();

        co.title = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
        co.icon = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
        co.appIntent= new Intent(intent);

        co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));

           cropOptions.add(co);
       }

       CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);

       AlertDialog.Builder builder = new AlertDialog.Builder(this);
       builder.setTitle("Choose Crop App");
       builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
           public void onClick( DialogInterface dialog, int item ) {
               startActivityForResult( cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
           }
       });

       builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
           @Override
           public void onCancel( DialogInterface dialog ) {

               if (mImageCaptureUri != null ) {
                   getContentResolver().delete(mImageCaptureUri, null, null );
                   mImageCaptureUri = null;
               }
           }
       } );

       AlertDialog alert = builder.create();

       alert.show();
        }
        }
}
}

then create Utility.java

package com.example.sqlitedbexample;

import java.io.ByteArrayOutputStream;

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

public class Utility {
// convert from bitmap to byte array
public static byte[] getBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, stream);
return stream.toByteArray();
}

// convert from byte array to bitmap
public static Bitmap getPhoto(byte[] image) {
return BitmapFactory.decodeByteArray(image, 0, image.length);
}
}

then create CropOption.java for crop image

package com.example.sqlitedbexample;

import android.content.Intent;
import android.graphics.drawable.Drawable;

public class CropOption {
public CharSequence title;
public Drawable icon;
public Intent appIntent;
}

and CropOptionAdapter.java

package com.example.sqlitedbexample;

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 android.content.Context;

import java.util.ArrayList;

public class CropOptionAdapter extends ArrayAdapter<CropOption> {
private ArrayList<CropOption> mOptions;
private LayoutInflater mInflater;
public CropOptionAdapter(Context context, ArrayList<CropOption> options) {
super(context, R.layout.crop_selector, options);
mOptions = options;
mInflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup group) {
if (convertView == null)
convertView = mInflater.inflate(R.layout.crop_selector, null);
CropOption item = mOptions.get(position);
if (item != null) {
((ImageView) convertView.findViewById(R.id.iv_icon)).setImageDrawable(item.icon);
((TextView) convertView.findViewById(R.id.tv_name)).setText(item.title);
return convertView;
}
return null;
}
}

then start creating classes for sqlite database ,first create TaskDatabaseHelper.java

package com.example.sqlitedbexample.sqlite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class TaskDatabaseHelper extends SQLiteOpenHelper {

public static final String TAG = "TaskDatabaseHelper";
public static final String DATABASE_NAME = "MyRegForm.db";
public static final int DATABASE_VERSION = 1;

public static final String TABLE_NAME = "Regform";
public static String ID="id";
public static final String REG_NAME = "reg_name";
public static final String REG_ADD = "reg_add";
public static final String REG_CITY = "reg_city";
public static final String REG_STATE = "reg_state";
public static final String REG_COUNTRY = "reg_country";
public static final String EMP_PHOTO = "photo";

private static final String DATABASE_CREATE = "create table " + TABLE_NAME + "(" + 
ID + " integer primary key autoincrement ," + 
REG_NAME + " text," +
REG_ADD + " text," + 
REG_CITY + " text," + 
REG_STATE + " text," + 
REG_COUNTRY + " text," +
EMP_PHOTO + " blob)";

public TaskDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
Log.i(TAG, TAG + "constructer");
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub

Log.i(TAG, TAG + "oncreate");
db.execSQL(DATABASE_CREATE);
}

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

db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}


then create TaskData.java

package com.example.sqlitedbexample.sqlite;


import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.util.Log;

import com.example.sqlitedbexample.FormClass;
import com.example.sqlitedbexample.Utility;

public class TaskData {

public static final String TAG = "TaskData";
private TaskDatabaseHelper taskdbhelper;
private SQLiteDatabase sqlitedb;
// Integer id;

private String[] taskcol = {TaskDatabaseHelper.ID,TaskDatabaseHelper.REG_NAME,
TaskDatabaseHelper.REG_ADD, TaskDatabaseHelper.REG_CITY,
TaskDatabaseHelper.REG_STATE, TaskDatabaseHelper.REG_COUNTRY,TaskDatabaseHelper.EMP_PHOTO};
private String[] taskcolname = {TaskDatabaseHelper.REG_NAME};

public TaskData(Context ctx) {
Log.i(TAG, TAG + "TaskData");
taskdbhelper = new TaskDatabaseHelper(ctx);
}

public void open() throws SQLException {

Log.i(TAG, TAG + "open");
if (sqlitedb == null) {
sqlitedb = taskdbhelper.getWritableDatabase();
}
}
// start code to find last inserted record
public Long GetLastRecord()
{
Long lastId = null;
final String query = "SELECT * FROM Regform ORDER BY id DESC LIMIT 1";
Cursor c = sqlitedb.rawQuery(query,null);
if (c != null && c.moveToFirst()) {
   lastId = c.getLong(0); //The 0 is the column index, we only have 1 column, so the index is 0
}
return lastId;
}
// end code to find last inserted record

public void createTask(String name, String add, String city,
String state, String country,byte[] usrimg) {

Log.i(TAG, TAG + "create task for insert ");
ContentValues contentvalue = new ContentValues();

contentvalue.put(TaskDatabaseHelper.REG_NAME,name);
contentvalue.put(TaskDatabaseHelper.REG_ADD, city);
contentvalue.put(TaskDatabaseHelper.REG_CITY, city);
contentvalue.put(TaskDatabaseHelper.REG_STATE, state);
contentvalue.put(TaskDatabaseHelper.REG_COUNTRY, country);
contentvalue.put(TaskDatabaseHelper.EMP_PHOTO, usrimg);
sqlitedb.insert(TaskDatabaseHelper.TABLE_NAME, null, contentvalue);
Log.i(TAG, TAG + "insert complete");

}

public void update(Integer id,String uname,String uadd,String ucity,String ustate,String ucountry,byte[] usrimg)
{
Log.i(TAG, TAG + "update start...");

ContentValues cv = new ContentValues();
cv.put(TaskDatabaseHelper.REG_NAME, uname);
cv.put(TaskDatabaseHelper.REG_ADD, uadd);
cv.put(TaskDatabaseHelper.REG_CITY, ucity);
cv.put(TaskDatabaseHelper.REG_STATE, ustate);
cv.put(TaskDatabaseHelper.REG_COUNTRY, ucountry);
cv.put(TaskDatabaseHelper.EMP_PHOTO, usrimg);
String whered= "id" + "=" + id; 
sqlitedb.update(TaskDatabaseHelper.TABLE_NAME, cv, whered , null);

Log.i(TAG, TAG + "update end...");
}

public void deleteTask(String id)
{
Log.i("delete task", "Delete Task");
long idis = Long.parseLong(id);
System.out.println("Sqlite database id is............."+idis);
sqlitedb.delete(TaskDatabaseHelper.TABLE_NAME, TaskDatabaseHelper.ID + " = " + idis, null);
}
private FormClass cursorTotask(Cursor cursor) {

Log.i(TAG, TAG + "cursortotask");

FormClass task = new FormClass();
task.setId(cursor.getInt(cursor.getColumnIndex(TaskDatabaseHelper.ID)));
task.setName(cursor.getString(cursor.getColumnIndex(TaskDatabaseHelper.REG_NAME)));
task.setAddress(cursor.getString(cursor.getColumnIndex(TaskDatabaseHelper.REG_ADD)));
task.setCity(cursor.getString(cursor.getColumnIndex(TaskDatabaseHelper.REG_CITY)));
task.setState(cursor.getString(cursor.getColumnIndex(TaskDatabaseHelper.REG_STATE)));
task.setCountry(cursor.getString(cursor.getColumnIndex(TaskDatabaseHelper.REG_COUNTRY)));
task.setBmp(cursor.getBlob(cursor.getColumnIndex(TaskDatabaseHelper.EMP_PHOTO)));
return task;
}

public List<FormClass> getAllTask() {

Log.i(TAG, TAG + "getalltasklist..");
List<FormClass> tasklist = new ArrayList<FormClass>();

Cursor cursor = sqlitedb.query(TaskDatabaseHelper.TABLE_NAME,taskcol,null,null,null,null,null);

cursor.moveToFirst();

while (!cursor.isAfterLast()) {
FormClass task = cursorTotask(cursor);
tasklist.add(task);

cursor.moveToNext();
}
cursor.close();
Log.i(TAG, TAG + "Get List Of Task...");

return tasklist;

}
public List<FormClass> getAllTaskName() {

Log.i(TAG, TAG + "getalltasklist..");
List<FormClass> tasklist = new ArrayList<FormClass>();

Cursor cursor = sqlitedb.query(TaskDatabaseHelper.TABLE_NAME,taskcolname,null,null,null,null,null);

cursor.moveToFirst();

while (!cursor.isAfterLast()) {
FormClass task = cursorTotask(cursor);
tasklist.add(task);

cursor.moveToNext();
}
cursor.close();
Log.i(TAG, TAG + "Get List Of Task...");

return tasklist;
}
//Cursor cursor = sqlitedb.query(TaskDatabaseHelper.TABLE_NAME,taskcol,TaskDatabaseHelper.TASK_DATE + " >= ?",new String[]{sdf.format(new Date())},null,null, TaskDatabaseHelper.TASK_DATE + " ASC, " + TaskDatabaseHelper.TASK_TIME + " ASC");
public FormClass GetRecord(int id)
{
FormClass gettask = new FormClass();

Cursor cursor = sqlitedb.query(TaskDatabaseHelper.TABLE_NAME, taskcol, TaskDatabaseHelper.ID + "="+ id, null, null, null,null);

if(cursor.moveToFirst()) {
gettask = cursorTotask(cursor);
cursor.moveToNext();
}

cursor.close();
Log.i(TAG, TAG + "Get Single data");
return gettask;
}
public List<FormClass> GetRecord(Integer id)
{
List<FormClass> gettask = new ArrayList<FormClass>();
Cursor cursor = sqlitedb.query(TaskDatabaseHelper.TABLE_NAME, taskcol, TaskDatabaseHelper.ID + "="+ id.toString(), null, null, null,null);
cursor.moveToFirst();
while(!cursor.isAfterLast())
{
FormClass taskobj = cursorTotask(cursor);
gettask.add(taskobj);
cursor.moveToNext();
}
cursor.close();
Log.i(TAG, TAG + "Get Single data");
return gettask;
}
public void close() {
Log.i(TAG, TAG + "close");
sqlitedb.close();
}
}

Thats it , use code and enjoy code with store and retrieve data with sqlite database. 




Sunday 6 April 2014

Android All Sharing Option

 //create the send intent  
   Intent shareIntent =   
    new Intent(android.content.Intent.ACTION_SEND);  
     
   //set the type  
   shareIntent.setType("text/plain");  
     
   //add a subject  
   shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,   
    "Insert Subject Here");  
     
   //build the body of the message to be shared  
   String shareMessage = "Insert message body here.";  
     
   //add the message  
   shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,   
    shareMessage);  
     
   //start the chooser for sharing  
   startActivity(Intent.createChooser(shareIntent,   
    "Insert share chooser title here"));  

Wednesday 2 April 2014

Image Next Previous Logic from List of Images

Make one class name ImageLoader

public class ImageLoader {

public static ArrayList<Bitmap> bitmarraylst;
Bitmap bitmap;
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
Context mContext;

public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
bitmarraylst = new ArrayList<Bitmap>();
mContext = context;
}

final int stub_id = R.drawable.defaultprofileimg;

public void DisplayImage(String url, ImageView imageView) {
// System.out.println("Getting url: "+url);

imageViews.put(imageView, url);
bitmap = memoryCache.get(url);

if (bitmap != null) {
bitmarraylst.add(bitmap);
imageView.setImageBitmap(bitmap);
} else {
queuePhoto(url, imageView);
Bitmap bitdefault = BitmapFactory.decodeResource(mContext.getResources(),stub_id);
bitmarraylst.add(bitdefault);
imageView.setImageResource(stub_id);
}


}

public void DisplayImageRounded(String url, ImageView imageView) {
// System.out.println("Getting url: "+url);

imageViews.put(imageView, url);
bitmap = memoryCache.get(url);
// bitmap = getRoundedCornerBitmap(bitmap);
if (bitmap != null)
imageView.setImageBitmap(bitmap);

else {
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}

private void queuePhoto(String url, ImageView imageView) {
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}

public Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);

// from SD cache
Bitmap b = decodeFile(f);
if (b != null)
return b;

// from web
try {
Bitmap bitmap = null;
if (url.toString().length() != 0) {
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} else {
return null;
}

} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}

// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);

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

// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}

// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;

public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}

class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;

PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad = photoToLoad;
}

public void run() {
// TODO Auto-generated method stub
if (imageViewReused(photoToLoad))
return;
Bitmap bmp = getBitmap(photoToLoad.url);
// current change for make list view Image Rounded
bmp = getRoundedCornerBitmap(bmp);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
Activity a = (Activity) photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
}

// @Override
// public void run() {
// if(imageViewReused(photoToLoad))
// return;
// Bitmap bmp=getBitmap(photoToLoad.url);
// memoryCache.put(photoToLoad.url, bmp);
// if(imageViewReused(photoToLoad))
// return;
// BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
// Activity a=(Activity)photoToLoad.imageView.getContext();
// a.runOnUiThread(bd);
// }
}

boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
if (tag == null || !tag.equals(photoToLoad.url))
return true;
return false;
}

// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;

public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
photoToLoad = p;
}

public void run()
        {
            if(imageViewReused(photoToLoad))
                return;
            if(bitmap!=null){
            
            
            bitmap = getRoundedCornerBitmap(bitmap);
                photoToLoad.imageView.setImageBitmap(bitmap);
            }
            else{
                photoToLoad.imageView.setImageResource(stub_id);
            }
        }
}

public void clearCache() {
memoryCache.clear();
fileCache.clear();
}

public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);

final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = 12;

paint.setAntiAlias(true);
canvas.drawARGB(10, 10, 10, 10);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);

// =======================

/*
* Path clipPath = new Path(); float radius = 10.0f; float padding =
* radius / 2; int w = bitmap.getWidth(); int h = bitmap.getHeight();
* clipPath.addRoundRect(new RectF(padding, padding, w - padding, h -
* padding), radius, radius, Path.Direction.CW);
* canvas.clipPath(clipPath);
*/

return output;
}

}

================================
Make one class name BitmapWorkerTask 

public class BitmapWorkerTask extends ImageWorker {

int width = 100;
int height = 100;
NotifyImageSet mNotifyImageSet;
NotifyImageBitmap mNotifyImageBitmap;

public BitmapWorkerTask(Context context, NotifyImageSet mImageSet) {
super(context);
// TODO Auto-generated constructor stub
mNotifyImageSet = mImageSet;
}

public BitmapWorkerTask(Context context, NotifyImageBitmap mImageSet) {
super(context);
// TODO Auto-generated constructor stub
mNotifyImageBitmap = mImageSet;
}

public BitmapWorkerTask(Context context, int imageWidth, int ImageHeight) {
super(context);
// TODO Auto-generated constructor stub
width = imageWidth;
height = ImageHeight;

}

public void setWidth(int width) {
this.width = width;
}

public void setHeight(int height) {
this.height = height;
}

@Override
protected Bitmap processBitmap(Object data) {
if(data == null) return null;
// File mFile = new File(data.toString());
//     int size = width < height ? height : width;
   
//     Bitmap mBitmap = Utility.decodeFile(mFile, size);
try {
return BitmapFactory.decodeStream(new FileInputStream(new File(String.valueOf(data))), null, null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return null;
}

public interface NotifyImageSet{
public void notifyImage();
}

public interface NotifyImageBitmap{
public void notifyImage(Bitmap mBitmap);
}


@Override
public void NotifyImage() {
// TODO Auto-generated method stub
if(mNotifyImageSet != null) {
mNotifyImageSet.notifyImage();
}
}

@Override
public void NotifyImageBitmap(Bitmap mBitmap) {
// TODO Auto-generated method stub
if(mNotifyImageBitmap != null) {
mNotifyImageBitmap.notifyImage(mBitmap);
}
}

}


Make one class name  FileCache

public class FileCache {
    
    private File cacheDir;
    
    public FileCache(Context context){
        //Find the dir to save cached images
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"LazyList");
        else
            cacheDir=context.getCacheDir();
        if(!cacheDir.exists())
            cacheDir.mkdirs();
    }
    
    public File getFile(String url){
        //I identify images by hashcode. Not a perfect solution, good for the demo.
        String filename=String.valueOf(url.hashCode());
        //Another possible solution (thanks to grantland)
        //String filename = URLEncoder.encode(url);
        File f = new File(cacheDir, filename);
        return f;
        
    }
    
    public void clear(){
        File[] files=cacheDir.listFiles();
        for(File f:files)
            f.delete();
    }


}



============================
Here is your mail Images listview click

lst.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long arg3) {
// TODO Auto-generated method stub
Long bitpos = parent.getItemIdAtPosition(position);
Intent ibitmap = new Intent(Current activity.this,
next activity.class);
ibitmap.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
ibitmap.putExtra("POSITION",
Integer.parseInt(bitpos.toString()));
startActivity(ibitmap);
}
});

===================
In next activity,

int pos = 0;
ArrayList<String> arrImages = new ArrayList<String>();
private BitmapWorkerTask mImageWorker;
ProgressDialog pbrdialog;
ImageView angleimg;
Button btnprev, btnnext;
public ImageLoader imageLoader;

in oncreate() method 

Intent ibitmap = getIntent();
if (null != ibitmap.getExtras()) {
pos = this.getIntent().getExtras().getInt("POSITION");

}

imageLoader = new ImageLoader(AngleImageLoad.this);
angleimg = (ImageView) findViewById(R.id.imgtouch);
btnnext = (Button) findViewById(R.id.btnright);

btnprev = (Button) findViewById(R.id.btnleft);

mImageWorker = new BitmapWorkerTask(this, new NotifyImageBitmap() {

@Override
public void notifyImage(Bitmap mBitmap) {
// TODO Auto-generated method stub
if(mBitmap != null){
pbrdialog.cancel();
angleimg.setImageBitmap(mBitmap);
}else{
pbrdialog.cancel();
angleimg.setImageResource(R.drawable.defaultprofileimg);
}
}
});
mImageWorker.setWidth(angleimg.getWidth());

mImageWorker.setHeight(angleimg.getHeight());





get image position then make one function to display image in imageview from its position

public void displayImage() {

if (arrImages.get(pos) != null) {
pbrdialog = new ProgressDialog(AngleImageLoad.this);
pbrdialog.setMessage("Loading...");
pbrdialog.show();
mImageWorker.loadImage(arrImages.get(pos), angleimg);
}

}


then on click of next and previous buttons are

public void MyPrevios() {
if (pos > 0) {
pos--;
displayImage();
} else {
Toast.makeText(getApplicationContext(), "First Image", Toast.LENGTH_SHORT).show();
}
}

public void MyNext() {
if (pos < arrImages.size() - 1) {
pos++;
displayImage();
} else {
Toast.makeText(getApplicationContext(), "Last Image", Toast.LENGTH_SHORT)
.show();
}

}

Wednesday 29 January 2014

Create GIF Wallpapaer

Write below code in main xml file

<?xml version="1.0" encoding="utf-8"?>
<wallpaper xmlns:android="http://schemas.android.com/apk/res/android" />

Create raw folder in below res folder and put your GIF file in that raw folder.


Create Service Class in scr folder name MyService and write below code in that service



import java.io.IOException;
import java.io.InputStream;

import android.graphics.Canvas;
import android.graphics.Movie;
import android.os.Handler;
import android.os.SystemClock;
import android.service.wallpaper.WallpaperService;
import android.util.Log;
import android.view.SurfaceHolder;

public class MyService extends WallpaperService {
    static final String TAG = "MyService";
    static final Handler mNyanHandler = new Handler();

    /**
     * @see android.service.wallpaper.WallpaperService#onCreate()
     */
    @Override
    public void onCreate() {
        super.onCreate();
    }

    /**
     * @see android.service.wallpaper.WallpaperService#onCreateEngine()
     */
    @Override
    public Engine onCreateEngine() {
        try {
            return new NyanEngine();
        } catch (IOException e) {
            Log.w(TAG, "Error creating NyanEngine", e);
            stopSelf();
            return null;
        }
    }

    class NyanEngine extends Engine {
        private final Movie mNyan;
        private final int mNyanDuration;
        private final Runnable mNyanNyan;
        float mScaleX;
        float mScaleY;
        int mWhen;
        long mStart;

        NyanEngine() throws IOException {
            InputStream is = getResources().openRawResource(R.raw.christmas);
            if (is != null) {
                try {
                    mNyan = Movie.decodeStream(is);
                    mNyanDuration = mNyan.duration();
                } finally {
                    is.close();
                }
            } else {
                throw new IOException("Unable to open R.raw.nyan");
            }

            mWhen = -1;
            mNyanNyan = new Runnable() {
                public void run() {
                    nyan();
                }
            };
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            mNyanHandler.removeCallbacks(mNyanNyan);
        }

        @Override
        public void onVisibilityChanged(boolean visible) {
            super.onVisibilityChanged(visible);
            if (visible) {
                nyan();
            } else {
                mNyanHandler.removeCallbacks(mNyanNyan);
            }
        }

        @Override
        public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            super.onSurfaceChanged(holder, format, width, height);
            mScaleX = width / (1f * mNyan.width());
            mScaleY = height / (1f * mNyan.height());
            nyan();
        }

        @Override
        public void onOffsetsChanged(float xOffset, float yOffset, float xOffsetStep,
                float yOffsetStep, int xPixelOffset, int yPixelOffset) {
            super.onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep, xPixelOffset, yPixelOffset);
            nyan();
        }

        void nyan() {
            tick();
            SurfaceHolder surfaceHolder = getSurfaceHolder();
            Canvas canvas = null;
            try {
                canvas = surfaceHolder.lockCanvas();
                if (canvas != null) {
                    nyanNyan(canvas);
                }
            } finally {
                if (canvas != null) {
                    surfaceHolder.unlockCanvasAndPost(canvas);
                }
            }
            mNyanHandler.removeCallbacks(mNyanNyan);
            if (isVisible()) {
                mNyanHandler.postDelayed(mNyanNyan, 1000L/25L);
            }
        }

        void tick() {
            if (mWhen == -1L) {
                mWhen = 0;
                mStart = SystemClock.uptimeMillis();
            } else {
                long mDiff = SystemClock.uptimeMillis() - mStart;
                mWhen = (int) (mDiff % mNyanDuration);
            }
        }

        void nyanNyan(Canvas canvas) {
            canvas.save();
            canvas.scale(mScaleX, mScaleY);
            mNyan.setTime(mWhen);
            mNyan.draw(canvas, 0, 0);
            canvas.restore();
        }
    }
}

below is my manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gifwall"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name">
        <service
            android:label="@string/app_name"
            android:name=".MyService"
            android:permission="android.permission.BIND_WALLPAPER">
            <intent-filter>
                <action android:name="android.service.wallpaper.WallpaperService" />
            </intent-filter>
            <meta-data android:name="android.service.wallpaper" android:resource="@layout/main_xml" />
        </service>
    </application>

</manifest>

Find Hours Diffrence in Kotlin

  In Kotlin, determining the difference in hours between two timestamps is a common task, especially in scenarios involving time-based calcu...