Android利用SQLite制作最简单成语小词典

UnzipAssets.java

package com.hu.andstar;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import android.content.Context;

public class UnzipAssets {

	/**
	 * 解压assets的zip压缩文件到指定目录
	 * @param context上下文对象
	 * @param assetName压缩文件名
	 * @param outputDirectory输出目录
	 * @param isReWrite是否覆盖
	 * @throws IOException
	 */
	public static void unZip(Context context, String assetName,
			String outputDirectory,boolean isReWrite) throws IOException {
		//创建解压目标目录
		File file = new File(outputDirectory);
		//如果目标目录不存在,则创建
		if (!file.exists()) {
			file.mkdirs();
		}
		//打开压缩文件
		InputStream inputStream = context.getAssets().open(assetName);
		ZipInputStream zipInputStream = new ZipInputStream(inputStream);
		//读取一个进入点
		ZipEntry zipEntry = zipInputStream.getNextEntry();
		//使用1Mbuffer
		byte[] buffer = new byte[1024 * 1024];
		//解压时字节计数
		int count = 0;
		//如果进入点为空说明已经遍历完所有压缩包中文件和目录
		while (zipEntry != null) {
			//如果是一个目录
			if (zipEntry.isDirectory()) {
				file = new File(outputDirectory + File.separator + zipEntry.getName());
				//文件需要覆盖或者是文件不存在
				if(isReWrite || !file.exists()){
					file.mkdir();
				}
			} else {
				//如果是文件
				file = new File(outputDirectory + File.separator
						+ zipEntry.getName());
				//文件需要覆盖或者文件不存在,则解压文件
				if(isReWrite || !file.exists()){
					file.createNewFile();
					FileOutputStream fileOutputStream = new FileOutputStream(file);
					while ((count = zipInputStream.read(buffer)) > 0) {
						fileOutputStream.write(buffer, 0, count);
					}
					fileOutputStream.close();
				}
			}
			//定位到下一个文件入口
			zipEntry = zipInputStream.getNextEntry();
		}
		zipInputStream.close();
	}
}

 用于第一次运行时解压数据文件到SD卡:

MainActivity.java:

package com.hu.andstar;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog.Builder;
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.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {

	// 指定数据库文件所在目录
	private final String DATABASE_PATH = android.os.Environment
			.getExternalStorageDirectory().getAbsolutePath() + "/andstar";
	// 指定数据库文件名
	private final String DATABASE_FILENAME = "data.db";

	private SQLiteDatabase database = null;
	private EditText etInput = null;
	private ImageButton ibSearch = null;
	private ListView lvWords = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// 找到控件
		etInput = (EditText) findViewById(R.id.editTextInput);
		ibSearch = (ImageButton) findViewById(R.id.imageButtonSearch);
		lvWords = (ListView) findViewById(R.id.listViewWords);
		initAll();
	}

	private void initAll() {
		// 获取并打开数据库
		database = openDatabase();
		// 设置ListView数据
		lvWords.setAdapter(getIndexs(""));
		// 当输入框文本改变时,让ListView现实的数据也随之改变
		etInput.addTextChangedListener(new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

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

			public void afterTextChanged(Editable s) {
				// 重新设置ListView的数据
				lvWords.setAdapter(getIndexs(etInput.getText().toString()));
			}
		});

		// 当ListView子项单击时,让文本框内容变成该项文本
		lvWords.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				etInput.setText(((TextView) view).getText());
				etInput.selectAll();
			}
		});

		// 设置查询按钮事件
		ibSearch.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// 查询SQL语句
				String sql = "SELECT dContent FROM words WHERE dIndex = @arg";
				Cursor cursor = database.rawQuery(sql, new String[] { etInput
						.getText().toString() });
				// 如果查询有结果,将第一个结果传递给显示结果的Activity
				if (cursor.getCount() > 0) {
					cursor.moveToFirst();
					Intent intent = new Intent();
					intent.putExtra("word", etInput.getText().toString());
					intent.putExtra("explain", cursor.getString(0));
					cursor.close();
					intent.setClass(MainActivity.this, ExplainActivity.class);
					MainActivity.this.startActivity(intent);
				}
			}
		});
	}

	// 获取ListView所要显示的数据
	ArrayAdapter<String> getIndexs(String input) {
		List<String> list = new ArrayList<String>();
		// 获取32条大于等于该文本的数据
		String sql = "SELECT dIndex FROM words WHERE dIndex >= @arg limit 0,32";
		// 执行查询语句
		Cursor cursor = database.rawQuery(sql, new String[] { input });
		if (cursor.getCount() > 0) {
			while (cursor.moveToNext()) {
				list.add(cursor.getString(0));
			}
			cursor.close();
		} else {// 如果获取结果为空
			list.add(getString(R.string.no_match));
		}
		return new ArrayAdapter<String>(MainActivity.this,
				android.R.layout.simple_list_item_1, list);// 返回ArrayAdapter
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// 退出选项
		if (item.getItemId() == R.id.menu_exit) {
			Builder builder = new Builder(MainActivity.this);
			builder.setMessage("确认退出吗?");
			builder.setTitle("提示");
			builder.setPositiveButton(R.string.button_positive,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							System.exit(0);
						}
					});
			builder.setNegativeButton(R.string.button_cancle, null);
			builder.show();
		} else {

		}
		return super.onOptionsItemSelected(item);
	}

	private SQLiteDatabase openDatabase() {// 打开数据库函数
		try {
			String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME;
			File databaseFile = new File(databaseFilename);
			// 如果SD卡上数据库文件不存在,则解压数据库文件
			if (!databaseFile.exists()) {
				UnzipAssets.unZip(MainActivity.this, "data.zip", DATABASE_PATH,
						true);
			}
			// 返回打开的数据库
			return SQLiteDatabase.openOrCreateDatabase(databaseFilename, null);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}

 

查词界面;

 
Android利用SQLite制作最简单成语小词典
 

ExplainActivity.java

package com.hu.andstar;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.webkit.WebView;
import android.widget.TextView;

/*用于显示查询结果
 * 使用WebView显示
 */
public class ExplainActivity extends Activity{
	
	private TextView tvWord = null;
	private WebView tvExplain = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_explain);
		tvWord = (TextView) findViewById(R.id.textViewWord);
		tvExplain = (WebView) findViewById(R.id.webViewExplain);
		Intent intent = getIntent();
		tvWord.setText(intent.getStringExtra("word"));
		String htmText = intent.getStringExtra("explain");
		tvExplain.loadDataWithBaseURL(null,htmText, "text/html",  "utf-8", null);
	}
}

 用于显示解释:

 

 
Android利用SQLite制作最简单成语小词典
 

你可能感兴趣的:(android)