Sunday, January 13, 2013

Android Contact Picker

We can pick the contacts in android from our phone contact list, to do this we need to follow few steps as follows.

make a new project with the name ContactPicker and with the name of main activity as

ContentPickerTester.java followed by the given code


package jitesh.example.contactpicker;

import jitesh.example.contactpicker.R;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class ContentPickerTester extends Activity {

  public static final int PICK_CONTACT = 1;

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.contentpickertester);

    Button button = (Button)findViewById(R.id.pick_contact_button);
   
    button.setOnClickListener(new OnClickListener() {
     public void onClick(View _view) {
        Intent intent = new Intent(Intent.ACTION_PICK,
                                   Uri.parse("content://contacts/"));
        startActivityForResult(intent, PICK_CONTACT);
      }
    });
  }
 
  @Override
  public void onActivityResult(int reqCode, int resCode, Intent data) {
    super.onActivityResult(reqCode, resCode, data);
       
    switch(reqCode) {
      case (PICK_CONTACT) : {
        if (resCode == Activity.RESULT_OK) {
          Uri contactData = data.getData();
          Cursor c = managedQuery(contactData, null, null, null, null);
          c.moveToFirst();
          String name = c.getString(c.getColumnIndexOrThrow(People.NAME));
          TextView tv = (TextView)findViewById(R.id.selected_contact_textview);
          tv.setText(name);
        }
        break;
      }
    }
  }
}

where contentpickertester.xml should have following layout


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <TextView
    android:id="@+id/selected_contact_textview"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
  />
  <Button
    android:id="@+id/pick_contact_button"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Pick Contact"
  />
</LinearLayout>

make an another ContactPicker.java with the given code


package jitesh.example.contactpicker;

import jitesh.example.contactpicker.R;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemClickListener;

public class ContactPicker extends Activity {
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
   
    Intent intent = getIntent();
    String dataPath = intent.getData().toString();
   
    final Uri data = Uri.parse(dataPath + "people/");
    final Cursor c = managedQuery(data, null, null, null, null);
       
    String[] from = new String[] {People.NAME};
    int[]  to = new int[] { R.id.itemTextView };
       
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
                                                          R.layout.listitemlayout,
                                                          c,
                                                          from,
                                                          to);
    ListView lv = (ListView)findViewById(R.id.contactListView);
    lv.setAdapter(adapter);
    lv.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
        // Move the cursor to the selected item
        c.moveToPosition(pos);
        // Extract the row id.
        int rowId = c.getInt(c.getColumnIndexOrThrow("_id"));
        // Construct the result URI.
        Uri outURI = Uri.parse(data.toString() + rowId);
        Intent outData = new Intent();
        outData.setData(outURI);
        setResult(Activity.RESULT_OK, outData);
        finish();
      }
    });
  }
}

now make a layout file with name main.xml with following code


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <ListView android:id="@+id/contactListView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
  />
</LinearLayout>

and the listitemlayout.xml with the given layout


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <TextView
    android:id="@+id/itemTextView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="10px"
    android:textSize="16px"
    android:textColor="#FFF"
  />
</LinearLayout>

the android manifest should have with the permission to pick the contacts as well . the manifest should look like this



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="jitesh.example.contactpicker"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".ContactPicker"
                  android:label="@string/app_name">
            <intent-filter>
              <action android:name="android.intent.action.PICK"></action>
              <category android:name="android.intent.category.DEFAULT"></category>
              <data android:path="contacts" android:scheme="content"></data>
            </intent-filter>
        </activity>
        <activity android:name=".ContentPickerTester"
                android:label="Contact Picker Test">
          <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
          </intent-filter>
        </activity>
    </application>
    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.READ_CONTACTS"/>
</manifest>





Android Custom TextView and it's use

We can write our custom components in android and we can use them according to our need as well for this purpose we need to follow few simple steps. in this example there is a custom text-view which is used in a custom list as well. please have a close look.

make a new project with some appropriate name and make a main class with name ToDoList.java and copy the following given code to it



package jitesh.example;

import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

public class ToDoList extends Activity {

  /** Called when the activity is first created. */
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Inflate your view
    setContentView(R.layout.main);
      
    // Get references to UI widgets
    ListView myListView = (ListView)findViewById(R.id.myListView);
    final EditText myEditText = (EditText)findViewById(R.id.myEditText);
    
