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().
Related
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 am trying to get timestamp to show- I have tried the onCreate query in different ways and also tried to to have addTime as a value in addPrime. Nothing seems to work. My intention is for the app to show previous primes and the time that they were found. The intention for the app is for the user to be able to close/kill the app and resume counting from last found prime number when restarting the app, if you have any hints how also this would be possible I would be grateful.
This is the PrimeDBManager class
public class PrimeDBManager extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "prime.db";
public static final String TABLE_PRIME = "prime";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_PRIMENO = "primeno";
public static final String COLUMN_DATETIME = "datetime";
public PrimeDBManager(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_PRIME + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_PRIMENO + " TEXT " + COLUMN_DATETIME + " DATETIME DEFAULT CURRENT_TIMESTAMP " + ");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRIME);
onCreate(db);
}
//Add a new prime to the database
public void addPrime(Prime prime){
ContentValues values = new ContentValues();
values.put(COLUMN_PRIMENO, prime.get_primeno());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_PRIME, null, values);
}
public void addTime(Prime prime) {
ContentValues values = new ContentValues();
values.put(COLUMN_DATETIME, prime.get_datetime());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_PRIME, null, values);
}
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_PRIME + " WHERE 1";
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast()) {
if (c.getString(c.getColumnIndex("primeno"))!=null){
dbString += c.getString(c.getColumnIndex("primeno"));
dbString += "\n";
}
c.moveToNext();
}
db.close();
return dbString;
}
}
Prime class
public class Prime {
private int _id;
private String _primeno;
private String _datetime;
public Prime(){ }
public Prime(String _primeno) {
this._primeno = _primeno;
}
public void set_id(int _id) {
this._id = _id;
}
public void set_primeno(String _primeno) {
this._primeno = _primeno;
}
public int get_id() {
return _id;
}
public String get_primeno() {
return _primeno;
}
public void set_datetime(String _datetime) {
this._datetime = _datetime;
}
public String get_datetime() {
return _datetime;
}
}
And lastly the MainActivity class
public class MainActivity extends ActionBarActivity {
Button primeButton;
int max = 500;
TextView primeText;
int j = 2;
TextView previousPrime;
PrimeDBManager dbManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
primeButton = (Button) findViewById(R.id.primeButton);
primeText = (TextView) findViewById(R.id.primeText);
previousPrime = (TextView) findViewById(R.id.previousPrime);
dbManager = new PrimeDBManager(this, null, null, 1);
printDatabase();
primeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
for (int i = j; i <= max; i++) {
if (isPrimeNumber(i)) {
primeText.setText(i+"");
j = i+1;
break;
}
}
Prime prime = new Prime(primeText.getText().toString());
dbManager.addPrime(prime);
dbManager.addTime(prime);
printDatabase();
}
});
}
public void printDatabase () {
String dbString = dbManager.databaseToString();
previousPrime.setText(dbString);
}
public boolean isPrimeNumber(int number) {
for (int i = 2; i <= number / 2; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
Ok, since you uploaded your project I think I got it working the way you want. It is working nonetheless.
There were several errors - mostly with logic. I tried to comment as much as I could so you can understand what/why I was doing everything.
One thing I did not comment was that the AndroidManifest needed permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
You can download the project here, or just look at the snippets:
MainActivity
I added a ListView so you can see all the primes. Also changed how/where we get the data from the DB, and how we save to DB.
public class MainActivity extends ActionBarActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private int max = 500;
private TextView primeText;
private int previousPrimeNumber;
private List<Prime> primes;
private PrimeAdapter adapter;
private MyDBHandler dbManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
primeText = (TextView) findViewById(R.id.primeText);
//get the object from previous session. Remember these are sorted by date
dbManager = new MyDBHandler(this);
primes = dbManager.getPrimeObjects();
//get the first prime. (AKA the last one added)
if (primes.size() != 0) {
previousPrimeNumber = primes.get(0).get_primeno(); //get the first item
primeText.setText(String.valueOf(previousPrimeNumber));
} else {
previousPrimeNumber = 2;
}
//create list view and adapter to display the data
ListView listView = (ListView) findViewById(R.id.listView);
adapter = new PrimeAdapter(this, primes);
listView.setAdapter(adapter);
findViewById(R.id.primeButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int primeNumber = -1;
//increment previousPrimeNumber by one so we wont keep using previousPrimeNumber
for (int i = previousPrimeNumber + 1; i <= max; i++) {
if (isPrimeNumber(i)) {
primeNumber = i;
primeText.setText(String.valueOf(i));
previousPrimeNumber = i + 1;
break;
}
}
if (primeNumber != -1) {
Prime prime = new Prime(primeNumber);
dbManager.addPrime(prime);
/* Yes, it saved to our database. But there is no reason for us to read from
* it too when we have the prime object right here. So just add it to the
* adapter and be done */
//The adapter is looking at the list primes. So add it to the top and notify
primes.add(0, prime);
adapter.notifyDataSetChanged();
} else {
Log.e(TAG, "Oops, there was an error. Invalid prime number");
}
}
});
}
public boolean isPrimeNumber(int number) {
for (int i = 2; i <= number / 2; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
/**
* If this is too confusing you can ignore it for now.
* However, I recommend understanding the android UIs before diving in to database storage.
* Take a look at this link:
* http://www.vogella.com/tutorials/AndroidListView/article.html
*/
private class PrimeAdapter extends ArrayAdapter<Prime> {
public PrimeAdapter(Context context, List<Prime> primes) {
// I am just using androids views. (android.R.id...)
super(context, android.R.layout.simple_list_item_2, primes);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
/* This method will automagically get called for every item in the list.
* This is an ARRAY adapter. So it has a list of the data we passed in on
* the constructor. So by calling "this" we are accessing it like it were a list
* which it really is. */
final Prime prime = this.getItem(position);
if (view == null) {
view = LayoutInflater.from(MainActivity.this)
.inflate(android.R.layout.simple_list_item_2, null);
}
/* if you look at simple_list_item_2, you will see two textViews. text1 and text2.
* Normally you would create this view yourself, but like i said, that is not the
* reason I am here */
// Notice I am referencing android.R.id. and not R.id. That is cause I am lazy and
// didn't create my own views.
TextView tv1 = (TextView) view.findViewById(android.R.id.text1);
TextView tv2 = (TextView) view.findViewById(android.R.id.text2);
tv1.setText(String.valueOf(prime.get_primeno()));
tv2.setText(prime.getDateTimeFormatted());
//now return the view so the listView knows to show it
return view;
}
}
MyDBHandler:
Changed the queries and added two methods that will convert Prime to a ContentValues object and from Cursor to a prime.
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "prime.db";
public static final String TABLE_PRIME = "prime";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_PRIMENO = "primeno";
public static final String COLUMN_DATETIME = "datetime";
public MyDBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_PRIME + "(" +
/* This must be in same order everywhere! */
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + // ID will be index 0
COLUMN_PRIMENO + " INTEGER, " + // Prime will be index 1
COLUMN_DATETIME + " LONG);"; // Date will be index 2
db.execSQL(query);
/* Something else to note: I changed the column types. You had text for these,
* which is fine. But the object that you are storing in each of these is not
* a string. So for consistency store the object as its original class type:
* PrimeNo == integer
* Datetime == long (milliseconds)
* This also makes it so sorting is much easier */
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRIME);
onCreate(db);
}
/**
* You want to save the entire Prime object at once. Not bits and pieces.
*
* #param prime
*/
public void addPrime(Prime prime) {
ContentValues values = writePrime(prime);
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_PRIME, null, values);
/* DON'T FORGET TO CLOSE YOUR DATABASE! */
db.close();
}
/**
* Again, you want to receive the entire prime object at once. Not bits.
*
* #return List of previous prime objects
*/
public List<Prime> getPrimeObjects() {
final List<Prime> primes = new ArrayList<Prime>();
final SQLiteDatabase db = getWritableDatabase();
/* Normally i would use this line of code:
final Cursor c = db.rawQuery("SELECT * FROM " + TABLE_PRIME, null);
but, you want to be sure you will get them order by DATE so you know
the first prime in the list is the last added. so I switched the query to this:
*/
final Cursor c = db.query(TABLE_PRIME,
new String[]{COLUMN_ID, COLUMN_PRIMENO, COLUMN_DATETIME},
null, null, null, null, //much null. So wow.
COLUMN_DATETIME + " DESC"); //order in descending.
/* After queried the first item will be our starting point */
c.moveToFirst();
while (c.moveToNext()) {
Prime p = buildPrime(c);
//check not null
if (p != null)
primes.add(p); //add to list
}
/* DON'T FORGET TO CLOSE YOUR DATABASE AND CURSOR! */
c.close();
db.close();
return primes;
}
/**
* Convert the Cursor object back in to a prime number
*
* #param cursor Cursor
* #return Prime
*/
private Prime buildPrime(Cursor cursor) {
final Prime prime = new Prime();
prime.set_id(cursor.getInt(0)); // id index as stated above
prime.set_primeno(cursor.getInt(1)); // prime index as stated above
prime.setDateTime(cursor.getLong(2)); // date index as stated above
return prime;
}
/**
* Convert the prime object in to ContentValues to write to DB
*
* #param prime prime
* #return ContentValues
*/
private ContentValues writePrime(Prime prime) {
ContentValues values = new ContentValues();
values.put(COLUMN_PRIMENO, prime.get_primeno()); //must insert first
values.put(COLUMN_DATETIME, prime.getDateTime()); //must insert second
return values;
}
}
Prime:
I just changed the value types. Prime's purpose is to store a prime integer. So why not make that field a integer?
public class Prime {
private static final String format = "yyyy-MM-dd HH:mm:ss";
private static final SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.ENGLISH);
private int _id;
private int _primeno;
private long dateTime = 0; //this is in milliseconds. Makes it easier to manage
public Prime() { }
public Prime(int primeNumber) {
//create a new prime object with a prime already known. set the date while we are at it
this._primeno = primeNumber;
this.dateTime = System.currentTimeMillis();
}
public void set_id(int _id) {
this._id = _id;
}
public void set_primeno(int _primeno) {
this._primeno = _primeno;
}
public int get_id() {
return _id;
}
public int get_primeno() {
return _primeno;
}
public long getDateTime() {
return dateTime;
}
public String getDateTimeFormatted() {
if (dateTime == 0) {
dateTime = System.currentTimeMillis();
}
Date date = new Date(dateTime);
return formatter.format(date);
}
public void setDateTime(long dateTime) {
this.dateTime = dateTime;
}
}
This seems to work.
In your values create db.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="prime_table_name">prime</string>
<string name="prime_table_column_id">_id</string>
<string name="prime_table_column_prime_no">prime_no</string>
<string name="prime_table_column_datetime">date_time</string>
<string-array name="prime_table_all_columns">
<item>#string/prime_table_column_id</item>
<item>#string/prime_table_column_prime_no</item>
<item>#string/prime_table_column_datetime</item>
</string-array>
<string name="createTableOfPrimes">CREATE TABLE prime ( _id INTEGER PRIMARY KEY AUTOINCREMENT, prime_no TEXT, date_time DATETIME DEFAULT CURRENT_TIMESTAMP );</string>
<string name="dropTableOfPrimes">DROP TABLE IF EXISTS prime</string>
<string name="insertIntoTableOfPrimes">INSERT INTO prime (prime_no, date_time) VALUES(?,?)</string>
</resources>
Prime class
package si.kseneman.utilities;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
public class Prime {
private static final String format = "yyyy-MM-dd HH:mm:ss";
private static final SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.ENGLISH);
private int id;
private String primeNo;
private Calendar dateTime;
public Prime(String primeNo) {
this.id = -1;
this.primeNo = primeNo;
this.dateTime = Calendar.getInstance();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPrimeNo() {
return primeNo;
}
public void setPrimeNo(String primeNo) {
this.primeNo = primeNo;
}
public String getDateTime() {
return formatter.format(dateTime.getTime());
}
public void setDateTime(Calendar calendar) {
this.dateTime = (Calendar) calendar.clone();
}
public void setDateTime(String dateTimeString) {
try {
dateTime.setTime(formatter.parse(dateTimeString));
} catch (ParseException e) {
dateTime.setTimeInMillis(0);
}
}
public void setDateTimeToNow() {
this.dateTime = Calendar.getInstance();
}
}
Prie SQL Lite Helper
package si.kseneman.utilities;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.lang.ref.WeakReference;
import si.kseneman.mobile.R;
public class PrimeDBSQLLiteHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "Prime.db";
private static final String TAG = PrimeDBSQLLiteHelper.class.getSimpleName();
private WeakReference<Context> mContext;
public PrimeDBSQLLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mContext = new WeakReference<Context>(context);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(getString(R.string.createTableOfPrimes));
Log.i(TAG, "DataBase created");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
sqLiteDatabase.execSQL(getString(R.string.dropTableOfPrimes));
this.onCreate(sqLiteDatabase);
}
private String getString(int resID) {
return mContext.get() != null ? mContext.get().getString(resID) : null;
}
}
Prime SingleTon database
package si.kseneman.utilities;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteStatement;
import android.os.Environment;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import si.kseneman.mobile.R;
public class PrimeDataSource {
private static final String TAG = PrimeDataSource.class.getSimpleName();
private static byte numberOfInstances;
private SQLiteDatabase database;
private PrimeDBSQLLiteHelper primeDBSQLLiteHelper;
private static PrimeDataSource instance;
private static final Object LOCK = new Object();
private Context context;
protected PrimeDataSource(Context context) {
this.context = context.getApplicationContext();
}
public static synchronized PrimeDataSource getInstance(Context context) {
if (instance == null) {
instance = new PrimeDataSource(context);
}
numberOfInstances++;
return instance;
}
public static synchronized void decrementNumberOfInstances() {
if (--numberOfInstances <= 0) {
instance.close();
}
numberOfInstances = numberOfInstances < 0 ? 0 : numberOfInstances; //Sanity?
}
public static synchronized void forceClose() {
numberOfInstances = 0;
instance.close();
}
private void close() {
if (isDatabaseOpenOpen()) {
primeDBSQLLiteHelper.close();
}
primeDBSQLLiteHelper = null;
instance = null;
database = null;
}
public synchronized void open() {
if (database == null || !database.isOpen()) {
primeDBSQLLiteHelper = new PrimeDBSQLLiteHelper(context);
database = primeDBSQLLiteHelper.getWritableDatabase();
}
}
public boolean isDatabaseOpenOpen() {
return database != null && database.isOpen();
}
public synchronized void deleteAllPrimesFromDb() {
try {
database.delete(getString(R.string.prime_table_name), null, null);
} catch (Exception e) {
// Was it really created?
createTableOfPrimes();
}
}
public synchronized void createTableOfPrimes() {
database.execSQL(getString(R.string.createTableOfPrimes));
}
public synchronized void dropTableOfJobs() {
database.execSQL(getString(R.string.dropTableOfPrimes));
}
public synchronized void dropDataBase() {
database.execSQL("DROP DATABASE IF EXISTS " + PrimeDBSQLLiteHelper.DATABASE_NAME);
}
public String getDatabasePath() {
return (Environment.getDataDirectory() + File.separator + PrimeDBSQLLiteHelper.DATABASE_NAME);
}
public synchronized void insertListOfPrimes(List<Prime> data) {
synchronized (LOCK) {
database.beginTransaction();
SQLiteStatement stmt = database.compileStatement(getString(R.string.insertIntoTableOfPrimes));
for (Prime p : data) {
stmt.bindString(1, p.getPrimeNo());
stmt.bindString(2, p.getDateTime());
stmt.executeInsert();
stmt.clearBindings();
}
database.setTransactionSuccessful();
database.endTransaction();
Log.i(TAG, "Insertion success");
}
}
private Prime cursorToPrime(Cursor cursor) {
// ID = 0 ; primeNo = 1; dateTime = 2;
Prime p = new Prime(cursor.getString(1));
p.setId(cursor.getInt(0));
p.setDateTime(cursor.getString(2));
return p;
}
public List<Prime> getListOfPrimes() {
synchronized (LOCK) {
List<Prime> listOfPrimes = new ArrayList<Prime>();
Cursor cursor = database.query(getString(R.string.prime_table_name), getStringArray(R.array.prime_table_all_columns), null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
listOfPrimes.add(cursorToPrime(cursor));
cursor.moveToNext();
}
return listOfPrimes;
}
}
public void insertPrime(Prime prime) {
synchronized (LOCK) {
database.beginTransaction();
SQLiteStatement stmt = database.compileStatement(getString(R.string.insertIntoTableOfPrimes));
stmt.bindString(1, prime.getPrimeNo());
stmt.bindString(2, prime.getDateTime());
stmt.executeInsert();
stmt.clearBindings();
database.setTransactionSuccessful();
database.endTransaction();
}
}
private int getCountFromCursor(Cursor cursor) {
int result = cursor.moveToFirst() ? cursor.getCount() : 0;
cursor.close();
return result;
}
public int getPrimeCount() {
synchronized (LOCK) {
Cursor cursor = database.query(getString(R.string.prime_table_name), new String[]{getString(R.string.prime_table_column_id)}, null, null, null, null, null);
return getCountFromCursor(cursor);
}
}
private String getString(int resID) {
return context.getString(resID);
}
private String[] getStringArray(int resID) {
return context.getResources().getStringArray(resID);
}
private String[] getStringArrayFromResources(int... integers) {
String[] result = new String[integers.length];
for (int i = 0; i < integers.length; ++i) {
result[i] = getString(integers[i]);
}
return result;
}
}
In Activity
private PrimeDataSource dataSource;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dataSource = PrimeDataSource.getInstance(getApplicationContext());
dataSource.open();
List<Prime> demoListOfPrimes = new ArrayList<Prime>(5);
demoListOfPrimes.add(new Prime("1"));
demoListOfPrimes.add(new Prime("3"));
demoListOfPrimes.add(new Prime("5"));
demoListOfPrimes.add(new Prime("7"));
demoListOfPrimes.add(new Prime("11"));
dataSource.insertListOfPrimes(demoListOfPrimes);
demoListOfPrimes = dataSource.getListOfPrimes();
if(demoListOfPrimes.size() == 0){
Log.i("", "Empty list");
}
for (Prime p : demoListOfPrimes) {
Log.i("Prime: ", p.getPrimeNo() + " ; " + p.getDateTime());
}
}
#Override
protected void onDestroy() {
super.onDestroy();
dataSource = null;
PrimeDataSource.decrementNumberOfInstances();
}
LogCat output:
04-07 22:45:18.590 1005-1005/si.kseneman.mobile I/PrimeDataSource﹕ Insertion success
04-07 22:45:18.590 1005-1005/si.kseneman.mobile I/Prime:﹕ 1 ; 2015-04-07 22:45:18
04-07 22:45:18.590 1005-1005/si.kseneman.mobile I/Prime:﹕ 3 ; 2015-04-07 22:45:18
04-07 22:45:18.590 1005-1005/si.kseneman.mobile I/Prime:﹕ 5 ; 2015-04-07 22:45:18
04-07 22:45:18.590 1005-1005/si.kseneman.mobile I/Prime:﹕ 7 ; 2015-04-07 22:45:18
04-07 22:45:18.590 1005-1005/si.kseneman.mobile I/Prime:﹕ 11 ; 2015-04-07 22:45:18
P.S. you may need to uninstall your app or drop your table for this to work
Here is a zip of a simple project that displays the numbers in a listview activity: LINK
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I want to get all database value into my arraylist and show in logcat. but i am facing some problem during getting value from arraylist. i put my hole code, i am able to get value but getting last value from model.
my MainActivity
package com.example.databasework;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
Button btnInsertCW, btnInsertCD, btnGetAllVAlue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnInsertCW = (Button) findViewById(R.id.btnInsertCW);
btnInsertCD = (Button) findViewById(R.id.btnInsertCD);
btnGetAllVAlue = (Button) findViewById(R.id.btnGetAllVAlue);
btnInsertCW.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v1) {
// TODO Auto-generated method stub
Database transactionDb = new Database(getApplicationContext());
TransactionModel transactionModel = new TransactionModel();
transactionDb.open();
transactionModel.setDate("14/2/2015");
transactionModel.setTime("11:12:15");
transactionModel.setEnrollment("CW");
transactionDb.insert(transactionModel);
transactionDb.close();
}
});
btnInsertCD.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v2) {
// TODO Auto-generated method stub
Database transactionDb = new Database(getApplicationContext());
TransactionModel transactionModel = new TransactionModel();
transactionDb.open();
transactionModel.setDate("28/3/2014");
transactionModel.setTime("09:08:06");
transactionModel.setEnrollment("CD");
transactionDb.insert(transactionModel);
transactionDb.close();
}
});
btnGetAllVAlue.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v3) {
// TODO Auto-generated method stub
ArrayList<TransactionModel> arrayList = new ArrayList<TransactionModel>();
Database transactionDb = new Database(getApplicationContext());
transactionDb.open();
arrayList = transactionDb.getReportPrintTrns();
transactionDb.close();
System.err.println(arrayList);
for (int i = 0; i < arrayList.size(); i++)
{
TransactionModel transactionModel = arrayList.get(i);
System.err.println(transactionModel.getEnrollment());
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
in arrayList = transactionDb.getReportPrintTrns(); want all database value.
My Database
package com.example.databasework;
import java.util.ArrayList;
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.util.Log;
public class Database {
private static final String DATABASE_NAME = "KisanMitra.db";
public static final String DATABASE_TABLE = "TransactionDb";
private static final int DATABASE_VERSION = 1;
public static final String TrnsNo = "TrnsNo";
public static final String Enrollment = "Enrollment";
public static final String CardNumber = "CardNumber";
public static final String EnrollmentAmount = "EnrollmentAmount";
public static final String Date = "Date";
public static final String Time = "Time";
public static final String ReturnStatus = "ReturnStatus";
public static final String TotalCashWithdrawalAmount = "TotalCashWithdrawalAmount";
public static final String TotalCashDepositAmount = "TotalCashDepositAmount";
public static final String TallyCash = "TallyCash";
public static final String KindPurchase = "KindPurchase";
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("create table " +DATABASE_TABLE + "("
+ TrnsNo + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
+ Enrollment + " text,"
+ Date + " text,"
+ CardNumber + " text,"
+ Time + " text,"
+ ReturnStatus + " text,"
+ EnrollmentAmount + " text,"
+ TotalCashDepositAmount + " text,"
+ TotalCashWithdrawalAmount + " text,"
+ KindPurchase + " text,"
+ TallyCash + " text);");
Log.e("TransationDb", "Create Succssfully");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion >= newVersion)
return;
String sql = null;
if (oldVersion == 1)
sql = "alter table " + DATABASE_TABLE + " add note text;";
if (oldVersion == 2)
sql = "";
Log.d("EventsData", "onUpgrade : " + sql);
if (sql != null)
db.execSQL(sql);
}
}
public Database open() throws SQLException {
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public Database(Context c) {
ourContext = c;
}
public void close() {
ourHelper.close();
}
public void insert(TransactionModel TransactionSetter)
{
String iEnrollment = TransactionSetter.getEnrollment();
String iEnrollmentAmount = TransactionSetter.getEnrollmentAmount();
String iDate = TransactionSetter.getDate();
String iTime = TransactionSetter.getTime();
String iReturnStatus = TransactionSetter.getReturnStatus();
String iCardNumber = TransactionSetter.getCardNumber();
String iTotalCashWithdrawalAmount = TransactionSetter.getTotalCashWithdrawalAmount();
String iTotalCashDepositAmount = TransactionSetter.getTotalCashDepositAmount();
String iTallyCash = TransactionSetter.getTallyCash();
String iKindPurchase = TransactionSetter.getKindPurchase();
ContentValues contentValues = new ContentValues();
contentValues.put(Enrollment, iEnrollment);
contentValues.put(EnrollmentAmount, iEnrollmentAmount);
contentValues.put(Date, iDate);
contentValues.put(Time, iTime);
contentValues.put(ReturnStatus, iReturnStatus);
contentValues.put(CardNumber, iCardNumber);
contentValues.put(TotalCashWithdrawalAmount,iTotalCashWithdrawalAmount);
contentValues.put(TotalCashDepositAmount, iTotalCashDepositAmount);
contentValues.put(TallyCash, iTallyCash);
contentValues.put(KindPurchase, iKindPurchase);
ourDatabase.insert(DATABASE_TABLE, null, contentValues);
}
public ArrayList<TransactionModel> getReportPrintTrns() {
ArrayList<TransactionModel> list = new ArrayList<TransactionModel>();
TransactionModel model = new TransactionModel();
String whereClause = Enrollment + " in ('CW', 'CD')";
String[] columns = new String[] { TrnsNo, Enrollment, EnrollmentAmount,
Date, Time, ReturnStatus, CardNumber,
TotalCashWithdrawalAmount, TotalCashDepositAmount, TallyCash, KindPurchase };
Cursor c=ourDatabase.query(DATABASE_TABLE, columns, whereClause,null,null,null,null);
int itransno = c.getColumnIndex(TrnsNo);
int iEnrollment = c.getColumnIndex(Enrollment);
int iEnrollmentAmount = c.getColumnIndex(EnrollmentAmount);
int iDate = c.getColumnIndex(Date);
int iTime = c.getColumnIndex(Time);
int iReturnStatus = c.getColumnIndex(ReturnStatus);
int iCardNumber = c.getColumnIndex(CardNumber);
int iTotalCashWithdrawalAmount = c.getColumnIndex(TotalCashWithdrawalAmount);
int iTotalCashDepositAmount = c.getColumnIndex(TotalCashDepositAmount);
int iTallyCash = c.getColumnIndex(TallyCash);
int iKindPurchase = c.getColumnIndex(KindPurchase);
if (c.moveToFirst()) {
do {
model.setTrnsNo(c.getString(itransno));
model.setEnrollment(c.getString(iEnrollment));
System.err.println("iEnrollmentType :- "+c.getString(iEnrollment));
model.setEnrollmentAmount(c.getString(iEnrollmentAmount));
model.setDate(c.getString(iDate));
model.setTime(c.getString(iTime));
model.setReturnStatus(c.getString(iReturnStatus));
model.setCardNumber(c.getString(iCardNumber));
model.setTotalCashWithdrawalAmount(c.getString(iTotalCashWithdrawalAmount));
model.setTotalCashDepositAmount(c.getString(iTotalCashDepositAmount));
model.setTallyCash(c.getString(iTallyCash));
model.setKindPurchase(c.getString(iKindPurchase));
list.add(model);
} while (c.moveToNext());
}
c.close();
c.deactivate();
return list;
}
}
My SetGet Model
package com.example.databasework;
public class TransactionModel {
String TrnsNo, Enrollment, EnrollmentAmount, Date, Time, ReturnStatus,
CardNumber, TotalCashWithdrawalAmount,
TotalCashDepositAmount, TallyCash, KindPurchase;
public TransactionModel() {
// TODO Auto-generated constructor stub
TrnsNo = "";
Enrollment = "";
EnrollmentAmount = "";
Date = "";
ReturnStatus = "";
Time = "";
CardNumber = "";
TotalCashWithdrawalAmount = "";
TotalCashDepositAmount = "";
TallyCash = "";
KindPurchase = "";
}
public String getTrnsNo() {
return TrnsNo;
}
public void setTrnsNo(String trnsNo) {
TrnsNo = trnsNo;
}
public String getEnrollment() {
return Enrollment;
}
public void setEnrollment(String enrollment) {
Enrollment = enrollment;
}
public String getEnrollmentAmount() {
return EnrollmentAmount;
}
public void setEnrollmentAmount(String enrollmentAmount) {
EnrollmentAmount = enrollmentAmount;
}
public String getDate() {
return Date;
}
public void setDate(String date) {
Date = date;
}
public String getTime() {
return Time;
}
public void setTime(String time) {
Time = time;
}
public String getReturnStatus() {
return ReturnStatus;
}
public void setReturnStatus(String returnStatus) {
ReturnStatus = returnStatus;
}
public String getCardNumber() {
return CardNumber;
}
public void setCardNumber(String cardNumber) {
CardNumber = cardNumber;
}
public String getTotalCashWithdrawalAmount() {
return TotalCashWithdrawalAmount;
}
public void setTotalCashWithdrawalAmount(String totalCashWithdrawalAmount) {
TotalCashWithdrawalAmount = totalCashWithdrawalAmount;
}
public String getTotalCashDepositAmount() {
return TotalCashDepositAmount;
}
public void setTotalCashDepositAmount(String totalCashDepositAmount) {
TotalCashDepositAmount = totalCashDepositAmount;
}
public String getTallyCash() {
return TallyCash;
}
public void setTallyCash(String tallyCash) {
TallyCash = tallyCash;
}
public String getKindPurchase() {
return KindPurchase;
}
public void setKindPurchase(String kindPurchase) {
KindPurchase = kindPurchase;
}
}
Getting Value
02-14 10:31:23.620: W/System.err(10564): iEnrollmentType :- CW
02-14 10:31:23.620: W/System.err(10564): iEnrollmentType :- CD
02-14 10:31:23.620: W/System.err(10564): iEnrollmentType :- CW
02-14 10:31:23.620: W/System.err(10564): iEnrollmentType :- CW
02-14 10:31:23.620: W/System.err(10564): iEnrollmentType :- CD
02-14 10:31:23.631: W/System.err(10564): CD
02-14 10:31:23.640: W/System.err(10564): CD
02-14 10:31:23.640: W/System.err(10564): CD
02-14 10:31:23.640: W/System.err(10564): CD
02-14 10:31:23.640: W/System.err(10564): CD
in Last Fine line i Am getting same value, but database has value like
CW
CD
CW
CW
CD
Create each time new object for TransactionModel in dowhile as follows
public ArrayList<TransactionModel> getReportPrintTrns() {
ArrayList<TransactionModel> list = new ArrayList<TransactionModel>();
TransactionModel model;
String whereClause = Enrollment + " in ('CW', 'CD')";
String[] columns = new String[] { TrnsNo, Enrollment, EnrollmentAmount,
Date, Time, ReturnStatus, CardNumber,
TotalCashWithdrawalAmount, TotalCashDepositAmount, TallyCash, KindPurchase };
Cursor c=ourDatabase.query(DATABASE_TABLE, columns, whereClause,null,null,null,null);
int itransno = c.getColumnIndex(TrnsNo);
int iEnrollment = c.getColumnIndex(Enrollment);
int iEnrollmentAmount = c.getColumnIndex(EnrollmentAmount);
int iDate = c.getColumnIndex(Date);
int iTime = c.getColumnIndex(Time);
int iReturnStatus = c.getColumnIndex(ReturnStatus);
int iCardNumber = c.getColumnIndex(CardNumber);
int iTotalCashWithdrawalAmount = c.getColumnIndex(TotalCashWithdrawalAmount);
int iTotalCashDepositAmount = c.getColumnIndex(TotalCashDepositAmount);
int iTallyCash = c.getColumnIndex(TallyCash);
int iKindPurchase = c.getColumnIndex(KindPurchase);
if (c.moveToFirst()) {
do {
model=new TransactionModel();
model.setTrnsNo(c.getString(itransno));
model.setEnrollment(c.getString(iEnrollment));
System.err.println("iEnrollmentType :- "+c.getString(iEnrollment));
model.setEnrollmentAmount(c.getString(iEnrollmentAmount));
model.setDate(c.getString(iDate));
model.setTime(c.getString(iTime));
model.setReturnStatus(c.getString(iReturnStatus));
model.setCardNumber(c.getString(iCardNumber));
model.setTotalCashWithdrawalAmount(c.getString(iTotalCashWithdrawalAmount));
model.setTotalCashDepositAmount(c.getString(iTotalCashDepositAmount));
model.setTallyCash(c.getString(iTallyCash));
model.setKindPurchase(c.getString(iKindPurchase));
list.add(model);
} while (c.moveToNext());
}
c.close();
c.deactivate();
return list;
}
hope it helps you.
Only one Problem In getReportPrintTrns() method. you have to initialize your Transaction Model. Like TransactionModel model=new TransactionModel();
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!
I have here my code. Data on the database are filtered by the title, how can i filter data by title or author? I think it is on these lines of codes on Catalogue.java:
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.fetchCollectionsByTitle(constraint.toString());
Here are my codes:
Catalogue.java
package com.cvsu.catalogue.db;
import com.cvsu.catalogue.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
//import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
#SuppressLint("NewApi")
public class Catalogue extends Activity {
private CollectionsDbAdapter dbHelper;
private SimpleCursorAdapter dataAdapter;
public final static String TITLE_EXTRA = "com.cvsu.catalogue.db._TITLE";
public final static String AUTHOR_EXTRA = "com.cvsu.catalogue.db._AUTHOR";
public final static String LOCATION_EXTRA = "com.cvsu.catalogue.db._LOCATION";
public final static String CALLNUMBER_EXTRA = "com.cvsu.catalogue.db._CALLNUMBER";
public final static String PUBLISHER_EXTRA = "com.cvsu.catalogue.db._PUBLISHER";
public final static String DATEPUBLISHED_EXTRA = "com.cvsu.catalogue.db._DATEPUBLISHED";
public final static String DESCRIPTION_EXTRA = "com.cvsu.catalogue.db._DESCRIPTION";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.catalogue_title);
dbHelper = new CollectionsDbAdapter(this);
dbHelper.open();
//Generate ListView from SQLite Database
displayListView();
}
private void displayListView() {
Cursor cursor = dbHelper.fetchAllCollections();
// The desired columns to be bound
String[] columns = new String[] {
CollectionsDbAdapter.KEY_TITLE,
CollectionsDbAdapter.KEY_AUTHOR,
CollectionsDbAdapter.KEY_LOCATION,
CollectionsDbAdapter.KEY_CALLNUMBER,
CollectionsDbAdapter.KEY_PUBLISHER,
CollectionsDbAdapter.KEY_DATEPUBLISHED,
CollectionsDbAdapter.KEY_DESCRIPTION
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.txtTitle,
R.id.txtAuthor,
//R.id.location,
//R.id.callnumber,
//R.id.publisher,
//R.id.datepublished,
//R.id.description,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.book_info_title,
cursor,
columns,
to,
0);
final ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listview, View view,
int position, long id ) {
// Get the cursor, positioned to the corresponding row in the result set
/*Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String bookTitle =
cursor.getString(cursor.getColumnIndexOrThrow("title"));
Toast.makeText(getApplicationContext(),
bookTitle, Toast.LENGTH_SHORT).show();*/
Intent i = new Intent (CatalogueTitle.this, BookInfoPage.class);
i.putExtra(TITLE_EXTRA, String.valueOf(id));
i.putExtra(AUTHOR_EXTRA, String.valueOf(id));
i.putExtra(LOCATION_EXTRA, String.valueOf(id));
i.putExtra(CALLNUMBER_EXTRA, String.valueOf(id));
i.putExtra(PUBLISHER_EXTRA, String.valueOf(id));
i.putExtra(DATEPUBLISHED_EXTRA, String.valueOf(id));
i.putExtra(DESCRIPTION_EXTRA, String.valueOf(id));
startActivity(i);
}
});
EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.fetchCollectionsByTitle(constraint.toString());
}
});
}
public static void main(String[] args) {
}
}
Collections.Java
package com.cvsu.catalogue.db;
public class Collections {
String title = null;
String author = null;
String location = null;
String callnumber = null;
String publisher = null;
String datepublished = null;
String description = null;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getCallNumber() {
return callnumber;
}
public void setCallNumber(String callnumber) {
this.callnumber = callnumber;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getDatePublished() {
return datepublished;
}
public void setDatePublished(String datepublished) {
this.datepublished = datepublished;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
CollectionsDbAdapter.java
package com.cvsu.catalogue.db;
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.util.Log;
public class CollectionsDbAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_TITLE = "title";
public static final String KEY_AUTHOR = "author";
public static final String KEY_LOCATION = "location";
public static final String KEY_CALLNUMBER = "callnumber";
public static final String KEY_PUBLISHER = "publisher";
public static final String KEY_DATEPUBLISHED = "datepublished";
public static final String KEY_DESCRIPTION = "description";
private static final String TAG = "CollectionsDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "LibraryCollections";
private static final String SQLITE_TABLE = "Collections";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
private static final String DATABASE_CREATE =
"CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
KEY_ROWID + " integer PRIMARY KEY autoincrement," +
KEY_TITLE + "," +
KEY_AUTHOR + "," +
KEY_LOCATION + "," +
KEY_CALLNUMBER + "," +
KEY_PUBLISHER + "," +
KEY_DATEPUBLISHED + "," +
KEY_DESCRIPTION + "," +
" UNIQUE (" + KEY_CALLNUMBER +"));";
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_CREATE);
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE);
onCreate(db);
}
}
public CollectionsDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public CollectionsDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
public long createCollections(String title, String author,
String location, String callnumber, String publisher, String datepublished, String description) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_AUTHOR, author);
initialValues.put(KEY_LOCATION, location);
initialValues.put(KEY_CALLNUMBER, callnumber);
initialValues.put(KEY_PUBLISHER, publisher);
initialValues.put(KEY_DATEPUBLISHED, datepublished);
initialValues.put(KEY_DESCRIPTION, description);
return mDb.insert(SQLITE_TABLE, null, initialValues);
}
public Cursor fetchCollectionsByTitle(String inputText) throws SQLException {
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
null, null, null, null, null);
}
else {
mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
KEY_TITLE + " like '%" + inputText + "%'", null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchCollectionsByAuthor(String inputText) throws SQLException {
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
null, null, null, null, null);
}
else {
mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
KEY_AUTHOR + " like '%" + inputText + "%'", null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchAllCollections() {
Cursor mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
#Override
public Cursor runQuery(CharSequence constraint) {
Cursor cur = null;
database.openDataBase();
if(constraint!=null){
cur = database.selectDataWithConstrain(constraint.toString());
}
return cur;
}
using this constarint write a query in your Database Class and get the data required either title or author
public Cursor selectDataWithConstrain(String c) {
// TODO Auto-generated method stub
Cursor cursor = myDataBase.rawQuery("SELECT * FROM tbl_xxx WHERE title LIKE '%"+c+"%'", null);
return cursor;
}
public Cursor fetchdatabyfilter(String inputText, String filtercolumn) throws SQLException {
Cursor row = null;
String query = "SELECT * FROM " + dbTable;
if (inputText == null || inputText.length() == 0 ) {
row = sqlDb.rawQuery(query, null);
} else {
query = "SELECT * FROM " + dbTable + " WHERE " + filtercolumn + " like '%" + inputText + "%' ";
row = sqlDb.rawQuery(query, null);
}
if (row != null)
{
row.moveToFirst();
}
return row;
}
mainactivity:
adapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return db.fetchdatabyfilter(constraint.toString(),"title" );
}
});