您的位置:首页 > 移动开发 > Android开发

android 电子词典

2015-06-16 20:18 363 查看
MinActiviy.java
package com.example.happydictionary;
import com.example.happydictionary.adapter.DictionaryAdapter;
import com.example.happydictionary.db.DBHelper;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener,
TextWatcher {
private DBHelper dbHelper; // 用户输入文本框
private AutoCompleteTextView word; // 定义数据库的名字
private SQLiteDatabase database;
private Button searchWord; // 搜索按钮
private TextView showResult; // 用户显示查询结果

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

dbHelper = new DBHelper(getBaseContext());// 打开数据库
database = dbHelper.openDatabase();

init();

searchWord.setOnClickListener(this); // 绑定监听器
word.addTextChangedListener(this); // 绑定文字改变监听器

}

public void init() {
searchWord = (Button) findViewById(R.id.btnSearch);
word = (AutoCompleteTextView) findViewById(R.id.etWord);
showResult = (TextView) findViewById(R.id.tvSearchResult);

}

public void afterTextChanged(Editable s) {
Cursor cursor = database.rawQuery(
"select english as _id from t_words where english like ?",
new String[] { s.toString() + "%" });

// 新建新的Adapter
DictionaryAdapter dictionaryAdapter = new DictionaryAdapter(this,cursor, true);

// 绑定适配器
word.setAdapter(dictionaryAdapter);

}

public void beforeTextChanged(CharSequence s, int start, int count,
int after) {

}

public void onTextChanged(CharSequence s, int start, int before, int count) {

}

