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. 




No comments:

Post a Comment

Comments

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...