英语词典小程序
2015-06-26 09:07
387 查看
内容简介:
英语词典小程序,是通过打开数据库来查询单词,通过openDatabase()方法来实现,另外也可以使用openDatabase()方法来实现实现从res\raw目录复制数据库文件到/sdcard/dictionary目录中,复制数据实际上先读取,再写入数据的过程。把数据库复制到手机内存中,更方便数据的读取。效果图:
代码:
MainActivity.java
package com.example.happydictionary; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import com.example.happydictionary.adapter.DictionaryAdapter; import com.example.happydictionary.db.DBHelper; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.CursorAdapter; 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中 } }
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 { private LayoutInflater layoutInflater; @Override 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"))); } // 绑定选项到列表中 @Override public void bindView(View view, Context context, Cursor cursor) { setView(view, cursor); } // 生成新的选项 @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = layoutInflater.inflate(R.layout.word_list_item, null); setView(view, cursor); return view; } public DictionaryAdapter(Context context, Cursor c, boolean autoRequery) { super(context, c, autoRequery); layoutInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); } }
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;
}
}
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 com.example.happydictionary.R.raw; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Environment; import android.util.Log; /** * 实现将数据库文件从raw目录拷贝到手机里存放数据库的位置 * * @author jiajilei */ public class DBHelper { private final int BUFFER_SIZE = 400000; public static final String NAME = "name"; public static final String DB_NAME = "idiom.db"; // 保存的数据库文件名 public static final String PACKAGE_NAME = "com.example.happydictionary";// 应用的包名 public static final String DB_PATH = "/data" + Environment.getDataDirectory().getAbsolutePath() + "/" + PACKAGE_NAME + "/databases"; /*// SDCard 定义数据库的存放路径 private final String DATABASE_PATH = android.os.Environment .getExternalStorageDirectory().getAbsolutePath() + "/dictionary";*/ private Context context; public DBHelper(Context context) { this.context = context; } public SQLiteDatabase openDatabase() { try { File myDataPath = new File(DB_PATH); if (!myDataPath.exists()) { myDataPath.mkdirs();// 如果没有这个目录则创建 } String dbfile = myDataPath + "/" + DB_NAME; if (!(new File(dbfile).exists())) {// 判断数据库文件是否存在,若不存在则执行导入,否则直接打开数据库 InputStream is = context.getResources().openRawResource( R.raw.dictionary); // 欲导入的数据库 FileOutputStream fos = new FileOutputStream(dbfile); byte[] buffer = new byte[BUFFER_SIZE]; int count = 0; while ((count = is.read(buffer)) > 0) { fos.write(buffer, 0, count); } fos.close(); is.close(); } SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null); return db; } catch (FileNotFoundException e) { Log.e("Database", "File not found"); e.printStackTrace(); } catch (IOException e) { Log.e("Database", "IO exception"); e.printStackTrace(); } return null; } public Cursor query(String name) { SQLiteDatabase db = this.getReadableDatabase(); return db.rawQuery("select * from t_words where english like '%" + name + "%' limit 10", null); } private SQLiteDatabase getReadableDatabase() { // TODO Auto-generated method stub return null; } }
Word.java
package com.example.happydictionary.entity; public class Word { private String english; private String chinese; public String getEnglish() { return english; } public void setEnglish(String english) { this.english = english; } public String getChinese() { return chinese; } public void setChinese(String chinese) { this.chinese = chinese; } }
DBHelperTest.java
package com.example.happydictionary.test; import com.example.happydictionary.db.DBHelper; import android.test.AndroidTestCase; public class DBHelperTest extends AndroidTestCase { public void testCreateDB(){ DBHelper dbHelper=new DBHelper(getContext()); dbHelper.openDatabase(); } }
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.happydictionary" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.happydictionary.MainActivity" android:label="@string/app_name" android:theme="@android:style/Theme.Black.NoTitleBar" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <uses-library android:name="android.test.runner" /> </application> <instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="com.example.happydictionary" > </instrumentation> </manifest>
相关文章推荐
- 微信团队:企业微信账号可申请微信支付功能
- javascript 判断微信浏览器
- mysql保存emoji表情(微信开发用户昵称..)
- 一次做ACM扩展出来的小程序
- iOS关于微信支付的一点小事
- 未来十年营销的主流趋势:微信营销
- 微信公众号二维码 链接
- android微信付费
- Iphone手机,微信调用支付JSAPI缺少参数 timeStamp
- 微信js接口自定义分享内容
- Android 超高仿微信图片选择器 图片该这么加载
- Android 高仿微信头像截取 打造不一样的自定义控件
- android高仿微信拍照、多选、预览、删除(去除相片)相册功能
- 定时采集指定微信公众号发布的文章!!终于搞定了!!哈哈
- 微信分享 添加URL Schemes
- PHP微信开发-------视频学习推荐
- 微信公众开发平台 手册
- Android笔记 ActionBar+Fragment+ViewPager实现仿微信首页滑动切换窗口
- 微信自定义菜单中文乱码问题
- 微信公众之智能硬件————序