从列表视图中插入项目和子项目

时间:2014-02-14 10:01:43

标签: android android-listview android-sqlite

我的列表视图有问题,我显示一个项目和子项目,我想在数据库中插入两个但它不起作用!!错误是我无法将其强制转换为文本视图 请有人帮助我。

这是我得到的错误:

    java.lang.ClassCastException: android.widget.TwoLineListItem cannot be cast to android.widget.TextView

这里是列表视图的代码:

    String[] databaseColumnNames = new String[] { DBAdapter.col_N_Ordre,DBAdapter.col_Nom_prénom};
    int[] toViewIDs = new int[] { android.R.id.text1,android.R.id.text2 };

    SimpleCursorAdapter myCursordapter = new SimpleCursorAdapter(this,android.R.layout.simple_expandable_list_item_2 , cursor, databaseColumnNames, toViewIDs);

    ListView list = (ListView) findViewById(android.R.id.list);

    list.setAdapter(myCursordapter); 

这里是插入代码:

  list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(final AdapterView<?> arg0, View arg1,
                final int position, long arg3) {

Toast.makeText(getApplicationContext(), " " + position, Toast.LENGTH_LONG).show();
    final String s = ((TextView)arg1).getText().toString();
    db.insertest(s);

查询是:

   public long insertest(String region) {
      ContentValues initialValues = new ContentValues();
          initialValues.put(col_Region,region);
      //initialValues.put(col_Provence_prefecture );
          return db.insert(MENAGE,null, initialValues);
  }

1 个答案:

答案 0 :(得分:1)

将以下代码放入listview项目中,单击侦听器

TextView v1 = (TextView)arg1.findViewById(android.R.id.text1);
String first = v1.getText().toString();
TextView v2 = (TextView)arg1.findViewById(android.R.id.text2);
String second = v2.getText().toString();

ContentValues cv = new ContentValues();
cv.put(DBAdapter.col_Region, first);
cv.put(DBAdapter._id, second);
myCursordapter.notifyDataSetChanged(); 
list.setAdapter(adapter); 

DBAdapter sql_Adapter = new DBAdapter(context);
sql_Adapter.open();

db.insertest(cv);
sql_Adapter.close();