使用SQLite保存数据并将其添加到ListView

时间:2017-12-27 12:04:45

标签: java android sqlite listview save

我的问题是应用程序崩溃,不幸的是,它显示应用已停止。

MainActivity.java

 public class MainActivity extends AppCompatActivity {


DatabaseHelper myDB;
Button btnAdd;
Button btnList;
TextView tvView;
EditText editText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnAdd = (Button) findViewById(R.id.btnAdd);
    btnList = (Button) findViewById(R.id.btnList);
    tvView = (TextView) findViewById(R.id.Textview);
    editText = (EditText) findViewById(R.id.editText);
    myDB=new DatabaseHelper(this);


    btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String newEntry = editText.getText().toString();
           if (newEntry.length() != 0) {
                AddData(newEntry);
                editText.setText("");
            } else {
                Toast.makeText(MainActivity.this, "You must put something in the text field", Toast.LENGTH_LONG).show();
            }
        }

    });
    btnList.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this, ListDataActivity.class);
            startActivity(intent);
        }
    });
}


public void AddData(String newEntry) {
    boolean insertData = myDB.addData(newEntry);
    // check inserted successfully
    if (insertData == true) {
        Toast.makeText(MainActivity.this, "Successfully Entered Data!", Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(MainActivity.this, "Something went wrong", Toast.LENGTH_LONG).show();
    }
}

}

ListAcitivity.java

公共类ListDataActivity扩展了AppCompatActivity {

DatabaseHelper myDB;
ListView listView;
ArrayAdapter<String>listAdapter;


@Override
protected void onCreate( Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_layout);

    listView=(ListView)findViewById(R.id.listView);
    myDB= new DatabaseHelper(this);


    //populate an ArrayList<String> from the databases and then view it
   ArrayList<String> theList=new ArrayList<>();
    Cursor data=myDB.getListContent();

    if(data.getCount()==0){
        Toast.makeText(ListDataActivity.this,"The database was empty",Toast.LENGTH_LONG).show();
    }else{
        while(data.moveToNext()){
            theList.add(data.getString(1));
            listAdapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,theList);
            listView.setAdapter(listAdapter);
        }
    }
}

DatabaseHelper.java

公共类DatabaseHelper扩展了SQLiteOpenHelper {

public static final String DATABASE_NAME = "mylist.db";
public  static final String TABLE_NAME = "mylist_data";
public static final String COL1 = "ID";
public static final String COL2 = "ITEM1";

public DatabaseHelper(Context context){
    super (context, DATABASE_NAME, null , 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String createTable="CREATE TABLE"+ TABLE_NAME +"(ID INTEGER PRIMARY KEY AUTOINCREMENT,"+
           "ITEM1 TEXT)";
            db.execSQL(createTable);
    db.close();


}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP IF TABLE EXITS "+ TABLE_NAME);
    onCreate(db);
    db.close();



}
public boolean addData(String item1) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL2, item1);


    long result = db.insert(TABLE_NAME, null, contentValues);

    //if date as instered incorrectly it will return -1
    if (result == -1) {
        return false;
    } else {
        return true;
    }
}
    /**
     * Return all the data from database
     * @return
     */
    public Cursor getListContent() {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor data =db.rawQuery("SELECT * FROM " + TABLE_NAME,null);
    return data;


}

}

LOGCAT show

12-27 07:29:26.268 24636-24636 / sg.edu.rp.c346.todolist E / AndroidRuntime:FATAL EXCEPTION:main                                                                          处理:sg.edu.rp.c346.todolist,PID:24636                                                                          java.lang.IllegalStateException:尝试重新打开已关闭的对象:SQLiteDatabase:/data/data/sg.edu.rp.c346.todolist/databases/mylist.db                                                                              在android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55)                                                                              在android.database.sqlite.SQLiteDatabase.endTransaction(SQLiteDatabase.java:520)                                                                              在android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:263)                                                                              在android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)                                                                              at sg.edu.rp.c346.todolist.DatabaseHelper.addData(DatabaseHelper.java:45)                                                                              at sg.edu.rp.c346.todolist.MainActivity.AddData(MainActivity.java:58)                                                                              at sg.edu.rp.c346.todolist.MainActivity $ 1.onClick(MainActivity.java:39)                                                                              在android.view.View.performClick(View.java:4438)                                                                              在android.view.View $ PerformClick.run(View.java:18422)                                                                              在android.os.Handler.handleCallback(Handler.java:733)                                                                              在android.os.Handler.dispatchMessage(Handler.java:95)                                                                              在android.os.Looper.loop(Looper.java:136)                                                                              在android.app.ActivityThread.main(ActivityThread.java:5017)                                                                              at java.lang.reflect.Method.invokeNative(Native Method)                                                                              在java.lang.reflect.Method.invoke(Method.java:515)                                                                              在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:779)                                                                              在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)                                                                              at dalvik.system.NativeStart.main(Native Method) 12-27 07:29:28.078 24636-24636 /? I /处理:发送信号。 PID:24636 SIG:9

3 个答案:

答案 0 :(得分:1)

看起来你没有初始化你的myDB实例。

在尝试将条目添加到LocalDB之前,在myDB = new DatabaseHelper(this)方法中的某处调用onCreate

答案 1 :(得分:0)

您必须在访问之前初始化myDB变量。在MainActivity.java中,您不能初始化Helper类。

 myDB= new DatabaseHelper(this);

就这样做。 也改变这个条件

if (editText.length() != 0) { // Change this to newEntry.length() !=0
            AddData(newEntry);
            editText.setText("");
        } else {
            Toast.makeText(MainActivity.this, "You must put something in the text field", Toast.LENGTH_LONG).show();
        }

希望这会奏效。

答案 2 :(得分:0)

您不应close() SQLiteDatabaseSQLiteOpenHelper onCreate() onUpgrade()给您close()。您自己获得的只有Stack of fragment in Hashmap个数据库句柄。