Junhao
Junhao

Reputation: 7

Saving data with SQLite and adding it to a ListView

My problem is the app crash, it shows, unfortunately, the app has stopped.

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

public class ListDataActivity extends 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

public class DatabaseHelper extends 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 Process: sg.edu.rp.c346.todolist, PID: 24636 java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/data/sg.edu.rp.c346.todolist/databases/mylist.db at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55) at android.database.sqlite.SQLiteDatabase.endTransaction(SQLiteDatabase.java:520) at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:263) at 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) at android.view.View.performClick(View.java:4438) at android.view.View$PerformClick.run(View.java:18422) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5017) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) at 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/Process: Sending signal. PID: 24636 SIG: 9

Upvotes: 0

Views: 1463

Answers (3)

laalto
laalto

Reputation: 152927

You should not close() the SQLiteDatabase given to you in SQLiteOpenHelper onCreate() and onUpgrade(). Only close() database handles you have obtained yourself.

Upvotes: 0

Akshay Gadhave
Akshay Gadhave

Reputation: 166

You must initialize the myDB variable before access it. In your MainActivity.java you not initialize Helper class.

 myDB= new DatabaseHelper(this);

Just do this. Also change this condition

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

Hope this will work.

Upvotes: 1

Ivan Wooll
Ivan Wooll

Reputation: 4332

It looks like you did not initialize your myDB instance.

Call myDB = new DatabaseHelper(this) somewhere in your onCreate method before you try to add entry into your LocalDB.

Upvotes: 1

Related Questions