2012-10-11 117 views
1

能否告诉我这段代码有什么问题。它运行但结果未列出。我只想要一个简单的SQLiteDB运行测试来完成我的另一个项目。我认为ArrayList使用有问题。使用ArrayList和ArrayAdapter的SQLite

public class MainActivity extends Activity { 

String names; 
ListView lvMain; 
ArrayList<String> values; 
ArrayAdapter<String> adapter; 

DBHelper dbHelper; 
EditText et; 
Button btnAdd; 
Button btnRead; 
Button btnClear; 
Button btnShow; 

Cursor c; 
int nameColIndex; 
int idColIndex; 

/** 
* Called when the activity is first created. 
*/ 
public void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    btnAdd = (Button) findViewById(R.id.btnAdd); 
    btnRead = (Button) findViewById(R.id.btnRead); 
    btnClear = (Button) findViewById(R.id.btnClear); 
    btnShow = (Button) findViewById(R.id.btnShow); 

    dbHelper = new DBHelper(this); 
    lvMain = (ListView) findViewById(R.id.lvMain); 
    values = new ArrayList<String>(); 

} 

public void onButtonClick(View v) { 

    ContentValues cv = new ContentValues(); 
    String name = et.getText().toString(); 
    SQLiteDatabase db = dbHelper.getWritableDatabase(); 

    switch (v.getId()) { 

     case R.id.btnAdd: 
      cv.put("name", name); 

      // вставляем запись и получаем ее ID 
      long rowID = db.insert("mytable", null, cv); 

      break; 

     case R.id.btnRead: 

      // делаем запрос всех данных из таблицы mytable, получаем Cursor 
      c = db.query("mytable", null, null, null, null, null, null); 

      // ставим позицию курсора на первую строку выборки 
      // если в выборке нет строк, вернется false 
      if (c.moveToFirst()) { 

       // определяем номера столбцов по имени в выборке 
       idColIndex = c.getColumnIndex("id"); 
       nameColIndex = c.getColumnIndex("name"); 

       do { 
        // получаем значения по номерам столбцов 

        c.getInt(idColIndex); 

       names = c.getString(nameColIndex); 

       values.add(names); 

        // переход на следующую строку 
        // а если следующей нет (текущая - последняя), то false - выходим из цикла 
       } while (c.moveToNext()); 

      } else { 
       c.close(); 
      } 

      break; 

     case R.id.btnClear: 

      // удаляем все записи 
      int clearCount = db.delete("mytable", null, null); 

      break; 

     case R.id.btnShow: 
      break; 
    } 

// закрываем подключение к БД 

    adapter = new ArrayAdapter<String>(this, 
      android.R.layout.simple_list_item_1, values); 

    lvMain.setAdapter(adapter); 


    dbHelper.close();  

    adapter.notifyDataSetChanged(); 

} 

class DBHelper extends SQLiteOpenHelper { 

public DBHelper(Context context) { 
    // конструктор суперкласса 
    super(context, "myDB", null, 1); 
} 

@Override 
public void onCreate(SQLiteDatabase db) { 

    // создаем таблицу с полями 
    db.execSQL("create table mytable (" 
     + "id integer primary key autoincrement," 
     + "name text," 
     + "email text" + ");"); 
} 

@Override 
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 

} 

}}

Here is main, may be I am missing something? 

    `<?xml version="1.0" encoding="utf-8"?> 
    <LinearLayout 
     xmlns:android="http://schemas.android.com/apk/res/android" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:orientation="vertical"> 
     <LinearLayout 
      android:id="@+id/linearLayout1" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content"> 
      <TextView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="Name" 
       android:layout_marginLeft="5dp" 
       android:layout_marginRight="5dp"> 
      </TextView> 
      <EditText 
       android:id="@+id/et" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_weight="1"> 
       <requestFocus> 
       </requestFocus> 
      </EditText> 
     </LinearLayout> 
     <LinearLayout 
      android:id="@+id/linearLayout2" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content"> 
      <Button 
       android:id="@+id/btnAdd" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:onClick="onButtonClick" 
       android:text="Add"> 
      </Button> 
      <Button 
       android:id="@+id/btnRead" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:onClick="onButtonClick" 
       android:text="Read"> 
      </Button> 
      <Button 
       android:id="@+id/btnClear" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:onClick="onButtonClick" 
       android:text="Clear"> 
      </Button> 
      <Button 
       android:id="@+id/btnShow" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:onClick="onButtonClick" 
       android:text="Show"> 
      </Button> 
     </LinearLayout> 
     <ListView 
      android:id="@+id/lvMain" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent"> 
     </ListView> 
    </LinearLayout>` 

回答

0
values = new ArrayList<String>(); 

valuesnull

变化:

dbHelper = new DBHelper(this); 
      lvMain = (ListView) findViewById(R.id.lvMain); 
      values = new ArrayList<String>(); 

    } 

    public void onButtonClick(View v) { 

     ContentValues cv = new ContentValues(); 
     String name = et.getText().toString(); 
     SQLiteDatabase db = dbHelper.getWritableDatabase(); 

     switch (v.getId()) { 
      case R.id.btnAdd: 
       cv.put("name", name); 
       long rowID = db.insert("mytable", null, cv); 
       break; 

      case R.id.btnRead: 
       c = db.query("mytable", null, null, null, null, null, null); 
       if (c.moveToFirst()) { 
        idColIndex = c.getColumnIndex("id"); 
        nameColIndex = c.getColumnIndex("name"); 

        do { 
         c.getInt(idColIndex); 
        names = c.getString(nameColIndex); 
        values.add(names); 
        } while (c.moveToNext()); 
       } else { 
        c.close(); 
       } 
       break; 

      case R.id.btnClear: 
       int clearCount = db.delete("mytable", null, null); 
       break; 

      case R.id.btnShow: 
       break; 
     } 
adapter = new ArrayAdapter<String>(this, 
       android.R.layout.simple_list_item_1, values); 
     lvMain.setAdapter(adapter); 
    dbHelper.close();  
    adapter.notifyDataSetChanged(); 



} 

}

+0

我试过了,就像你建议的那样。 Evene将DBHelper放入MainActivity中。当我按下添加时,应用程序崩溃。 – user1706819

+0

我已经想通了。谢谢大家的时间和精力。 – user1706819

+1

Sardor,ukam,rakhmat。 – user1706819

0

在onClick()方法的最后尝试调用adapter.notifyDataSetChanged();这将刷新所有使用适配器将值设置为视图的视图。

相关问题