I am learning how to deal with SQLLite database to store data in android studio. I have written the code as below and it should log the 2 entries on the console but its not happening. Can anyone tell me why?
import androidx.appcompat.app.AppCompatActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SQLiteDatabase myDatabase = this.openOrCreateDatabase("Users", MODE_PRIVATE, null);
myDatabase.execSQL("CREATE TABLE IF NOT EXISTS users (name VARCHAR2, age INT(3))");
myDatabase.execSQL("INSERT INTO users(name, age) VALUES('Sajid', 22)");
myDatabase.execSQL("INSERT INTO users(name, age) VALUES('Shoaib', 28)");
Cursor c = myDatabase.rawQuery("SELECT * FROM users", null);
int nameIndex = c.getColumnIndex("name");
int ageIndex = c.getColumnIndex("age");
c.moveToFirst();
while(c!=null)
{
Log.i("Name", c.getString(nameIndex));
Log.i("Age", c.getString(ageIndex));
c.moveToNext();
}
}
}`
Your code should be like this:
Cursor c = myDatabase.rawQuery("SELECT * FROM users", null);
int nameIndex = c.getColumnIndex("name");
int ageIndex = c.getColumnIndex("age");
while(c.moveToNext())
{
Log.i("Name", c.getString(nameIndex));
Log.i("Age", c.getString(ageIndex));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.