2017-07-29 29 views
0

我正在开发一个android项目。在我的sqlite数据库中,我收到了一些与这些问题相关的问题,答案和textview id。在我的xml中,我有“textA”,“ textB“,”textBLABLA“。我也有这些ID在我的数据库中。从数据库中获取textview id并使用它

要从数据库中获取textview编号,我使用这个sql代码。

private void getText(int id) { 
Cursor getTextView = myDatabase.rawQuery("SELECT textView FROM questions WHERE id = ?", new String[] {String.valueOf(id)}); 
int textIndex = getTextView.getColumnIndex("textView"); 

我可以得到这个值。但是我怎样才能使用这个值来编辑那个textview呢?例如改变它的背景颜色像;

questionTextView.setBackgroundColor(Color.BLACK); 
+0

你可以显示你如何把这些ID在数据库中的代码? –

+0

我把它们通过数据库浏览器手动SQLite.Then使用Android设备管理器来更改它与旧one.I可以得到的值,但不知道如何使用它们提到 – MePengusta

+0

创建一个textview对象与此ID(从您的数据库) 'TextView questionTextView =(TextView)findViewById(idFetchedFromDb);' 然后用这个对象编辑文本视图。 –

回答

0

您刚刚提取了列索引而不是列中的值。

private void getText(int id) { 
Cursor getTextView = myDatabase.rawQuery("SELECT textView FROM questions WHERE id = ?", new String[] {String.valueOf(id)}); 
int textIndex = getTextView.getColumnIndex("editText"); // this gives you the column index you requested 

// AD THIS AFTER ABOVE CODE 
if(getTextView.moveToNext()){ 
    int textViewId = getTextView.getInt(textIndex); // this gives you the value from the column index you provide and and the row you on which the current cursor is 
    TextView questionTextView = (TextView) findViewById(textViewId); 
    /* UPDATE */ 
    questionTextView.setBackgroundColor(Color.Black); 
} 

您需要从提取的列索引中获取值。

+0

上调用虚拟方法'void android.widget.TextView.setBackgroundColor(int)'我做了这个。现在我想改变那个textview的背景颜色 questionTextView.setBackgroundColor( Color.BLACK); 但它崩溃。可能是什么问题? – MePengusta

+0

你的日志猫说什么?空指针? –

+0

是的。 java.lang.NullPointerException:尝试调用空对象引用虚拟方法'void android.widget.TextView.setBackgroundColor(int)' – MePengusta

相关问题