用于在listview中填充TextView和ToggleButton的游标适配器

时间:2017-09-04 01:42:54

标签: android listview

我在Activity类中实现了以下代码。同时,应用程序在启动时崩溃。

我错过了什么?

public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Object> {
private ListView obj;
DBHelper mydb;
SimpleCursorAdapter dataAdapter;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Cursor rs = mydb.getAllAlarms();
    startManagingCursor(rs);
    String[] from = new String[]{"name"};
    int[] to = new int[]{R.id.alarm_name};

    dataAdapter = new SimpleCursorAdapter(this, R.layout.listview_row, rs, from, to, 0);
obj = (ListView)findViewById(R.id.listViewAlarms);
obj.setAdapter(dataAdapter);
getSupportLoaderManager().initLoader(0, null, this);

    obj.setOnItemClickListener(new OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
            //obj.getItemAtPosition(arg2);
            // TODO Auto-generated method stub
            String itemVal =(String) arg0.getItemAtPosition(arg2);

            Bundle dataBundle = new Bundle();
            dataBundle.putString("name", itemVal);
            Intent intent = new
                    Intent(getApplicationContext(),DisplayAlarm.class);
            intent.putExtras(dataBundle);
            startActivity(intent);
        }
    });

}

感谢您的帮助。

约瑟夫

1 个答案:

答案 0 :(得分:1)

您还没有将光标放在适配器中。 从此

更改您的代码
dataAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.listview_row,
            null, new String[] { mydb.ALARMS_COLUMN_NAME, mydb.ALARMS_ACTIVATED},
            new int[] { R.id.alarm_name, R.id.alarm_activated }, 0);

dataAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.listview_row,
            rs, new String[] { mydb.ALARMS_COLUMN_NAME, mydb.ALARMS_ACTIVATED},
            new int[] { R.id.alarm_name, R.id.alarm_activated }, 0);

此外,不要使用mydb.ALARMS_COLUMN_NAME, mydb.ALARMS_ACTIVATED,只需传递列名称。