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();
Related
I don't know how but my sqlite database seems to be only capable of storing one item instead of a lot. my database helper seems to return false whenever i add an item. How can i fix it?
Everytime I add a instance of a product to the database it returns false and only keeps one item but doesn't add anymore items.
Here's my product class:
public class ProductModel {
private int id;
private String name;
private float price;
private int quantity;
private float total;
private int inBasket;
public ProductModel(int id, String name, float price, int quantity, int inBasket) {
this.id = id;
this.name = name;
this.price = price;
this.quantity = quantity;
this.total = this.price * this.quantity;
this.inBasket = inBasket;
}
public ProductModel(){
}
#Override
public String toString() {
String n = this.name.toUpperCase();
return n + "\n Price:" + price + "\n Qty:" + quantity + "\n inBasket:"+inBasket+"\n Total:" + total;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public float getTotal() {
return total;
}
public void setTotal(float price, int quantity) {
this.total = price * quantity;
}
public int getInBasket() {
return inBasket;
}
public void setInBasket(int inBasket) {
this.inBasket = inBasket;
}
}
Here's my dataBaseHelper:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class DataBaseHelper extends SQLiteOpenHelper {
public static final String PRODUCT_TABLE = "PRODUCT_TABLE";
public static final String COL_ID = "PRODUCT_ID";
public static final String COL_NAME = "PRODUCT_NAME";
public static final String COL_PRICE = "PRODUCT_PRICE";
public static final String COL_QUANTITY = "PRODUCT_QUANTITY";
public static final String COL_TOTAL = "PRODUCT_TOTAL";
public static final String COL_IN_BASKET = "PRESENT_BASKET";
public static final String CREATE_TABLE_QUERY = "CREATE TABLE "+ PRODUCT_TABLE +"(" +
COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_NAME + " TEXT, " +
COL_PRICE + " FLOAT, " +
COL_QUANTITY + " INT, " +
COL_TOTAL + " FLOAT, " +
COL_IN_BASKET + " INT);";
public DataBaseHelper(#Nullable Context context) {
super(context, "ProductList.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_QUERY);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }
public boolean addItem(ProductModel productModel){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COL_ID, productModel.getId());
cv.put(COL_NAME, productModel.getName());
cv.put(COL_PRICE, productModel.getPrice());
cv.put(COL_QUANTITY, productModel.getQuantity());
cv.put(COL_TOTAL, productModel.getTotal());
cv.put(COL_IN_BASKET, productModel.getInBasket());
long insert = db.insert(PRODUCT_TABLE, null, cv);
if(insert==-1){
return false;
}
else { return true; }
}
public boolean deleteOne(ProductModel productModel){
SQLiteDatabase db = this.getReadableDatabase();
String QueryString = "DELETE FROM "+PRODUCT_TABLE+" WHERE " +COL_ID+ "=" +productModel.getId();
Cursor cursor = db.rawQuery(QueryString, null);
if(cursor.moveToFirst()){
return true;
}
else{ return false; }
}
public List<ProductModel> getEverything(){
List<ProductModel> returnList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
String QueryString = "SELECT * FROM " + PRODUCT_TABLE;
Cursor cursor = db.rawQuery(QueryString, null);
if(cursor.moveToFirst()){
do{
int productID = cursor.getInt(0);
String productName = cursor.getString(1);
float productPrice = cursor.getFloat(2);
int productQuantity = cursor.getInt(3);
int inBasket = cursor.getInt(5);
ProductModel newProduct = new ProductModel(productID, productName, productPrice, productQuantity, inBasket);
returnList.add(newProduct);
}while(cursor.moveToNext());
}else{ /*nothing*/ }
//close both cursor & db when done
cursor.close();
db.close();
return returnList;
}
}
And the corresponding activty that handles the adding of data to database:
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
Button bt_add;
EditText et_name, et_price, et_qty;
ListView lv_itemlist;
ArrayAdapter productArrayAdapter;
DataBaseHelper dataBaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_add = findViewById(R.id.bt_add);
et_name = findViewById(R.id.et_name);
et_price = findViewById(R.id.et_price);
et_qty = findViewById(R.id.et_qty);
lv_itemlist = findViewById(R.id.lv_itemlist);
dataBaseHelper = new DataBaseHelper(MainActivity.this);
ShowProductOnListView(dataBaseHelper);
bt_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProductModel productModel = new ProductModel();
try{
productModel.setId(-1);
productModel.setName(et_name.getText().toString());
productModel.setPrice(Float.parseFloat(et_price.getText().toString()));
productModel.setQuantity(Integer.parseInt(et_qty.getText().toString()));
productModel.setInBasket(1);//1 for true, 0 for false;
productModel.setTotal(productModel.getPrice(), productModel.getQuantity());
Log.d("CheckAdd" ,""+productModel.getTotal()); //checks if the total is in the product
}
catch (Exception e){
Log.d("CheckAdd" ,"Error on btn_add");
}
DataBaseHelper databaseHelper = new DataBaseHelper(MainActivity.this);
boolean success = databaseHelper.addItem(productModel);
Log.d("CheckAdd" ,"Success value:"+success);//expected true
ShowProductOnListView(dataBaseHelper);
}
});
lv_itemlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ProductModel clickedProduct = (ProductModel) parent.getItemAtPosition(position);
dataBaseHelper.deleteOne(clickedProduct);
ShowProductOnListView(dataBaseHelper);
}
});
}
private void ShowProductOnListView(DataBaseHelper dataBaseHelper) {
productArrayAdapter = new ArrayAdapter<ProductModel>(MainActivity.this, android.R.layout.simple_list_item_1,dataBaseHelper.getEverything());
lv_itemlist.setAdapter(productArrayAdapter);
}
}
use this simple for set Data to DB or get Data from DB
private ContentValues modelToContentValue(Model model)
{
ContentValues contentValues = new ContentValues();
contentValues.put("Price" , model.getPrice());
// And else ....
return contentValues;
}
private ArrayList<Model> cursorToModel(Cursor cursor)
{
ArrayList<Model> Models = new ArrayList<>();
cursor.moveToFirst();
while (!cursor.isAfterLast())
{
Model model = new Model();
model.setPrice(cursor.getFloat(cursor.getColumnIndex("Price")));
// And else ....
models.add(model);
cursor.moveToNext();
}
return models;
}
I use this method to insert in the table
public boolean insertGroup(ArrayList<Model> models)
{
SQLiteDatabase db = dbHelper.getWritableDatabase();
try
{
db.beginTransaction();
for (Model model : models)
{
ContentValues contentValues = modelToContentValue(model);
db.insertOrThrow("TableName" , null , contentValues);
}
db.setTransactionSuccessful();
db.endTransaction();
db.close();
return true;
}
catch (Exception exception)
{
exception.printStackTrace();
if (db.inTransaction())
{
db.endTransaction();
}
if (db.isOpen())
{
db.close();
}
return false;
}
}
I use this method to read the table
public ArrayList<Model> getAll()
{
ArrayList<Model> models = new ArrayList<>();
try
{
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.query("TableName", allColumns(), null, null, null, null, null);
if (cursor != null)
{
if (cursor.getCount() > 0)
{
models = cursorToModel(cursor);
}
cursor.close();
}
db.close();
catch (Exception exception)
{
exception.printStackTrace();
}
private String[] allColumns()
{
return new String[]
{
"Price",
// and else ....
};
}
Inside the listener of bt_add, with this line:
productModel.setId(-1);
you set the id of productModel to -1.
Then, the 1st time you execute the code the new row is inserted with PRODUCT_ID equal to -1.
But, for any subsequent call to addItem() the insert fails because PRODUCT_ID is the PRIMARY KEY of the table and that means that it is unique and you can't have more than 1 rows with PRODUCT_ID equal to -1.
The column PRODUCT_ID, since you defined it as INTEGER PRIMARY KEY AUTOINCREMENT does not need any value in the insert code. This will be taken care of by SQLite.
So, remove this line from the listener:
productModel.setId(-1);
and this line:
cv.put(COL_ID, productModel.getId());
from addItem().
Much like the title says. I have followed my class tutorials but chunks seem to be missing and it gets a bit confusing flicking between video lectures and pdf's when you're not too well versed in such.
When the app is executed the user can search for a song by year, or display all records within the database. However, originally all records would display from clicking the search by year button instead of the display all button. The search function works as intended but the display all button I cannot seem to figure out, despite following my lecturer's tutorials.
The first section of code is "MainActivity.java" and the second is "OpenDatabse.java"
package com.example.dbcopyexample1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MainActivity extends AppCompatActivity
{
private static String DATABASE_PATH_AND_NAME;
private static String CHECK_DATABASES_FOLDER;
//private static final String DATABASE_NAME = "music.db";
private static final String LOG_TAG = "MUSIC_DB";
Context ctx;
OpenDatabase sqh;
SQLiteDatabase sqdb;
// Control Objects
EditText searchByYearEditText;
Button searchButton;
TextView numRecordTextView;
Button displayAllRecordsButton;
TextView resultsTextView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupDatabaseStrings();
setUpDatabase();
InitDataBase(); // open the music.db for reading and writing
//sqh.DisplayRecords( sqdb ); // Display the songtable records to the run window
setupControls();
numRecordTextView.setText( Integer.toString( sqh.numberOfRecordsInSongtable( sqdb ) ) );
} // protected void onCreate(Bundle savedInstanceState)
protected void setupControls()
{
searchByYearEditText = findViewById(R.id.searchByYearEditText);
searchButton = findViewById(R.id.searchButton);
searchButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
resultsTextView.setText( sqh.searchByYearInSongtable( sqdb,
searchByYearEditText.getText().toString()) );
}
});
numRecordTextView = findViewById(R.id.numRecordTextView);
displayAllRecordsButton = findViewById(R.id.displayAllRecordsButton);
displayAllRecordsButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
}
});
resultsTextView = findViewById(R.id.resultsTextView);
} // protected void setupControls()
protected void setupDatabaseStrings()
{
// Full path to where we will copy music.db to on the emulator!
DATABASE_PATH_AND_NAME = "/data/data/" + getApplicationContext().getPackageName() +
"/databases/" + OpenDatabase.DATABASE_NAME;
// Used to check if the "databases" folder exists
CHECK_DATABASES_FOLDER = "/data/data/" + getApplicationContext().getPackageName() +
"/databases";
// Debug information
Log.i("DATABASE_PATH_AND_NAME","DATABASE_PATH_AND_NAME = " + DATABASE_PATH_AND_NAME);
Log.i("CHECK_DATABASES_FOLDER","CHECK_DATABASES_FOLDER = " + CHECK_DATABASES_FOLDER);
} // protected void setupDatabaseStrings()
protected void setUpDatabase()
{
ctx = this.getBaseContext();
Log.w("CTX","ctx = " + ctx);
Log.w("getBaseContext()","getBaseContext = " + getBaseContext());
try
{
CopyDataBaseFromAsset();
}
catch (IOException e)
{
e.printStackTrace();
}
} // protected void setUpDatabase()
protected void CopyDataBaseFromAsset() throws IOException
{
Log.w( LOG_TAG , "Starting copying...");
String outputFileName = DATABASE_PATH_AND_NAME;
File databaseFolder = new File( CHECK_DATABASES_FOLDER );
// databases folder exists ? No - Create it and copy !!!
if ( !databaseFolder.exists() )
{
databaseFolder.mkdir();
// Open the sqlite database "music.db" found in the assets folder
InputStream in = ctx.getAssets().open(OpenDatabase.DATABASE_NAME);
OutputStream out = new FileOutputStream(outputFileName);
byte[] buffer = new byte[1024];
int length;
while ( (length = in.read(buffer)) > 0 )
{
out.write(buffer,0,length);
} // while ( (length = in.read(buffer)) > 0 )
out.flush();
out.close();
in.close();
Log.w(LOG_TAG, "Completed.");
} // if ( !databaseFolder.exists() )
} // protected void CopyDataBaseFromAsset() throws IOException
public void InitDataBase()
{
// Init the SQLite Helper Class
sqh = new OpenDatabase(this);
// RETRIEVE A READABLE AND WRITEABLE DATABASE
sqdb = sqh.getWritableDatabase();
} // public void InitDataBase()
public void DisplayRecords()
{
Cursor c = sqdb.rawQuery("SELECT * FROM songtable", null);
if (c != null)
{
if (c.moveToFirst())
{
do
{
String id = c.getString(0);
String songtitle = c.getString(1);
String year = c.getString(2);
String artist = c.getString(3);
String album = c.getString(4);
Log.w("SONG_TABLE", "ID = " + id + " Songtitle = " + songtitle);
} while (c.moveToNext());
}
}
c.close();
} // public void DisplayRecords()
} // public class MainActivity extends AppCompatActivity
package com.example.dbcopyexample1;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class OpenDatabase extends SQLiteOpenHelper
{
public static final String DATABASE_NAME = "music.db";
// TOGGLE THIS NUMBER FOR UPDATING TABLES AND DATABASE
private static final int DATABASE_VERSION = 1;
OpenDatabase(Context context)
{
super( context, DATABASE_NAME, null, DATABASE_VERSION );
} // OpenDatabase(Context context)
#Override
public void onCreate(SQLiteDatabase db)
{
} // public void onCreate(SQLiteDatabase db)
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
} // public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
public String searchByYearInSongtable(SQLiteDatabase sqdb, String searchYear)
{
String result = "";
Cursor c = sqdb.rawQuery("SELECT * FROM songtable where year = '" + searchYear + "'",
null);
if (c != null) {
if (c.moveToFirst()) {
do {
String id = c.getString(0);
result = result + id + ",";
String songtitle = c.getString(1);
result = result + songtitle + ",";
String year = c.getString(2);
result = result + year + ",";
String artist = c.getString(3);
result = result + artist + ",";
String album = c.getString(4);
result = result + album + "\n"; // new line control character
Log.w("SONG_TABLE", "ID = " + id + " Songtitle = " + songtitle);
} while (c.moveToNext());
} else
{
result = "No Records Found for the Search Year = " + searchYear;
}
}
c.close();
return result;
} // public String allRecordsInSongtable(SQLiteDatabase sqdb)
public int numberOfRecordsInSongtable(SQLiteDatabase sqdb)
{
int count = 0;
Cursor c = sqdb.rawQuery("SELECT count(*) FROM songtable", null);
if (c != null)
{
if (c.moveToFirst())
{
do
{
String id = c.getString(0);
count = Integer.parseInt( id );
} while (c.moveToNext());
}
}
c.close();
return count;
} // public int numberOfRecordsInSongtable(SQLiteDatabase sqdb)
} // public class OpenDatabase extends SQLiteOpenHelper
You have not called your DisplayRecords() function to display records on tap of displayAllRecordsButton.
displayAllRecordsButton = findViewById(R.id.displayAllRecordsButton);
displayAllRecordsButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
DisplayRecords();
}
});
Also, in the DisplayRecords() method, you need to set text to the text view.
Below is your code I edited to display records.
public void DisplayRecords()
{
String result = "";
Cursor c = sqdb.rawQuery("SELECT * FROM songtable", null);
if (c != null)
{
if (c.moveToFirst())
{
do
{
String id = c.getString(0);
String songtitle = c.getString(1);
String year = c.getString(2);
String artist = c.getString(3);
String album = c.getString(4);
Log.w("SONG_TABLE", "ID = " + id + " Songtitle = " + songtitle);
result = result + "ID = " + id + "Song Title = " + songtitle + "Artist = " + artist + "Album = " + album + "Year = " + year + "\n";
} while (c.moveToNext());
}
}
c.close();
resultsTextView.setText(result);
} // public void DisplayRecords()
I am not able to match or compare two dates one from Database and second is current date.I have five checkboxes. When 1st user checkes a checkbox and insert its value by clicking the save button. 2nd time when he check 2 or more checkboxes Now here I want to update last record by date. I set date as primary key in that table.
NamazCounterActivity
package com.example.shakeelmughal.assanislam;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.preference.PreferenceManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class NamazCounterActivity extends AppCompatActivity {
DatabaseHelper mydb;
CheckBox cb1,cb2,cb3,cb4,cb5;
Button B1,B2,B3;
TextView tv;
int vcb1=0,vcb2=0,vcb3=0,vcb4=0,vcb5=0;
Date date = new Date();
String a="1";
public static final String SHARED_PREF = "sharedPrefs";
public static final String CHECK1 = "check1";
public static final String CHECK2 = "check2";
public static final String CHECK3 = "check3";
public static final String CHECK4 = "check4";
public static final String CHECK5 = "check5";
private Boolean chb1,chb2,chb3,chb4,chb5;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_namaz_counter);
try {
mydb = new DatabaseHelper(this);
} catch (IOException e) {
e.printStackTrace();
}
tv = findViewById(R.id.textView24);
cb1 = findViewById(R.id.namaz1);
cb2 = findViewById(R.id.namaz2);
cb3 = findViewById(R.id.namaz3);
cb4 = findViewById(R.id.namaz4);
cb5 = findViewById(R.id.namaz5);
B1 = findViewById(R.id.result);
B2 = findViewById(R.id.dateee);
B3 = findViewById(R.id.sumr);
c_date();
B1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor c = mydb.getAllData1();
if (c.moveToFirst())
{
if(mydb.date().equals(c.getString(0)))
{
Updateingdata();
}
else
{
InsertingData();
}
}
else
{
InsertingData();
}
SaveData();
}
});
B3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor c = mydb.getAllData();
if(c.getCount() == 0)
{
Toast.makeText(NamazCounterActivity.this,"Empty",Toast.LENGTH_SHORT).show();
}
StringBuffer stringBuffer = new StringBuffer();
while (c.moveToNext())
{
stringBuffer.append("ID: " +c.getString(0 )+"\n");
stringBuffer.append("Fajar: " +c.getString(1)+"\n");
stringBuffer.append("Zohr: " +c.getString(2)+"\n");
stringBuffer.append("Asr: " +c.getString(3)+"\n");
stringBuffer.append("Magrib: " +c.getString(4)+"\n" );
stringBuffer.append("Isha: " +c.getString(5)+"\n");
}
showData("Data",stringBuffer.toString());
}
});
//home button
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
//functions for save old values
loadData();
updateViews();
}
//function for going back to previous activity
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
public void InsertingData()
{
if(cb1.isChecked())
{
vcb1 = 1;
}
else
{
vcb1 = 0;
}
if(cb2.isChecked())
{
vcb2 = 1;
}
else
{
vcb2 = 0;
}
if(cb3.isChecked())
{
vcb3 = 1;
}
else
{
vcb3 = 0;
}
if(cb4.isChecked())
{
vcb4 = 1;
}
else
{
vcb4 = 0;
}
if(cb5.isChecked())
{
vcb5 = 1;
}
else
{
vcb5 = 0;
}
boolean result = mydb.InsertData(date().toString(),Integer.toString(vcb1),Integer.toString(vcb2),Integer.toString(vcb3),Integer.toString(vcb4),Integer.toString(vcb5));
if(result == true)
{
Toast.makeText(NamazCounterActivity.this, "Prayer Saved",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(NamazCounterActivity.this, "Some Error", Toast.LENGTH_LONG).show();
}
}
public void Updateingdata()
{
if(cb1.isChecked())
{
vcb1 = 1;
}
else
{
vcb1 = 0;
}
if(cb2.isChecked())
{
vcb2 = 1;
}
else
{
vcb2 = 0;
}
if(cb3.isChecked())
{
vcb3 = 1;
}
else
{
vcb3 = 0;
}
if(cb4.isChecked())
{
vcb4 = 1;
}
else
{
vcb4 = 0;
}
if(cb5.isChecked())
{
vcb5 = 1;
}
else
{
vcb5 = 0;
}
boolean res = mydb.UpdateData(B2.getText().toString(),Integer.toString(vcb1),Integer.toString(vcb2),Integer.toString(vcb3),Integer.toString(vcb4),Integer.toString(vcb5));
if(res == true)
{
Toast.makeText(NamazCounterActivity.this,"Data Updated",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(NamazCounterActivity.this,"Data Not Updated",Toast.LENGTH_SHORT).show();
}
}
//for date ()
public void c_date() {
date.setTime(System.currentTimeMillis()); //set to current time
B2.setText(date.toString());
SimpleDateFormat dateFormat = new SimpleDateFormat("EEEEEEEEE, MMM dd, yyyy");
B2.setText(dateFormat.format(date));
}
public void SaveData()
{
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF,MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(CHECK1, cb1.isChecked());
editor.putBoolean(CHECK2, cb2.isChecked());
editor.putBoolean(CHECK3, cb3.isChecked());
editor.putBoolean(CHECK4, cb4.isChecked());
editor.putBoolean(CHECK5, cb5.isChecked());
editor.apply();
}
public void loadData()
{
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF,MODE_PRIVATE);
chb1 = sharedPreferences.getBoolean(CHECK1, false);
chb2 = sharedPreferences.getBoolean(CHECK2, false);
chb3 = sharedPreferences.getBoolean(CHECK3, false);
chb4 = sharedPreferences.getBoolean(CHECK4, false);
chb5 = sharedPreferences.getBoolean(CHECK5, false);
}
public void updateViews()
{
cb1.setChecked(chb1);
cb2.setChecked(chb2);
cb3.setChecked(chb3);
cb4.setChecked(chb4);
cb5.setChecked(chb5);
}
public void showData(String title, String message)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
public java.sql.Date date()
{
long millis=System.currentTimeMillis();
java.sql.Date date=new java.sql.Date(millis);
return date;
}
}
DatabaseHelper.java
package com.example.shakeelmughal.assanislam;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Date;
import static android.content.ContentValues.TAG;
import static java.time.LocalTime.now;
/**
* Created by Shakeel Mughal on 5/30/2018.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
public Context context;
private SQLiteDatabase db2;
public AssetManager mngr;
SQLiteDatabase db;
private Resources mResources;
private InputStream inputstream = null;
private final static String Dbname = "NamazCounter.db";
private final static String Tbname = "DailyWork";
private final static String Tbname2 = "items";
private final static String Col_1 = "ID";
private final static String Col_2 = "Fajar";
private final static String Col_3 = "Zohr";
private final static String Col_4 = "Asr";
private final static String Col_5 = "Magrib";
private final static String Col_6 = "Isha";
private final static String NCol_1 = "date_for";
private final static String NCol_2 = "fajr";
private final static String NCol_3 = "shurooq";
private final static String NCol_4 = "dhuhr";
private final static String NCol_5 = "asr";
private final static String NCol_6 = "maghrib";
private final static String NCol_7 = "isha";
public DatabaseHelper(Context context) throws IOException {
super(context, Dbname, null, 1);
this.context = context;
mResources = context.getResources();
mngr = context.getAssets();
db = this.getWritableDatabase();
db = this.getReadableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
//namaz counter
final String Table1 = "CREATE TABLE "+Tbname+"(ID PRIMARY KEY TEXT, Fajar TEXT, Zohr TEXT, Asr TEXT, Magrib TEXT, Isha TEXT)";
//for namaz timing
final String Table2 = "CREATE TABLE "+Tbname2+"(date_for TEXT, fajr TEXT, shurooq TEXT, dhuhr TEXT, asr TEXT, maghrib TEXT,isha TEXT)";
db.execSQL(Table1);
db.execSQL(Table2);
Log.d(TAG, "DataBase Created");
try {
readDataToDb(db);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ Tbname);
db.execSQL("DROP TABLE IF EXISTS "+ Tbname2);
onCreate(db);
}
public void openDatabase() {
String dbPath = context.getDatabasePath(Dbname).getPath();
if (db != null) {
db.isOpen();
return;
}
db = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}
public void closeDatabase() {
if (db != null) {
db.close();
}
}
//Json fun
private String readJsonDataFromFile() throws IOException {
StringBuilder builder = new StringBuilder();
try {
String jsonDataString = null;
inputstream = mngr.open("NamazTiming.json");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputstream, "UTF-8"));
while ((jsonDataString = bufferedReader.readLine()) != null) {
builder.append(jsonDataString);
}
} finally {
if (inputstream != null) {
inputstream.close();
}
}
return new String(builder);
}
public void readDataToDb(SQLiteDatabase db) throws IOException, JSONException {
final String date = "date_for";
final String namaz1 = "fajr";
final String namaz2 = "shurooq";
final String namaz3 = "dhuhr";
final String namaz4 = "asr";
final String namaz5 = "maghrib";
final String namaz6 = "isha";
try {
String jsonDataString = readJsonDataFromFile();
JSONArray jsonfileJSONArray = new JSONArray(jsonDataString);
for (int i = 0; i < jsonfileJSONArray.length(); i++) {
String dateid;
String nmz1;
String nmz2;
String nmz3;
String nmz4;
String nmz5;
String nmz6;
JSONObject jsonfileObject = jsonfileJSONArray.getJSONObject(i);
dateid = jsonfileObject.getString(date);
nmz1 = jsonfileObject.getString(namaz1);
nmz2 = jsonfileObject.getString(namaz2);
nmz3 = jsonfileObject.getString(namaz3);
nmz4 = jsonfileObject.getString(namaz4);
nmz5 = jsonfileObject.getString(namaz5);
nmz6 = jsonfileObject.getString(namaz6);
ContentValues jsonfilevalues = new ContentValues();
jsonfilevalues.put(NCol_1, dateid);
jsonfilevalues.put(NCol_2, nmz1);
jsonfilevalues.put(NCol_3, nmz2);
jsonfilevalues.put(NCol_4, nmz3);
jsonfilevalues.put(NCol_5, nmz4);
jsonfilevalues.put(NCol_6, nmz5);
jsonfilevalues.put(NCol_7, nmz6);
long rowID= db.insert(Tbname2, null, jsonfilevalues);
if(rowID>-1){
int catid=0;
Cursor cursor = db.rawQuery("SELECT "+ NCol_1 + " FROM "+ Tbname2+" where "+ NCol_1 + "='" + now() + "'" , null);
cursor.moveToFirst();
if (cursor.moveToNext()) {
catid = (cursor.getInt(0));
}
cursor.close();
JSONArray jsonitemsarray= (JSONArray) jsonfileObject.get("itemsList");
readitem(db,jsonitemsarray);
}
Log.d(TAG, "Inserted sucessfully" + jsonfilevalues);
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage(), e);
e.printStackTrace();
}
}
private void readitem(SQLiteDatabase db,JSONArray jsonfileJSONArray) throws IOException, JSONException {
final String date1 = "date_for";
final String namaz1 = "fajr";
final String namaz2 = "shurooq";
final String namaz3 = "dhuhr";
final String namaz4 = "asr";
final String namaz5 = "maghrib";
final String namaz6 = "isha";
try {
for (int i = 0; i < jsonfileJSONArray.length(); i++) {
String Did;
String nmzz1 ;
String nmzz2 ;
String nmzz3 ;
String nmzz4 ;
String nmzz5 ;
String nmzz6 ;
JSONObject jsonfileObject1 = jsonfileJSONArray.getJSONObject(i);
Did = jsonfileObject1.getString(date1);
nmzz1 = jsonfileObject1.getString(namaz1);
nmzz2 = jsonfileObject1.getString(namaz2);
nmzz3 = jsonfileObject1.getString(namaz3);
nmzz4 = jsonfileObject1.getString(namaz4);
nmzz5 = jsonfileObject1.getString(namaz5);
nmzz6 = jsonfileObject1.getString(namaz6);
ContentValues jsonfilevalues1 = new ContentValues();
jsonfilevalues1.put(NCol_1, Did);
jsonfilevalues1.put(NCol_2, nmzz1);
jsonfilevalues1.put(NCol_3, nmzz2);
jsonfilevalues1.put(NCol_4, nmzz3);
jsonfilevalues1.put(NCol_5, nmzz4);
jsonfilevalues1.put(NCol_6, nmzz5);
jsonfilevalues1.put(NCol_7, nmzz6);
db.insert(Tbname2, null, jsonfilevalues1);
Log.d(TAG, "Inserted sucessfully" + jsonfilevalues1);
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage(), e);
e.printStackTrace();
}
}
//inserting for counter
public boolean InsertData(String d_date, String Fjr, String zhr, String assr, String mgrb, String isa)
{
SQLiteDatabase db = this.getReadableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Col_1,d_date);
contentValues.put(Col_2,Fjr);
contentValues.put(Col_3,zhr);
contentValues.put(Col_4,assr);
contentValues.put(Col_5,mgrb);
contentValues.put(Col_6,isa);
long success = db.insert(Tbname,null,contentValues);
if(success == -1)
{
return false;
}
else
{
return true;
}
}
public boolean UpdateData(String id,String n1, String n2, String n3,String n4,String n5)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Col_1,id);
contentValues.put(Col_2,n1);
contentValues.put(Col_3,n2);
contentValues.put(Col_4,n3);
contentValues.put(Col_3,n4);
contentValues.put(Col_4,n5);
db.update(Tbname,contentValues,"ID = ?", new String[]{id});
return true;
}
public Cursor getAllDataForNamaz()
{
openDatabase();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cs = db.rawQuery("SELECT * FROM "+ Tbname2 + " WHERE date_for = "+ date(),null);
closeDatabase();
return cs;
}
public Date date()
{
long millis=System.currentTimeMillis();
java.sql.Date date=new java.sql.Date(millis);
return date;
}
public Cursor getAllData()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor cs = db.rawQuery("SELECT * FROM "+ Tbname,null);
return cs;
}
public Cursor getAllData1()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor cs = db.rawQuery("SELECT ID FROM "+ Tbname,null);
return cs;
}
}
I advise you to convert all your date into timestamp and use only timestamp for comparaison (you can also save date as timestamp in your database) :
System.currentTimeMillis() // Current timestamp
date.time // timestamp of the SQL Date object
if (timestamp1 > timestamp2) {
// timestamp1 after timestamp2
} else if (timestamp1 < timestamp2) {
// timestamp1 before timestamp2
} else {
// timestamp1 == timestamp2
}
Try this code first convert data into this format..."dd/mm/yyyy"
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);
if (new Date().after(strDate)) {
// define log
}
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
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);