Wednesday, October 26, 2011

Using Sqlite database in android

To quote from the website of sqlite
"SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactionalSQL database engine."
It is small database which an android programmer can use conveniently in his/her program.

Let us learn how to use sqlite database in steps.

Opening database : openOrCreateDatabase fuction can be used to open an existing db or create a new one if it does not exist.
SQLiteDatabase mydb;
mydb = mContext.openOrCreateDatabase("mysqdb",
SQLiteDatabase.OPEN_READWRITE, null);

 First parameter is name of database and second one is mode of opening the file. Third parameter if present will be cursorfactory which is used to allow sub classes of cursor to be returned from a query. You can even use openDatabase function. On success the db is returned. The function throws SqliteException if there is error.

Next let us try to create a table with 3 fields - id, name and salary. We need to have a string which stores the create table sql statement.
String sqlStatement = "create table if not exists  nameSal" +  
"(_id Integer PRIMARY KEY AUTOINCREMENT ,Name text, salary Integer)";
mydb.execSQL(sqlStatement);

Note that _id field is made primary key as well as auto increment which will ensure each row gets unique _id automatically.
if not exists clause ensures that if the table is already present, there will not be any error. And the function call just returns.

execSQL will execute the SQL statement and creates the table.

Next let us see, how to add records to the table. To add records to the table, you can use contentValues and insert statement.
ContentValues v=new ContentValues();
 v.put("name", "Anil");
 v.put("salary", 24000);  
 mydb.insert("nameSal" , null, v);

You store key-value pairs in contentValues and then use insert function which takes table name as first parameter, nullColumnhack as second parameter and contentValue as third parameter.

Next let us consider how to extract data from our table. A query function can be used for this purpose. Query will return a cursor.
mCursor = mydb.query(nameSal, null, null, null, null,
null, null);


Here first argument is the table name to query.
Second argument is the column list to return- if null all columns are returnred
Third argument is selection like where clause in select statement excluding where
Fourth argument are the values to be filled for ? in selection 
Fifth argument is group by clause 
sixth argument is having clause which denotes which row groups to be returned
seventh argument is order by column
eighth argument is maximum number of columns to be returned


Let us look at another example using query
Cursor c = mydb.query("nameSal",new String[]{"name","salary"},
"salary > 26000",
null,
null,null,
"salary ASC ",null);
Here the query will return the columns name and salary given by second argument, where salary is greater than 26000 (the condition is given by 3rd argument). The rows returned will be arranged in ascending order of salary(7th argument).

Once we get the cursor, we can iterate through the rows using loop. Look at the example below.
c.moveToFirst();
do{ String name = c.getString(0); int salary = c.getInt(1); Toast.makeText(this, "name is "+name+" salary is "+salary, 2000).show(); }while(c.moveToNext());
c.moveToNext method will return false when the end is reached.

Saturday, October 1, 2011

Using multiselect list with a dialog

AlertDialog is a versatile dialog. It can be used even for displaying a list where multiple values can be checked.

First you create a alertdialog.
AlertDialog.Builder  d = new AlertDialog.Builder(yourcontext);


Next you create the array which holds the items to be displayed

 String elements [] = {"Burger","Pizza","Cake","Coke","Fruits"};


Next you add multichoiceitems to the dialog

d.setMultiChoiceItems(elements, null , new OnMultiChoiceClickListener() {
 @Override
 public void onClick(DialogInterface dialog, int which, boolean isChecked) {
       if(isChecked){
          String str = elements[which];
          Toast.makeText(youractivity.this,
                    "you have selected"+str,
                     Toast.LENGTH_LONG).show();
        }
   }
 });
d.setPositiveButton("Save", new OnClickListener() {
   @Override
   public void onClick(DialogInterface dialog, int which) {
yourOnClickMethod();
   }
});
d.show();
Now our dialog looks something like this





 The second parameter to setMultiChoiceItems is a boolean array, which will have true for all items which must be checked. If you do not want any to be checked, it can be null as we have used.
