Android sqlite insert data SQLiteException - java

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

Related

Get ArrayList<String> from SQLite

I'm saving my ArrayList in SQLite. Save codes:
public void HistoryADD(ArrayList<String> full, String owner){
int size = full.size();
SQLiteDatabase db = getWritableDatabase();
try{
for (int i = 0; i < size ; i++){
ContentValues cv = new ContentValues();
cv.put(FULL, full.get(i));
cv.put(OWNER, owner);
db.insert(TABLE_NAME, null, cv);
}
System.out.println("added:" + full);
db.close();
}catch (Exception e){
System.out.println("Failed to add" + full);
}
}
And IT's working. I want to get this ArrayLists from SQLite. List Code:
public ArrayList<String> History_list(String owner) {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> history_list = new ArrayList<>();
Cursor cursor = db.rawQuery("SELECT * from " + TABLE_NAME + " WHERE owner='"+owner+"'",
new String[] {});
cursor.close();
return history_list;
}
But list code not working. What's wrong in this codes?
Thanks.
You need do something like that:
Cursor cursor = db.rawQuery(...);
try {
while (cursor.moveToNext()) {
//Here you have to add the item in your array list
}
} finally {
cursor.close();
}
public ArrayList<String> History_list(String owner) {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> history_list = new ArrayList<>();
Cursor cursor = db.rawQuery("SELECT * from " + TABLE_NAME + " WHERE owner"+"=?",new String[] {owner});
while (cursor.moveToNext()){
int owner_value= cursor.getColumnIndex(owner);
if (owner_value>0) history_list.add(cursor.getString(owner));
}
cursor.close();
return history_list;
}

Unable to permanently store data in a database

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.

How do I delete by ID in SQLite?

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

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

Android Sqlite shows no such table

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 ) ; ";

Categories

Resources