【问题标题】:How to save/retrieve words to/from SQlite database?如何在 SQlite 数据库中保存/检索单词?
【发布时间】:2011-11-12 17:40:55
【问题描述】:

对不起,如果我重复我的问题,但我仍然不知道该怎么做以及如何处理这个问题。

我的应用是一本字典。我假设用户需要将他们想要记住的单词添加到收藏夹列表中。因此,我创建了一个收藏按钮,它在两个阶段起作用:

  • 短按将当前查看的单词保存到收藏夹列表中;
  • 并长按可查看收藏列表,以便用户单击任何单词再次查找。

我喜欢使用 SQlite 数据库来存储最喜欢的单词,但我想知道如何完成这项任务。具体来说,我的问题是:

  1. 我应该使用当前的字典 SQLite 数据库还是创建一个新的 SQLite 数据库来收藏单词?
  2. 在每种情况下,我必须编写哪些代码来处理上述任务?

有人可以帮忙吗?

这是字典代码:


package mydict.app;

import java.util.ArrayList;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.util.Log;

public class DictionaryEngine {
static final private String SQL_TAG = "[MyAppName - DictionaryEngine]";

private SQLiteDatabase mDB = null;

private String mDBName;
private String mDBPath;
//private String mDBExtension;
public ArrayList<String> lstCurrentWord = null;
public ArrayList<String> lstCurrentContent = null;
//public ArrayAdapter<String> adapter = null;

public DictionaryEngine()
{
    lstCurrentContent = new ArrayList<String>();
    lstCurrentWord = new ArrayList<String>();
}

public DictionaryEngine(String basePath, String dbName, String dbExtension)
{
    //mDBExtension = getResources().getString(R.string.dbExtension);
    //mDBExtension = dbExtension;
    lstCurrentContent = new ArrayList<String>();
    lstCurrentWord = new ArrayList<String>();

    this.setDatabaseFile(basePath, dbName, dbExtension);
}

public boolean setDatabaseFile(String basePath, String dbName, String dbExtension)
{
    if (mDB != null)
    {
        if (mDB.isOpen() == true) // Database is already opened
        {
            if (basePath.equals(mDBPath) && dbName.equals(mDBName)) // the opened database has the same name and path -> do nothing
            {
                Log.i(SQL_TAG, "Database is already opened!");
                return true;
            }
            else
            {
                mDB.close();
            }
        }
    }

    String fullDbPath="";

    try
    {
        fullDbPath = basePath + dbName + "/" + dbName + dbExtension;
        mDB = SQLiteDatabase.openDatabase(fullDbPath, null, SQLiteDatabase.OPEN_READWRITE|SQLiteDatabase.NO_LOCALIZED_COLLATORS);
    }
    catch (SQLiteException ex)
    {
        ex.printStackTrace();
        Log.i(SQL_TAG, "There is no valid dictionary database " + dbName +" at path " + basePath);
        return false; 
    }

    if (mDB == null)
    {
        return false;
    }

    this.mDBName = dbName;
    this.mDBPath = basePath;

    Log.i(SQL_TAG,"Database " + dbName + " is opened!");

    return true;
}

public void getWordList(String word)
{
    String query;
    // encode input
    String wordEncode = Utility.encodeContent(word);

    if (word.equals("") || word == null)
    {
        query = "SELECT id,word FROM " + mDBName + " LIMIT 0,15" ;
    }
    else
    {
        query = "SELECT id,word FROM " + mDBName + " WHERE  word >= '"+wordEncode+"' LIMIT 0,15";
    }
    //Log.i(SQL_TAG, "query = " + query);

    Cursor result = mDB.rawQuery(query,null);

    int indexWordColumn = result.getColumnIndex("Word");
    int indexContentColumn = result.getColumnIndex("Content");

    if (result != null)
    {
        int countRow=result.getCount();
        Log.i(SQL_TAG, "countRow = " + countRow);
        lstCurrentWord.clear();
        lstCurrentContent.clear();
        if (countRow >= 1)
        {
            result.moveToFirst();
            String strWord = Utility.decodeContent(result.getString(indexWordColumn));
            String strContent = Utility.decodeContent(result.getString(indexContentColumn));
            lstCurrentWord.add(0,strWord);
            lstCurrentContent.add(0,strContent);
            int i = 0;
            while (result.moveToNext()) 
            {
                strWord = Utility.decodeContent(result.getString(indexWordColumn));
                strContent = Utility.decodeContent(result.getString(indexContentColumn));
                lstCurrentWord.add(i,strWord);
                lstCurrentContent.add(i,strContent);
                i++;
            } 

        }

        result.close();
    }

}

public Cursor getCursorWordList(String word)
{
    String query;
    // encode input
    String wordEncode = Utility.encodeContent(word);

    if (word.equals("") || word == null)
    {
        query = "SELECT id,word FROM " + mDBName + " LIMIT 0,15" ;
    }
    else
    {
        query = "SELECT id,content,word FROM " + mDBName + " WHERE  word >= '"+wordEncode+"' LIMIT 0,15";
    }
    //Log.i(SQL_TAG, "query = " + query);

    Cursor result = mDB.rawQuery(query,null);

    return result;      
}

public Cursor getCursorContentFromId(int wordId)
{
    String query;
    // encode input
    if (wordId <= 0)
    {
        return null;
    }
    else
    {
        query = "SELECT id,content,word FROM " + mDBName + " WHERE Id = " + wordId ;
    }
    //Log.i(SQL_TAG, "query = " + query);
    Cursor result = mDB.rawQuery(query,null);

    return result;      
}

public Cursor getCursorContentFromWord(String word)
{
    String query;
    // encode input
    if (word == null || word.equals(""))
    {
        return null;
    }
    else
    {
        query = "SELECT id,content,word FROM " + mDBName + " WHERE word = '" + word + "' LIMIT 0,1";
    }
    //Log.i(SQL_TAG, "query = " + query);

    Cursor result = mDB.rawQuery(query,null);

    return result;      
}

public void closeDatabase()
{
    mDB.close();
}

public boolean isOpen()
{
    return mDB.isOpen();
}

public boolean isReadOnly()
{
    return mDB.isReadOnly();
}

}

