电子词典具有离线查询和在线查询两种功能,离线查询不用联网就可以查询到单词的释义,不过,只能查询本数据库中的一些单词,查询不到的单词是因为本数据库中没有,所以这一缺点还有待改进;如果想查询离线查不到的单词,可使用在线查询,词典会调用有道词典在线解答,会有更多的释义。此APP还有很多不足之处,还有待改进。
词典数据保存在小型数据库sqlite中,在res的raw文件夹下。
APPt图标 APP引导界面 离线 查询界面
查询结果以对话框的形式显示 生词本界面通过listvtew展示 在线查询界面
在线查询调用有道词典界面
EditWord.java
//电子词典的编辑界面文件,输入单词可查询。
package com.example.dictionary;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class EditWord extends Activity implements OnClickListener {
private String action;
private EditText zhushi;
private EditText meanning;
private Button confirm;
private Button cancel;
int index = -1;
private Bundle bundle;
private ArrayList> arrayList;
@SuppressWarnings("unchecked")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 设置隐藏标题
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.edit);
Bundle bundle = this.getIntent().getExtras();
action = bundle.getString("action");
initWidgets();
}
private void initWidgets() {
// spelling是单词,meanning是解释,confirm是确定,cancel是取消
zhushi = (EditText) findViewById(R.id.zhushi);
meanning = (EditText) findViewById(R.id.meanning);
confirm = (Button) findViewById(R.id.button1);
cancel = (Button) findViewById(R.id.button2);
cancel.setOnClickListener(this);
confirm.setOnClickListener(this);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (action.equals("edit")) {
zhushi.setText(bundle.getString("word"));
meanning.setText(bundle.getString("explain"));
index = bundle.getInt("index");
}
}
@SuppressWarnings("unchecked")
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String word = meanning.getText().toString().trim();
String explain = zhushi.getText().toString().trim();
if (v == cancel) {
finish();
}
if (v == confirm) {
if (meanning.getText().toString().equals("")
|| zhushi.getText().toString().equals("")) {
Toast.makeText(EditWord.this, "信息不能为空", Toast.LENGTH_SHORT)
.show();
}
else {
Intent intent = getIntent();
arrayList = (ArrayList>) new ObjectFile()
.readObjectFile();
if (null == arrayList) {
arrayList = new ArrayList>();
}
if (!TextUtils.isEmpty(word) && !TextUtils.isEmpty(explain)) {
if (index == -1) {
HashMap map = new HashMap();
map.put("word", word);
map.put("explain", explain);
arrayList.add(map);
}else{
HashMap map = new HashMap();
map.put("word", word);
map.put("explain", explain);
arrayList.set(index, map);
}
new ObjectFile().writeObjectFile(arrayList);
}
SimpleAdapter adapter = new SimpleAdapter(this, arrayList,
android.R.layout.simple_list_item_2, new String[] {
"word", "explain" }, new int[] {
android.R.id.text1, android.R.id.text2 });
Intent intent1 = new Intent(this, MainActivity.class);
intent.putExtra("word", word);
intent.putExtra("explain", explain);
startActivity(intent1);
EditWord.this.finish();
}
}
}
}
HomeActivity.java
//电子词典的开始引导界面文件
package com.example.dictionary;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.Window;
import android.view.WindowManager;
public class HomeActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//设置隐藏标题栏
requestWindowFeature(Window.FEATURE_NO_TITLE);
//设置全屏
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.home);
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(1000);
shiftActivityToHome();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
private void shiftActivityToHome(){
Intent intent=new Intent(HomeActivity.this,MainActivity.class);
startActivity(intent);
//把当前也关闭
HomeActivity.this.finish();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
MainActivity.java
package com.example.dictionary;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.Window;
import android.view.WindowManager;
public class HomeActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//设置隐藏标题栏
requestWindowFeature(Window.FEATURE_NO_TITLE);
//设置全屏
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.home);
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(1000);
shiftActivityToHome();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
private void shiftActivityToHome(){
Intent intent=new Intent(HomeActivity.this,MainActivity.class);
startActivity(intent);
//把当前也关闭
HomeActivity.this.finish();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
NoteBook.java
//生词本界面文件,将生词标记然后添加到生词本使用ListView控件展示。
package com.example.dictionary;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class NoteBook extends Activity {
public static final int MENU_ADD = 1;
public static final int MENU_TUICHU = MENU_ADD + 1;
private ArrayList> arrayList;
private ListView listView1;
@SuppressWarnings("unchecked")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note_book);
listView1 = (ListView) findViewById(R.id.listView1);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Intent intent = getIntent();
final String word = intent.getStringExtra("word");
final String explain = intent.getStringExtra("explain");
arrayList = (ArrayList>) new ObjectFile()
.readObjectFile();
if (null == arrayList) {
arrayList = new ArrayList>();
}
if (!TextUtils.isEmpty(word) && !TextUtils.isEmpty(explain)) {
HashMap map = new HashMap();
map.put("word", word);
map.put("explain", explain);
arrayList.add(map);
new ObjectFile().writeObjectFile(arrayList);
}
final SimpleAdapter adapter = new SimpleAdapter(this, arrayList,
android.R.layout.simple_list_item_2, new String[] { "word",
"explain" }, new int[] { android.R.id.text1,
android.R.id.text2 });
listView1.setAdapter(adapter);
// 为listView1视图添加setOnItemClickListener监听
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView arg0, View arg1,
final int arg2, long arg3) {
// 对于选中的项进行处理
AlertDialog.Builder builder = new Builder(NoteBook.this);
builder.setIcon(R.drawable.dialog_icon);
builder.setMessage("确认操作");
builder.setTitle("提示");
builder.setPositiveButton("删除", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
arrayList.remove(arg2);
new ObjectFile().writeObjectFile(arrayList);
adapter.notifyDataSetChanged();
dialog.dismiss();
}
});
builder.setNeutralButton("编辑", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Intent intent = new Intent();
// Bundle bundle = new Bundle();
// bundle.putString("word", word);
// bundle.putString("explain", explain);
// intent.putExtras(bundle);
// intent.setClass(NoteBook.this, EditWord.class);
// startActivity(intent);
// dialog.dismiss();
}
});
builder.setNegativeButton("取消", null).show();
// TODO Auto-generated method stub
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
menu.add(0, MENU_ADD, 0, "添加新单词");
menu.add(0, MENU_TUICHU, 1, "退出");
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_ADD: {
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putString("action", "add");
intent.putExtras(bundle);
intent.setClass(this, EditWord.class);
startActivity(intent);
break;
}
case MENU_TUICHU: {
finish();
}
}
return super.onOptionsItemSelected(item);
}
}
ObjectFile.java
package com.example.dictionary;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ObjectFile {
private String path = "/sdcard/word/word.txt";
public File createFile() {
File file = new File(path);
File parentFile = file.getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return file;
}
public Object readObjectFile() {
ObjectInputStream mis = null;
Object mObject = null;
File file = new File(path);
if (!file.exists()) {
return null;
} else {
try {
mis = new ObjectInputStream(new FileInputStream(file));
mObject = mis.readObject();
mis.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mObject;
}
}
public void DeleteObjectFile(Object object){
}
public boolean writeObjectFile(Object object) {
ObjectOutputStream mos = null;
try {
mos = new ObjectOutputStream(new FileOutputStream(createFile()));
mos.writeObject(object);
mos.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return false;
}
return true;
}
}
OfflineQuery.java
//离线查询单词界面文件,调用本地数据库,只能查询到数据库中有的单词,数据库中没有的将无法查询到。
package com.example.dictionary;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import com.iflytek.speech.RecognizerResult;
import com.iflytek.speech.SpeechError;
import com.iflytek.ui.RecognizerDialog;
import com.iflytek.ui.RecognizerDialogListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class OfflineQuery extends Activity implements OnClickListener,
TextWatcher {
public static final int MENU_ABOUT = 1;
public static final int MENU_TUICHU = MENU_ABOUT + 2;
private final String DATABASE_PATH = android.os.Environment
.getExternalStorageDirectory().getAbsolutePath() + "/dictionary";
private AutoCompleteTextView actvWord;
private final String DATABASE_FILENAME = "dictionary.db";
private SQLiteDatabase database;
private Button btnSelectWord;
private Button Clear;
private TextView mTextView;
private String result;
private ArrayList> arrayList;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.offline_query);
database = openDatabase();
btnSelectWord = (Button) findViewById(R.id.ButtonGo);
actvWord = (AutoCompleteTextView) findViewById(R.id.seek);
Clear = (Button) findViewById(R.id.clearButton);
btnSelectWord.setOnClickListener(this);
actvWord.addTextChangedListener(this);
Clear.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
actvWord.setText("");
}
});
}
public class DictionaryAdapter extends CursorAdapter {
private LayoutInflater layoutInflater;
public CharSequence convertToString(Cursor cursor) {
return cursor == null ? "" : cursor.getString(cursor
.getColumnIndex("_id"));
}
private void setView(View view, Cursor cursor) {
TextView tvWordItem = (TextView) view;
tvWordItem.setText(cursor.getString(cursor.getColumnIndex("_id")));
tvWordItem.setPadding(15, 10, 10, 15);
tvWordItem.setTextSize(18);
}
public DictionaryAdapter(Context context, Cursor c, boolean autoRequery) {
super(context, c, autoRequery);
// TODO Auto-generated constructor stub
layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// TODO Auto-generated method stub
setView(view, cursor);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
View view = new TextView(OfflineQuery.this);
setView(view, cursor);
return view;
}
}
private SQLiteDatabase openDatabase() {
try {
// 获得dictionary.db文件的绝对路径
String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME;
File dir = new File(DATABASE_PATH);
// 如果/sdcard/dictionary目录中存在,创建这个目录
if (!dir.exists())
dir.mkdir();
// 如果在/sdcard/dictionary目录中不存在
// dictionary.db文件,则从res\raw目录中复制这个文件到
// SD卡的目录(/sdcard/dictionary)
if (!(new File(databaseFilename)).exists()) {
// 获得封装dictionary.db文件的InputStream对象
InputStream is = getResources().openRawResource(
R.raw.dictionary);
FileOutputStream fos = new FileOutputStream(databaseFilename);
byte[] buffer = new byte[8192];
int count = 0;
// 开始复制dictionary.db文件
while ((count = is.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
fos.close();
is.close();
}
// 打开/sdcard/dictionary目录中的dictionary.db文件
SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(
databaseFilename, null);
return database;
} catch (Exception e) {
}
return null;
}
public void afterTextChanged(Editable s) {
// 必须将english字段的别名设为_id
Cursor cursor = database.rawQuery(
"select english as _id from t_words where english like ?",
new String[] { s.toString() + "%" });
DictionaryAdapter dictionaryAdapter = new DictionaryAdapter(this,
cursor, true);
actvWord.setAdapter(dictionaryAdapter);
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
public void onClick(View view) {
// TODO Auto-generated method stub
String sql = "select chinese from t_words where english=?";
Cursor cursor = database.rawQuery(sql, new String[] { actvWord
.getText().toString() });
result = "未找到该单词.";
// 如果查找单词,显示其中文的意思
if (cursor.getCount() > 0) {
// 必须使用moveToFirst方法将记录指针移动到第1条记录的位置
cursor.moveToFirst();
result = cursor.getString(cursor.getColumnIndex("chinese"));
}
if (actvWord.getText().toString().equals("")) {
Toast.makeText(OfflineQuery.this, "查询内容不能为空!", Toast.LENGTH_LONG)
.show();
return;
}
// 显示查询结果对话框
new AlertDialog.Builder(this)
.setIcon(R.drawable.dialog_icon)
.setTitle("查询结果")
.setMessage(result)
.setPositiveButton("加入生词本",
new DialogInterface.OnClickListener() {
@SuppressWarnings("unchecked")
@Override
public void onClick(DialogInterface dialog,
int which) {
Intent intent = getIntent();
if (!result.equals("未找到该单词.")) {
String word = actvWord.getText().toString()
.trim();
String explain = result;
arrayList = (ArrayList>) new ObjectFile()
.readObjectFile();
if (null == arrayList) {
arrayList = new ArrayList>();
}
if (!TextUtils.isEmpty(word)
&& !TextUtils.isEmpty(result)) {
HashMap map = new HashMap();
map.put("word", word);
map.put("explain", result);
arrayList.add(map);
new ObjectFile()
.writeObjectFile(arrayList);
}
}
}
}).setNegativeButton("关闭", null).show();
SimpleAdapter adapter = new SimpleAdapter(this, arrayList,
android.R.layout.simple_list_item_2, new String[] { "word",
"explain" }, new int[] { android.R.id.text1,
android.R.id.text2 });
}
// 语音部分
private static final String APPID = "appid=4f2d3a06";
private String text = "";
public void say(View view) {
RecognizerDialog isrDialog = new RecognizerDialog(this, APPID);
/*
* 设置引擎目前支持五种 ”sms”:普通文本转写 “poi”:地名搜索 ”vsearch”:热词搜索 ”video”:视频音乐搜索
* ”asr”:命令词识别
*/
isrDialog.setEngine("sms", null, null);
isrDialog.setListener(recoListener);
isrDialog.show();
}
// 语言识别监听器,有两个方法
RecognizerDialogListener recoListener = new RecognizerDialogListener() {
@Override
public void onResults(ArrayList results,
boolean isLast) {
// 服务器识别完成后会返回集合,我们这里就只得到最匹配的那一项
text = results.get(0).text;
System.out.println(text);
}
@Override
public void onEnd(SpeechError error) {
if (error == null) {
// 完成后就把结果显示在EditText上
actvWord.setText(text);
}
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
menu.add(0, MENU_ABOUT, 0, "说明");
menu.add(0, MENU_TUICHU, 1, "退出");
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_ABOUT: {
Intent intent = new Intent();
intent.setClass(this, About.class);
startActivity(intent);
break;
}
case MENU_TUICHU: {
finish();
}
}
return super.onOptionsItemSelected(item);
}
}
OnlineQuery.java
//在线查询界面文件,在线查询将会调用有道词典对单词进行释义。
package com.example.dictionary;
import java.util.ArrayList;
import com.iflytek.speech.RecognizerResult;
import com.iflytek.speech.SpeechError;
import com.iflytek.ui.RecognizerDialog;
import com.iflytek.ui.RecognizerDialogListener;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.Toast;
public class OnlineQuery extends Activity{
private Button ButtonGo;
private AutoCompleteTextView seek;
private WebView myWebView1;
private Button clearButton;
public static final int MENU_ABOUT = 1;
public static final int MENU_TUICHU = MENU_ABOUT + 2;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.online_query);
ButtonGo = (Button)findViewById(R.id.ButtonGo);
seek = (AutoCompleteTextView) findViewById(R.id.seek);
clearButton = (Button)findViewById(R.id.clearButton);
myWebView1 = (WebView)findViewById(R.id.myWebView1);
ButtonGo.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
String strURI = (seek.getText().toString());
strURI = strURI.trim();
if(strURI.length()==0)
{
Toast.makeText(OnlineQuery.this, "查询内容不能为空!", Toast.LENGTH_LONG).show();
}
else
{
String strURL = "http://dict.youdao.com/m/search?keyfrom=dict.mindex&q="+strURI;
myWebView1.loadUrl(strURL);
}
}
});
http://dict.youdao.com/m/serch?keyfrom=dict.mindex&vendor=%24vendor&q=happy
clearButton.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v){
seek.setText("");
}
});
}
//语音部分
private static final String APPID = "appid=4f2d3a06";
private String text="";
public void say(View view) {
RecognizerDialog isrDialog = new RecognizerDialog(this, APPID);
/*
* 设置引擎目前支持五种 ”sms”:普通文本转写 “poi”:地名搜索 ”vsearch”:热词搜索 ”video”:视频音乐搜索
* ”asr”:命令词识别
*/
isrDialog.setEngine("sms", null, null);
isrDialog.setListener(recoListener);
isrDialog.show();
}
// 语言识别监听器,有两个方法
RecognizerDialogListener recoListener = new RecognizerDialogListener() {
@Override
public void onResults(ArrayList results,
boolean isLast) {
// 服务器识别完成后会返回集合,我们这里就只得到最匹配的那一项
text = results.get(0).text;
System.out.println(text);
}
@Override
public void onEnd(SpeechError error) {
if (error == null) {
// 完成后就把结果显示在EditText上
seek.setText(text);
}
}
};
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
menu.add(0, MENU_ABOUT, 0, "说明");
menu.add(0, MENU_TUICHU, 1, "退出");
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_ABOUT: {
Intent intent = new Intent();
intent.setClass(this, About.class);
startActivity(intent);
break;
}
case MENU_TUICHU: {
finish();
}
}
return super.onOptionsItemSelected(item);
}
}