I'm building a note taking app in Android. I have developed insertion of the note in the app right now which I have done through SQLite database. Now I want to delete the particular note from the SQLite database through the context menu. When user long presses any record in the app it will through a context menu with "Delete" option. Now, My problem is I'm able to remove item from listview but it's not getting deleted from database.
Here's my code:
MainActivity.java:
#Override
public boolean onContextItemSelected(MenuItem item) {
int position;
super.onContextItemSelected(item);
if(item.getTitle().equals("Delete")) {
//Add code
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
position = (int)info.id;
//Notes note_id = (Notes)adapter.getNote(info.position);
db.deleteNote(new Notes(position));
list.remove(position);
this.adapter.notifyDataSetChanged();
}
return true;
};
DatabaseHandler.java:
package com.amitmerchant.notesapp;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "notesManager";
private static final String TABLE_NOTES = "notes";
private static final String KEY_ID = "_id";
private static final String KEY_NOTE = "note";
private static final String KEY_DATE = "date_added";
public DatabaseHandler(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db){
String CREATE_NOTES_TABLE = "CREATE TABLE "+TABLE_NOTES+"("+KEY_ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"+KEY_NOTE+" TEXT,"+KEY_DATE+" DATE"+")";
db.execSQL(CREATE_NOTES_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTES);
// Create tables again
onCreate(db);
}
// Adding new contact
public void addNote(Notes note) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NOTE, note.getNote()); // Contact Name
// Inserting Row
db.insert(TABLE_NOTES, null, values);
db.close(); // Closing database connection
}
// Getting single contact
public Notes getNote(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NOTES, new String[] { KEY_ID,
KEY_NOTE, KEY_DATE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Notes note = new Notes(Integer.parseInt(cursor.getString(0)),
cursor.getString(1));
// return contact
return note;
}
// Getting All Contacts
public List<Notes> getAllNotes() {
List<Notes> noteList = new ArrayList<Notes>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NOTES;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Notes note = new Notes();
note.setId(Integer.parseInt(cursor.getString(0)));
note.setNote(cursor.getString(1));
// Adding contact to list
noteList.add(note);
} while (cursor.moveToNext());
}
// return contact list
return noteList;
}
// Getting contacts Count
public int getNotesCount() {
String countQuery = "SELECT * FROM " + TABLE_NOTES;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
// Updating single contact
public int updateNote(Notes note) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NOTE, note.getNote());
// updating row
return db.update(TABLE_NOTES, values, KEY_ID + " = ?",
new String[] { String.valueOf(note.getId()) });
}
// Deleting single contact
public void deleteNote(Notes note) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NOTES, KEY_ID + " = ?",
new String[] { String.valueOf(note.getId()) });
db.close();
}
}
Notes.java
package com.amitmerchant.notesapp;
public class Notes {
// private variables
int _id;
String _note;
String _note_date;
// Empty constructor
public Notes() {
}
public Notes(int id, String _note) {
this._id = id;
this._note = _note;
}
public Notes(String _note) {
this._note = _note;
}
public Notes(int id) {
this._id = id;
}
public int getId() {
return this._id;
}
public void setId(int id) {
this._id = id;
}
public String getNote() {
return this._note;
}
public void setNote(String note) {
this._note = note;
}
}
Guys, what am I doing wrong here? Please correct me. Thanks!
Related
I don't know how but my sqlite database seems to be only capable of storing one item instead of a lot. my database helper seems to return false whenever i add an item. How can i fix it?
Everytime I add a instance of a product to the database it returns false and only keeps one item but doesn't add anymore items.
Here's my product class:
public class ProductModel {
private int id;
private String name;
private float price;
private int quantity;
private float total;
private int inBasket;
public ProductModel(int id, String name, float price, int quantity, int inBasket) {
this.id = id;
this.name = name;
this.price = price;
this.quantity = quantity;
this.total = this.price * this.quantity;
this.inBasket = inBasket;
}
public ProductModel(){
}
#Override
public String toString() {
String n = this.name.toUpperCase();
return n + "\n Price:" + price + "\n Qty:" + quantity + "\n inBasket:"+inBasket+"\n Total:" + total;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public float getTotal() {
return total;
}
public void setTotal(float price, int quantity) {
this.total = price * quantity;
}
public int getInBasket() {
return inBasket;
}
public void setInBasket(int inBasket) {
this.inBasket = inBasket;
}
}
Here's my dataBaseHelper:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class DataBaseHelper extends SQLiteOpenHelper {
public static final String PRODUCT_TABLE = "PRODUCT_TABLE";
public static final String COL_ID = "PRODUCT_ID";
public static final String COL_NAME = "PRODUCT_NAME";
public static final String COL_PRICE = "PRODUCT_PRICE";
public static final String COL_QUANTITY = "PRODUCT_QUANTITY";
public static final String COL_TOTAL = "PRODUCT_TOTAL";
public static final String COL_IN_BASKET = "PRESENT_BASKET";
public static final String CREATE_TABLE_QUERY = "CREATE TABLE "+ PRODUCT_TABLE +"(" +
COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_NAME + " TEXT, " +
COL_PRICE + " FLOAT, " +
COL_QUANTITY + " INT, " +
COL_TOTAL + " FLOAT, " +
COL_IN_BASKET + " INT);";
public DataBaseHelper(#Nullable Context context) {
super(context, "ProductList.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_QUERY);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }
public boolean addItem(ProductModel productModel){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COL_ID, productModel.getId());
cv.put(COL_NAME, productModel.getName());
cv.put(COL_PRICE, productModel.getPrice());
cv.put(COL_QUANTITY, productModel.getQuantity());
cv.put(COL_TOTAL, productModel.getTotal());
cv.put(COL_IN_BASKET, productModel.getInBasket());
long insert = db.insert(PRODUCT_TABLE, null, cv);
if(insert==-1){
return false;
}
else { return true; }
}
public boolean deleteOne(ProductModel productModel){
SQLiteDatabase db = this.getReadableDatabase();
String QueryString = "DELETE FROM "+PRODUCT_TABLE+" WHERE " +COL_ID+ "=" +productModel.getId();
Cursor cursor = db.rawQuery(QueryString, null);
if(cursor.moveToFirst()){
return true;
}
else{ return false; }
}
public List<ProductModel> getEverything(){
List<ProductModel> returnList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
String QueryString = "SELECT * FROM " + PRODUCT_TABLE;
Cursor cursor = db.rawQuery(QueryString, null);
if(cursor.moveToFirst()){
do{
int productID = cursor.getInt(0);
String productName = cursor.getString(1);
float productPrice = cursor.getFloat(2);
int productQuantity = cursor.getInt(3);
int inBasket = cursor.getInt(5);
ProductModel newProduct = new ProductModel(productID, productName, productPrice, productQuantity, inBasket);
returnList.add(newProduct);
}while(cursor.moveToNext());
}else{ /*nothing*/ }
//close both cursor & db when done
cursor.close();
db.close();
return returnList;
}
}
And the corresponding activty that handles the adding of data to database:
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
Button bt_add;
EditText et_name, et_price, et_qty;
ListView lv_itemlist;
ArrayAdapter productArrayAdapter;
DataBaseHelper dataBaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_add = findViewById(R.id.bt_add);
et_name = findViewById(R.id.et_name);
et_price = findViewById(R.id.et_price);
et_qty = findViewById(R.id.et_qty);
lv_itemlist = findViewById(R.id.lv_itemlist);
dataBaseHelper = new DataBaseHelper(MainActivity.this);
ShowProductOnListView(dataBaseHelper);
bt_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProductModel productModel = new ProductModel();
try{
productModel.setId(-1);
productModel.setName(et_name.getText().toString());
productModel.setPrice(Float.parseFloat(et_price.getText().toString()));
productModel.setQuantity(Integer.parseInt(et_qty.getText().toString()));
productModel.setInBasket(1);//1 for true, 0 for false;
productModel.setTotal(productModel.getPrice(), productModel.getQuantity());
Log.d("CheckAdd" ,""+productModel.getTotal()); //checks if the total is in the product
}
catch (Exception e){
Log.d("CheckAdd" ,"Error on btn_add");
}
DataBaseHelper databaseHelper = new DataBaseHelper(MainActivity.this);
boolean success = databaseHelper.addItem(productModel);
Log.d("CheckAdd" ,"Success value:"+success);//expected true
ShowProductOnListView(dataBaseHelper);
}
});
lv_itemlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ProductModel clickedProduct = (ProductModel) parent.getItemAtPosition(position);
dataBaseHelper.deleteOne(clickedProduct);
ShowProductOnListView(dataBaseHelper);
}
});
}
private void ShowProductOnListView(DataBaseHelper dataBaseHelper) {
productArrayAdapter = new ArrayAdapter<ProductModel>(MainActivity.this, android.R.layout.simple_list_item_1,dataBaseHelper.getEverything());
lv_itemlist.setAdapter(productArrayAdapter);
}
}
use this simple for set Data to DB or get Data from DB
private ContentValues modelToContentValue(Model model)
{
ContentValues contentValues = new ContentValues();
contentValues.put("Price" , model.getPrice());
// And else ....
return contentValues;
}
private ArrayList<Model> cursorToModel(Cursor cursor)
{
ArrayList<Model> Models = new ArrayList<>();
cursor.moveToFirst();
while (!cursor.isAfterLast())
{
Model model = new Model();
model.setPrice(cursor.getFloat(cursor.getColumnIndex("Price")));
// And else ....
models.add(model);
cursor.moveToNext();
}
return models;
}
I use this method to insert in the table
public boolean insertGroup(ArrayList<Model> models)
{
SQLiteDatabase db = dbHelper.getWritableDatabase();
try
{
db.beginTransaction();
for (Model model : models)
{
ContentValues contentValues = modelToContentValue(model);
db.insertOrThrow("TableName" , null , contentValues);
}
db.setTransactionSuccessful();
db.endTransaction();
db.close();
return true;
}
catch (Exception exception)
{
exception.printStackTrace();
if (db.inTransaction())
{
db.endTransaction();
}
if (db.isOpen())
{
db.close();
}
return false;
}
}
I use this method to read the table
public ArrayList<Model> getAll()
{
ArrayList<Model> models = new ArrayList<>();
try
{
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.query("TableName", allColumns(), null, null, null, null, null);
if (cursor != null)
{
if (cursor.getCount() > 0)
{
models = cursorToModel(cursor);
}
cursor.close();
}
db.close();
catch (Exception exception)
{
exception.printStackTrace();
}
private String[] allColumns()
{
return new String[]
{
"Price",
// and else ....
};
}
Inside the listener of bt_add, with this line:
productModel.setId(-1);
you set the id of productModel to -1.
Then, the 1st time you execute the code the new row is inserted with PRODUCT_ID equal to -1.
But, for any subsequent call to addItem() the insert fails because PRODUCT_ID is the PRIMARY KEY of the table and that means that it is unique and you can't have more than 1 rows with PRODUCT_ID equal to -1.
The column PRODUCT_ID, since you defined it as INTEGER PRIMARY KEY AUTOINCREMENT does not need any value in the insert code. This will be taken care of by SQLite.
So, remove this line from the listener:
productModel.setId(-1);
and this line:
cv.put(COL_ID, productModel.getId());
from addItem().
Code
public class SettingsContacts extends AppCompatActivity {
private RecyclerView contactsList;
private List<ContactsHelper> contacts = new ArrayList<>();
private LinearLayoutManager linearLayoutManager;
private ContactsAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_contacts);
contactsList = (RecyclerView) findViewById(R.id.usersList);
//Add the data first
addDataToList();
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
//and then create a object and pass the lis
mAdapter = new ContactsAdapter(contacts);
contactsList.setHasFixedSize(true);
contactsList.setLayoutManager(linearLayoutManager);
contactsList.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}
public void addDataToList() {
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor != null) {
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id},
null);
if (phoneCursor != null) {
if (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts.add(new ContactsHelper(name, phoneNumber));
phoneCursor.close();
}
}
}
}
}
cursor.close();
}
}
}
This displays all the contacts in the users phone in an activity... How do i move the data into a table in SQLite?
Progress so far:
public class DatabaseHelper extends SQLiteOpenHelper {
// Table Name
public static final String TABLE_NAME = "Contacts";
// Table columns
public static final String ID = "ID";
public static final String Contact_Name = "Contact_Name";
public static final String Phone_Number = "Phone_Number";
// Database Information
static final String DB_NAME = "MessagePlus_Contacts";
// database version
static final int DB_VERSION = 1;
// Creating table query
private static final String CREATE_TABLE = "Create Table " + TABLE_NAME + "(" + ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + Contact_Name + " TEXT NOT NULL, " + Phone_Number + " INT NOT NULL);";
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
Helper
public class ContactsHelper {
private String Name;
private String PhoneNumber;
public ContactsHelper() {
}
public ContactsHelper(String Name, String PhoneNumber) {
this.Name = Name;
this.PhoneNumber = PhoneNumber;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getPhoneNumber() {
return PhoneNumber;
}
public void setPhoneNumber(String PhoneNumber) {
this.PhoneNumber = PhoneNumber;
}
}
I've got to this point but I don't know how to proceed because I have so far only worked with adding/modifying data by clicking a button or similar to that.
How do I move the complete data to SQLite and when new contact is added obviously it wont get added to table automatically so when I add a feature like swipe to refresh I want the new contact to be added to the data as well?
Solution:
Add this method in your DatabaseHelper class:
public void insertData(String contactName, String phoneNumber) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DatabaseHelper.Contact_Name, contactName);
values.put(DatabaseHelper.Phone_Number, phoneNumber);
db.insert(DatabaseHelper.TABLE_NAME, null, values);
// close db connection
db.close();
}
then, Firstly, make DatabaseHelper global object in your SettingsContacts class:
public DatabaseHelper database;
Add this in youronCreate()
database = new DatabaseHelper(SettingsContacts.this);
then after this, add the below line in addDataToList() method as shown:
Add this line:
database.insertData(name, phoneNumber)
as shown in below code (Write Here):
if (phoneCursor != null) {
if (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts.add(new ContactsHelper(name, phoneNumber));
phoneCursor.close();
....... (Write Here)
}
}
That's it.
Hope it works.
To see if the data is already inserted, you can check the count of your table:
public int getCount() {
String countQuery = "SELECT * FROM " + DatabaseHandler.TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
// return count
return count;
}
Write the above method in you Database Handler class.
Then, in your activity after calling insertData(..), you can write like:
int count = database.getCount();
Log.e("Count From DB: ", String.valueOf(count));
I don't know what is wrong here
package mytwistedidea.wordpress.com.testingdata;
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;
import android.os.Message;
import android.util.Log;
import java.util.ArrayList;
/**
* Created by Nishant on 22-02-2017.
*/
public class DatabaseHelper {
static MyHelper helper;
public DatabaseHelper(Context context){
helper = new MyHelper(context);
}
public long insertStudent(int roll, String name, String attended){
SQLiteDatabase sqLiteDatabase = helper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(MyHelper.ROLL,roll);
contentValues.put(MyHelper.NAME,name);
contentValues.put(MyHelper.ATTENDED,attended);
Long id = sqLiteDatabase.insert(MyHelper.TABLE_NAME_STUDENT,null,contentValues);
sqLiteDatabase.close();
return id;
}
public static ArrayList<String> getStudent(Integer roll){
SQLiteDatabase sqLiteDatabase = helper.getReadableDatabase();
ArrayList<Integer> previousRoll = new ArrayList<Integer>();
String columns[] = {MyHelper.ROLL};
String query = "SELECT * FROM "+MyHelper.TABLE_NAME_STUDENT+" WHERE roll='" + roll;
Cursor cursor = sqLiteDatabase.rawQuery(query,null);
if (cursor != null) {
cursor.moveToFirst();
}
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add(cursor.getString(cursor.getColumnIndex(MyHelper.ROLL)));
arrayList.add(cursor.getString(cursor.getColumnIndex(MyHelper.NAME)));
arrayList.add(cursor.getString(cursor.getColumnIndex(MyHelper.ATTENDED)));
return arrayList;
/*
Cursor cursor = sqLiteDatabase.query(MyHelper.TABLE_NAME_STUDENT,columns,null,null,null,null,null);
if(cursor.moveToFirst()){
do{
previousRoll.add(Integer.parseInt(cursor.getString(cursor.getColumnIndex(MyHelper.ROLL))));
}while (cursor.moveToNext());
}if(previousRoll.size() == 0){
previousRoll.add(0,0);
return previousRoll;
}
return previousRoll;*/
}
public static ArrayList<String> getAllStudent(){
SQLiteDatabase sqLiteDatabase = helper.getReadableDatabase();
ArrayList<String> previousStudent = new ArrayList<String>();
String columns[] = {MyHelper.ROLL,MyHelper.NAME,MyHelper.ATTENDED};
Cursor cursor = sqLiteDatabase.query(MyHelper.TABLE_NAME_STUDENT,columns,null,null,null,null,null);
if(cursor.moveToFirst()){
do{
previousStudent.add(cursor.getString(cursor.getColumnIndex(MyHelper.ROLL)));
previousStudent.add(cursor.getString(cursor.getColumnIndex(MyHelper.NAME)));
previousStudent.add(cursor.getString(cursor.getColumnIndex(MyHelper.ATTENDED)));
}while (cursor.moveToNext());
}if(previousStudent.size() == 0){
previousStudent.add(0," ");
return previousStudent;
}
return previousStudent;
}
public static ArrayList<Integer> getStudentRoll(){
SQLiteDatabase sqLiteDatabase = helper.getReadableDatabase();
ArrayList<Integer> previousRoll = new ArrayList<Integer>();
String columns[] = {MyHelper.ROLL};
Cursor cursor = sqLiteDatabase.query(MyHelper.TABLE_NAME_STUDENT,columns,null,null,null,null,null);
if(cursor.moveToFirst()){
do{
previousRoll.add(Integer.parseInt(cursor.getString(cursor.getColumnIndex(MyHelper.ROLL))));
}while (cursor.moveToNext());
}if(previousRoll.size() == 0){
previousRoll.add(0);
return previousRoll;
}
return previousRoll;
}
public static ArrayList<String> getStudentName(){
SQLiteDatabase sqLiteDatabase = helper.getReadableDatabase();
ArrayList<String> previousName = new ArrayList<String>();
String columns[] = {MyHelper.NAME};
Cursor cursor = sqLiteDatabase.query(MyHelper.TABLE_NAME_STUDENT,columns,null,null,null,null,null);
if(cursor.moveToFirst()){
do{
previousName.add(cursor.getString(cursor.getColumnIndex(MyHelper.ROLL)));
}while (cursor.moveToNext());
}if(previousName.size() == 0){
previousName.add(0," ");
return previousName;
}
return previousName;
}
public static ArrayList<Integer> getStudentAttendence(){
SQLiteDatabase sqLiteDatabase = helper.getReadableDatabase();
ArrayList<Integer> previousAttendence = new ArrayList<Integer>();
String columns[] = {MyHelper.ATTENDED};
Cursor cursor = sqLiteDatabase.query(MyHelper.TABLE_NAME_STUDENT,columns,null,null,null,null,null);
if(cursor.moveToFirst()){
do{
previousAttendence.add(Integer.parseInt(cursor.getString(cursor.getColumnIndex(MyHelper.ATTENDED))));
}while (cursor.moveToNext());
}if(previousAttendence.size() == 0){
previousAttendence.add(0,0);
return previousAttendence;
}
return previousAttendence;
}
class MyHelper extends SQLiteOpenHelper{
private static final String DATABASE_NAME = "mystudent.db";
private static final String TABLE_NAME_STUDENT = "student";
private static final int DATABASE_VERSION = 1;
private static final String NAME = "name";
private static final String ROLL = "roll";
private static final String ATTENDED = "attended";
private static final String CREATE_TABLE = "CREATE TABLE"+TABLE_NAME_STUDENT+
"("+ROLL+" INTEGER PRIMARY KEY, "+
NAME+" VARCHAR(255), "+
ATTENDED+" INTEGER);";
private static final String DROP_STUDENT = "DROP TABLE IF EXISTS "+TABLE_NAME_STUDENT;
private Context context;
public MyHelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
if(db != null){
try{
db.execSQL(CREATE_TABLE);
}
catch (SQLException e){
e.printStackTrace();
}
}
}
#Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try{
db.execSQL(DROP_STUDENT);
onCreate(db);
}
catch (SQLException e){
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try{
db.execSQL(DROP_STUDENT);
onCreate(db);
}
catch (SQLException e){
e.printStackTrace();
}
}
}
}
I am new to databases.
I don't know which part is wrong so I posted the whole code.
The problem is in below line
private static final String CREATE_TABLE = "CREATE
TABLE"+TABLE_NAME_STUDENT+
"("+ROLL+" INTEGER PRIMARY KEY, "+
NAME+" VARCHAR(255), "+
ATTENDED+" INTEGER);";
it should be like
private static final String CREATE_TABLE = "CREATE TABLE
"+TABLE_NAME_STUDENT+
"("+ROLL+" INTEGER PRIMARY KEY, "+
NAME+" VARCHAR(255), "+
ATTENDED+" INTEGER);";
There should be a space between"CREATE TABLE" and TABLE_NAME_STUDENT
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 ) ; ";
I'm new to Java and just tried to make a database. I managed to make a DB and all but when I want to read the values it seems to get an error.
This is my code for my settings activity (which asks for setting values and add them in the DB on a specific ID)
public class Settings extends Activity{
Button Save;
static Switch SwitchCalculations;
public static String bool;
public static List<Integer> list_id = new ArrayList<Integer>();
public static List<String> list_idname = new ArrayList<String>();
public static List<String> list_kind = new ArrayList<String>();
public static List<String> list_value = new ArrayList<String>();
static Integer[] arr_id;
static String[] arr_idname;
static String[] arr_kind;
static String[] arr_value;
public static final String TAG = "Settings";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
Save = (Button) findViewById(R.id.btnSave);
SwitchCalculations = (Switch) findViewById(R.id.switchCalcOnOff);
readData();
Save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
writeData();
//Toast.makeText(this, "Data has been saved.", Toast.LENGTH_SHORT).show();
readData();
Save.setText("Opgeslagen");
}
});
}
public void writeData() {
int id = 1;
String idname = "switchCalcOnOff";
String kind = "switch";
boolean val = SwitchCalculations.isChecked();
String value = new Boolean(val).toString();
dbHelper_Settings dbh = new dbHelper_Settings(this);
SQLiteDatabase db = dbh.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(dbh.C_ID, id);
cv.put(dbh.C_IDNAME, idname);
cv.put(dbh.C_KIND, kind);
cv.put(dbh.C_VALUE, value);
if (dbh.C_ID.isEmpty() == true) {
db.insert(dbh.TABLE, null, cv);
Log.d(TAG, "Insert: Data has been saved.");
} else if (dbh.C_ID.isEmpty() == false) {
db.update(dbh.TABLE, cv, "n_id='1'", null);
Log.d(TAG, "Update: Data has been saved.");
} else {
Log.d(TAG, "gefaald");
}
db.close();
}
public void readData() {
dbHelper_Settings dbh = new dbHelper_Settings(this);
SQLiteDatabase db = dbh.getWritableDatabase();
List<String> list_value = new ArrayList<String>();
String[] arr_value;
list_value.clear();
Cursor cursor = db.rawQuery("SELECT " + dbh.C_VALUE + " FROM " + dbh.TABLE + ";", null);
if (cursor.moveToFirst()) {
do {
list_value.add(cursor.getString(0));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()){
cursor.close();
}
db.close();
arr_value = new String[list_value.size()];
for (int i = 0; i < list_value.size(); i++){
arr_value[i] = list_value.get(i);
}
}
}
Then I have my dbHelper activity see below:
package com.amd.nutrixilium;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class dbHelper_Settings extends SQLiteOpenHelper{
private static final String TAG="dbHelper_Settings";
public static final String DB_NAME = "settings.db";
public static final int DB_VERSION = 10;
public final String TABLE = "settings";
public final String C_ID = "n_id"; // Special for id
public final String C_IDNAME = "n_idname";
public final String C_KIND = "n_kind";
public final String C_VALUE = "n_value";
Context context;
public dbHelper_Settings(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
}
// oncreate wordt maar 1malig uitgevoerd per user voor aanmaken van database
#Override
public void onCreate(SQLiteDatabase db) {
String sql = String.format("create table %s (%s int primary key, %s TEXT, %s TEXT, %s TEXT)", TABLE, C_ID, C_IDNAME, C_KIND, C_VALUE);
Log.d(TAG, "onCreate sql: " + sql);
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + TABLE); // wist een oudere database versie
Log.d(TAG, "onUpgrate dropped table " + TABLE);
this.onCreate(db);
}
}
And the weird thing is I don't get any error messages here.
But I used Log.d(TAG, text) to check where the script is being skipped and that is at cursor.moveToFirst().
So can anyone help me with this problem?
Here, contrary to what you seem to expect, you actually check that a text constant is not empty:
if (dbh.C_ID.isEmpty() == true) {
It isn't : it always contains "n_id"
I think your intent was to find a record with that id and, depending on the result, either insert or update.
You should do just that: attempt a select via the helper, then insert or update as in the code above.
Edit:
Add to your helper something like this:
public boolean someRowsExist(SQLiteDatabase db) {
Cursor cursor = db.rawQuery("select EXISTS ( select 1 from " + TABLE + " )", new String[] {});
cursor.moveToFirst();
boolean exists = (cursor.getInt(0) == 1);
cursor.close();
return exists;
}
And use it to check if you have any rows in the DB:
if (dbh.someRowsExist(db)) { // instead of (dbh.C_ID.isEmpty() == true) {
Looks like you're having trouble debugging your query. Android provides a handy method DatabaseUtils.dumpCursorToString() that formats the entire Cursor into a String. You can then output the dump to LogCat and see if any rows were actually skipped.