Datetime does not show up - java

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

Related

My sqlite database is only inserting one item android studio (java)

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().

SQlite null database

I am building a simple bank app (no security what so ever) and have a login activity that verifies the input with an SQLite database. My method returns 1 if is a match and 0 if not. The problem is it always returns 0 because the database is null according to debug. I'm not sure why the variable I use in the login method is null. The data insert is working as I've checked using SQLite browser.
Here is the SQLite database with the login() method at the bottom:
public class CustomerDatabase{
private SQLiteDatabase database;
private SQLiteOpenHelper openHelper;
//Database constants
public static final String DB_Name = "customers.db";
public static final int DB_Version = 1;
public static final String CUSTOMER_TABLE = "Customers";
public static final String CARD_ACCESS_NO = "accessNo";
public static final int CARD_ACCESS_NO_COLUMN = 0;
public static final String CUSTOMER_PASSWORD = "password";
public static final int CUSTOMER_PASSWORD_COLUMN = 2;
public static final String CUSTOMER_NAME = "custName";
public static final int CUSTOMER_NAME_COLUMN = 1;
public static final String CHECKING_ACCOUNT_FUNDS = "checkAccFunds";
public static final int CHECKING_ACCOUNT_FUNDS_COLUMN = 3;
public static final String SAVINGS_ACCOUNT_FUNDS = "saveAccFunds";
public static final int SAVINGS_ACCOUNT_FUNDS_COLUMN = 4;
public static final String CHECKING_ACCOUNT_NO = "checkAccNo";
public static final int CHECKING_ACCOUNT_NO_COLUMN = 5;
public static final String SAVINGS_ACCOUNT_NO = "saveAccNo";
public static final int SAVINGS_ACCOUNT_NO_COLUMN = 6;
//DDL for creating the db
public static final String CREATE_CUSTOMER_TABLE =
"CREATE TABLE " + CUSTOMER_TABLE + " (" +
CARD_ACCESS_NO + " INTEGER PRIMARY KEY, " +
CUSTOMER_NAME + " TEXT, " +
CHECKING_ACCOUNT_NO + " TEXT, " +
CUSTOMER_PASSWORD + " TEXT, " +
CHECKING_ACCOUNT_FUNDS + " TEXT, " +
SAVINGS_ACCOUNT_NO + " TEXT, " +
SAVINGS_ACCOUNT_FUNDS + " TEXT)";
public CustomerDatabase(Context context){
openHelper = new DBHelper(context, DB_Name, DB_Version);
}
//method to store accountHolder objects into the database
public AccountHolder saveAccHolder(AccountHolder holder){
database = openHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CARD_ACCESS_NO, holder.getAccessCardNo());
values.put(CUSTOMER_NAME, holder.getName());
values.put(CUSTOMER_PASSWORD, holder.getPassword());
values.put(CHECKING_ACCOUNT_FUNDS, holder.getCheckingAccountFunds());
values.put(CHECKING_ACCOUNT_NO, holder.getCheckingAccountNo());
values.put(SAVINGS_ACCOUNT_NO, holder.getSavingsAccountNo());
values.put(SAVINGS_ACCOUNT_FUNDS, holder.getSavingsAccountFunds());
long id = database.insert(CUSTOMER_TABLE, null, values);
holder.setDbId(id);
database.close();
return holder;
}
private static class DBHelper extends SQLiteOpenHelper{
public DBHelper(Context context, String name, int version){
super(context, name, null, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + CUSTOMER_TABLE);
db.execSQL(CREATE_CUSTOMER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVer, int newVer) {
db.execSQL("DROP TABLE IF EXISTS " + CUSTOMER_TABLE);
onCreate(db);
}
}
/**Method will be used by the bank to check if user is authorized */
public int login(String accessNo, String password){
String[] selectArgs = new String[]{accessNo,password};
try{
int i = 0;
Cursor cursor = null;
cursor = database.rawQuery("SELECT * FROM CUSTOMER_TABLE WHERE accessNo =? AND password=?",selectArgs);
cursor.moveToFirst();
i = cursor.getCount();
cursor.close();
return i;
}
catch (Exception e){ e.printStackTrace();}
return 0;
}
}
Debug says that the database variable is null at login() at line cursor = database.rawQuery()...
Here is the login activity logic:
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(edtAccessCardNo.length() != 0 || edtPassword.length() != 0){
String accessNoInput = edtAccessCardNo.getText().toString();
String passwordInput = edtPassword.getText().toString();
boolean checkVerify = isVerifiedUser(accessNoInput, passwordInput);
if(checkVerify){
Intent intent = new Intent(getApplicationContext(), BankActivity.class);
startActivity(intent);
}else{
txtErrorDisplay.setText("Unable to login.");
}
}else{
edtAccessCardNo.setHint("This is a required field");
edtPassword.setHint("This is a required field");
}
}
});
}
//Method to create dummy accountHolder objects
public void getAndSaveDummyHolders(){
CustomerDatabase custDb = new CustomerDatabase(this);
for(int i = 0; i < 5; i++){
AccountHolder holder = new AccountHolder(
holderNames[i], accessNo[i],
passwords[i], checkAccNo[i], savAccNo[i],
checkAccFunds[i], savAccFunds[i]);
custDb.saveAccHolder(holder);
}
}
//verify the user using method in customer database
public boolean isVerifiedUser(String userAccessCard, String userPassword){
CustomerDatabase custDb = new CustomerDatabase(getApplicationContext());
int check = custDb.login(userAccessCard, userPassword);
if(check == 1){
return true;
}else{
return false;
}
}

