The realization method of English dictionary based on Android _android

Source: Internet
Author: User
Tags sqlite sqlite database

The English Dictionary is a frequently used application in mobile phones. So in this article, Android will be combined to discuss how to implement an Android version of an English dictionary. There are many ways to implement English dictionaries. In this paper, we use the SQLite database to save English word information. The system finds the Chinese information corresponding to the specified English by sqlite the word information stored in the database. Of course, the realization of such an English dictionary needs to solve a series of technical problems. For example, how to publish the database file that holds the English word information with the program (APK file), how to open the database after publication, how to display all the words that begin with the input string when you enter the first few letters in the Autocompletetextview component prompt list. The detailed answers to these questions will be given gradually in this chapter.

The technical problems to be solved and the preliminary solution to the realization of electronic dictionaries

In this paper, we will give the main technical problems to realize the electronic dictionary, and give the preliminary answer or hint of these technical questions.

For detailed answers and code, please refer to the content later in this article.
The main technical problems and answers are as follows:

1. How to publish the SQLite database (dictionary.db file) with apk file?
Answer: You can copy the Dictionary.db file to the Res\raw directory in the Eclipse Android project, as shown in Figure 1. All files in the Res\raw directory are not compressed so that the files in that directory can be extracted directly.


Figure 1 Copying the dictionary.db file to the Res\raw directory

2. How do I open the database file in the Res\raw directory?

Answer: You cannot open the database file directly in the Res\raw directory on Android, and you need to copy the file to a directory on your phone's memory or SD card when the program is first started, and then open the database file. The basic method of replication is to use the Getresources (). Openrawresource method to obtain the InputStream object of the resource in the Res\raw directory, and then write the data from that InputStream object to the corresponding file in the other directory. The Sqlitedatabase.openorcreatedatabase method can be used in the Android SDK to open SQLite database files in any directory.

3. If you enter two or more letters in the Autocompletetextview component, display a list of all words that begin with the input string?

Answer: The adapter used by Autocompletetextview is a custom adapter class, and the structure of the class is as follows:

public class Dictionaryadapter extends CursorAdapter
{
  
}

Note that you cannot isolate the word from the entire database, and then generate a adapter object and then use the Setadapter method to set the adapter object for the Autocompletetextview component. The Autocompletetextview component does not filter for us words that begin with a string. These jobs need to be implemented by the developer through coding.

The basic idea is to monitor the input of characters in the Autocompletetextview component in the Aftertextchanged event of the Autocompletetextview class. Generates a adapter object whenever a character is entered, and then associates the newly generated adapter object with the Autocompletetextview. The effect of displaying a list of words beginning with an input string is shown in Figure 2.

Figure 2 shows a list of words beginning with the input string

Copy and open a database file that holds English words

In the English dictionary implemented in this article, the OpenDatabase method is used to open the database file (the file is in the dictionary directory of the SD card), so to run the English dictionary implemented in this article, you need to install the SD card in the mobile phone or simulator. If the file does not exist, the system automatically creates the/sdcard/dictionary directory and copies the dictionary.db files from the Res\raw directory to the/sdcard/dictionary directory. The implementation code for the OpenDatabase method is as follows:

 Private Sqlitedatabase OpenDatabase () {try {//Get dictionary.db file absolute path String databasefilename = Database_pa
   TH + "/" + database_filename;
   File dir = new file (Database_path);
   If the/sdcard/dictionary directory exists, create this directory if (!dir.exists ()) Dir.mkdir (); If the//dictionary.db file is not present in the/sdcard/dictionary directory, copy the file from the Res\raw directory to the//SD card directory (/sdcard/dictionary) if (! New file (DatabaseFileName)). Exists ()) {//Get the InputStream object that encapsulates the Dictionary.db file InputStream is = Getresources (). op
    Enrawresource (r.raw.dictionary);
    FileOutputStream fos = new FileOutputStream (databasefilename);
    byte[] buffer = new byte[8192];
    int count = 0;
    Start copying the dictionary.db file while (count = is.read (buffer) > 0) {fos.write (buffer, 0, count);
    } fos.close ();
   Is.close (); //Open the Dictionary.db file in the/sdcard/dictionary directory sqlitedatabase database = sqlitedatabase.openorcreatedatabase (dat
   Abasefilename, NULL);
  return database; catch (excePtion e) {} return null;

 }

Several constants are used in the OpenDatabase method, which are defined in the main class (main) of the program, and the code is as follows:

public class Main extends activity implements Onclicklistener, Textwatcher
{
 private final String Database_path = Android.os.Environment
   . getExternalStorageDirectory (). GetAbsolutePath ()
   + "/dictionary";
 Private final String database_filename = "dictionary.db";
}

Query word

The core of an English dictionary is to find the Chinese meaning of English words. Before looking for Chinese meaning, you first need to use the OpenDatabase method to open the SQLite database in the OnCreate method of the main class, as follows:

Database = OpenDatabase ();

Where the database is the Sqlitedatabase type variable defined in the main class.
Then add the following code to the lookup button's Click event to find the English word and display the Chinese meaning.

