Friday, June 29, 2012

Enable IME and select it

So you wrote your own IME and gloating over it. But users are bugging you about how to use it. And the active installation rate is dismal. So what do you do.

You do what great artists do. Copy the design. I saw somewhere that they are letting you enable your keyboard and set that as active IME.

So the code is quite simple, in fact very simple.

To display all the keyboards and enable your keyboard, call the following code


 Intent i = new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS);
    startActivity(i);



Here is the screen you see.



When you want to make your keyboard as the default IME, here is the code you write

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showInputMethodPicker();




Sunday, March 11, 2012

Do not lose the .keystore file

First a caution:

I was working hard (according my standards in updating my Indian news app. And today was the D day. I tried publishing it. But market site told I should use the same keystore as my previous version. My computer is formatted recently and I have not taken the back up of that keystore file.

Now there is nothing else I can do except for unpublishing it and publishing with a new package name. I will be losing all my downloads.

So please keep your .keystore file and its password very very safely. As someone in stockoverflow suggested, send it to yourself in gmail.

Thursday, March 1, 2012

How to display auto-scorlling text (marquee)

If you want to display which keeps scrolling automatically on a single line textview, you can use the following steps.

First of all, in your xml file, set the following properties for your textview

android:singleline = "true"
android:ellipsize="marquee"

But still you see that your text is showing marquee. Please remember that the text will  auto-scroll only when it has focus or it is selected.

So add the following text in your code.

yourtextview.setSelected(true);

Now you can see that your text view will display auto scrolling text

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.