e.g
boolean selected[]= {true,false,false,true,true};
d.setMultiChoiceItems(elements,selected,
new OnMultiChoiceClickListener(){
                    --------
                    -------
});
With this modification, initially first, fourth and fifth items will be checked.

 

Saturday, September 17, 2011

Threads and Handlers

Newbies in Android face difficulty with communicating between different threads.

It is better to create a new background thread instead of delaying the UI thread when there is lengthy task.
Let us say you want to read an html file. If you read this file in UI thread, the program appears to be unresponsive. Hence it is better to read the file in a background thread.
But when this reading is completed, how do you show the html in a webview in this example? The background threads can not access the ui widgets. Hence there is a need to communicate between ui thread and background thread.
This can be done with Handlers. Handlers are used to send and process messages. A handler created in  a thread, can process all the messages sent by this thread.



You should create a handler class for processing messages


private class MyHandler extends Handler{
@Override
public void handleMessage(Message msg) {  
 
if(msg.getData().getString("message").equals("your message here")){
Toast.makeText(ShowPage.this, "your toast here...", Toast.LENGTH_LONG).show();
}
}
    
    }

Next  initialize an object of this MyHandler class in onCreate

class MyActivity extends Activity
{
    MyHandler mHandler;
//more variables here
//


public void onCreate(Bundle b){
            //some code here
            mHandler = new MyHandler();
            //
}


Let us say I create a thread to write to a file

Thread th = new Thread(){
        public void run(){
            //here goes my lengthy
            //processing statements
            ------


           //processing completed
           Message msg = new Message();
           Bundle b = new Bundle();
                           b.putString("message", "your message here");//key and value
           msg.setData(b); 
                           mHandler.sendMessage(msg);//inform that thread is completed
}
}//my thread ends here


At the end, I should create a message object and write the string to it. Then send this message to the handler.
Handler has handleMessage method which checks at the string and if it is matching, takes appropriate action.

That's all.  Our thread with handler is ready to go.




Thursday, September 15, 2011

Kannada/ Hindi/Marathi keyboard for Android

Many of you might be wondering how to type kannada in your android phone.  I have developed and published an app in android market which is kannda Input Method Editor.  Here is the link.  You install the apk and then you enable the keyboard. During typing, make sure you select kannada input method.
In fact my app supports Devanagari font also. So those of you who want to type in Hindi/marathi can use the app.
Please leave your comments and help me in improving it.



Saturday, September 10, 2011

Orientation change in android

Many times you want to have a different layout for landscape view and another one for portrait view.

The simplest way to achieve this is

1> create folder    /res/layout-land
2> in this folder store your layout xml file for landscape view
3> The xml file name must be same for both portrait and landscape orientations

That's it. Now if the user rotates his screen, automatically the landscape layout will be used


And when user changes orientation, the activity restarts. If you do not want that to happen

Add this line to manifest file

<activity
android:configChanges="orientation|keyboardHidden"
--
>

Now the activity will not restart if the orientation is changed.


Saturday, August 6, 2011

How to install custom (kannada e.g.) font in your Samsung phone

I was struggling to install the kannada font in my Samsung galaxy 551 since 3-4 days and today I finally succeeded.

First and foremost, you need to root your android phone. Rooting means you should get super user access. Without superuser access, you can not copy your ttf file to /systems/fonts folder.

There are many free apps available to root your android phone. The one I used is,  SuperOneClick. You should download and unzip the program to your pc. And then connect your android phone with usb cable.  Enable usb debugging mode.  Then start SuperOneClick.exe  and click on the root button. The program will root your phone.
For more detailed instruction on how to install superoneclick please go through this link 
I suspect, once rooted, the phone needs to be rebooted again.
You can be sure if you are rooted if when you type su in terminal on phone , superoneclick will ask your permission for root access to terminal program.

Next your terminal will show # instead of $

Next set of commands can be given from terminal emulator or adb on your computer.


Next you need to remount /system folder in read write mode.





mount -o remount /dev/mtdblock4 /system
mount -o remount /dev/mmcblk0 /sdcard

Next backup your DroidSansFallback.ttf

cd /system/fonts
cp DroidSansFallback.ttf /sdcard
Delete this file
rm DroidSansFallback.ttf
Now copy your kannada/required font file to DroidSansFallback.ttf. I have used Sampige.ttf


cat /sdcard/Sampige.ttf > DroidSansFallback.ttf


Mount the system folder back in read only mode
 
mount -o ro,remount /dev/mtdblock4 /system

Enjoy your favorite news or other contents  in your custom font.

