I'm new to the sqlite database and in my project, I need to add data just after create the database. I tried in this way and here is my code.
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView v = (TextView)findViewById(R.id.textView1);
MySqlHelper helper = new MySqlHelper(this);
v.setText(helper.getBird(2));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I created another class to open sqlite database.
public class MySqlHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "BirdDB";
private static final String TABLE_BIRDS = "birds";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String[] COLUMNS = {KEY_ID,KEY_NAME};
public MySqlHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_TABLE = "CREATE TABLE birds ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"name TEXT )";
db.execSQL(CREATE_TABLE);
db.close();
SQLiteDatabase dbase = this.getWritableDatabase();
dbase.insert(TABLE_BIRDS, null, addBirdData("Sri Lanka Jungle Flowl"));
dbase.insert(TABLE_BIRDS, null, addBirdData("Red Faced Mal Koha"));
dbase.close();
}
@Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS birds");
this.onCreate(db);
}
public ContentValues addBirdData(String birdName){
ContentValues values = new ContentValues();
values.put(KEY_NAME, birdName);
return values;
}
public String getBird(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor =
db.query(TABLE_BIRDS, // a. table
COLUMNS, // b. column names
" id = ?", // c. selections
new String[] { String.valueOf(id) }, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null); // h. limit
if (cursor != null)
cursor.moveToFirst();
String name = cursor.getString(1);
db.close();
return name;
}
It gives me java.lang.IllegalStateException: (conn# 0) already closed exception
Help me to avoid from this and achieve to insert data just after database creation.
Cursorfor populating aListView(or other classes which extendAdapterView), change the name of your id column to be_id. Note the underscore prefix.