Unable to permanently store data in a database - java

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.

Related

Returning SQLite query and returning as text

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

Interchange ids of android database

How to go about if i want to interchange the contents of my android data base as shown below:
before
1 hello world
2 Android Nougat
after
1 Android Nougat
2 hello world
You don't need to change the positions in Database. You need to add additional int value to a database (not id). And change this value according to a new position. For first object you make it 2; for a second - 1. And when you retrieve data from your database you just sort it according to this value.
Example
String orderBy = "POSITION ASC";
Cursor cursor = database.query(TABLE_NAME, logTableColumns, null, null,
null, null, orderBy);
public class QueueDatabase extends SQLiteOpenHelper {
public QueueDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static final int DATABASE_VERSION = 1;
// Database Name
public static final String DATABASE_NAME = "queue.sqlite";
//Table names
public static final String TABLE_QUEUE = "Queue";
public static final String KEY_ID = "id";
public static final String KEY_SNAME = "key_sname";
public static final String KEY_ANAME = "key_aname";
public static final String KEY_URL = "key_url";
public static final String KEY_ORDER = "key_order";
public static final String CREATE_TABLE_QUEUE= "CREATE TABLE IF NOT EXISTS "
+ TABLE_QUEUE
+ "("
+ KEY_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_SNAME
+ " TEXT,"
+ KEY_ANAME
+ " TEXT,"
+ KEY_URL
+ " TEXT,"
+ KEY_ORDER
+ " TEXT "
+")";
public long insertQueue(ArrayList<Music> mTaskArr)
{
long row_id = 0;
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
for(int i = 0;i<mTaskArr.size() ;i++) {
values.put(KEY_SNAME, mTaskArr.get(i).getTitle());
values.put(KEY_ANAME, mTaskArr.get(i).getArtist());
values.put(KEY_URL, mTaskArr.get(i).getUrl());
row_id = db.insert(TABLE_QUEUE, null, values);
}
db.close();
return row_id;
}
public void updateOrder(long rowID, int newPos) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(KEY_ORDER, newPos);
db.update(TABLE_QUEUE, cv, KEY_ID + "=" + rowID, null);
}
public boolean updateQueue (Integer id, String S, String A, String U) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_SNAME,S);
contentValues.put(KEY_ANAME,A);
contentValues.put(KEY_URL,U);
db.update(TABLE_QUEUE, contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public void dropTable() {
SQLiteDatabase db = this.getWritableDatabase();
String sql = "drop table " + TABLE_QUEUE;
try {
db.execSQL(sql);
} catch (SQLException e) {
System.out.println(e);
}
}
public ArrayList<Music> getAllQueue() {
ArrayList<Music> ar = new ArrayList<Music>();
String selectQuery = "SELECT * FROM " + TABLE_QUEUE;
//Log.d("QUERY",""+selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()) {
do {
Music r = new Music();
r.setId(c.getInt(c.getColumnIndex(KEY_ID)));
r.setTitle( c.getString(c.getColumnIndex(KEY_SNAME)));
r.setArtist( c.getString(c.getColumnIndex(KEY_ANAME)));
r.setUrl(c.getString(c.getColumnIndex(KEY_URL)));
ar.add(r);
} while (c.moveToNext());
}
db.close();
return ar;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_QUEUE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onCreate(db);
}
public void arrange() {
SQLiteDatabase db = this.getWritableDatabase();
String[] rank = new String[]{ QueueDatabase.KEY_ID };
Cursor c = db.query(QueueDatabase.TABLE_QUEUE, rank, null, null, null, null, QueueDatabase.KEY_ORDER+" ASC");
}
}
this is how u enter data in database:
q.add(new Music(T, U, A));
qd.insertQueue(q);

edit content in database SQLiteDatabase

