Reputation: 670
I was trying to save some data to SqLite so that my app can support in offline mode. But I am unable to initialize SqLite. After following docs, I have the following code so far which behaves weird and I don't know why. Can someone please help me?
public class PlayGame extends AppCompatActivity implements View.OnClickListener {
public SQLiteDatabase database;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_game);
if (database != null) {
Log.d("check", "Database Not Null");
Cursor c = database.rawQuery("select * from LeaderBoard", null);
c.moveToFirst();
while (c.moveToNext()) {
Log.e("check", c.getString(0) + " " + c.getString(1) + " " + c.getString(2));
}
}
if (database == null) {
Log.d("check", "Database Null");
database = openOrCreateDatabase("your database name", MODE_PRIVATE, null);
database.execSQL("CREATE TABLE IF NOT EXISTS LeaderBoard(Name VARCHAR(200),Score INT,Tap INT);");
database.execSQL("INSERT INTO LeaderBoard VALUES('user',5,10);");
}
Log.d("check", database.toString());
}
}
LogCat shows Database Null first then it shows a object of database. First if block is never run, every time it initializes the database and after that again makes it null null in onCreate.
Upvotes: 0
Views: 69
Reputation: 152817
That's how Android's activity lifecycle works. When an activity is instantiated its fields get default values as any Java object, with references being initialized to null, and then the framework calls onCreate()
exactly once. When onCreate()
is called again it is another instance of the same class.
To manage database schema versioning, consider using SQLiteOpenHelper
.
Upvotes: 2