    final ArrayList<String> todoItems = new ArrayList<String>();
    int resID = R.layout.todolist_item;
    final ArrayAdapter<String> aa = new ArrayAdapter<String>(this, resID,
                                                             todoItems);
    myListView.setAdapter(aa);
        
    myEditText.setOnKeyListener(new OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
          if (event.getAction() == KeyEvent.ACTION_DOWN)
            if (keyCode == KeyEvent.KEYCODE_ENTER)
            {
              todoItems.add(0, myEditText.getText().toString());
              aa.notifyDataSetChanged();
              myEditText.setText("");
              return true;
            }
          return false;
        }
      });
  }
}

Now go throug the main.xml and copy the following layout


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <EditText
    android:id="@+id/myEditText"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="New To Do Item"
  />
  <ListView  
    android:id="@+id/myListView"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
  />
</LinearLayout>

after it we need to make a class with name TodoListItemView.java and copy the following code to it

package jitesh.example;


import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TextView;

public class TodoListItemView extends TextView {

  private Paint marginPaint;
  private Paint linePaint;
  private int paperColor;
  private float margin;

  public TodoListItemView (Context context, AttributeSet ats, int ds) {
    super(context, ats, ds);
    init();
  }

  public TodoListItemView (Context context) {
    super(context);
    init();
  }

  public TodoListItemView (Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
  }

  private void init() {
    // Get a reference to our resource table.
    Resources myResources = getResources();

    // Create the paint brushes we will use in the onDraw method.
    marginPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    marginPaint.setColor(myResources.getColor(R.color.notepad_margin));
    linePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    linePaint.setColor(myResources.getColor(R.color.notepad_lines));

    // Get the paper background color and the margin width.
    paperColor = myResources.getColor(R.color.notepad_paper);
    margin = myResources.getDimension(R.dimen.notepad_margin);
  }

  @Override
  public void onDraw(Canvas canvas) {
    // Color as paper
    canvas.drawColor(paperColor);

    // Draw ruled lines
    canvas.drawLine(0, 0, getMeasuredHeight(), 0, linePaint);
    canvas.drawLine(0, getMeasuredHeight(), 
                       getMeasuredWidth(), getMeasuredHeight(), 
                       linePaint);

    // Draw margin
    canvas.drawLine(margin, 0, margin, getMeasuredHeight(), marginPaint);

    // Move the text across from the margin
    canvas.save();
    canvas.translate(margin, 0);

    // Use the TextView to render the text.
    super.onDraw(canvas);
    canvas.restore();
  }
}

the correspondigly use layout is todolist_item.xml where the above custom textview is used.


<?xml version="1.0" encoding="utf-8"?>
<jitesh.example.TodoListItemView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:padding="10dp"
  android:scrollbars="vertical"
  android:textColor="@color/notepad_text"
  android:fadingEdge="vertical"
/>

inside the values folder under res make a new colors.xml and write the following values there


<?xml version="1.0" encoding="utf-8"?>
<resources>
  <color name="notepad_paper">#C23838</color>
  <color name="notepad_lines">#4338C2</color>
  <color name="notepad_margin">#164E4A</color>
  <color name="notepad_text">#4D1810</color>
</resources>

in same way make another dimens.xml with following


<?xml version="1.0" encoding="utf-8"?>
<resources> 
  <dimen name="notepad_margin">100dp</dimen> 
</resources>







Thursday, January 10, 2013

Android message passing between activities

Make a project with the name MessagePassingBetweenActivities

1)create main class as CallingActivity.java and copy following code to it


package jitesh.example.messagepassingbetweenactivities;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class CallingActivity extends Activity {
   
    public static final int CALLED_ACTIVITY = 1;
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button nextActivity = (Button) findViewById(R.id.button1);
        nextActivity.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                Intent intent = new Intent(CallingActivity.this, CalledActivity.class);
                Bundle b = new Bundle();

                EditText firstName = (EditText) findViewById(R.id.firstName);
                EditText lastName = (EditText) findViewById(R.id.lastName);
                EditText age = (EditText) findViewById(R.id.age);

                b.putString("firstName", firstName.getText().toString());
                b.putString("lastName", lastName.getText().toString());
                b.putInt("age", Integer.parseInt(age.getText().toString()));
               
                //Add the set of extended data to the intent and start it
                intent.putExtras(b);
                startActivityForResult(intent,CALLED_ACTIVITY);
            }
        });
    }
   
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        switch(requestCode) {
        case CALLED_ACTIVITY:
            if (resultCode == RESULT_OK) {
               
                Bundle bundle = data.getExtras();
               
                EditText firstName = (EditText) findViewById(R.id.firstName);
                firstName.setText(bundle.getString("firstName"));
                EditText lastName = (EditText) findViewById(R.id.lastName);
                lastName.setText(bundle.getString("lastName"));
                EditText age = (EditText) findViewById(R.id.age);
                age.setText(Integer.toString(bundle.getInt("age")));
                break;
            }
        }

    }
}

