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"/>

      

Thursday, May 31, 2012

Return result back to main Activity using SharedPreference android Example

These is second method (first is already discuss in previous post) to get result from call activity.

In this example I am use SharedPreferences to retrieve result from called activity.

This method is also used to get result from anywhere in application.
You can set result from any activity and get it from any activity.

Here is complete example of SharedPreferences and how to return result from called activity to main activity.

1.  Create main activity and call new activity using startActivityForResult
     
   
public class SharedPreferenceActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        Button btnGetResult=(Button) findViewById(R.id.btnResult);
       
        final Intent intent=new Intent(this,SecondActivity.class);
       
       
       
        btnGetResult.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
                startActivityForResult(intent, 1);    // call new activity
               
            }
        });
       
    }
   
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
           
            SharedPreferences myPreferences=getSharedPreferences("MYPREF",    Activity.MODE_PRIVATE);    // get preference created in called activity.
           
            String str=myPreferences.getString("STR", "empty");    //here STR is variable name same as secondActivity
           
            TextView tv=(TextView) findViewById(R.id.tvShow);
           
            tv.setText(str);
       
    }
}


2.   SecondActivity set result in SharedPreferences

     public class SecondActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.secondlayout);
       
        final SharedPreferences myPreference=getSharedPreferences("MYPREF", Activity.MODE_PRIVATE);
       
        Button btnOk=(Button) findViewById(R.id.btnOk);
        btnOk.setOnClickListener(new OnClickListener() {
          
            @Override
            public void onClick(View v) {
                EditText etText=(EditText) findViewById(R.id.etText);
                String str=etText.getText().toString();
      
                              
                SharedPreferences.Editor editor=myPreference.edit();
          
                editor.putString("STR", str);  // put value in preference
                editor.commit();   // it is must if not commit preference then it not save.
              
                finish();    // finishes current activity
            }
        });
    }
}


3.  Register second activity in AndroidManifest.xml

       <activity android:name="SecondActivity"></activity>

Return Result back to main Activity Android example

To receive result back from called activity you can use startActivityForResult() instead of startActivity() it override onActivityResult() to receive result.

Here is complete example of how to retrieve result from calling activity.

1.  Create class from which you want to start new activity.
     
    public class SetResultActivity extends Activity {
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        Button btnGetResult=(Button) findViewById(R.id.btnResult);
       
        final Intent intent=new Intent(this,SecondActivity.class);
       
        btnGetResult.setOnClickListener(new OnClickListener() {
          
            @Override
            public void onClick(View v) {
                startActivityForResult(intent, 1);    // call new activity
              
            }
        });
       
       
    }
   
    // these method call when called activity finished.


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
      
   
        if(resultCode==1)           // check result code set in secondActivity that is 1
        {
          
            String str=data.getStringExtra("STR");
          
            TextView tv=(TextView) findViewById(R.id.tvShow);
          
            tv.setText(str);
        }
        else
            Log.i("Result", "not Receive");
    }

}



2.    Create second Activity from which you want to receive result.

        public class SecondActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.secondlayout);
       
        final Intent intent=new Intent();
       
        Button btnOk=(Button) findViewById(R.id.btnOk);
        btnOk.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
                EditText etText=(EditText) findViewById(R.id.etText);
                String str=etText.getText().toString();
       
                               
                intent.putExtra("STR", str);    // set value in intent
               
                setResult(1,intent);    // set result here 1 is result code used in when    //we  return multiple result back to main activity
 
                finish();    // finishes current activity
            }
        });
    }
}


3. Register secondActivity in AndroidManifest.xml

       <activity android:name="SecondActivity"></activity>

Starting New Activity from another activity

If you want to start new activity from existing activity then follow following steps:

1.   right-click on package in which you want to create new activity then after select new -> class -> enter class name -> finish

It create new class on your package as show below.

          public class SecondActivity {

          }

2.  Extend Activity class

public class SecondActivity extends Activity {


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

      }
}

3. Register newly created activity in your AndroidManifest.xml

           <activity  android:label="Test"
            android:name=".SecondActivity" >
        </activity>

4.  in main activity from you want to start new activity write following code

        - Create intent
                Intent intent=new Intent(this,SecondActivity.class);
       - start Activity
                 startActivity(intent);