Android Spelling Checker Tutorial


The Android platform offers a spelling checker framework that lets you implement and access spell checking in your application.
In order to use spelling checker , you need to implement SpellCheckerSessionListener interface and override its methods. Its syntax is given below:
public class HelloSpellCheckerActivity extends Activity implements SpellCheckerSessionListener {
@Override
public void onGetSuggestions(final SuggestionsInfo[] arg0) {
   // TODO Auto-generated method stub
}

@Override
public void onGetSentenceSuggestions(SentenceSuggestionsInfo[] arg0) {
   // TODO Auto-generated method stub 
}
}
Next thing you need to do is to create an object of SpellCheckerSession class. This object can be instantiated by calling newSpellCheckerSession method of TextServicesManager class. This class handles interaction between application and text services. You need to request system service to instantiate it. Its sytnax is given below:
private SpellCheckerSession mScs;
final TextServicesManager tsm = (TextServicesManager) getSystemService(
Context.TEXT_SERVICES_MANAGER_SERVICE);
mScs = tsm.newSpellCheckerSession(null, null, this, true);   
The last thing you need to do is to call getSuggestions method to get suggestion for any text , you want. The suggestions will be passed onto the onGetSuggestions method from where you can do whatever you want.
mScs.getSuggestions(new TextInfo(editText1.getText().toString()), 3);
This method takes two parameters. First parameter is the string in the form of TextInfo object , and second paramater is the cookie number used to distinguish suggestions.
Apart from the the methods , there are other methods provided by the SpellCheckerSession class for better handling suggestions. These methods are listed below:
Sr.NoMethod & description
1cancel()
Cancel pending and running spell check tasks
2close()
Finish this session and allow TextServicesManagerService to disconnect the bound spell checker
3getSentenceSuggestions(TextInfo[] textInfos, int suggestionsLimit)
Get suggestions from the specified sentences
4getSpellChecker()
Get the spell checker service info this spell checker session has.
5isSessionDisconnected()
True if the connection to a text service of this session is disconnected and not alive.br>

Example

Here is an example demonstrating the use of Spell Checker. It creates a basic spell checking application that allows you to write text and get suggestions.
To experiment with this example , you can run this on an actual device or in an emulator.
StepsDescription
1You will use Eclipse IDE to create an Android application and name it as HelloSpellCheckerActivity under a package com.example.hellospellchecker. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file to add necessary code.
3Modify the res/layout/main to add respective XML components
4Modify the res/values/string.xml to add necessary string components
5Run the application and choose a running android device and install the application on it and verify the results
Following is the content of the modifed main activity filesrc/com.example.hellospellchecker/MainActivity.java.
package com.example.android.hellospellchecker;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.textservice.SentenceSuggestionsInfo;
import android.view.textservice.SpellCheckerSession;
import android.view.textservice.SpellCheckerSession.SpellCheckerSessionListener;
import android.view.textservice.SuggestionsInfo;
import android.view.textservice.TextInfo;
import android.view.textservice.TextServicesManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class HelloSpellCheckerActivity extends Activity implements SpellCheckerSessionListener {

   private static final int NOT_A_LENGTH = -1;
   private TextView mMainView;
   private SpellCheckerSession mScs;
   private EditText editText1;

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      mMainView = (TextView)findViewById(R.id.main);
      editText1 = (EditText)findViewById(R.id.editText1);
   }

   @Override
   public void onResume() {
      super.onResume();
      final TextServicesManager tsm = (TextServicesManager) getSystemService(
      Context.TEXT_SERVICES_MANAGER_SERVICE);
      mScs = tsm.newSpellCheckerSession(null, null, this, true);         
   }

   @Override
   public void onPause() {
      super.onPause();
      if (mScs != null) {
         mScs.close();
      }
   }

   public void go(View view){
      Toast.makeText(getApplicationContext(), editText1.getText().toString(),  
      Toast.LENGTH_SHORT).show();
      mScs.getSuggestions(new TextInfo(editText1.getText().toString()), 3);

   }
   @Override
   public void onGetSuggestions(final SuggestionsInfo[] arg0) {
      final StringBuilder sb = new StringBuilder();

      for (int i = 0; i < arg0.length; ++i) {
         // Returned suggestions are contained in SuggestionsInfo
         final int len = arg0[i].getSuggestionsCount();
         sb.append('\n');
         for (int j = 0; j < len; ++j) {
            sb.append("," + arg0[i].getSuggestionAt(j));
       }
       sb.append(" (" + len + ")");
   }
   runOnUiThread(new Runnable() {

      public void run() {
         mMainView.append(sb.toString());
      }
   });

   }
   @Override
   public void onGetSentenceSuggestions(SentenceSuggestionsInfo[] arg0) {
      // TODO Auto-generated method stub

   }
}
Following is the modified content of the xml res/layout/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" >

   <TextView
      android:id="@+id/main"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="@string/pre"
      />

   <Button
      android:id="@+id/mainbtn"
      android:layout_width="150dip"
      android:layout_height="50dip"
      android:onClick="go"
      android:text="@string/suggest" />

   <EditText
      android:id="@+id/editText1"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:ems="10" >

      <requestFocus />
   </EditText>

</LinearLayout>
Following is the content of the res/values/string.xml.
<?xml version="1.0" encoding="utf-8"?>

<resources>

   <string name="app_name">HelloSpellChecker</string>
   <string name="suggest">suggest</string>
   <string name="pre">Suggestions</string>

</resources>
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>

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

   <uses-sdk android:minSdkVersion="14" />

   <application
      android:label="@string/app_name" >
      <activity
         android:label="@string/app_name"
         android:name=".HelloSpellCheckerActivity" >
         <intent-filter >
            <action android:name="android.intent.action.MAIN" />

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

</manifest>
Let's try to run our Spell Checker application we just modified. I assume you had created your AVDwhile doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:
Android Spell Checker Tutorial
Now what you need to do is to enter any text in the field. For example , i have entered some text. Press the suggestions button. The following notification would appear in you AVD along with suggestions:
Android Spell Checker Tutorial
Now change the text and press the button again , like i did. And this is what comes on screen.
Android Spell Checker Tutorial

Comments

Popular Posts