2) the main.xml should look like this


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center|top"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="25dip"
            android:gravity="center"
            android:text="Calling Activity"
            android:textSize="24.5sp" />

        <TableLayout
            android:id="@+id/tableLayout1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:stretchColumns="1" >

            <TableRow
                android:id="@+id/tableRow1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

                <TextView
                    android:id="@+id/textView2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="First Name" />

                <EditText
                    android:id="@+id/firstName"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />
            </TableRow>

            <TableRow
                android:id="@+id/tableRow2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

                <TextView
                    android:id="@+id/textView3"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Last Name" />

                <EditText
                    android:id="@+id/lastName"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />
            </TableRow>

            <TableRow
                android:id="@+id/tableRow3"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

                <TextView
                    android:id="@+id/textView4"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Age" />

                <EditText
                    android:id="@+id/age"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="number" />
            </TableRow>
        </TableLayout>

        <Button
            android:id="@+id/button1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Call Next Activity" />
    </LinearLayout>

</LinearLayout>

3) make a java class with name CalledActivity.java and copy the given code to it


package jitesh.example.messagepassingbetweenactivities;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class CalledActivity extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.another);
        getParameters();
       
        Button nextActivity = (Button) findViewById(R.id.button1);
        nextActivity.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                Bundle b = new Bundle();
                EditText firstName = (EditText) findViewById(R.id.firstName2);
                EditText lastName = (EditText) findViewById(R.id.lastName2);
                EditText age = (EditText) findViewById(R.id.age2);

                b.putString("firstName", firstName.getText().toString());
                b.putString("lastName", lastName.getText().toString());
                b.putInt("age", Integer.parseInt(age.getText().toString()));
               
                //Add the set of extended data to the intent and start it
                Intent intent = new Intent();
                intent.putExtras(b);
                setResult(RESULT_OK,intent);      
                finish();
            }
        });
    }

    public void getParameters() {

        if (CalledActivity.this.getIntent().getExtras() != null)
        {
            Bundle bundle = this.getIntent().getExtras();
           
            EditText firstName = (EditText) findViewById(R.id.firstName2);
            firstName.setText(bundle.getString("firstName"));
            EditText lastName = (EditText) findViewById(R.id.lastName2);
            lastName.setText(bundle.getString("lastName"));
            EditText age = (EditText) findViewById(R.id.age2);
            age.setText(Integer.toString(bundle.getInt("age")));
        }

    }

}

4)make another.xml and should look like this layout


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

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center|top"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView8"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="25dip"
            android:gravity="center"
            android:text="Called Activity"
            android:textSize="24.5sp" />

        <TableLayout
            android:id="@+id/tableLayout2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:stretchColumns="1" >

            <TableRow
                android:id="@+id/tableRow1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

                <TextView
                    android:id="@+id/textView5"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="First Name" />

                <EditText
                    android:id="@+id/firstName2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />
            </TableRow>

            <TableRow
                android:id="@+id/tableRow2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

                <TextView
                    android:id="@+id/textView6"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Last Name" />

                <EditText
                    android:id="@+id/lastName2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />
            </TableRow>

            <TableRow
                android:id="@+id/tableRow3"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

                <TextView
                    android:id="@+id/textView7"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Age" />

                <EditText
                    android:id="@+id/age2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="number" />
            </TableRow>
        </TableLayout>

        <Button
            android:id="@+id/button1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Back to Previous Activity" >
        </Button>
    </LinearLayout>

</LinearLayout>

do not forget to register the activity CalledActivity at manifest. use the given line there!!


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="jitesh.example.messagepassingbetweenactivities"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".CallingActivity"
            android:label="@string/title_activity_calling" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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







Android using external database

we can use external databse in our applications.


If we want to use a SQLite database in Android, you can use the procedure described in the Storage page.
 This example performs the following operations:
  • Copy
  • Open
  • Select
  • Insert
  • Close
Note : Database facts:
  • Don't forget to add the android_metadata table in your SQLite database! :)