I created a database with SQLiteDatabase, everything works fine, except when I want to change the content of some columns .. I'm using db.update, but it seems not work. someone can help me understand what I'm doing wrong? thank you all
public class Note_DBHelper extends SQLiteOpenHelper {
private Context ctx;
//version of database
private static final int version = 1;
//database name
private static final String DB_NAME = "notesDB";
//name of table
private static final String TABLE_NAME = "notes";
//column names
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "noteTitle";
private static final String KEY_CONTENT = "noteContent";
private static final String KEY_TESTO = "noteTesto";
private static final String KEY_TXT_COLORE = "noteColore";
private static final String KEY_DATE = "date";
//sql query to creating table in database
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY AUTOINCREMENT, "+KEY_TITLE+" TEXT NOT NULL, "+KEY_CONTENT+" TEXT NOT NULL,"+KEY_TESTO+" TEXT NOT NULL, "+KEY_TXT_COLORE+" TEXT NOT NULL, "+KEY_DATE+" TEXT);";
//contructor of Note_DBHelper
public Note_DBHelper(Context context) {
super(context, DB_NAME, null, version);
this.ctx = context;
}
//creating the table in database
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
//in case of upgrade we're dropping the old table, and create the new one
#Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
db.execSQL("DROP TABLE IF EXIST " + TABLE_NAME);
onCreate(db);
}
//function for adding the note to database
public void addNote(String title, String content,String testo, String txt_colore) {
SQLiteDatabase db = this.getWritableDatabase();
//creating the contentValues object
//read more here -> http://developer.android.com/reference/android/content/ContentValues.html
ContentValues cv = new ContentValues();
cv.put("noteTitle", title);
cv.put("noteContent", content);
cv.put("noteTesto", testo);
cv.put("noteColore", txt_colore);
cv.put("date", new Date().toString());
//inserting the note to database
db.insert(TABLE_NAME, null, cv);
//closing the database connection
db.close();
//see that all database connection stuff is inside this method
//so we don't need to open and close db connection outside this class
}
//getting all notes
public Cursor getNotes(SQLiteDatabase db) {
//db.query is like normal sql query
//cursor contains all notes
Cursor c = db.query(TABLE_NAME, new String[] {KEY_TITLE, KEY_CONTENT,KEY_TESTO,KEY_TXT_COLORE}, null, null, null, null, "id DESC");
//moving to the first note
c.moveToFirst();
//and returning Cursor object
return c;
}
public Cursor getNotes2(SQLiteDatabase db) {
//db.query is like normal sql query
//cursor contains all notes
Cursor c = db.query(TABLE_NAME, new String[] {KEY_ID, KEY_TITLE}, null, null, null, null, "id DESC");
//moving to the first note
c.moveToFirst();
//and returning Cursor object
return c;
}
public Cursor getNote(SQLiteDatabase db, int id) {
Cursor c = db.query(TABLE_NAME, new String[] {KEY_TITLE, KEY_CONTENT,KEY_TESTO, KEY_TXT_COLORE, KEY_DATE}, KEY_ID + " = ?", new String[] { String.valueOf(id) }, null, null, null);
c.moveToFirst();
return c;
}
public void removeNote(int id) {
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ?", new String[] { String.valueOf(id) });
db.close();
}
public void updateNote(String title, String content,String testo, String txt_colore, String editTitle) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("noteTitle", title);
cv.put("noteContent", content);
cv.put("noteTesto", testo);
cv.put("noteColore", txt_colore);
cv.put("date", new Date().toString());
db.update(TABLE_NAME, cv, KEY_TITLE + " LIKE '" + editTitle + "'", null);
db.close();
}
Use this
db.update(TABLE_NAME, cv, KEY_ID + "=" + id, null);
then in your createNote class
dbhelper.updateNote(title, content, id);

Implement editing contacts after being stored in the database

I'm adapting an application that manages contacts with database interaction.
In the application, I am inserting and deleting contacts but I'm struggling to implement the method to edit the contacts and record the contact edited in the database.
The onContextItemSelected method is in place and lack only that part.
onContextItemSelected method in MainActivity
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case EDIT:
// TODO: Implement editing a contact
break;
case DELETE:
dbHandler.deleteContact(Contacts.get(longClickedItemIndex));
Contacts.remove(longClickedItemIndex);
contactAdapter.notifyDataSetChanged();
break;
}
return super.onContextItemSelected(item);
}
DatabaseHandler class with updateContact method
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "controleAgenda",
TABLE_CONTACTS = "contatos",
KEY_ID = "id",
KEY_NAME = "nome",
KEY_PHONE = "telefone",
KEY_ADDRESS = "endereco",
KEY_EMAIL = "email",
KEY_IMAGEURI = "imageUri";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_CONTACTS + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT," + KEY_PHONE + " TEXT," + KEY_ADDRESS + " TEXT," + KEY_EMAIL + " TEXT," + KEY_IMAGEURI + " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
onCreate(db);
}
public void createContact(Contato contato) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contato.getName());
values.put(KEY_PHONE, contato.getPhone());
values.put(KEY_ADDRESS, contato.getAddress());
values.put(KEY_EMAIL, contato.getEmail());
values.put(KEY_IMAGEURI, contato.getImageURI().toString());
db.insert(TABLE_CONTACTS, null, values);
db.close();
}
public Contato getContact(int id) {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID, KEY_NAME, KEY_PHONE, KEY_EMAIL, KEY_ADDRESS, KEY_IMAGEURI }, KEY_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null );
if (cursor != null)
cursor.moveToFirst();
Contato contato = new Contato(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), Uri.parse(cursor.getString(5)));
db.close();
cursor.close();
return contato;
}
public void deleteContact(Contato contato) {
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + "=?", new String[] { String.valueOf(contato.getId()) });
db.close();
}
public int getContactsCount() {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_CONTACTS, null);
int count = cursor.getCount();
db.close();
cursor.close();
return count;
}
public int updateContact(Contato contato) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contato.getName());
values.put(KEY_PHONE, contato.getPhone());
values.put(KEY_ADDRESS, contato.getAddress());
values.put(KEY_EMAIL, contato.getEmail());
values.put(KEY_IMAGEURI, contato.getImageURI().toString());
int rowsAffected = db.update(TABLE_CONTACTS, values, KEY_ID + "=?", new String[] { String.valueOf(contato.getId()) });
db.close();
return rowsAffected;
}
public List<Contato> getAllContacts() {
List<Contato> contacts = new ArrayList<Contato>();
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_CONTACTS, null);
if (cursor.moveToFirst()) {
do {
contacts.add(new Contato(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), Uri.parse(cursor.getString(5))));
}
while (cursor.moveToNext());
}
cursor.close();
db.close();
return contacts;
}
}