这是收藏按钮下方的代码,用于保存和加载收藏列表:


btnAddFavourite = (ImageButton) findViewById(R.id.btnAddFavourite);
btnAddFavourite.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // Add code here to save the favourite, e.g. in the db.
                Toast toast = Toast.makeText(ContentView.this, R.string.messageWordAddedToFarvourite, Toast.LENGTH_SHORT);
                toast.show();
            }
        });

    btnAddFavourite.setOnLongClickListener(new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {

                // Open the favourite Activity, which in turn will fetch the saved favourites, to show them.
                Intent intent = new Intent(getApplicationContext(), FavViewFavourite.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                getApplicationContext().startActivity(intent); 

                return false;
            }
        });
}

【问题讨论】:

  • 你不需要创建一个新的数据库,在我看来你只需要两个查询,一个从收藏夹表中获取所有收藏夹,一个将收藏夹保存到表中。
  • 我强烈建议你在 android 中使用 DBAdaptor。链接:devx.com/wireless/Article/40842/0/page/1
  • 非常感谢。我会按照你们的提示尝试。

标签: android sqlite dictionary


【解决方案1】:

你需要有两张桌子

  1. 单词
  2. 收藏夹

单词(id, word, meaning,...)

收藏夹(id, word_id)

在收藏夹表中有一个外键指向单词表中的单词。

我只解决了您需要构建表格的方式。

*已编辑*

words(id, name, meaning, timestamp)
favortie(id, word_id)

【讨论】:

  • @user998032 您只需要一个数据库,其中包含 Harsha M V 建议的两个表。
  • 非常感谢。这就是我一直在想的。但我确实需要一个例子来效仿。你能帮忙吗?
  • 分享你现在的表格我会为你修改它
  • @Harsha M V:非常感谢,但抱歉您指的是数据库?这是我的示例数据库:link
  • 非常感谢。我想我可以使用 SQLite Browser 来完成这项任务。我正在按照您提供的链接创建一个 DBAdapter 类,但我真的不知道如何将收藏夹存储到现有 SQLite 数据库中的新表中。
猜你喜欢
  • 2011-09-24
  • 1970-01-01
  • 2013-06-28
  • 1970-01-01
  • 2012-06-29
  • 2012-11-30
  • 1970-01-01
  • 1970-01-01
  • 2016-10-10
相关资源
最近更新 更多