0

I have connected a database in my Android Application. Now I have created a button and when it is clicked, that should get the next data from the table of database. I have cursor and he moveToFirst() and moveToNext() methods in my code. also I have set onclick listener to my button. but in output when I click the button, its is not fetching the next data from database

heres the part of code where I have tried to set on click listener for button

 c=myDbHelper.query(myDbHelper.DB_PATH +"/MainTable",null, null, null, null,null, null);
        c.moveToFirst();

                 myques=(TextView)findViewById(R.id.question);
                 myrg=(RadioGroup)findViewById(R.id.rg1);
                 myc1=(RadioButton)findViewById(R.id.radio0);
                 myc2=(RadioButton)findViewById(R.id.radio1);
                 myc3=(RadioButton)findViewById(R.id.radio2);
                 myc4=(RadioButton)findViewById(R.id.radio3);
                 NxtQues=(Button)findViewById(R.id.button1); 

               myques.setText(c.getString(1));
               myc1.setText(c.getString(2));
               myc2.setText(c.getString(3));
               myc3.setText(c.getString(4));
               myc4.setText(c.getString(5));
               NxtQues.setOnClickListener(new OnClickListener()
            {
                @Override
                public void onClick(View V)
                {

                    c.moveToNext();
                }

            });

what changes should I make in this code to set on click listener in a proper way.

4

1 回答 1

0

所以在你的代码中有一些问题。首先在这里:

c = myDbHelper.query(myDbHelper.DB_PATH +"/MainTable", ...);

由于 query() 方法的第一个参数是“原始”表名,因此您无法为其分配数据库的完整路径(如果它不是真正的表名......),这是错误的。只需像这样分配MainTable

c = myDbHelper.query("MainTable", null, null, null, null, null, null);

那么你关于从数据库中获取数据的逻辑一点都不好。您只为您的小部件分配了一次值,并且没有更多。它们永远不会被刷新,您需要调用尽可能多的 setText() 方法来更新小部件的内容。实际上,您不会更新它们。

您需要将逻辑更改为:

@Override
public void onClick(View V) {
  if (c.moveToNext()) {
     myques.setText(c.getString(1));
     myc1.setText(c.getString(2));
     myc2.setText(c.getString(3));
     myc3.setText(c.getString(4));
     myc4.setText(c.getString(5));
  }
}

建议: 当您使用 Cursor 的“getters”方法时,我建议您使用列名来获取列索引:

myques.setText(c.getString(c.getColumnIndex("columnName")));
于 2013-04-07T08:52:33.510 回答