Sq-lite database retrieve data to array list [closed]

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

Order of list items populated from SQLLite DB is incorrect

I have a SQLLite DB that stores an ftp site's login information (name,address,username,password,port,passive). When an item (site) is clicked in the list, it's supposed to load the name, address, username, password etc. into the corresponding EditTexts. What's happening is that the password value is getting loaded into the address EditText and the address isn't getting loaded anywhere.
My Activity's addRecord function looks like this:
public void addRecord() {
long newId = myDb.insertRow(_name, _address, _username, _password,
_port, _passive);
Cursor cursor = myDb.getRow(newId);
displayRecordSet(cursor);
}
The order of the parameters in insertRow() correspond to the order in my DBAdapter, however when I change the order of the parameters I can get the address and password values to end up in the correct EditTexts, just never all of them at once. What am I doing wrong?
public class DBAdapter {
// ///////////////////////////////////////////////////////////////////
// Constants & Data
// ///////////////////////////////////////////////////////////////////
// For logging:
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_NAME = "name";
public static final String KEY_ADDRESS = "address";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_PORT = "port";
public static final String KEY_PASSIVE = "passive";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_ADDRESS = 2;
public static final int COL_USERNAME = 3;
public static final int COL_PASSWORD = 4;
public static final int COL_PORT = 5;
public static final int COL_PASSIVE = 6;
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_NAME,
KEY_ADDRESS, KEY_USERNAME, KEY_PASSWORD, KEY_PORT, KEY_PASSIVE };
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "Sites";
public static final String DATABASE_TABLE = "SiteTable";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_SQL = "create table "
+ DATABASE_TABLE
+ " ("
+ KEY_ROWID
+ " integer primary key autoincrement, "
/*
* CHANGE 2:
*/
// TODO: Place your fields here!
// + KEY_{...} + " {type} not null"
// - Key is the column name you created above.
// - {type} is one of: text, integer, real, blob
// (http://www.sqlite.org/datatype3.html)
// - "not null" means it is a required field (must be given a
// value).
// NOTE: All must be comma separated (end of line!) Last one must
// have NO comma!!
+ KEY_NAME + " string not null, " + KEY_ADDRESS
+ " string not null, " + KEY_USERNAME + " string not null, "
+ KEY_PASSWORD + " string not null, " + KEY_PORT
+ " integer not null," + KEY_PASSIVE + " integer not null"
// Rest of creation:
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
// ///////////////////////////////////////////////////////////////////
// Public methods:
// ///////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String name, String address, String user,
String pass, int port, int passive) {
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_ADDRESS, address);
initialValues.put(KEY_USERNAME, user);
initialValues.put(KEY_PASSWORD, pass);
initialValues.put(KEY_PORT, port);
initialValues.put(KEY_PASSIVE, passive);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String name, String address,
String username, String password, int port, int passive) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, name);
newValues.put(KEY_ADDRESS, address);
newValues.put(KEY_USERNAME, username);
newValues.put(KEY_PASSWORD, password);
newValues.put(KEY_PORT, port);
newValues.put(KEY_PASSIVE, passive);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
// ///////////////////////////////////////////////////////////////////
// Private Helper Classes:
// ///////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading. Used to
* handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version "
+ oldVersion + " to " + newVersion
+ ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
public class SiteManager extends Activity {
DBAdapter myDb;
public FTPClient mFTPClient = null;
public EditText etSitename;
public EditText etAddress;
public EditText etUsername;
public EditText etPassword;
public EditText etPort;
public CheckBox cbPassive;
public ListView site_list;
public Button clr;
public Button test;
public Button savesite;
public Button close;
public Button connect;
String _name;
String _address;
String _username;
String _password;
int _port;
int _passive = 0;
List<FTPSite> model = new ArrayList<FTPSite>();
ArrayAdapter<FTPSite> adapter;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.site_manager);
site_list = (ListView) findViewById(R.id.siteList);
adapter = new SiteAdapter(this, R.id.ftpsitename, R.layout.siterow,
model);
site_list.setAdapter(adapter);
etSitename = (EditText) findViewById(R.id.dialogsitename);
etAddress = (EditText) findViewById(R.id.dialogaddress);
etUsername = (EditText) findViewById(R.id.dialogusername);
etPassword = (EditText) findViewById(R.id.dialogpassword);
etPort = (EditText) findViewById(R.id.dialogport);
cbPassive = (CheckBox) findViewById(R.id.dialogpassive);
close = (Button) findViewById(R.id.closeBtn);
connect = (Button) findViewById(R.id.connectBtn);
clr = (Button) findViewById(R.id.clrBtn);
test = (Button) findViewById(R.id.testBtn);
savesite = (Button) findViewById(R.id.saveSite);
addListeners();
openDb();
displayRecords();
}
public void addListeners() {
connect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent returnResult = new Intent();
returnResult.putExtra("ftpname", _name);
returnResult.putExtra("ftpaddress", _address);
returnResult.putExtra("ftpusername", _username);
returnResult.putExtra("ftppassword", _password);
returnResult.putExtra("ftpport", _port);
setResult(RESULT_OK, returnResult);
finish();
}
});
test.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_name = etSitename.getText().toString();
_address = etAddress.getText().toString();
_username = etUsername.getText().toString();
_password = etPassword.getText().toString();
_port = Integer.parseInt(etPort.getText().toString());
if (cbPassive.isChecked()) {
_passive = 1;
} else {
_passive = 0;
}
boolean status = ftpConnect(_address, _username, _password,
_port);
ftpDisconnect();
if (status == true) {
Toast.makeText(SiteManager.this, "Connection Succesful",
Toast.LENGTH_LONG).show();
savesite.setVisibility(0);
} else {
Toast.makeText(SiteManager.this,
"Connection Failed:" + status, Toast.LENGTH_LONG)
.show();
}
}
});
savesite.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_name = etSitename.getText().toString();
_address = etAddress.getText().toString();
_username = etUsername.getText().toString();
_password = etPassword.getText().toString();
_port = Integer.parseInt(etPort.getText().toString());
if (cbPassive.isChecked()) {
_passive = 1;
} else {
_passive = 0;
}
addRecord();
adapter.notifyDataSetChanged();
}
});
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
clr.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
clearAll();
}
});
site_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
final FTPSite item = (FTPSite) parent
.getItemAtPosition(position);
String tmpname = item.getName();
String tmpaddress = item.getAddress();
String tmpuser = item.getUsername();
String tmppass = item.getPassword();
int tmpport = item.getPort();
String tmp_port = Integer.toString(tmpport);
int tmppassive = item.isPassive();
etSitename.setText(tmpname);
etAddress.setText(tmpaddress);
etUsername.setText(tmpuser);
etPassword.setText(tmppass);
etPort.setText(tmp_port);
if (tmppassive == 1) {
cbPassive.setChecked(true);
} else {
cbPassive.setChecked(false);
}
}
});
}
public void addRecord() {
long newId = myDb.insertRow(_name, _username, _address,_password,
_port, _passive);
Cursor cursor = myDb.getRow(newId);
displayRecordSet(cursor);
}
private void openDb() {
myDb = new DBAdapter(this);
myDb.open();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
closeDb();
}
private void closeDb() {
myDb.close();
}
public void displayRecords() {
Cursor cursor = myDb.getAllRows();
displayRecordSet(cursor);
}
protected void displayRecordSet(Cursor c) {
// String msg = "";
if (c.moveToFirst()) {
do {
// int id = c.getInt(0);
_name = c.getString(1);
_address = c.getString(2);
_username = c.getString(3);
_password = c.getString(4);
_port = c.getInt(5);
FTPSite sitesFromDB = new FTPSite();
sitesFromDB.setName(_name);
sitesFromDB.setAddress(_address);
sitesFromDB.setUsername(_username);
sitesFromDB.setAddress(_password);
sitesFromDB.setPort(_port);
sitesFromDB.setPassive(_passive);
model.add(sitesFromDB);
adapter.notifyDataSetChanged();
} while (c.moveToNext());
}
c.close();
}
public void clearAll() {
myDb.deleteAll();
adapter.notifyDataSetChanged();
}
public boolean ftpConnect(String host, String username, String password,
int port) {
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login(username, password);
mFTPClient.enterLocalPassiveMode();
return status;
}
} catch (Exception e) {
// Log.d(TAG, "Error: could not connect to host " + host );
}
return false;
}
public boolean ftpDisconnect() {
try {
mFTPClient.logout();
mFTPClient.disconnect();
return true;
} catch (Exception e) {
// Log.d(TAG,
// "Error occurred while disconnecting from ftp server.");
}
return false;
}
class SiteAdapter extends ArrayAdapter<FTPSite> {
private final List<FTPSite> objects;
private final Context context;
public SiteAdapter(Context context, int resource,
int textViewResourceId, List<FTPSite> objects) {
super(context, R.id.ftpsitename, R.layout.siterow, objects);
this.context = context;
this.objects = objects;
}
/** #return The number of items in the */
public int getCount() {
return objects.size();
}
public boolean areAllItemsSelectable() {
return false;
}
/** Use the array index as a unique id. */
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.siterow, parent, false);
TextView textView = (TextView) rowView
.findViewById(R.id.ftpsitename);
textView.setText(objects.get(position).getName());
return (rowView);
}
}
I think you should try to use :
int keyNameIndex = c.getColumnIndex(DBAdapter.KEY_NAME);
_name = c.getString(keyNameIndex);
Instead of using direct number.I am not sure it cause the bug, but it gonna be better exercise. Hope it's help.
There is mismatch in your arguments see below
public long insertRow(String name, String address, String user,
String pass, int port, int passive) {
public void addRecord() {
long newId = myDb.insertRow(_name, _username, _address,_password,
_port, _passive);
Cursor cursor = myDb.getRow(newId);
displayRecordSet(cursor);
}
you are passing username to address and address to user
This is embarrassing. I had sitesFromDB.setAddress(_password); instead of sitesFromDB.setPassword(_password);

cursor.moveToFirst seems to be skipped

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.

Categories

Resources