 Thanks to the article
How to install custom fonts on rooted droid phone 

 




Monday, July 18, 2011

Simple ListView Adapter and list item select

When you are using a listview in your applications many a times you will write your own adapter to display items in a listview. But if your list is very simple showing a list of strings, you can use inbuilt adapters like ArrayAdapter, SimpleCursorAdapter etc.

ArrayAdapter
Let us look at an example

<?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:layout_height="wrap_content" 
android:id="@+id/listView1" 
android:layout_width="match_parent"
 
android:layout_margin="20dp"
></ListView>
</LinearLayout>

And the oncreate function of activity reads like this

       super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        String []s = new String[]{"Lorem","Ipsum","dolor","sit","amet"};
        ListView lv = (ListView)findViewById(R.id.listView1);
        lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,s));

So this arrayadapter just needs the array to be displayed in the list, the context and the textview resource id. Instead of defining another resource id, I have used in built resource. Now our list looks like this

If you want to change the appearance of your list, you can define your own list view as shown.
Add another xml file with just a textview . Do not use any layout.
tv.xml

<TextView android:text="TextView" android:id="@+id/textView1"
android:background="#0489B1"
android:textColor="#000000"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_margin="20dp"
android:padding="5dp"></TextView>
Now use this as layout in arrayadpter
 lv.setAdapter(new ArrayAdapter<String>(this, R.layout.tv,s));


And after you set the background color of linear layout in main to blue, this is how your list looks like


Next step will be write a listener to the list. You should attach an OnItemClickListener to this listview.

 lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
 ListView lv = (ListView) arg0;
 TextView tv = (TextView) lv.getChildAt(arg2);
 String s = tv.getText().toString();
 Toast.makeText(SamplesActivity.this, "Clicked item is"+s, Toast.LENGTH_LONG).show();
} });
Instead of Toasting, you can perform any required processing. 
What if you want to use the list for selecting one of the items? Again the simplest way to use this is to use android.R.layout.simple_list_item_single_choic

       lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_single_choice,s));
        lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);   
Now our list lets us select exactly one item
I did change the background color of linear layout to blue in main.xml because the builtin android layouts show list elements in white text which will be invisible if the background is also white.
How do you find out which item is selected from the listview? 
Let us use a button, on click of which we will display the selected item of the list
Modified main.xml is

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


<ListView android:layout_height="wrap_content" android:id="@+id/listView1"
android:layout_width="match_parent" android:divider="#00ffffff"
android:dividerHeight="10dp" android:layout_margin="20dp"></ListView>
<Button android:text="OK" android:id="@+id/button1"
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_gravity="center_horizontal"></Button>
</LinearLayout>


Let us add the button and onclicklistener to it.

        btn =(Button) findViewById(R.id.button1);
        btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int p =  lv.getCheckedItemPosition();
String s = ((TextView) lv.getChildAt(p)).getText().toString(); Toast.makeText(SamplesActivity.this, "Selected item is "+s, Toast.LENGTH_LONG).show();
}
});
So now our list looks like this.




Finally let us see how to select multiple elements from the list. 
First of all change the list mode multiple select


lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);


Then we should use lv.setCheckedItemPositions() which returns a sparseboolean array. The array elements are true if that item is selected



btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SparseBooleanArray sp = lv.getCheckedItemPositions();
StringBuffer str = new StringBuffer();
for(int i=0;i<sp.size();i++){
if(sp.valueAt(i)==true){
String s = ((TextView) lv.getChildAt(i)).getText().toString();
str = str.append(" "+s);
}
}  
Toast.makeText(SamplesActivity.this, "Selected items are "+str.toString(), Toast.LENGTH_LONG).show();
}
});
And, our multi select list is ready!