make a new project with name ExternalDataBase and a mainactivity with name  ExternalDBActivity.java, copy the following given code to it

package use.jitesh.externaldb;

import java.io.IOException;




import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class ExternalDBActivity extends Activity {
private static final String TAG = "ExtDB";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView contentLog = (TextView) findViewById(R.id.content_log);

// Create the database
DataBaseHelper myDbHelper = new DataBaseHelper(
this.getApplicationContext());
myDbHelper = new DataBaseHelper(this);

try {
myDbHelper.createDataBase();
contentLog.append("Database Created\n");
} catch (IOException ioe) {
throw new Error("Unable to create database");
}

// Open the database
try {

myDbHelper.openDataBase();
contentLog.append("Database Opened\n");
} catch (SQLException sqle) {
sqle.printStackTrace();
}

// Get the readable version
SQLiteDatabase db = myDbHelper.getReadableDatabase();
contentLog.append("Get the readable database\n");

// Make a select
Cursor cur = db.rawQuery(
"SELECT name FROM serval_developers ORDER BY name ASC;", null);

cur.moveToPosition(0);
Log.v(TAG, "Nb Col:" + cur.getColumnCount());
Log.v(TAG, "Nb Records:" + cur.getCount());
cur.close();
contentLog.append("Select:\t" + cur.getColumnCount() + " cols, "
+ cur.getCount() + " rows\n");

// Make an insert
ContentValues values = new ContentValues();
values.put("name", "Jitesh");
values.put("surname", "Upadhyay");
long servalCatID = db.insert("serval_developers", null, values);
Log.v(TAG, "Serval Cat Inserted @: " + servalCatID);
contentLog.append("Insert @ \t" + servalCatID + "\n");

// Check insert
cur = db.rawQuery(
"SELECT name FROM serval_developers ORDER BY name ASC;", null);

cur.moveToPosition(0);
Log.v(TAG, "Nb Col:" + cur.getColumnCount());
Log.v(TAG, "Nb Records:" + cur.getCount());
cur.close();
contentLog.append("Select:\t" + cur.getColumnCount() + " cols, "
+ cur.getCount() + " rows\n");

// dumb
cur = db.rawQuery(
"SELECT name, surname FROM serval_developers ORDER BY name ASC;",
null);
contentLog.append("\nDUMP\n");
int i = 0;
cur.moveToFirst();
while (cur.isAfterLast() == false) {
contentLog.append("(" + i++ + ")\t\t" + cur.getString(0) + "\t"
+ cur.getString(1) + "\n");
cur.moveToNext();
}

cur.moveToPosition(0);

// Close
myDbHelper.close();
contentLog.append("Database closed.");

// YEAH
}
}

make a java class with name DataBaseHelper.java and copy following code to it

package use.jitesh.externaldb;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseHelper extends SQLiteOpenHelper{
 
    private static String DB_PATH = "/data/data/use.jitesh.externaldb/databases/";
 
    private static String DB_NAME = "db.sqlite3";
 
    private SQLiteDatabase myDataBase; 
 
    private final Context myContext;
 
    /**
     * Constructor
     * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
     * @param context
     */
    public DataBaseHelper(Context context) {
 
    super(context, DB_NAME, null, 1);
        this.myContext = context;
    }
 
  /**
     * Creates a empty database on the system and rewrites it with your own database.
     * */
    public void createDataBase() throws IOException{
 
    boolean dbExist = checkDataBase();
 
    if(dbExist){
    //do nothing - database already exist
    }else{
 
    //By calling this method and empty database will be created into the default system path
               //of your application so we are gonna be able to overwrite that database with our database.
        this.getReadableDatabase();
 
        try {

    copyDataBase();
 
    } catch (IOException e) {
 
        throw new Error("Error copying database");
 
        }
    }
 
    }
 
    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase(){
 
    SQLiteDatabase checkDB = null;
 
    try{
    String myPath = DB_PATH + DB_NAME;
    checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
 
    }catch(SQLiteException e){
 
    //database does't exist yet.
 
    }
 
    if(checkDB != null){
 
    checkDB.close();
 
    }
 
    return checkDB != null ? true : false;
    }
 
    /* (non-Javadoc)
* @see android.database.sqlite.SQLiteOpenHelper#getReadableDatabase()
*/
@Override
public synchronized SQLiteDatabase getReadableDatabase() {
return super.getReadableDatabase();
}

/**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     * */
    private void copyDataBase() throws IOException{
 
    //Open your local db as the input stream
    InputStream myInput = myContext.getAssets().open(DB_NAME);
 
    // Path to the just created empty db
    String outFileName = DB_PATH + DB_NAME;
 
    //Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);
 
    //transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0){
    myOutput.write(buffer, 0, length);
    }
 
    //Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();
 
    }
 
    public void openDataBase() throws SQLException{
 
    //Open the database
        String myPath = DB_PATH + DB_NAME;
    myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY|SQLiteDatabase.NO_LOCALIZED_COLLATORS);
 
    }
 
    @Override
