I am trying to store registration data in the database. There are two tables - geregistry3 and getypes2. Insertion works normally in getypes2. But while inserting data into geregistry3, it either does not get stored or only one tuple is stored (that too temporarily, goes back to empty on restarting that activity) if I don't close the database with db.close(). There are no exceptions or errors displayed in any logs and stacktraces.
Kindly help!
GEDatabaseHandler.java
package com.example.akshayjk.attempt1.SQL;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class GEDatabaseHandler extends SQLiteOpenHelper {
public GEDatabaseHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
private static final String datatbase="mydatabase.db";
private static final String table_name1="geregistry3";
private static final int database_version=1;
public static final String email="email_id";
public static final String group_name="group_name";
public static final String doe="doe";
public static final String timing="timing";
private static final String create_table1="CREATE TABLE " + table_name1 + "( " + email+" TEXT, "+group_name+" TEXT, "+doe+" NUMBER, "+timing+" TEXT "+ ");";
private static final String table_name2="getypes2";
public static final String group_name1="group_name";
public static final String timings="timing";
private static final String create_table2="CREATE TABLE "+ table_name2+"( "+group_name1+" TEXT, "+timings+" TEXT, "+ doe+" NUMBER );";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(create_table2);
db.execSQL(create_table1);
fillGetypes(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + table_name2);
db.execSQL("DROP TABLE IF EXISTS " + table_name1);
// Create tables again
onCreate(db);
}
public void fillGetypes(SQLiteDatabase db){
String[] types={"Bodypump", "Barre", "Cycle 45"};
int[] times={1200,1230,1630,1700,1730,1745,1830,1900,1930};
String[]day={"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
ContentValues values = new ContentValues();
values.put(group_name1,types[0]);
values.put(timings,times[0]);
values.put(doe,day[0]);
db.insert(table_name2, null, values);
values=new ContentValues();
values.put(group_name1,types[0]);
values.put(timings,times[4]);
values.put(doe,day[0]);
db.insert(table_name2, null, values);;
values=new ContentValues();
values.put(group_name1,types[0]);
values.put(timings,times[3]);
values.put(doe,day[1]);
db.insert(table_name2, null, values);;
values=new ContentValues();
values.put(group_name1,types[0]);
values.put(timings,times[4]);
values.put(doe,day[2]);
db.insert(table_name2, null, values);;
values=new ContentValues();
values.put(group_name1,types[0]);
values.put(timings,times[8]);
values.put(doe,day[3]);
db.insert(table_name2, null, values);;
values=new ContentValues();
values.put(group_name1,types[0]);
values.put(timings,times[0]);
values.put(doe,day[4]);
db.insert(table_name2, null, values);;
values=new ContentValues();
values.put(group_name1,types[0]);
values.put(timings,times[2]);
values.put(doe,day[4]);
db.insert(table_name2, null, values);;
values=new ContentValues();
values.put(group_name1,types[1]);
values.put(timings,times[0]);
values.put(doe,day[0]);
db.insert(table_name2, null, values);;
values=new ContentValues();
values.put(group_name1,types[1]);
values.put(timings,times[3]);
values.put(doe,day[1]);
db.insert(table_name2, null, values);;
values=new ContentValues();
values.put(group_name1,types[1]);
values.put(timings,times[6]);
values.put(doe,day[3]);
db.insert(table_name2, null, values);;
values=new ContentValues();
values.put(group_name1,types[1]);
values.put(timings,times[5]);
values.put(doe,day[4]);
db.insert(table_name2, null, values);;
values=new ContentValues();
values.put(group_name1,types[2]);
values.put(timings,times[4]);
values.put(doe,day[0]);
db.insert(table_name2, null, values);;
values=new ContentValues();
values.put(group_name1,types[2]);
values.put(timings,times[6]);
values.put(doe,day[0]);
db.insert(table_name2, null, values);;
values=new ContentValues();
values.put(group_name1,types[2]);
values.put(timings,times[0]);
values.put(doe,day[1]);
db.insert(table_name2, null, values);;
values=new ContentValues();
values.put(group_name1,types[2]);
values.put(timings,times[6]);
values.put(doe,day[1]);
db.insert(table_name2, null, values);;
values=new ContentValues();
values.put(group_name1,types[2]);
values.put(timings,times[3]);
values.put(doe,day[2]);
db.insert(table_name2, null, values);;
values=new ContentValues();
values.put(group_name1,types[2]);
values.put(timings,times[2]);
values.put(doe,day[3]);
db.insert(table_name2, null, values);;
values=new ContentValues();
values.put(group_name1,types[2]);
values.put(timings,times[0]);
values.put(doe,day[4]);
db.insert(table_name2, null, values);;
}
public void addRegister(GroupData groupData){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(email,groupData.getEmailId());
values.put(group_name,groupData.getgroup());
values.put(doe,groupData.getdOB());
values.put(timing,groupData.gettiming());
// Inserting Row
try {
db.execSQL("INSERT INTO "+table_name1+" VALUES(?,?,?,?)",new String[]{groupData.getEmailId(),groupData.getgroup(),groupData.getdOB(),String.valueOf(groupData.gettiming())});
db.close(); // Closing database connection
}catch (Exception e){
e.printStackTrace();
}
/*
*/
}
public boolean isTableExists(){
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor = db.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '"+table_name1+"'", null);
if(cursor!=null) {
if(cursor.getCount()>0) {
cursor.close();
return true;
}
cursor.close();
}
return false;
}
public List<GroupData> getAllRegister(){
String[] columns = {
"*"
};
SQLiteDatabase db = this.getReadableDatabase();
List<GroupData> groupData=new ArrayList<>();
// query user table with condition
Cursor cursor = db.query(table_name1, //Table to query
columns, //columns to return
null, //columns for the WHERE clause
null, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null); //The sort order
int cursorCount=0;
if(cursor.moveToFirst()){
do {
GroupData user = new GroupData();
user.setEmailId(cursor.getString(cursor.getColumnIndex(email)));
user.setDoB(cursor.getString(cursor.getColumnIndex(doe)));
user.settiming(Integer.parseInt(cursor.getString(cursor.getColumnIndex(timings))));
user.setgroup(cursor.getString(cursor.getColumnIndex(group_name1)));
// Adding user record to list
groupData.add(user);
} while (cursor.moveToNext());
}
if(cursor!=null && !cursor.isClosed()){
cursorCount=cursor.getCount();
cursor.close();
}
db.close();
return groupData;
}
public int checkcount(String exgroup, String Doe, int timing){
String[] columns = {
"*"
};
SQLiteDatabase db = this.getReadableDatabase();
// selection criteria
String selection = group_name+ " = ? AND "+doe+" = ? AND " +timings+" = ?";
// selection argument
String[] selectionArgs = {exgroup,Doe, String.valueOf(timing)};
// query user table with condition
Cursor cursor = db.query(table_name1, //Table to query
columns, //columns to return
selection, //columns for the WHERE clause
selectionArgs, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null); //The sort order
int cursorCount=0;
if(cursor!=null && !cursor.isClosed()){
cursorCount=cursor.getCount();
cursor.close();
}
db.close();
return cursorCount;
}
public int checkexists(String email, String exgroup, String Doe, int timing){
String[] columns = {
"*"
};
SQLiteDatabase db = this.getReadableDatabase();
// selection criteria
String selection = this.email+" = ? AND "+group_name+ " = ? AND "+doe+" = ? AND " +timings+" = ?";
// selection argument
String[] selectionArgs = {email,exgroup,Doe, String.valueOf(timing)};
// query user table with condition
Cursor cursor = db.query(table_name1, //Table to query
columns, //columns to return
selection, //columns for the WHERE clause
selectionArgs, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null); //The sort order
int cursorCount=0;
if(cursor!=null && !cursor.isClosed()){
cursorCount=cursor.getCount();
cursor.close();
}
db.close();
return cursorCount;
}
public List<GroupData> retTypes(String exgroup){
Date now=new Date();
int i;
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("EEEE");
String daynow=simpleDateFormat.format(now);
String[] day={"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
for(i=0;i<day.length;i++){
if(day[i].equals(daynow))
break;
}
simpleDateFormat=new SimpleDateFormat("HH:mm");
Calendar calendar=Calendar.getInstance();
String time=simpleDateFormat.format(calendar.getTime());
String nowtime=time.replace(":","");
int timeNow= Integer.parseInt(nowtime);
nowtime="0"+new Integer(timeNow).toString();
String[] columns = {
"*"
};
List<GroupData> groupDataList=new ArrayList<GroupData>();
SQLiteDatabase db = this.getReadableDatabase();
// selection criteria
String selection = group_name1+" = ? AND " +doe+" IN (?,?,?)";
// selection argument
String[] selectionArgs = {exgroup,day[i%7],day[(i+1)%7],day[(i+2)%7]};
// query user table with condition
Cursor cursor = db.query(table_name2, //Table to query
columns, //columns to return
selection, //columns for the WHERE clause
selectionArgs, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null); //The sort order
int cursorCount = cursor.getCount();
if (cursor.moveToFirst()) {
do {
GroupData user = new GroupData();
user.setgroup(cursor.getString(cursor.getColumnIndex(group_name1)));
user.settiming(Integer.parseInt(cursor.getString(cursor.getColumnIndex(timing))));
user.setDoB(cursor.getString(cursor.getColumnIndex(doe)));
// Adding user record to list
groupDataList.add(user);
} while (cursor.moveToNext());
}
if(cursor!=null && !cursor.isClosed())
cursor.close();
db.close();
return groupDataList;
}
public List<GroupData> retTypes(String exgroup, String chosenDay){
Date now=new Date();
int i;
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("EEEE");
String daynow=simpleDateFormat.format(now);
String[] day={"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
for(i=0;i<day.length;i++){
if(day[i].equals(daynow))
break;
}
simpleDateFormat=new SimpleDateFormat("HH:mm");
Calendar calendar=Calendar.getInstance();
String time=simpleDateFormat.format(calendar.getTime());
String nowtime=time.replace(":","");
int timeNow= Integer.parseInt(nowtime);
nowtime=new Integer(timeNow+1000).toString();
String[] columns = {
"*"
};
List<GroupData> groupDataList=new ArrayList<GroupData>();
SQLiteDatabase db = this.getReadableDatabase();
// selection criteria
String selection = group_name1+" = ? AND " +doe+" = ?";
// selection argument
String[] selectionArgs = {exgroup,chosenDay};
// query user table with condition
Cursor cursor = db.query(table_name2, //Table to query
columns, //columns to return
selection, //columns for the WHERE clause
selectionArgs, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null); //The sort order
int cursorCount = cursor.getCount();
if (cursor.moveToFirst()) {
do {
GroupData user = new GroupData();
user.setgroup(cursor.getString(cursor.getColumnIndex(group_name1)));
user.settiming(Integer.parseInt(cursor.getString(cursor.getColumnIndex(timing))));
user.setDoB(cursor.getString(cursor.getColumnIndex(doe)));
// Adding user record to list
groupDataList.add(user);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return groupDataList;
}
}
GE_Form.java
package com.example.akshayjk.attempt1.HFW_Activities;
public class GE_Form extends AppCompatActivity{
public static GEDatabaseHandler gdb;
public List<GroupData> groupData=new ArrayList<GroupData>();
public Spinner spTypes,spDays,spTimings;
public Button button;
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(GE_Form.this, HFW.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_geform);
Bundle bundle = getIntent().getExtras();
final String email = bundle.getString("email");
button = findViewById(R.id.button_registerge);
gdb = new GEDatabaseHandler(GE_Form.this, null, null, 4);
String[] types = {"Bodypump", "Barre", "Cycle 45"};
String[] days;
String[] timings;
ArrayAdapter<String> adapter1;
final ArrayList<String> s1 = new ArrayList<>();
final ArrayList<String> s2 = new ArrayList<String>();
final String[] s3;
final String[] s4;
spTypes = findViewById(R.id.ge_sp1);
adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, types);
spTypes.setAdapter(adapter1);
spDays = findViewById(R.id.ge_sp2);
spTimings = findViewById(R.id.ge_sp3);
final TextView textView = findViewById(R.id.test2);
spTypes.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
final String group = spTypes.getSelectedItem().toString().trim();
groupData = gdb.retTypes(group);
s1.clear();
for (GroupData g : groupData) {
s1.add(g.getdOB());
textView.append(g.getdOB() + " " + g.getgroup() + " " + g.gettiming() + "\n");
}
Set<String> hs = new HashSet<>();
hs.addAll(s1);
s1.clear();
s1.addAll(hs);
ArrayAdapter<String> adapter2;
adapter2 = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, s1);
adapter2.notifyDataSetChanged();
spDays.setAdapter(adapter2);
spDays.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String days = spDays.getSelectedItem().toString().trim();
s2.clear();
groupData = gdb.retTypes(group, days);
for (GroupData g : groupData) {
s2.add(String.valueOf(g.gettiming()));
}
Set<String> hs = new HashSet<>();
hs.addAll(s2);
s2.clear();
s2.addAll(hs);
ArrayAdapter<String> adapter3;
adapter3 = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, s2);
adapter3.notifyDataSetChanged();
spTimings.setAdapter(adapter3);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
if (groupData.isEmpty()) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
Calendar calendar = Calendar.getInstance();
String time = simpleDateFormat.format(calendar.getTime());
String nowtime = time.replace(":", "");
int timeNow = Integer.parseInt(nowtime);
nowtime = "0" + new Integer(timeNow).toString();
Toast.makeText(getApplicationContext(), nowtime, Toast.LENGTH_LONG).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String edex = spTypes.getSelectedItem().toString().trim();
String eddoe = spDays.getSelectedItem().toString().trim();
int edtime = Integer.parseInt(spTimings.getSelectedItem().toString().trim());
GroupData gd = new GroupData();
if (gdb.checkexists(email, edex, eddoe, edtime) != 0) {
Toast.makeText(getApplicationContext(), "Already Registered", Toast.LENGTH_LONG).show();
} else {
if (gdb.checkcount(edex, eddoe, edtime) < 5) {
gd.setEmailId(email);
gd.setDoB(eddoe);
gd.setgroup(edex);
gd.settiming(edtime);
gdb.addRegister(gd);
textView.setText("");
}
List<GroupData> groupData1 = gdb.getAllRegister();
if (groupData1.isEmpty())
textView.append("Not writing into table");
for (GroupData d : groupData1) {
textView.append("\n" + d.getEmailId() + " " + d.getgroup() + " " + d.getdOB() + " " + d.gettiming());
}
if (gdb.isTableExists()) {
textView.append("Exists");
} else
textView.append("Does not exist");
}
}
});
}
}
If you check the documentation, you find that passing null as the database name, creates an in-memory database, which means that it is not persisted.
Here
So try passing any database name (just any string) when you are creating GEDatabaseHandler.
After that check if your data is persisted correctly.
I am quite new Android Development and figured I should start by trying to create a simple ToDo List App using SQLite. I have all of the basic functionality in place: adding, updating, and deleting tasks. However, I am adding, updating, and deleting by the title of the task, rather than by the ID. This creates problems with duplicate tasks (e.g. tasks of the same name are deleted simultaneously). After much internet search, I still cannot find a way to do this. I would appreciate any help offered!
Here's my code:
public class TaskDbHelper extends SQLiteOpenHelper {
public TaskDbHelper(Context context) {
super(context, TaskContract.DB_NAME, null, TaskContract.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String createTable = "CREATE TABLE " + TaskContract.TaskEntry.TABLE + " ( " +
TaskContract.TaskEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
TaskContract.TaskEntry.COL_TASK_TITLE + " TEXT NOT NULL, " +
TaskContract.TaskEntry.COL_TASK_DATE + " DATE);";
sqLiteDatabase.execSQL(createTable);
}
}
Activity where tasks are shown
public class ShowTaskActivity extends AppCompatActivity {
private TaskDbHelper mHelper;
private ListView mTaskListView;
private ArrayAdapter<String> mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task);
mHelper = new TaskDbHelper(this);
mTaskListView = (ListView) findViewById(R.id.list_todo);
updateUI();
}
private void updateUI() {
ArrayList<String> taskList = new ArrayList<>();
SQLiteDatabase sqLiteDatabase = mHelper.getReadableDatabase();
Cursor cursor = sqLiteDatabase.query(
TaskContract.TaskEntry.TABLE, // Name of the table to be queried
new String[]{ // Which columns are returned
TaskContract.TaskEntry._ID,
TaskContract.TaskEntry.COL_TASK_TITLE,
TaskContract.TaskEntry.COL_TASK_DATE},
null, null, null, null, null);
while (cursor.moveToNext()) {
int index = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TITLE);
taskList.add(cursor.getString(index));
}
if (mAdapter == null) {
mAdapter = new ArrayAdapter<>(this,
task, // What view to use for the items
R.id.task_title, // Where to put the string of data
taskList); // Where to get the data
mTaskListView.setAdapter(mAdapter);
} else {
mAdapter.clear();
mAdapter.addAll(taskList);
mAdapter.notifyDataSetChanged();
}
cursor.close();
sqLiteDatabase.close();
}
// TODO: Change to delete by ID, not name
public void deleteTask(View view) {
View parent = (View) view.getParent();
TextView taskTextView = (TextView) parent.findViewById(R.id.task_title);
String task = taskTextView.getText().toString();
SQLiteDatabase sqLiteDatabase = mHelper.getWritableDatabase();
sqLiteDatabase.delete(
TaskContract.TaskEntry.TABLE, // Where to delete
TaskContract.TaskEntry.COL_TASK_TITLE + " = ?", // Boolean check
new String[]{task}); // What to delete
sqLiteDatabase.close();
updateUI();
}
}
Task adding Code
public void addTask(String task, String date) {
SQLiteDatabase sqLiteDatabase = mHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(TaskContract.TaskEntry.COL_TASK_TITLE, task);
contentValues.put(TaskContract.TaskEntry.COL_TASK_DATE, date);
sqLiteDatabase.insertWithOnConflict(
TaskContract.TaskEntry.TABLE,
null,
contentValues,
SQLiteDatabase.CONFLICT_REPLACE);
sqLiteDatabase.close();
}
String rowId; //Set your row id here
SQLiteDatabase sqLiteDatabase = mHelper.getWritableDatabase();
sqLiteDatabase.delete(
TaskContract.TaskEntry.TABLE, // Where to delete
KEY_ID+" = ?",
new String[]{rowId}); // What to delete
sqLiteDatabase.close();
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ?",new String[]{Long.toString(id)} );
db.close();
You can try this method to delete By id
public void deleteData(String tableName, Integer id) {
try {
if (mWritableDB != null) {
mWritableDB.execSQL("delete from " + tableName + " Where id = " + id);
}
} catch (Exception _exception) {
_exception.printStackTrace();
}
}
I have a query (getMinScore) which takes the min value from my table, I need to take this and display it in a text field but in it's current state it displays
High Score: android.database.SQLiteCursor#.......
I don't know what this means, how can I get the string value from this?
I am calling the query from my GameView class as in the second block of code. Really appreciate any help!
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "scores.db";
public static final String TABLE_NAME = "scores_table";
public static final String COLUMN_ID = "ID";
public static final String COLUMN_SCORE = "SCORE";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT, SCORE INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String score) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_SCORE, score);
long result = db.insert(TABLE_NAME, null, contentValues);
System.out.println("Data inserted" + score);
if(result == -1) {
return false;
}
else {
return true;
}
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
return res;
}
public Cursor getMinScore() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select min (SCORE) from " + TABLE_NAME, null);
return res;
}
public boolean updateData(String id, String score) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_ID, id);
contentValues.put(COLUMN_SCORE, score);
db.update(TABLE_NAME, contentValues, "ID = ?", new String[] { id });
return true;
}
public Integer deleteData(String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "ID = ?", new String[] { id });
}
}
GameView.java
String minScore = mydb.getMinScore().toString();
TextPaint tp = new TextPaint();
tp.setColor(Color.GREEN);
tp.setTextSize(40);
tp.setTypeface(Typeface.create("Courier", Typeface.BOLD));
canvas.drawText("Moves: " + String.valueOf(turns), 10, 1180, tp);
canvas.drawText("High score: " + mydb.getMinScore(), 10, 1280, tp);
A Cursor is an object that gives you access to the results of a database query by iterating over the rows. You can't just print out the cursor, you need to check if there is a next row and then pull the value out from it.
You could change your getMinScore method to return the minScore value instead of returning the cursor:
public int getMinScore() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select min (SCORE) from " + TABLE_NAME, null);
if(res.moveToNext()) {
// return the integer from the first column
return res.getInt(0);
} else {
// there were no results
return -1;
}
}
Have a read of the documentation to understand the cursor methods.
You have to get your value from the returning Cursor object. In your case you can use
int score = res.getInt(res.getColumnIndex("SCORE"));
Be sure to check the returning cursor is not NULL by checking cursor count > ZERO.
Change your method
public Cursor getMinScore() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select min (SCORE) from " + TABLE_NAME, null);
return res;
}
To
public int getMinScore() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select min (SCORE) from " + TABLE_NAME, null);
if (res.getCount() > 0) {
return res.getInt(res.getColumnIndex("SCORE"));
} else {
return -1; // Some defualt value when no data is retrieved
}
}
you Should always close Cursor to prevent memory leak
so
public int getMinScore() {
int result = -1;
Cursor res = db.rawQuery("select min (SCORE) from " + TABLE_NAME, null);
if (res.moveToFirst()) {
result = res.getInt(0);
}
if (!res.isClosed()){
res.close();
}
return result;
}
}
i think it better to user method open and close instead of calling getWritableDatabase() every time
public void open() {
bdd = dbHelper.getWritableDatabase();
}
public void close() {
bdd.close();
}
i want to add some image uri's to the Database. my Database table has two columns id and String Uri. The Problem is it shows No such table exist when trying to insert some Uris to Table. Here is my Code of Database Adapter Class.
package com.example.mystorage;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBAdapter {
// for customer registration
static final String KEY_ID = "id";
static final String KEY_URI = "uri";
static final String DATABASE_NAME = "IMAGE_DB";
static final String DATABASE_TABLE = "temp_images1";
static final int DATABASE_VERSION = 2;
static final String DATABASE_CREATE = "create table temp_images1 (id integer autoincrement, "
+ "uri text not null);";
final Context context;
DatabaseHelper DBHelper;
SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS temp_images1");
onCreate(db);
}
}
public DBAdapter open() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}
public void close() {
DBHelper.close();
}
// //////////////////////////////////////for
// customerRegistration////////////////
// customer registration for retrieve data
public Cursor getAllImages() {
return db.query(DATABASE_TABLE, new String[] {KEY_URI}, null,
null, null, null, null);
}
public Cursor getContentimage(long id) throws SQLException {
Cursor c = db.query(true, DATABASE_TABLE,
new String[] { KEY_ID, KEY_URI },
KEY_ID + "=" + id, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// customer registration for update data
public boolean updateimages(long id, String uri) {
ContentValues args = new ContentValues();
// args.put(KEY_ID,id);
args.put(KEY_URI, uri);
return db.update(DATABASE_TABLE, args, KEY_ID + "=" + id, null) > 0;
}
// customer registration for insert data
public long insertImages(String uri) {
ContentValues args = new ContentValues();
//args.put(KEY_ID, id);
args.put(KEY_URI, uri);
long n = db.insert(DATABASE_TABLE, null, args);
//db.insertOrThrow(DATABASE_TABLE, null, args);
return n;
}
// customer registration for remove data
public boolean deleteImages(long id) {
return db.delete(DATABASE_TABLE, KEY_ID + "=" + id, null) > 0;
}
}
here is My ImageAdapter class where i am calling the insert method.
mThumbs is uri Arraylist to Store the Content of Database While Retrieving.
public ImageAdapter(Context c, android.net.Uri uri) {
mContext = c;
db= new DBAdapter(mContext);
try {
db.open();
db.insertImages(uri.toString());
db.close();
}catch(Exception e){
e.printStackTrace();
}
upadteAllImages();
notifyDataSetChanged();
}
public ImageAdapter(Context c, ArrayList<Uri> imageUris) {
mContext = c;
db= new DBAdapter(mContext);
try {
db.open();
for (int i = 0; i < imageUris.size(); i++){
db.insertImages(imageUris.get(i).toString());
}
db.close();
}catch(Exception e){
e.printStackTrace();
}
upadteAllImages();
notifyDataSetChanged();
}
private void upadteAllImages() {
mTHumbs.clear();
try{
db.open();
Cursor c = db.getAllImages();
if (c.moveToFirst()) {
while (c.moveToNext()){
String uri = c.getString(1);
mTHumbs.add(Uri.parse(uri));
}
}
//mTHumbs.add((Uri) db.getAllImages());
db.close();
}catch(Exception e){
e.printStackTrace();
}
}
String query = "CREATE TABLE " + DATABASE_TABLE + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_URI + " TEXT not null "+)";
Fix the syntax error in your CREATE TABLE. AUTOINCREMENT can only be used with INTEGER PRIMARY KEY and you're missing the PRIMARY KEY.
Remove the try-catch in your onCreate() so that you get an exception in case of a syntax problem.
Uninstall your app so that the old database is removed and your helper onCreate() gets run again with the fixed SQL.
Some minor changes are required to create a table in database.
Please see this-
" CREATE TABLE temp_images1 ( id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "uri TEXT NOT NULL ) ; ";