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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用SQLite保存数据并将其添加到ListView相关的知识,希望对你有一定的参考价值。

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

main activity.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();
    }
}

}

list A磁体vi同意.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);
        }
    }
}

database helper.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秀

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 at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55)位于android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:263)的android.database.sqlite.SQLiteOpenper.getWritableDatabase(SQLiteOpenHelper.java:164 )sg.edu.rp.c346.todolist.DatabaseHelper.addData(DatabaseHelper.java:45)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.View.View.View上的android.view.View $ View(java.:18422)上的android.view. os.Handler.handleCallback(处理程序。 java:733)在android.o.Dandler.dispatchMessage(Handler.java:95)的android.app.Looper.loop(Looper.java:136)android.app.ActivityThread.main(ActivityThread.java:5017)at at java.lang.reflect.Method.invokeNative(Native Method)在java.lang.reflect.Method.invoke(Method.java:515)at 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

答案

你不应该close()SQLiteDatabase SQLiteOpenHelperonCreate()给你的onUpgrade()。只有你自己获得的close()数据库句柄。

另一答案

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

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

另一答案

您必须在访问之前初始化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();
        }

希望这会奏效。

以上是关于使用SQLite保存数据并将其添加到ListView的主要内容,如果未能解决你的问题,请参考以下文章

将数据从列表视图(从 Rest Api 生成)传递到另一个活动并将其保存到 SQLite 数据库中

当我从用户获取数据并将其保存到 SQLite 数据库中时,我应该怎么做才能使列表视图在片段中工作

解析嵌套的 JSON 并将其保存到 SQLite 中,然后检索它

Android:如何用相机拍照并将位图转换为字节数组并保存到sqlite db?

如何使用 sqlite 将我的图像保存到数据库中? [关闭]

如何使用 VBA 在 Excel 中添加连接(到外部数据源)并将其保存到该 Excel 电子表格的连接列表