public synchronized void close() {
 
       if(myDataBase != null)
       myDataBase.close();
 
       super.close();
 
}
 
@Override
public void onCreate(SQLiteDatabase db) {
 
}
 
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 
}
 
        // Add your public helper methods to access and get content from the database.
       // You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
       // to you to create adapters for your views.
 
}

the main.xml layout should have following layout 

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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/op_log" >
    </TextView>

    <TextView
        android:id="@+id/content_log"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" >
    </TextView>

</LinearLayout>

it is omportant to put a an sqlite file with the name "db.sqlite3" and it should have following structure as in given images/screenshots





Thursday, January 3, 2013

Android Speech To Text

make a project with name SpeechToTextDemo and a main activity with the name MainActivity and copy the following code to it


import java.util.ArrayList;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

protected static final int RESULT_SPEECH = 1;

private ImageButton btnSpeak;
private TextView txtText;

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

txtText = (TextView) findViewById(R.id.txtText);

btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);

btnSpeak.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {

Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);

intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");

try {
startActivityForResult(intent, RESULT_SPEECH);
txtText.setText("i love you");
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(),
"Ops! Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT);
t.show();
}
}
});

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

switch (requestCode) {
case RESULT_SPEECH: {
if (resultCode == RESULT_OK && null != data) {

ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

txtText.setText(text.get(0));
}
break;
}

}
}
}

activity_main.xml is the layout where you need to copy the following layout to it

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/textView1"
    android:layout_toLeftOf="@+id/textView1"
    android:gravity="center"
    android:orientation="vertical" >

    <ImageButton
        android:id="@+id/btnSpeak"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:contentDescription="@string/speak"
        android:src="@android:drawable/ic_btn_speak_now" />

    <TextView
        android:id="@+id/txtText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

Android Text To Speech(TTS)

In this blog the TTS is discussed as it is always nice to use TTS in android . we just need to follow few steps.
 make a new project with name AndroidTextToSpeech and a main activity with the name AndroidTextToSpeechActivity.java and a layout as main.xml

1) copy the following code to yours AndroidTextToSpeechActivity.java


import java.util.Locale;

import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class AndroidTextToSpeechActivity extends Activity implements
TextToSpeech.OnInitListener {
/** Called when the activity is first created. */

private TextToSpeech tts;
private Button btnSpeak;
private EditText txtText;

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

tts = new TextToSpeech(this, this);

btnSpeak = (Button) findViewById(R.id.btnSpeak);

txtText = (EditText) findViewById(R.id.txtText);

// button on click event
btnSpeak.setOnClickListener(new View.OnClickListener() {

public void onClick(View arg0) {
speakOut();
}

});
}

@Override
public void onDestroy() {
// Don't forget to shutdown!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}

public void onInit(int status) {
// TODO Auto-generated method stub

if (status == TextToSpeech.SUCCESS) {

int result = tts.setLanguage(Locale.US);

// tts.setPitch(5); // set pitch level

// tts.setSpeechRate(2); // set speech speed rate

if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "oops it is not supported");
} else {
btnSpeak.setEnabled(true);
speakOut();
}

} else {
Log.e("TTS", "Initilization Failed");
}

}

private void speakOut() {

String text = txtText.getText().toString();

tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}

2) and now in this step you need to make a layout as follows at main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="#044372">
   
<TextView android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Text To Speech (TTS)"
    android:padding="15dip"
    android:textColor="#ffffff"
    android:textSize="26dip"
    android:gravity="center"
    android:textStyle="bold"/>

    <EditText android:id="@+id/txtText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="Enter your text here"
        android:layout_marginTop="20dip"      
        android:layout_margin="10dip"/>
   
    <Button android:id="@+id/btnSpeak"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Text to Speech"
        android:layout_margin="10dip"/>

</LinearLayout>

3) run the program  at emulator/device and you can see the output