public void OnClick (view view)
 {
  String sql = ' Select Chinese from t_words where english=? '; 
  Cursor Cursor = database.rawquery (sql, new string[]
  {actvword.gettext (). toString ()});
  String result = "The word was not found."
  If you look up a word, display its Chinese information
  if (Cursor.getcount () > 0)
  {
   //You must use the Movetofirst method to move the record pointer to the position
   of the 1th record Cursor.movetofirst ();
   result = Cursor.getstring (Cursor.getcolumnindex ("Chinese"));
  }
  Displays the Query Results dialog box
  new Alertdialog.builder (this). Settitle ("Query Results"). Setmessage (Result).
    Setpositivebutton ("Off" , null). Show ();

 

Here we should know the result of a t_words table in a dictionary.db, which has only two fields: 中文版 and Chinese. The English and Chinese descriptions of the words are shown respectively. If you want to get a Chinese description of the word, just look for the Chinese field. As shown in the code in the OnClick method. The effect of the query word is as shown in Figure 3.

Figure 3 Querying English words

If you display a list of words that begin with an input string

      Although our English dictionary has been working well so far, for the convenience of our readers, the automatic prompt for word input will be added in this section. That is, if the reader enters the first few letters of a word in the Autocompletetextview component, the component automatically lists all the words in the database that begin with that string. The effect is shown in Figure 2. Having such a feature allows the user to find the words only if they know the first few letters of the word.
       because the Autocompletetextview component uses a custom adapter class, the complete code for this custom adapter class is given below.

 public class Dictionaryadapter extends CursorAdapter {private Layoutinflater layoutinflater; @Override public charsequence converttostring (Cursor Cursor) {return Cursor = null?
  "": cursor.getstring (cursor. Getcolumnindex ("_id")); The text//View parameter used to set the value of the _id field (that is, the Chinese field) to TextView component represents the TextView component for displaying list items private void Setview (view view, Cursor CU
 Rsor) {TextView Tvworditem = (TextView) view;
  Tvworditem.settext (cursor.getstring) (Cursor.getcolumnindex ("_id"));
  @Override public void BindView (view view, context, Cursor Cursor) {Setview (view, Cursor); @Override public view Newview (context context, Cursor Cursor, ViewGroup parent) {View view = Layoutinflater.i
   Nflate (R.layout.word_list_item, NULL);
   Setview (view, cursor);
  return view;
   Public Dictionaryadapter (context, Cursor C, Boolean autorequery) {Super (context, C, autorequery); Get Layoutinflater Object layoutinflater = (LAYOUTINFLA) through system servicester) context. Getsystemservice (Context.layout_inflater_service);

 }
 }

The following 3 points should be noted when writing the Dictionaryadapter class:

1. In order to bind the cursor object to the Autocompletetextview component, the Dictionaryadapter class must inherit from the CursorAdapter class.

2. Because the ConvertToString method in the CursorAdapter class directly returns the address of the cursor object, the ConvertToString method must be overridden in the Dictionaryadapter class to return the currently selected word. The source code for the ConvertToString method in the CursorAdapter class.

 Public charsequence converttostring (Cursor Cursor)
 {
   //If Cursor is not NULL, returns the address of the Cursor object (cursor.tostring ()) return
  cursor = null? "": cursor.tostring ();
 }
 

The source code for the Converttotostring method after overlay is as follows:

Public charsequence converttostring (Cursor Cursor)
{return
 Cursor = null? "": cursor.getstring (Cursor
     . Getcolumnindex ("_id"));
}

Notice here that the text in the Autocompletetextview component is set with the return value of the ConvertToString method after a word in the word list in the Autocompletetextview component is selected. Therefore, you must use the cursor getstring to get the corresponding field values.

3. Because the cursor object and the adapter binding must have a field called "_id", in this case, the Chinese field name is mapped to the "_id" field.

To monitor text entry in the Autocompletetextview component, the Android.text.TextWatcher interface needs to be implemented. In this interface only need to implement the Aftertextchanged method, the code is as follows:

public void aftertextchanged (Editable s)
{
  //The alias of the 中文版 field must be set to _id 
  Cursor Cursor = Database.rawquery (
    "Select 中文版 as _id from T_words where Chinese like?",
    new string[]{s.tostring () + "%"});
  Dictionaryadapter dictionaryadapter = new Dictionaryadapter (This,cursor, true);
  Actvword is the variable
  actvword.setadapter (dictionaryadapter) of the Autocompletetextview type defined in the main class;

As you can see from the code above, the alias for the Chinese field name in the query SQL statement is "_id".

4. In the Dictionaryadapter class, you need to use the BindView and Newview methods to set each list item. The BindView method is responsible for setting up a list item that already exists, that is, the list item has generated the corresponding Component object. The Newview method is responsible for setting up a new list item in which you need to create a view object to display the current list item. In this example, the Word_list_item.xml layout file is used to display each list item, and the code is as follows:

<?xml version= "1.0" encoding= "Utf-8"?> <textview xmlns:android=
"http://schemas.android.com/apk/res/" Android "
 android:id=" @+id/tvworditem "
 android:layout_width=" fill_parent "
 android:layout_height=" Wrap_content "
 android:textappearance="? Android:attr/textappearancelarge "
 android:gravity=" Center_ Vertical "
 android:paddingleft=" 6dip "
 android:textcolor=" #000 " 
 android:minheight="? android:attr/ Listpreferreditemheight "
/>

This paper introduces the implementation method of the English dictionary based on Android. To realize the English dictionary, we need to solve 3 problems: How to publish the SQLite database file of the English word with the apk file, how to open the database file in the SD card, and how to display the English word list at the beginning of the input string in the Autocompletetextview component. The last thing to mention is that when you write a custom Dictionaryadapter class, you must overwrite the Conterttostring method to display the selected word in the Autocompletetextview component when the user's option is a list item. Instead of the cursor object address.

This is the entire content of this article, I hope to learn more about Android software programming help.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.