Android sqlite insert data SQLiteException

#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
// providers data
// db.execSQL("insert into "
// + TABLE_PROVIDERS
// + " (_id, provider_id, parent_id, title, image, sh_n, enable, visible, image_bg, type, is_group, hide_in_search, limit_min, limit_max, off_on_line, invoice_search) "
// + "VALUES (1,600,101,'Источники оплаты','',1,1,0,'','',1,1,0,0,0,0)");
ContentValues cv = new ContentValues();
cv.put("_id", 1);
cv.put("provider_id", 600);
cv.put("parent_id", 101);
cv.put("title", "Bla");
cv.put("image", "bla");
cv.put("sh_n", 1);
cv.put("enable", 1);
cv.put("visible", 1);
cv.put("image_bg", "");
cv.put("type", "");
cv.put("is_group", 1);
cv.put("hide_in_search", 1);
cv.put("limit_min", 10);
cv.put("limit_max", 10000);
cv.put("off_on_line", 1);
cv.put("invoice_search", 1);
db.insertOrThrow(TABLE_PROVIDERS, null, cv);
}
Now I'm doing as was suggested, inserting row by row:
import java.util.*;
import android.content.*;
import android.database.*;
import android.database.sqlite.*;
public class ProviderDataSource {
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
public ProviderDataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public List<Provider> getProvidersByParentId(long parentId) {
List<Provider> providersList = new ArrayList<Provider>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_PROVIDERS, new String[] { "provider_id", "title", "image" }, " parent_id=" + parentId,
null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Provider provider = cursorToProvider(cursor);
providersList.add(provider);
cursor.moveToNext();
}
cursor.close();
System.out.println("getProvidersByParentId");
return providersList;
}
private Provider cursorToProvider(Cursor cursor) {
Provider provider = new Provider();
provider.setId(cursor.getInt(1));
provider.setTitle(cursor.getString(3));
provider.setImg(cursor.getString(4));
return provider;
}
}
It doesn't work. It seems like the row wasn`t inserted and the array returnd by getProvidersByParentId method is empty. Parent_id as argument is 101.
Your insert statement is wrong. In SQLite, you cant insert multiple records by separating them with comma, in fact you need to prepare separate insert commands for that. But if your SQLite version is 3.7.11 then its possible.
Read this.
You can do it with a for loop like this
// add a button click event like
String[] arr1 = new String[n];
String[] arr2 = new String[n];
String[] arr3 = new String[n];
addButton.setOnClickListener
(
new View.OnClickListener()
{
#Override public void onClick(View v) {
for(int i=1;1<4;i++){
try
{
// ask the database manager to add a row given the two strings
//db object of database manager class
db.addValues
(
arr1[i] ,
arr2[i] ,
arr3[i] ,
);
}
catch (Exception e)
{
Log.e("Add Error", e.toString());
e.printStackTrace();
}
}
);
// function of insertion
public void addValues(String Col1, String Col2,
String col3)
{
ContentValues values = new ContentValues();
values.put(Columns1, Col1);
values.put(Columns2, Col2);
values.put(Columns3, Col3);
try{
db.insert(Course_Info_Table, null, values);
}
catch(Exception e)
{
}
}
use ContentValues to insert data into table like this.
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("_id", 1);
cv.put("provider_id", 600);
cv.put("parent_id", 0);
cv.put("title", "Источники оплаты");
cv.put("image", "");
cv.put("sh_n", 1);
cv.put("enable", 1);
cv.put("visible", 0);
cv.put("image_bg", "");
cv.put("type", "");
cv.put("is_group", 1);
cv.put("hide_in_search", 1);
cv.put("limit_min", 0);
cv.put("limit_max", 0);
cv.put("off_on_line", 0);
cv.put("invoice_search", 0);
db.insertOrThrow(TABLE_PROVIDERS, null, cv);
db.close();
for multiple records call this methods multiple times.
public void insertMydata(int _id, int provider_id, int parent_id /*....add more parameters as you required */){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("_id", _id);
cv.put("provider_id", provider_id);
cv.put("parent_id", parent_id);
/*
......
.....
put more code here for other columns
......
*/
db.insertOrThrow(TABLE_PROVIDERS, null, cv);
db.close();
}

Categories

Resources