Android首选项 - 数据库中的ListPreference无效

时间:2013-04-16 05:36:25

标签: android android-preferences

我正在努力将偏好添加到我的应用程序中,一切都很顺利,直到我尝试从数据库中获取数组以加载到ListPreference中。我正在使用两个两个单独的数组,用于条目和用于entryValues。一切都很好,直到我尝试将CharSequence []传递给setEntries并设置entryValues函数。

以下是代码:

public class EditPreferences extends PreferenceActivity {
private SQLiteDatabase db;
private TimesheetDatabaseHelper dbHelp = new TimesheetDatabaseHelper(this);

@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preference_activity);

    ListPreference projectsList = (ListPreference)findPreference("@string/perfProjectKey");
    /** Open the database table for reading and writing */
    db = dbHelp.getReadableDatabase();
    String getProjects = "select _id, name from projects;";

    Cursor cu = db.rawQuery(getProjects, null);
    Log.d("Database call:", "Success");
    Log.d("Database Rows Returned:", String.valueOf(cu.getCount()));

    List<String> entries = new ArrayList<String>();
    List<String> entryValues = new ArrayList<String>();

    if(cu != null && cu.getCount() > 0){
        cu.moveToFirst();

        do {
            entries.add(cu.getString(1));
            entryValues.add(Integer.toString(cu.getInt(0)));
        } while (cu.moveToNext());

    }
    cu.close();
    db.close();
    Log.d("Out of the loop", "and probably closed");

    final CharSequence[] entryCharSeq = entries.toArray(new CharSequence[entries.size()]);
    final CharSequence[] entryValsChar = entryValues.toArray(new CharSequence[entryValues.size()]);
    Log.d("Past the cast", "maybe we work?");
    Log.d("Entries size:", Integer.toString(entries.size()));
    Log.d("Entry Values size:", Integer.toString(entryValues.size()));

    projectsList.setEntries(entryCharSeq);
    Log.d("We got here:", "TRUE!");
    projectsList.setEntryValues(entryValsChar);

}

}

根据堆栈跟踪,如果需要我可以发布,它是第55行的nullPointerException,而55是

projectsList.setEntries(entryCharSeq);

我不知道什么是错的。希望有人可以提供帮助。

1 个答案:

答案 0 :(得分:3)

更改

ListPreference projectsList = (ListPreference)findPreference("@string/perfProjectKey");

ListPreference projectsList = (ListPreference)findPreference(getString(R.string.perfProjectKey));