public void onClick(View view) {
// 查询指定的单词
String sql = "select chinese from t_words where english=?";

Cursor cursor = database.rawQuery(sql, new String[] { word.getText()
.toString() });

String result = "查无该词"; // 如果查找单词,显示其中文的意思

if (cursor.getCount() > 0) {

cursor.moveToFirst(); // 须使用moveToFirst方法将记录指针移动到第1条记录的位置
result = cursor.getString(cursor.getColumnIndex("chinese"))
.replace("&", "&");
}

showResult.setText(word.getText() + "\n" + result.toString());// 将结果显示到TextView中
}

}
<pre name="code" class="java">DictionaryAdapter.java
package com.example.happydictionary.adapter;import com.example.happydictionary.R;import android.content.Context;import android.database.Cursor;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.CursorAdapter;import android.widget.TextView;//自定义Adapter类public class DictionaryAdapter extends CursorAdapter {<span style="white-space:pre">	</span>private LayoutInflater layoutInflater;<span style="white-space:pre">	</span>@Override<span style="white-space:pre">	</span>public CharSequence convertToString(Cursor cursor) {<span style="white-space:pre">		</span>return cursor == null ? "" : cursor.getString(cursor<span style="white-space:pre">				</span>.getColumnIndex("_id"));<span style="white-space:pre">	</span>}<span style="white-space:pre">	</span>// 将单词信息显示到列表中<span style="white-space:pre">	</span>private void setView(View view, Cursor cursor) {<span style="white-space:pre">		</span>TextView tvWordItem = (TextView) view;<span style="white-space:pre">		</span>tvWordItem.setText(cursor.getString(cursor.getColumnIndex("_id")));<span style="white-space:pre">	</span>}<span style="white-space:pre">	</span>// 绑定选项到列表中<span style="white-space:pre">	</span>@Override<span style="white-space:pre">	</span>public void bindView(View view, Context context, Cursor cursor) {<span style="white-space:pre">		</span>setView(view, cursor);<span style="white-space:pre">	</span>}<span style="white-space:pre">	</span>// 生成新的选项<span style="white-space:pre">	</span>@Override<span style="white-space:pre">	</span>public View newView(Context context, Cursor cursor, ViewGroup parent) {<span style="white-space:pre">		</span>View view = layoutInflater.inflate(R.layout.word_list_item, null);<span style="white-space:pre">		</span>setView(view, cursor);<span style="white-space:pre">		</span>return view;<span style="white-space:pre">	</span>}<span style="white-space:pre">	</span>public DictionaryAdapter(Context context, Cursor c, boolean autoRequery) {<span style="white-space:pre">		</span>super(context, c, autoRequery);<span style="white-space:pre">		</span>layoutInflater = (LayoutInflater) context<span style="white-space:pre">				</span>.getSystemService(Context.LAYOUT_INFLATER_SERVICE);<span style="white-space:pre">	</span>}}
<pre name="code" class="java">WordDao,java
package com.example.happydictionary.dao;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import com.example.happydictionary.db.DBHelper;public class WordDao {private DBHelper dbHelper;private SQLiteDatabase sqLiteDatabase;public WordDao(Context context){dbHelper=new DBHelper(context);}     public String getChinese(String english){    sqLiteDatabase=dbHelper.openDatabase();    String sql="select chinese from t_words where english=?";    Cursor cursor=sqLiteDatabase.rawQuery(sql, new String[]{english});    String chinese="查无该词";    if(cursor.moveToFirst()){    chinese=cursor.getString(cursor.getColumnIndex("chinese"));    }    return chinese;     }     }
<pre name="code" class="java">DBHelper.java
package com.example.happydictionary.db;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import com.example.happydictionary.R;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.os.Environment;import android.util.Log;/** * 实现将数据库文件从raw目录拷贝到手机里存放数据库的位置 *  * @author cabbage */public class DBHelper {<span style="white-space:pre">	</span>private final int BUFFER_SIZE = 400000;<span style="white-space:pre">	</span>public static final String NAME = "name";<span style="white-space:pre">	</span>public static final String DB_NAME = "idiom.db"; // 保存的数据库文件名<span style="white-space:pre">	</span>public static final String PACKAGE_NAME = "com.example.happydictionary";// 应用的包名<span style="white-space:pre">	</span>public static final String DB_PATH = "/data"<span style="white-space:pre">			</span>+ Environment.getDataDirectory().getAbsolutePath() + "/"<span style="white-space:pre">			</span>+ PACKAGE_NAME + "/databases";<span style="white-space:pre">	</span>/*// SDCab243rd 定义数据库的存放路径<span style="white-space:pre">	</span>private final String DATABASE_PATH = android.os.Environment<span style="white-space:pre">			</span>.getExternalStorageDirectory().getAbsolutePath() + "/dictionary";*/<span style="white-space:pre">	</span>private Context context;<span style="white-space:pre">	</span>public DBHelper(Context context) {<span style="white-space:pre">		</span>this.context = context;<span style="white-space:pre">	</span>}<span style="white-space:pre">	</span>public SQLiteDatabase openDatabase() {<span style="white-space:pre">		</span>try {<span style="white-space:pre">			</span>File myDataPath = new File(DB_PATH);<span style="white-space:pre">			</span>if (!myDataPath.exists()) {<span style="white-space:pre">				</span>myDataPath.mkdirs();// 如果没有这个目录则创建<span style="white-space:pre">			</span>}<span style="white-space:pre">			</span>String dbfile = myDataPath + "/" + DB_NAME;<span style="white-space:pre">			</span>if (!(new File(dbfile).exists())) {// 判断数据库文件是否存在,若不存在则执行导入,否则直接打开数据库<span style="white-space:pre">				</span>InputStream is = context.getResources().openRawResource(<span style="white-space:pre">						</span>R.raw.dictionary); // 欲导入的数据库<span style="white-space:pre">				</span>FileOutputStream fos = new FileOutputStream(dbfile);<span style="white-space:pre">				</span>byte[] buffer = new byte[BUFFER_SIZE];<span style="white-space:pre">				</span>int count = 0;<span style="white-space:pre">				</span>while ((count = is.read(buffer)) > 0) {<span style="white-space:pre">					</span>fos.write(buffer, 0, count);<span style="white-space:pre">				</span>}<span style="white-space:pre">				</span>fos.close();<span style="white-space:pre">				</span>is.close();<span style="white-space:pre">			</span>}<span style="white-space:pre">			</span>SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile,<span style="white-space:pre">					</span>null);<span style="white-space:pre">			</span>return db;<span style="white-space:pre">		</span>} catch (FileNotFoundException e) {<span style="white-space:pre">			</span>Log.e("Database", "File not found");<span style="white-space:pre">			</span>e.printStackTrace();<span style="white-space:pre">		</span>} catch (IOException e) {<span style="white-space:pre">			</span>Log.e("Database", "IO exception");<span style="white-space:pre">			</span>e.printStackTrace();<span style="white-space:pre">		</span>}<span style="white-space:pre">		</span><span style="white-space:pre">		</span>return null;<span style="white-space:pre">	</span>}<span style="white-space:pre">	</span>public Cursor query(String name) { <span style="white-space:pre">		</span>SQLiteDatabase db = this.getReadableDatabase(); <span style="white-space:pre">		</span>return db.rawQuery("select * from t_words where english like '%" + name + "%' limit 10", null); <span style="white-space:pre">	</span>}<span style="white-space:pre">	</span>private SQLiteDatabase getReadableDatabase() {<span style="white-space:pre">		</span>// TODO Auto-generated method stub<span style="white-space:pre">		</span>return null;<span style="white-space:pre">	</span>}<span style="white-space:pre">	</span><span style="white-space:pre">	</span><span style="white-space:pre">	</span>}
<pre name="code" class="java">Word.java
package com.example.happydictionary.entity;public class Word {<span style="white-space:pre">	</span>private String english;<span style="white-space:pre">	</span>private String chinese;<span style="white-space:pre">	</span>public String getEnglish() {<span style="white-space:pre">		</span>return english;<span style="white-space:pre">	</span>}<span style="white-space:pre">	</span>public void setEnglish(String english) {<span style="white-space:pre">		</span>this.english = english;<span style="white-space:pre">	</span>}<span style="white-space:pre">	</span>public String getChinese() {<span style="white-space:pre">		</span>return chinese;<span style="white-space:pre">	</span>}<span style="white-space:pre">	</span>public void setChinese(String chinese) {<span style="white-space:pre">		</span>this.chinese = chinese;<span style="white-space:pre">	</span>}}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="@drawable/mainbg"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context=".MainActivity" >        <Button        android:id="@+id/btnSearch"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignBaseline="@+id/etWord"        android:layout_alignBottom="@+id/etWord"        android:layout_marginLeft="16dp"        android:layout_toRightOf="@+id/etWord"        android:background="@drawable/ibsearchword"        android:onClick="searchWord"        android:text="@string/serachWord" />    <TextView        android:id="@+id/tvSearchResult"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:layout_alignLeft="@+id/etWord"        android:layout_below="@+id/etWord"        android:layout_marginTop="22dp"        android:textSize="25sp"        android:background="@drawable/bg_roundcorner"        android:textAppearance="?android:attr/textAppearanceMedium" />    <AutoCompleteTextView        android:id="@+id/etWord"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_alignParentTop="true"        android:layout_marginTop="31dp"        android:background="@android:drawable/edit_text"        android:ems="10"        android:hint="@string/searchHint"        android:singleLine="true"        android:textColor="#552006"        android:textColorHint="#782f10" >        <requestFocus />    </AutoCompleteTextView></RelativeLayout>
word_list_item.xml
<?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:gravity="center_vertical"    android:minHeight="?android:attr/listPreferredItemHeight"    android:paddingLeft="6dip"    android:textAppearance="?android:attr/textAppearanceLarge"    android:textColor="@color/gray" />
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: