我有一个字典应用程序,它从SQL数据库获取数据。 该数据库有一个“ First table”表,其中包含3列ID,单词,含义(单词法语,英语)
我插入了具有相同列的新表“第二表”,但这一次与我的意思相反(英语中的单词表示法语) 我想插入一个按钮以在搜索方法“使用法语单词进行搜索和使用英语单词进行搜索的按钮”之间切换 当用户单击按钮“ FR> ENG”时,我想从第一个表中获取数据(法语中的单词是英语),单击时则相反 按钮“ ENG> FR”,使用我之前添加的第二个表格(英语中的单词表示法语)
DataBaseHelper.java
public class DataBaseHelper extends SQLiteOpenHelper {
public static String DB_PATH;
public final Context context;
public SQLiteDatabase database;
public static String DB_NAME = "Database";
public SQLiteDatabase getDb() {
return this.database;
}
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.context = context;
DB_PATH = String.format("//data//data//%s//databases//", new Object[]{context.getPackageName()});
openDataBase();
}
public void createDataBase() {
if (checkDataBase()) {
Log.i(getClass().toString(), "Database already exists");
return;
}
getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
Log.e(getClass().toString(), "Copying error");
throw new Error("Error copying database!");
}
}
private boolean checkDataBase() {
SQLiteDatabase checkDb = null;
try {
checkDb = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, 0);
} catch (SQLException e) {
Log.e(getClass().toString(), "Error while checking db");
}
if (checkDb != null) {
checkDb.close();
}
if (checkDb != null) {
return true;
}
return false;
}
private void copyDataBase() throws IOException {
InputStream externalDbStream = this.context.getAssets().open(DB_NAME);
OutputStream localDbStream = new FileOutputStream(DB_PATH + DB_NAME);
byte[] buffer = new byte[1024];
while (true) {
int bytesRead = externalDbStream.read(buffer);
if (bytesRead > 0) {
localDbStream.write(buffer, 0, bytesRead);
} else {
localDbStream.close();
externalDbStream.close();
return;
}
}
}
public SQLiteDatabase openDataBase() throws SQLException {
String path = DB_PATH + DB_NAME;
if (this.database == null) {
createDataBase();
this.database = SQLiteDatabase.openDatabase(path, null, 0);
}
return this.database;
}
public synchronized void close() {
if (this.database != null) {
this.database.close();
}
super.close();
}
public void onCreate(SQLiteDatabase db) {
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
DataManager.java
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Base64;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
public class DataManager {
DataBaseHelper myDbHelper;
SQLiteDatabase db;
public DataManager(Context context) {
myDbHelper = new DataBaseHelper(context);
myDbHelper.createDataBase();
try {
myDbHelper.openDataBase();
} catch (SQLException sqle) {
sqle.printStackTrace();
}
db = myDbHelper.getReadableDatabase();
}
//Get All Data
public List<Word> getAllData() {
Cursor cur = db.rawQuery("select * from table_fr_eng LIMIT 5000;", null);
List<Word> item_data = new ArrayList<Word>();
if (cur.getCount() != 1) {
if (cur.moveToFirst()) {
do {
Word obj = new Word();
obj.id = cur.getString(cur.getColumnIndex("Id"));
obj.word = cur.getString(cur.getColumnIndex("Word"));
obj.is_fav = cur.getString(cur.getColumnIndex("is_favourite"));
if (obj.is_fav!=null) {
} else {
obj.is_fav="0";
}
obj.meaning = cur.getString(cur.getColumnIndex("Meaning"));
item_data.add(obj);
} while (cur.moveToNext());
}
}
return item_data;
}
//Get Search Data
public List<Word> getAllSearchData(String search) {
Cursor cur = db.rawQuery("SELECT * FROM table_fr_eng WHERE Word LIKE '" + search + "%' LIMIT 30", null);
List<Word> item_data = new ArrayList<Word>();
if (cur.getCount() != 0) {
if (cur.moveToFirst()) {
do {
Word obj = new Word();
obj.id = cur.getString(cur.getColumnIndex("Id"));
obj.word = cur.getString(cur.getColumnIndex("Word"));
obj.is_fav = cur.getString(cur.getColumnIndex("is_favourite"));
if (obj.is_fav!=null) {
} else {
obj.is_fav="0";
}
obj.meaning = cur.getString(cur.getColumnIndex("Meaning"));
item_data.add(obj);
} while (cur.moveToNext());
}
}
return item_data;
}
//Add Word And Meaning
public Boolean InsertWord(String strWord, String strMeaning) {
String insertQuery = "INSERT INTO table_fr_eng(Word,Meaning) values('" + strWord + "','"
+ strMeaning + "')";
db.execSQL(insertQuery);
db.close();
return true;
}
//Get Day of The Word
public Word DayOfWord() {
Cursor cur = db.rawQuery("SELECT * FROM table_fr_eng ORDER BY RANDOM() LIMIT 1 ;",null);
Word objWord = new Word();
if (cur.getCount() != 0) {
if (cur.moveToFirst()) {
do {
objWord.word = cur.getString(cur.getColumnIndex("Word"));
objWord.meaning = cur.getString(cur.getColumnIndex("Meaning"));
} while (cur.moveToNext());
}
}
return objWord;
}
//Add Favourite Word
public void FavouriteWord(String id) {
String updateQuery = "UPDATE table_fr_eng SET is_favourite='"+1+"' WHERE Id=" +id;
SQLiteDatabase db = this.myDbHelper.getWritableDatabase();
db.execSQL(updateQuery);
db.close();
}
//Add UnFavourite Word
public void UnFavouriteWord(String id) {
String updateQuery = "UPDATE table_fr_eng SET is_favourite='' WHERE Id=" +id;
SQLiteDatabase db = this.myDbHelper.getWritableDatabase();
db.execSQL(updateQuery);
db.close();
}
//Get All Favourite Word
public List<Word> getAllFavouriteData() {
Cursor cur = db.rawQuery("select * from table_fr_eng where is_favourite=1;",null);
List<Word> item_data = new ArrayList<Word>();
if (cur.getCount() != 0) {
if (cur.moveToFirst()) {
do {
Word obj = new Word();
obj.id = cur.getString(cur.getColumnIndex("Id"));
obj.word = cur.getString(cur.getColumnIndex("Word"));
if (obj.is_fav!=null) {
} else {
obj.is_fav="1";
}
obj.meaning = cur.getString(cur.getColumnIndex("Meaning"));
item_data.add(obj);
} while (cur.moveToNext());
}
}
return item_data;
}
//Add History
public void InsertHistoryWord(String word, String meaning) {
String insertQuery = "INSERT INTO tblHistory(word,meaning) values('" + word + "','"
+ Base64.encodeToString(meaning.getBytes(), Base64.DEFAULT) + "')";
db.execSQL(insertQuery);
db.close();
}
//Get All History Word
public List<Word> getAllHistoryData() {
Cursor cur = db.rawQuery("select * from tblHistory;", null);
List<Word> item_data = new ArrayList<Word>();
if (cur.getCount() != 0) {
if (cur.moveToFirst()) {
do {
Word obj = new Word();
obj.id = cur.getString(cur.getColumnIndex("Id"));
obj.word = cur.getString(cur.getColumnIndex("word"));
obj.meaning = cur.getString(cur.getColumnIndex("meaning"));
byte[] data1 = Base64.decode(obj.meaning, Base64.DEFAULT);
try {
obj.meaning = new String(data1, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
item_data.add(obj);
} while (cur.moveToNext());
}
}
return item_data;
}
//Delete History
public List<Word> getDeleteHistoryData() {
List<Word> item_data = new ArrayList<Word>();
String deleteQuery = "delete from tblHistory";
db.execSQL(deleteQuery);
db.close();
return item_data;
}
//Get Quiz Word and Meaning
public List<Word> Quiz() {
Cursor cur = db.rawQuery("SELECT * FROM table_fr_eng ORDER BY RANDOM() LIMIT 4 ;",null);
List<Word> item_data = new ArrayList<Word>();
if (cur.getCount() != 0) {
if (cur.moveToFirst()) {
do {
Word obj = new Word();
obj.id = cur.getString(cur.getColumnIndex("Id"));
obj.word = cur.getString(cur.getColumnIndex("Word"));
obj.meaning = cur.getString(cur.getColumnIndex("Meaning"));
item_data.add(obj);
} while (cur.moveToNext());
}
}
return item_data;
}
//Delete Favourite Word
public List<Word> getDeleteFavouriteData() {
List<Word> item_data = new ArrayList<Word>();
String deleteQuery = "delete from table_fr_eng where is_favourite";
db.execSQL(deleteQuery);
db.close();
return item_data;
}
}
答案 0 :(得分:0)
以下是一个有效的示例,它将根据单击的按钮给出输入到编辑文本中的单词的含义。
例如如果输入是,并且单击 Eng-> Fr 按钮,则会显示 单词Yes表示法语中的Oui。 强>。如果单击 Fr-> Eng 按钮,则会显示 单词是,表示我不懂英语。 (即没有在法语中为yes的意思。
反过来输入 Oui 会说 单词Oui意思是英语 或 Oui意味着我不知道法语。
这是SQLiteOpenHelper的子类,是在Android中访问SQLiteDatabase的一种典型方法:-
public class MyDBHelper extends SQLiteOpenHelper {
public static final String DBNAME = "translator";
public static final int DBVERSION = 1;
public static final String TBL_ENGFR = "engfr";
public static final String TBL_FRENG = "freng";
public static final String COL_ID = BaseColumns._ID;
public static final String COL_WORD = "word";
public static final String COl_MEANING = "meaning";
public static final int TRANSLATOR_TYPE_ENGLISH_TO_FRENCH = 0;
public static final int TRANSLATOR_TYPE_FRENCH_TO_ENGLISH = 1;
SQLiteDatabase mDB;
public MyDBHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
mDB = this.getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(crt_table_sql(getTableToUse(TRANSLATOR_TYPE_ENGLISH_TO_FRENCH)));
db.execSQL(crt_table_sql(getTableToUse(TRANSLATOR_TYPE_FRENCH_TO_ENGLISH)));
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public String getMeaningOfWord(String word, int type) {
String rv = "";
String whereclause = COL_WORD + "=?";
String[] whereargs = new String[]{word};
Cursor csr = mDB.query(getTableToUse(type),null,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
rv = csr.getString(csr.getColumnIndex(COl_MEANING));
}
csr.close();
return rv;
}
public long addWord(String word, String meaning,int type) {
ContentValues cv = new ContentValues();
cv.put(COL_WORD,word);
cv.put(COl_MEANING,meaning);
return mDB.insert(getTableToUse(type),null,cv);
}
private String crt_table_sql(String table) {
return "CREATE TABLE IF NOT EXISTS " + table + "(" +
COL_ID + " INTEGER PRIMARY KEY, " +
COL_WORD + " TEXT, " +
COl_MEANING + " TEXT" +
")";
}
private String getTableToUse(int type) {
String rv = "";
switch (type) {
case TRANSLATOR_TYPE_ENGLISH_TO_FRENCH:
rv = TBL_ENGFR;
break;
case TRANSLATOR_TYPE_FRENCH_TO_ENGLISH:
rv = TBL_FRENG;
break;
}
return rv;
}
}
在所有情况下,基础表都是根据定义帮助程序的两个常量所表示的int值(0(英语至法语)或1(法语至英语))确定的。
主要活动中的按钮还使用常量来确定含义的语言。
此活动包含3个UI元素,一个用于输入单词的编辑文本和两个按钮。单击一个将使用相应的表格来确定单词的含义。
public class MainActivity extends AppCompatActivity {
EditText mWordToGetMeaningOf;
Button mENG_TO_FR, mFR_TO_ENG;
Context mContext;
String mCurrentmeaning;
MyDBHelper mDBhlpr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
mWordToGetMeaningOf = this.findViewById(R.id.word_to_get_meaning_of);
mENG_TO_FR = this.findViewById(R.id.eng_to_fr);
mFR_TO_ENG = this.findViewById(R.id.fr_to_eng);
mDBhlpr = new MyDBHelper(this);
addSomeData();
mENG_TO_FR.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCurrentmeaning = mDBhlpr.getMeaningOfWord(mWordToGetMeaningOf.getText().toString(),MyDBHelper.TRANSLATOR_TYPE_ENGLISH_TO_FRENCH);
displayMeaning(MyDBHelper.TRANSLATOR_TYPE_ENGLISH_TO_FRENCH);
}
});
mFR_TO_ENG.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCurrentmeaning = mDBhlpr.getMeaningOfWord(mWordToGetMeaningOf.getText().toString(),MyDBHelper.TRANSLATOR_TYPE_FRENCH_TO_ENGLISH);
displayMeaning(MyDBHelper.TRANSLATOR_TYPE_FRENCH_TO_ENGLISH);
}
});
}
/**
* Toasts the meaning of the word (also writes the same message to the log)
* @param type
*/
private void displayMeaning(int type) {
String meaning_type = "";
switch (type) {
case MyDBHelper.TRANSLATOR_TYPE_ENGLISH_TO_FRENCH:
meaning_type = "French";
break;
case MyDBHelper.TRANSLATOR_TYPE_FRENCH_TO_ENGLISH:
meaning_type = "English";
break;
}
if (mCurrentmeaning.length() < 1) {
mCurrentmeaning = " I don't know ";
}
String message = "The Word " +
mWordToGetMeaningOf.getText().toString() +
" means " + mCurrentmeaning +
" in " + meaning_type + ".";
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
Log.d("MEANING",message);
}
/**
* Add some testing data
*/
private void addSomeData() {
mDBhlpr.addWord("Yes","Oui",MyDBHelper.TRANSLATOR_TYPE_ENGLISH_TO_FRENCH);
mDBhlpr.addWord("Oui","Yes",MyDBHelper.TRANSLATOR_TYPE_FRENCH_TO_ENGLISH);
}
}