如何保存复选框的状态数据库(无论真假州) [英] How to save state of checkboxes in database (both true and false states)

查看:153
本文介绍了如何保存复选框的状态数据库(无论真假州)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Andr​​oid应用我有一个数据库,其中存储短语对象和主题对象,其他数据。这些词组有一个属性 sourceLanguage (String)和一个 isSelected 属性(字符串也因为SQLite没有布尔 - 不记得为什么我没有用0和1,但是这是不相关)。该主题包含一个或多个短语。

In my Android app I have a DB where store Phrase objects, and Theme objects, among other data. These phrases have an attribute sourceLanguage (String) and an isSelected attribute (String too, since SQLITE doesn't have boolean - can't recall why I didn't use 0 and 1, but that's not relevant). The themes contain one or more phrases.

我有一个活动,用户被赋予一个的ListView 与主题的列表。当他拿起一个主题,一个警告对话框显示了复选框词组列表,因此他可以选择一个或多个。我想使用从AlertDialog复选框的信息,更改更新数据库每个短语 isSelected 来真或假,这取决于用户的选择。

I have one activity where the user is given a listView with a list of themes. When he picks a theme, an alert dialog displays with a checkbox list of phrases so he can select one or more. I'd like to update each phrase in the DB using the information from the AlertDialog checkboxes, changing isSelected to "true" or to "false", depending on the user's choice.

我的困难是,我在网上找到到目前为止的例子可以保存元素的真实的状态,而不是假。所以,如果一个短语存储为真,后又改为假,它根本不会出现在 selectedItems ,我没有一个参考访问它,它修改为假。我想出了几个解决方案,但我不相信任何,这是你能不能帮我。

My difficulty is that the examples I found online so far allow to save the "true" state of the elements, but not the "false". So if a phrase is stored as "true", and then changed to "false", it will simply not appear in the selectedItems, and I don't have a reference to access it and modify it to "false". I've come up with a couple of solutions, but I'm not confident about any, and this is where you could help me.

我的AlertDialog方式:

My AlertDialog method:

private void showAlertDialog(int themeId, String themeName) {
    // TODO Auto-generated method stub

// Build the list of phrases for respective theme and list of previously selected items
final DatabaseHandler db = new DatabaseHandler(this);
List<Phrase> allThemePhr = db.getPhrases("with_theme", themeId, null); // all phrases for selected theme 
CharSequence[] sourceLanguageAllPhr = new String[allThemePhr.size()]; // source language of all phrases for selected theme
boolean[] selectedItems = new boolean[allThemePhr.size()]; // selected items only
final List<String> sourceLanguageSelectedPhr = new ArrayList<String>();
final List<String> sourceLanguageNOTSelectedPhr = new ArrayList<String>();

for (int i = 0 ; i < allThemePhr.size() ; i++){
    sourceLanguageAllPhr[i] = allThemePhr.get(i).getSource_language();
    selectedItems[i] = false;
    if (allThemePhr.get(i).getItemSelected() == "true"){
        selectedItems[i] = true;
        sourceLanguageSelectedPhr.add(allThemePhr.get(i).getSource_language());
    }
}


// Build the dialog
@SuppressWarnings("rawtypes")
final ArrayList selectedPhrases = new ArrayList();

AlertDialog.Builder builder = new AlertDialog.Builder(PickTheme.this);
builder.setTitle(themeName)
        .setMultiChoiceItems(sourceLanguageAllPhr, selectedItems, new DialogInterface.OnMultiChoiceClickListener() {
            @SuppressWarnings("unchecked")
            @Override
            public void onClick(DialogInterface dialog, int which,
                    boolean isChecked) {
                // TODO Auto-generated method stub
                if(isChecked){
                    selectedPhrases.add(which);
                    //sourceLanguageSelectedPhr.add(selectedPhrases.get(which).toString());
                } else if (selectedPhrases.contains(which)){
                    selectedPhrases.remove(Integer.valueOf(which));
                    //sourceLanguageSelectedPhr.remove(selectedPhrases.get(which).toString());
                    //sourceLanguageNOTSelectedPhr.add(selectedPhrases.get(which).toString());
                }
            }
        })
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                //for (String sourceLanguage : sourceLanguageSelectedPhr){
                    //db.updatePhrase(sourceLanguage, "true");
                    //Log.i("selectedPhrase", selectedPhrases.get(which).toString());
                //}
            }
        })
        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub

            }
        });
    builder.create().show();
}

在我DatabaseHelper类中,我定义了这些方法,可以用于更新语句:

In my DatabaseHelper class, I've defined these methods that can be used to update phrases:

// updating a phrase

public int updatePhrase(Phrase phrase){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_PHRASE_ID, phrase.getWord_id());
values.put(COLUMN_SOURCE_LANGUAGE, phrase.getSource_language());
values.put(COLUMN_TARGET_LANGUAGE, phrase.getTarget_language());
values.put(COLUMN_PHRASE_REMINDER_DATE, phrase.getTarget_language());
values.put(COLUMN_PHRASE_THEME_ID, phrase.getTheme_id());
values.put(COLUMN_PHRASE_REMINDER_ID, phrase.getTheme_id());

int phraseUpdated = db.update(PHRASES_TABLE, values, COLUMN_PHRASE_ID + " =?", new String[] {String.valueOf(phrase.getWord_id())});
db.close();
return phraseUpdated;
}

// updating a phrase based on given source_language
public void updatePhrase(String sourceLanguage, String isSelected){
    SQLiteDatabase db = this.getWritableDatabase();
    String updateStatement = "UPDATE " + PHRASES_TABLE
                             + " SET " + COLUMN_ITEM_SELECTED + " = " + isSelected
                             + " WHERE " + COLUMN_SOURCE_LANGUAGE + " = " + sourceLanguage;
    db.execSQL(updateStatement);
}

到目前为止,我已经想到了一些解决方案,这其中似乎是最好的:当选择/取消选择一个短语,从 allThemePhr 得到它,相应地更新对象,并将其保存在另一个列表。如果用户单击确定,使用该列表来更新数据库。我的问题是:如何将我的值相匹配,在 allThemePhr 各自的对象?如果我能想出​​如何获取复选框的文字,应该是可以接受的,因为它对应于词组的 SOURCE_LANGUAGE 属性

So far, I've thought of a few solutions, this one seemed the best: when a phrase is selected / de-selected, get it from the allThemePhr, update the object accordingly, and save it in another List. If user clicks OK, use that list to update the DB. My problem is: how to I match the value of which with the respective object in allThemePhr ? If I can figure out how to get the checkbox text, that should be acceptable, since it corresponds to the source_language attribute of phrase?

也许有一个简单的解决方案?

Maybe there is a simpler solution?

感谢

推荐答案

有就是那句对象在全球短语列表中该指数与指数之间的匹配 allThemePhr ,所以没有必要去通过复选框的字符串/值 sourceLanguage

There is a match between the index which and the index the phrase objects have in the global phrases List allThemePhr, so no need to go through the string of the checkbox / the value of sourceLanguage.

所以,我只是创建了一个地图,我存储索引和复选框(的器isChecked )。然后,如果用户pressesOK,我通过地图迭代,从 allThemePhr 得到相应的词组对象,并对其进行更新。

So, I simply created a map where I store the correspondence between the index which and the status of the checkbox (isChecked). Then, if the user presses "OK", I iterate through that map, get the corresponding phrase object from allThemePhr and update it.

下面是最后的code:

Here is the final code:

private void showAlertDialog(int themeId, String themeName) {
// TODO Auto-generated method stub

// Build the list of phrases for respective theme and list of previously selected items
final DatabaseHandler db = new DatabaseHandler(this);
final List<Phrase> allThemePhr = db.getPhrases("with_theme", themeId, null); // all phrases for selected theme 
final Map<Integer, Boolean> selectionChanges = new HashMap<Integer,Boolean>();
CharSequence[] sourceLanguageAllPhr = new String[allThemePhr.size()]; // source language of all phrases for selected theme
boolean[] selectedItems = new boolean[allThemePhr.size()]; // selected items only


for (int i = 0 ; i < allThemePhr.size() ; i++){
    Phrase phrase = allThemePhr.get(i);
    sourceLanguageAllPhr[i] = phrase.getSource_language();


    if (phrase.getItemSelected().equals("true")){
        selectedItems[i] = true;
    }
}


// Build the dialog
AlertDialog.Builder builder = new AlertDialog.Builder(PickTheme.this);
builder.setTitle(themeName)
        .setMultiChoiceItems(sourceLanguageAllPhr, selectedItems, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which,
                    boolean isChecked) {

                selectionChanges.put(which, isChecked);


            }
        })
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                for (Map.Entry<Integer, Boolean> entry : selectionChanges.entrySet()){
                    Phrase phrase = allThemePhr.get(entry.getKey());

                    phrase.setItemSelected(String.valueOf(entry.getValue()));


                }
            }
        })
        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub

            }
        });
        builder.create().show();
}

这篇关于如何保存复选框的状态数据库(无论真假州)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