Friday, June 29, 2012

Create Database

These are many way to create database in android application.
When your application install only that time database is created and it deleted when you remove your application from device.

For this you need know about SQLiteOpenHelper.

Here is small demo of how to create database and how to use it.

1.  Create class that extends SQLiteOpenHelper class in that create sub-class of table data that you need in onCreate() method you write code for table creation.

public class Database extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "database.db";
    private static final int DATABASE_VERSION = 1;
    SQLiteDatabase sqlitedatabase = null;

    public Database(Context context) {

        super(context, DATABASE_NAME, null, DATABASE_VERSION);

    }

    public static final class EMP {
        public final static String TABLE_NAME = "employee";

        public final static String _ID = "_id";
        public final static String NAME = "emp_name";

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        sqlitedatabase = db;

        sqlitedatabase.execSQL("create table " + EMP.TABLE_NAME + "(" + EMP._ID
                + " Integer primary key autoincrement," + EMP.NAME + " text);");
    }

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

    }
}



2. Create class that contains all the function that you will use in your application.

public class DatabaseFunction {
    SQLiteDatabase db = null;
    Database database;

    DatabaseFunction(Context context) {
        database = new Database(context);
        db = database.getWritableDatabase();

    }

    public long insertData(String name)
    {
        ContentValues cv = new ContentValues();
        cv.put(EMP.NAME    , name);
        return db.insert(EMP.TABLE_NAME, null, cv);
    }
   
    public int deleteData(String name)
    {
        return db.delete(EMP.TABLE_NAME, EMP.NAME+"=?", new String[]{name});
    }
   
    public int updateDate(String oldName, String newName)
    {
        ContentValues cv =new ContentValues();
        cv.put(EMP.NAME, newName);
        return db.update(EMP.TABLE_NAME, cv, EMP.NAME+"=?", new String[]{oldName});
    }
    public Cursor selectFromEmp() {
        return db.query(EMP.TABLE_NAME, null, null, null, null, null, null);
    }

    // close SQLiteDatabase object it must
    public void close() {
        db.close();
    }

}

3. How to use above database in your application
    Create object of DatabaseFunction class that contains your function that you want to use in your application

using object of DatabaseFunction call appropriate method.


public class EmpActivity extends Activity{

@Override
    protected void onCreate(Bundle savedInstanceState) {
   
        super.onCreate(savedInstanceState);
        setContentView(R.layout.emp);
        DatabaseFunction df=new DatabaseFunction(getApplicationContext()) ;
       
        String name = "abc";
        df.insertData(name);
        Cursor c=df. selectFromEmp();
        // perform any operation on cursor
        if( c!=null && c.getCount()>0)
        {
            c.moveToFirst();
            String nm = c.getString(c.getColumnIndex(EMP.NAME));
            Log.i("Name", nm);
        }
//         then close cursor object first
       c.close();
      
       String newName = "xyz";
      
       // for updating table
       df.updateDate("abc", newName);
       c=df. selectFromEmp();
       // display updated values from cursor
       if( c!=null && c.getCount()>0)
       {
           c.moveToFirst();
           String nm = c.getString(c.getColumnIndex(EMP.NAME));
           Log.i("Name", nm);
       }
      
       // delete value from table
       df.deleteData(newName);
      
//     then close DatabaseFunction object
       df.close();
    }

}

Thank you for referring my blog.
Please write comment for any suggestion and improvement for writing blog.






Saturday, June 2, 2012

Save Activity state example in Android

In some application it is needed to store activity state/data. If this data not store before activity finishes it loss the data. So before finishing activity you need to store data somewhere from where you can get it back when activity restarted.

There are many way to store activity state but here I am uses of SharePreferences. It uses because it easy to manage to user.

Here is complete example of save state of activity.

----------------------------------------------------------------------------------------------

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;

public class SavingActivityStateActivity extends Activity {
   
   
    @Override
    protected void onDestroy() {
        saveState();
        super.onDestroy();
    }

    EditText etName;
    EditText etAddress;
    EditText etEmail;
    EditText etPno;
   
    RadioGroup rgGender;
    CheckBox chbsingle;
    Spinner spEdu;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        loadUI();    // it load previously saved data if any data stored in preference.
     
    }
  
// load data from saved preference.
    private void loadUI() {
       
        SharedPreferences savedPref=getPreferences(MODE_PRIVATE);
       
        setEditText(R.id.etName,  savedPref.getString("Name", ""));
        setEditText(R.id.etAddress,  savedPref.getString("Address", ""));
        setEditText(R.id.etEmail,  savedPref.getString("Email", ""));
        setEditText(R.id.etPno,  savedPref.getString("Pno", ""));
       
        String gender=savedPref.getString("Gender", "Male");
       

        rgGender=(RadioGroup) findViewById(R.id.rgGender);
       
        if(gender.equals("Male"))
        {
            RadioButton rbMale=(RadioButton) findViewById(R.id.rbMale);
            rbMale.setChecked(true);
        }
        else if(gender.equals("Female"))
        {
            RadioButton rbFemale=(RadioButton) findViewById(R.id.rbFemale);
            rbFemale.setChecked(true);
        }
       
        boolean single=savedPref.getBoolean("Single", true);
        chbsingle=(CheckBox) findViewById(R.id.chbSingle);
       
        chbsingle.setChecked(single);
       
        spEdu=(Spinner) findViewById(R.id.spEducation);
        int edu=savedPref.getInt("Edu", 0);
        spEdu.setSelection(edu);
       
    }

    @Override
    protected void onPause() {
   
        super.onPause();
        // before finishing activity data of each field is store to preference using this method.
        saveState();
    }

    // save data to preference
    private void saveState() {
        SharedPreferences savePref=getPreferences(MODE_PRIVATE);
        // create preference

        SharedPreferences.Editor editor=savePref.edit();
        // create editor of preference to edit


        // following code save each value of view to share preference       
        editor.putString("Name",getEditText(R.id.etName));
        editor.putString("Address",getEditText(R.id.etAddress));
        editor.putString("Email",getEditText(R.id.etEmail));
        editor.putString("Pno",getEditText(R.id.etPno));
       
        rgGender=(RadioGroup) findViewById(R.id.rgGender);
        int selected=rgGender.getCheckedRadioButtonId();
       
        RadioButton rbSelected=(RadioButton) findViewById(selected);
        String gender=rbSelected.getText().toString();
   

        editor.putString("Gender", gender);
       
        chbsingle=(CheckBox) findViewById(R.id.chbSingle);
       
        boolean single=chbsingle.isChecked();
       
        editor.putBoolean("Single", single);
       
        spEdu=(Spinner) findViewById(R.id.spEducation);
       
        int edu=spEdu.getSelectedItemPosition();
       
        editor.putInt("Edu", edu);
        editor.commit();
    }

    private String getEditText(int id)
    {
        String text="";
       
        EditText et=(EditText) findViewById(id);
        text=et.getText().toString();
        return text;
    }
   
   
    private void setEditText(int id, String text)
    {   
        EditText et=(EditText) findViewById(id);
        et.setText(text);
    }
}

Friday, June 1, 2012

Video Recording example in Android

Here is complete example of how to record video in android device.
(Note: test project in real device not in emulator)

1.  Video View Activity
   
     
import java.io.File;
import java.io.IOException;
import java.util.Date;
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.Menu;
import android.view.SurfaceView;
import android.widget.Toast;

public class VideoViewActivity extends Activity implements Callback {

    @Override
    protected void onDestroy() {
        stopRecording();
        super.onDestroy();
    }

    private SurfaceHolder surfaceHolder;
    private SurfaceView surfaceView;
    public MediaRecorder mrec = new MediaRecorder();   
    private Camera mCamera;


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

        surfaceView = (SurfaceView) findViewById(R.id.surface_camera);
        mCamera = Camera.open();
       
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
               
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {

        menu.add(0, 0, 0, "Start");
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        if(item.getTitle().equals("Start"))
        {
            try {
               
                startRecording();
                item.setTitle("Stop");

            } catch (Exception e) {

                String message = e.getMessage();
                Log.i(null, "Problem " + message);
                mrec.release();
            }

        }
        else if(item.getTitle().equals("Stop"))
        {
            mrec.stop();
            mrec.release();
            mrec = null;
            item.setTitle("Start");
        }

        return super.onOptionsItemSelected(item);
    }

    protected void startRecording() throws IOException
    {
        if(mCamera==null)
            mCamera = Camera.open();
       
         String filename;
         String path;
       
         path= Environment.getExternalStorageDirectory().getAbsolutePath().toString();
        
         Date date=new Date();
         filename="/rec"+date.toString().replace(" ", "_").replace(":", "_")+".mp4";
        
         //create empty file it must use
         File file=new File(path,filename);
        
        mrec = new MediaRecorder();

        mCamera.lock();
        mCamera.unlock();

        // Please maintain sequence of following code.

        // If you change sequence it will not work.
        mrec.setCamera(mCamera);   
        mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        mrec.setAudioSource(MediaRecorder.AudioSource.MIC);    
        mrec.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mrec.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
        mrec.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mrec.setPreviewDisplay(surfaceHolder.getSurface());
        mrec.setOutputFile(path+filename);
        mrec.prepare();
        mrec.start();

       
    }

    protected void stopRecording() {

        if(mrec!=null)
        {
            mrec.stop();
            mrec.release();
            mCamera.release();
            mCamera.lock();
        }
    }

    private void releaseMediaRecorder() {

        if (mrec != null) {
            mrec.reset(); // clear recorder configuration
            mrec.release(); // release the recorder object
        }
    }

    private void releaseCamera() {
        if (mCamera != null) {
            mCamera.release(); // release the camera for other applications
            mCamera = null;
        }

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,int height) {     

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {      

        if (mCamera != null) {
            Parameters params = mCamera.getParameters();
            mCamera.setParameters(params);
            Log.i("Surface", "Created");
        }
        else {
            Toast.makeText(getApplicationContext(), "Camera not available!",
                    Toast.LENGTH_LONG).show();

            finish();
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        mCamera.stopPreview();
        mCamera.release();      

    }
}




2. main.xml file


      
         <SurfaceView android:id="@+id/surface_camera"     xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerInParent="true"
        android:layout_weight="1"
        >
    </SurfaceView>






3.  Get following permission in AndroidManifest.xml

  
      <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>