I have created a simple android application which asks for the users details such as name, number, blood type and saves it in a database. This happens in edit texts on the editscreen the application is then suppose to display all the data in the Main Activity screen in a TextView. I have made the code so that it displays the text in the textview however when I switch the application off and back on again the text simply disappears and is no longer there, I am also trying to make the text stay in the edit text like
Name: Jim
But when I change screens, so for example If I go from MainActivity to EditScreen the text is no longer visible in the Edit Screen.
Edit Screen which has the edit texts
package com.example.androidsimpledbapp1;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class EditScreen extends Activity {
/*
* Code Issues:
* Data is not being persisted on screen
* Also the edit text data is not being persisted
* Database is not overwriting row in the DB e.g. GaryJamesJimmy instead of Overwriting
* Database needs to retrieve all other rows and display them in the TextView
* Will need to implement overwriting functionality on the DB for each row
* Is Data even persisting?
*/
EditText firstNameInput;
EditText bloodTypeInput;
EditText contacNameInput;
EditText phoneNumberInput;
EditText relationshipInput;
MyDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_screen);
//Setting EditTexts
firstNameInput = (EditText) findViewById(R.id.inputname);
bloodTypeInput = (EditText) findViewById(R.id.inputblood);
contacNameInput = (EditText) findViewById(R.id.inputcontact);
phoneNumberInput = (EditText) findViewById(R.id.inputnum);
relationshipInput = (EditText) findViewById(R.id.inputraltion);
//Setting DbHandler object
dbHandler = new MyDBHandler(this, null, null, 1);
}
public void saveMe(View v){
/*
* Making a new object
* Object takes 5 parameters
*/
Details detail = new Details(firstNameInput.getText().toString(),
bloodTypeInput.getText().toString(),
contacNameInput.getText().toString(),
phoneNumberInput.getText().toString(),
relationshipInput.getText().toString());
dbHandler.addProduct(detail);
//Sending Text To Main Activity
String dbString = dbHandler.databaseToString();
Intent myIntent = new Intent(v.getContext(),MainActivity.class);
myIntent.putExtra("mytext",dbString);
startActivity(myIntent);
//End of Sending to Main Activity
//Settint the text in Edit Text
firstNameInput.setText(dbString);
}
public void clearBtnPressed(View v){
dbHandler.deleteProducts();
}
}
Main Activity - This is the screen with the textview where the text is suppose to be displayed
package com.example.androidsimpledbapp1;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView mTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Grabs the TextView
mTextView = (TextView)findViewById(R.id.dbname);
mTextView.setText(getIntent().getStringExtra("mytext"));
}
//Changing Activity
public void editBtnPressed(View v){
Intent intent = new Intent(MainActivity.this, EditScreen.class);
startActivity(intent);
}
}
Database Class
package com.example.androidsimpledbapp1;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import android.content.Context;
import android.content.ContentValues;
public class MyDBHandler extends SQLiteOpenHelper {
/*
* Class for Working with DB
*/
//Update each time DB structure changes e.g. adding new property
private static final int DATABASE_VERSION =1;
//DB Name
private static final String DATABASE_NAME = "details.db";
//Table name
public static final String TABLE_PRODUCTS = "products";
//DB Columns
public static final String COLUMN_ID = "_Id";
public static final String COLUMN_PERSONNAME = "firstName";
public static final String COLUMN_PERSONBLOOD = "bloodType";
public static final String COLUMN_PERSONCONTACT = "contactName";
public static final String COLUMN_PERSONNUMBER = "phoneNumber";
public static final String COLUMN_PERSONRELATION = "relationship";
//Constructor
/*
* Passing information to super class in SQL
* Context is background information
* name of db
* Database version
*/
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version){
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
/*
* What to do first time when you create DB
* Creates the table the very first time
* (non-Javadoc)
* #see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
* Remember to use Commas as shown below
*/
#Override
public void onCreate(SQLiteDatabase db){
String query = "CREATE TABLE "+ TABLE_PRODUCTS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+
COLUMN_PERSONNAME + " TEXT, "+
COLUMN_PERSONBLOOD + " TEXT, "+
COLUMN_PERSONCONTACT + " TEXT, "+
COLUMN_PERSONNUMBER + " TEXT, " +
COLUMN_PERSONRELATION + " TEXT " +
");";
//Execute the query
db.execSQL(query);
}
/*
* If ever upgrading DB call this method
* (non-Javadoc)
* #see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int)
*/
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
//Delete the current table
db.execSQL("DROP TABLE IF EXISTS" + TABLE_PRODUCTS);
//create new table
onCreate(db);
}
//Add new row to the database
public void addProduct(Details details){
//Built in class - set values for different columns
//Makes inserting rows quick and easy
ContentValues values = new ContentValues();
values.put(COLUMN_PERSONNAME, details.get_firstName());
values.put(COLUMN_PERSONBLOOD, details.get_bloodType());
values.put(COLUMN_PERSONCONTACT, details.get_contactName());
values.put(COLUMN_PERSONNUMBER, details.get_phoneNumber());
values.put(COLUMN_PERSONRELATION, details.get_relationship());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_PRODUCTS, null, values);
db.close();
}
/*Updating Rows in the Database
public void updateProducts(Details details){
ContentValues cv = new ContentValues();
SQLiteDatabase db = getWritableDatabase();
db.update(TABLE_PRODUCTS, cv, COLUMN_ID + "=" + 1, null);
}
*/
/*Table was deleted*/
public void deleteProducts(){
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_PRODUCTS, null, null);
}
//Take DB and Convert to String
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
//Every Column and row
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
//Cursor points to a location in your results
//First row point here, second row point here
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast()){
//Extracts first name and adds to string
if(c.getString(c.getColumnIndex("firstName"))!=null){
dbString += c.getString(c.getColumnIndex("firstName"));
c.moveToNext();
/*
* Displaying all other columns
*/
}
}
db.close();
return dbString;
}
}
Details Class
package com.example.androidsimpledbapp1;
public class Details {
//primary key
private int _id;
//Properties
private String _firstName;
private String _bloodType;
private String _contactName;
private String _phoneNumber;
private String _relationship;
//Dont Have to Enter Everything each time
public Details(){
}
public Details(String firstName){
this.set_firstName(firstName);
}
//Passing in details
//Setting values from the user
public Details(String firstName, String bloodType,
String contactName, String phoneNumber,
String relationship){
this.set_firstName(firstName);
this.set_bloodType(bloodType);
this.set_contactName(contactName);
this.set_phoneNumber(phoneNumber);
this.set_relationship(relationship);
}
//Retrieve the data
public int get_id() {
return _id;
}
//Setter allows to give property
public void set_id(int _id) {
this._id = _id;
}
public String get_firstName() {
return _firstName;
}
public void set_firstName(String _firstName) {
this._firstName = _firstName;
}
public String get_bloodType() {
return _bloodType;
}
public void set_bloodType(String _bloodType) {
this._bloodType = _bloodType;
}
public String get_contactName() {
return _contactName;
}
public void set_contactName(String _contactName) {
this._contactName = _contactName;
}
public String get_phoneNumber() {
return _phoneNumber;
}
public void set_phoneNumber(String _phoneNumber) {
this._phoneNumber = _phoneNumber;
}
public String get_relationship() {
return _relationship;
}
public void set_relationship(String _relationship) {
this._relationship = _relationship;
}
}
When you switch your app, it's on pause state which may be the cause of your problem.
I suggest you search for "saving activity when onPause state"
Related
I want all edit text content that I have saved in SQL to be displayed on the edit bills activity when I click on the list item, but I am only able to retrieve the name and display it again in the intent. Rather than saving another data it should update the record with the new data if I save the existing record another time in the editbills_activity.
Here is my DBAdapter.java
package com.example.dhruv.bills;
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 DBAdapter {
public static final String KEY_ROWID = "id";
public static final String KEY_NAME = "name";
public static final String KEY_AMOUNT = "amount";
public static final String KEY_DUEDATE = "duedate";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "billsdb";
private static final String DATABASE_TABLE = "bills";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE =
"create table if not exists assignments (id integer primary key autoincrement, "
+ "name VARCHAR not null, amount VARCHAR, duedate date );";
// Replaces DATABASE_CREATE using the one source definition
private static final String TABLE_CREATE =
"CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE + "(" +
KEY_ROWID + " INTEGER PRIMARY KEY, " + // AUTOINCREMENT NOT REQD
KEY_NAME + " DATE NOT NULL, " +
KEY_AMOUNT + " VARCHAR ," +
KEY_DUEDATE + " DATE " +
")";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(TABLE_CREATE); // NO need to encapsulate in try clause
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts"); //????????
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a record into the database---
public long insertRecord(String name, String amount, String duedate)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_AMOUNT, amount);
initialValues.put(KEY_DUEDATE, duedate);
//return db.insert(DATABASE_TABLE, null, initialValues);
// Will return NULL POINTER EXCEPTION as db isn't set
// Replaces commented out line
return DBHelper.getWritableDatabase().insert(DATABASE_TABLE,
null,
initialValues
);
}
//---deletes a particular record---
public boolean deleteContact(long rowId)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
//---retrieves all the records--- SEE FOLLOWING METHOD
public Cursor getAllRecords()
{SQLiteDatabase db = DBHelper.getWritableDatabase();
String query ="SELECT * FROM " + DATABASE_TABLE;
Cursor data = db.rawQuery(query,null);
return data;
}
//As per getAllRecords but using query convenience method
public Cursor getAllAsCursor() {
return DBHelper.getWritableDatabase().query(
DATABASE_TABLE,
null,null,null,null,null,null
);
}
public Cursor getItemID(String name) {
SQLiteDatabase db = DBHelper.getWritableDatabase();
String query = "SELECT " + KEY_ROWID + " FROM " + DATABASE_TABLE +
" WHERE " + KEY_NAME + " = '" + name + "'";
Cursor data = db.rawQuery(query, null);
return data;
}
//---retrieves a particular record--- THIS WILL NOT WORK - NO SUCH TABLE
/* public Cursor getRecord()
{String query1 ="SELECT * FROM" + KEY_TITLE;
Cursor mCursor = db.rawQuery(query1,null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}*/
// Retrieve a row (single) according to id
public Cursor getRecordById(long id) {
return DBHelper.getWritableDatabase().query(
DATABASE_TABLE,
null,
KEY_ROWID + "=?",
new String[]{String.valueOf(id)},
null,null,null
);
}
//---updates a record---
/* public boolean updateRecord(long rowId, String name, String amount, String duedate)
{
ContentValues args = new ContentValues();
args.put(KEY_NAME, name);
args.put(KEY_AMOUNT, amount);
args.put(KEY_DUEDATE, duedate);
String whereclause = KEY_ROWID + "=?";
String[] whereargs = new String[]{String.valueOf(rowId)};
// Will return NULL POINTER EXCEPTION as db isn't set
//return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
// Replaces commented out line
return DBHelper.getWritableDatabase().update(DATABASE_TABLE,
args,
whereclause,
whereargs
) > 0;
}*/
}
Here is my Bills.java
(MainActivity)
Problem: Bills.java has the list view that shows the intent whenever the item in list view is clicked, but it does not put the amount and date or update the record. Instead it saves another record.
Solution: I want to retrieve it and display all (name ,amount,duedate) and instead of saving another record it should update it.
package com.example.dhruv.bills;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class bills extends AppCompatActivity {
DBAdapter dbAdapter;
ListView mrecycleview;
private static final String TAG ="assignments";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bills);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mrecycleview =(ListView) findViewById(R.id.mRecycleView);
dbAdapter = new DBAdapter(this);
// mlistview();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),Editbills.class);
startActivity(i);
}
});
mlistview();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_bills, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void mlistview(){
Log.d(TAG,"mlistview:Display data in listview");
Cursor mCursor = dbAdapter.getAllRecords();
ArrayList<String> listData = new ArrayList<>();
while (mCursor.moveToNext()){
listData.add(mCursor.getString(1));
}
ListAdapter adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,listData);
mrecycleview.setAdapter(adapter);
mrecycleview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name = adapterView.getItemAtPosition(i).toString();
Log.d(TAG, "onItemClick: You Clicked on " + name);
Cursor data = dbAdapter.getItemID(name); //get the id associated with that name
int itemID = -1;
while(data.moveToNext()){
itemID = data.getInt(0);
}
if(itemID > -1){
Log.d(TAG, "onItemClick: The ID is: " + itemID);
Intent editScreenIntent = new Intent(bills.this, Editbills.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
startActivity(editScreenIntent);
}
else{
}
}
});
}
}
here is my editbills.java code
package com.example.dhruv.bills;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class Editbills extends AppCompatActivity {
Button button;
private static final String Tag= "assignments";
DBAdapter db = new DBAdapter(this);
private String selectedName;
private int selectedID;
DBAdapter dbAdapter;
private EditText editText,editText2,editText3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editbills);
button=(Button)findViewById(R.id.button);
editText =(EditText)findViewById(R.id.editText);
editText2=(EditText)findViewById(R.id.editText2);
editText3 =(EditText)findViewById(R.id.editText3);
//get the intent extra from the ListDataActivity
Intent receivedIntent = getIntent();
//now get the itemID we passed as an extra
selectedID = receivedIntent.getIntExtra("id",-1); //NOTE: -1 is just the default value
//now get the name we passed as an extra
selectedName = receivedIntent.getStringExtra("name");
//set the text to show the current selected name
editText.setText(selectedName);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("test", "adding");
db.open();
long id = db.insertRecord(editText.getText().toString(), editText2.getText().toString(), editText3.getText().toString());
db.close();
Toast.makeText(Editbills.this," Added", Toast.LENGTH_LONG).show();
Intent q = new Intent(getApplicationContext(),bills.class);
startActivity(q);
}
});
}
}
There are two parts/questions.
First to retrieve the data, so that it can be displayed in the editbills activity, you can utilise the row's id that is passed to the activity in conjunction with the getRecordById method.
I'd suggest that adding a method to the editbills class will simplyfy matters.
private void populateDisplay(int id) {
Cursor csr = dbAdapter.getRecordById(id);
if (csr.moveToFirst()) {
editText.setText(csr.getString(csr.getColumnIndex(DBAdapter.KEY_NAME)));
editText2.setText(csr.getString(csr.getColumnIndex(DBAdapter.KEY_AMOUNT)));
editText3.setText(csr.getString(csr.getColumnIndex(DBAdapter.KEY_DUEDATE)));
}
csr.close();
}
You could invoke the above method after retrieving the id from the Intent using :-
populateDisplay(selectedID);
To update based upon the content's of the EditTexts un-comment the updateRecord method in DBAdapter.java and the change :-
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("test", "adding");
db.open();
long id = db.insertRecord(editText.getText().toString(), editText2.getText().toString(), editText3.getText().toString());
db.close();
Toast.makeText(Editbills.this," Added", Toast.LENGTH_LONG).show();
Intent q = new Intent(getApplicationContext(),bills.class);
startActivity(q);
}
});
to :-
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (dbAdapter.updateRecord(
selectedId,
editText.getText().toString(),
editText2.getText().toString(),
editText3.getText().toString())
) {
Log.d("TEST","Row successfully updated.");
Toast.makeText(getApplicationContext(),"Row Updated.",Toast.LENGTH_LONG).show();
populateDisplay(selectedId);
} else {
Toast.makeText(getApplicationContext(),"Row not Updated",Toast.LENGTH_LONG).show();
}
Intent q = new Intent(getApplicationContext(),bills.class);
startActivity(q);
}
});
You will additionally have to add a line initialise the dbAdapter i.e. dbAdapter = new DBAdapter(this); i.d suggest adding this line immediately after the line setContentView(R.layout.activity_editbills);
Note the above code is in-principle and has not been thoroughly tested so it may contains errors.
Edit complete working example :-
The following code is basically an implementation of the above, except modified to utilise a Bill class. Rather than an ArrayList<String> as the source for the Adapter it has ArrayList<Bill>.
Thus all the data (id, name, amount and duedate) is available.
You should notice that I've overridden the toString method to return a String that combines the name, amount and duedate. The ArrayAdapter uses the object's toString method to populate the view.
Saying that the critical value is the rowid or an alias of rowid as this can be used to identify a row even if the other data is identical (as would happen when running this example more than once due to the addSomeData method). Hence, only the id is extracted and passed to the Editbills activity when an item in the list is long clicked (changed from just clicked to reduce the potential for accidental use).
Bill.java
public class Bill {
private long id;
private String name;
private String amount;
private String duedate;
public Bill(long id, String name, String amount, String duedate) {
this.id = id;
this.name = name;
this.amount = amount;
this.duedate = duedate;
}
/*
Note if this Constructor used then setId should be used
*/
public Bill(String name, String amount, String duedate) {
new Bill(0,name,amount,duedate);
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getDuedate() {
return duedate;
}
public void setDuedate(String duedate) {
this.duedate = duedate;
}
/*
As ArrayAdapter uses toString method change this
to return all items
*/
#Override
public String toString() {
return name + " " + amount + " " + duedate;
}
}
MainActivity.java
This is the equivalent to your Bills.java without a lot of the bloat such as FAB. :-
public class MainActivity extends AppCompatActivity {
public static final String ID_INTENTEXTRA = DBAdapter.KEY_ROWID + "_INTENTEXTRA"; //<<<< ADDED
DBAdapter mDBAdapter;
Cursor mCsr;
ListView mrecycleview;
ArrayAdapter adapter; //<<<< NOT ListAdapter
Context context; // ADDED
private static final String TAG ="assignments";
ArrayList<Bill> mBillList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
mrecycleview = this.findViewById(R.id.mRecycleView);
mDBAdapter = new DBAdapter(this);
addSomeData();
adapter = new ArrayAdapter<Bill>(
this,
android.R.layout.simple_list_item_1,
mBillList
);
mrecycleview.setAdapter(adapter);
mrecycleview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Bill b = (Bill) adapter.getItem(position);
Intent i = new Intent(context,Editbills.class);
i.putExtra(ID_INTENTEXTRA,b.getId()); //Get ID
startActivity(i);
return true;
}
});
rebuildBillList();
}
//<<<< ADDED Method to refresh the ListView resumed
#Override
protected void onResume() {
super.onResume();
rebuildBillList();
}
// Add some data (note will add 2 rows each time it is run)
private void addSomeData() {
mDBAdapter.insertRecord("Bill1","2018-10-02","English");
mDBAdapter.insertRecord("Bill2","2018-09-03","Mathematics");
mDBAdapter.insertRecord("Bill3","2018-11-04", "Geography");
}
public void rebuildBillList() {
mBillList.clear();
mCsr = mDBAdapter.getAllAsCursor();
while (mCsr.moveToNext()) {
mBillList.add(new Bill(
mCsr.getLong(mCsr.getColumnIndex(DBAdapter.KEY_ROWID)),
mCsr.getString(mCsr.getColumnIndex(DBAdapter.KEY_NAME)),
mCsr.getString(mCsr.getColumnIndex(DBAdapter.KEY_AMOUNT)),
mCsr.getString(mCsr.getColumnIndex(DBAdapter.KEY_DUEDATE))
)
);
}
adapter.notifyDataSetChanged();
}
}
Note the above adds 3 rows each time it is run.
Editbills.java
public class Editbills extends AppCompatActivity {
Button button;
private static final String Tag = "assignments";
DBAdapter db = new DBAdapter(this);
private String selectedName;
private long selectedID;
DBAdapter dbAdapter;
private EditText editText,editText2,editText3;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editbills);
context = this;
dbAdapter = new DBAdapter(this); //<<<< ADDED
button=(Button)findViewById(R.id.button);
editText =(EditText)findViewById(R.id.edittext);
editText2=(EditText)findViewById(R.id.edittext2);
editText3 =(EditText)findViewById(R.id.edittext3);
//get the intent extra from the ListDataActivity
Intent receivedIntent = getIntent();
//now get the itemID we passed as an extra
selectedID = receivedIntent.getLongExtra(MainActivity.ID_INTENTEXTRA,-1L); //NOTE: -1 is just the default value
populateDisplay(selectedID);
//now get the name we passed as an extra
//selectedName = receivedIntent.getStringExtra("name");
//set the text to show the current selected name
//editText.setText(selectedName); <<<< commented out
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*
Log.d("test", "adding");
db.open();
long id = db.insertRecord(editText.getText().toString(), editText2.getText().toString(), editText3.getText().toString());
db.close();
Toast.makeText(Editbills.this," Added", Toast.LENGTH_LONG).show();
*/
/*
* <<<< Not the way as it ends/closes the existing activity
Intent q = new Intent(getApplicationContext(),MainActivity.class);
startActivity(q);
*/
String toast = "Updated.";
if (dbAdapter.updateRecord(selectedID,
editText.getText().toString(),
editText2.getText().toString(),
editText3.getText().toString())) {
} else {
toast = "Not Updated.";
}
Toast.makeText(context,toast,Toast.LENGTH_LONG).show();
finish(); //<<<< ends/closes this activity and returns to calling activity
}
});
}
private void populateDisplay(long id) {
Cursor csr = dbAdapter.getRecordById(id);
if (csr.moveToFirst()) {
editText.setText(csr.getString(csr.getColumnIndex(DBAdapter.KEY_NAME)));
editText2.setText(csr.getString(csr.getColumnIndex(DBAdapter.KEY_AMOUNT)));
editText3.setText(csr.getString(csr.getColumnIndex(DBAdapter.KEY_DUEDATE)));
}
csr.close();
}
}
Basically as per the original answer.
DBAdapter.java
public class DBAdapter {
public static final String KEY_ROWID = "id";
public static final String KEY_NAME = "name";
public static final String KEY_AMOUNT = "amount";
public static final String KEY_DUEDATE = "duedate";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "billsdb";
private static final String DATABASE_TABLE = "bills";
private static final int DATABASE_VERSION = 2;
// Replaces DATABASE_CREATE using the one source definition
private static final String TABLE_CREATE =
"CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE + "(" +
KEY_ROWID + " INTEGER PRIMARY KEY, " + // AUTOINCREMENT NOT REQD
KEY_NAME + " DATE NOT NULL, " +
KEY_AMOUNT + " VARCHAR ," +
KEY_DUEDATE + " DATE " +
")";
private Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(TABLE_CREATE); // NO need to encapsulate in try clause
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts"); //????????
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
//---opens the database--- NOT NEEDED
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database--- NOT NEEDED
public void close()
{
DBHelper.close();
}
//---insert a record into the database---
public long insertRecord(String name, String amount, String duedate)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_AMOUNT, amount);
initialValues.put(KEY_DUEDATE, duedate);
return DBHelper.getWritableDatabase().insert(DATABASE_TABLE,
null,
initialValues
);
}
//---deletes a particular record---
public boolean deleteContact(long rowId)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
//---retrieves all the records--- SEE FOLLOWING METHOD
public Cursor getAllRecords()
{SQLiteDatabase db = DBHelper.getWritableDatabase();
String query ="SELECT * FROM " + DATABASE_TABLE;
Cursor data = db.rawQuery(query,null);
return data;
}
//As per getAllRecords but using query convenience method
public Cursor getAllAsCursor() {
return DBHelper.getWritableDatabase().query(
DATABASE_TABLE,
null,null,null,null,null,null
);
}
public Cursor getItemID(String name) {
SQLiteDatabase db = DBHelper.getWritableDatabase();
String query = "SELECT " + KEY_ROWID + " FROM " + DATABASE_TABLE +
" WHERE " + KEY_NAME + " = '" + name + "'";
Cursor data = db.rawQuery(query, null);
return data;
}
// Retrieve a row (single) according to id
public Cursor getRecordById(long id) {
return DBHelper.getWritableDatabase().query(
DATABASE_TABLE,
null,
KEY_ROWID + "=?",
new String[]{String.valueOf(id)},
null,null,null
);
}
//---updates a record---
public boolean updateRecord(long rowId, String name, String amount, String duedate) {
ContentValues args = new ContentValues();
args.put(KEY_NAME, name);
args.put(KEY_AMOUNT, amount);
args.put(KEY_DUEDATE, duedate);
String whereclause = KEY_ROWID + "=?";
String[] whereargs = new String[]{String.valueOf(rowId)};
return DBHelper.getWritableDatabase().update(DATABASE_TABLE,
args,
whereclause,
whereargs
) > 0;
}
}
Basically as was except that upDateRecord has been un-commented, again as per the original answer.
Results
1st Run - MainActivity (Bills) :-
Long Click Bill2 (note changed from Click as Long Click is less prone to accidental use)
Change data (Update button not clicked)
Update Button Clicked (Toast was Updated.)
Note use of finish() to return to the invoking activity and then the use of onResume to refresh the list according to the updated data (possibly your next question).
using startActivity will simply result in issues.
Note Values are date and course rather then amount and duedate because I didn't change the values in the addSomeData method (easily done).
the actual data itself is irrelevant to the process.
I am creating an android application that will be using a SQLite database. I have created a separate class called DBAdapter that holds all the methods relating to the database.
My issue comes when I try to access these methods from the main activity. I am still learning but I would normally instantiate the DBAdapter class and then I would be able to reference the methods. However the approach I am taking isnt working. Below is the single line of how I am trying to instantiate the class and under that is the rest of the class.
The error I am getting is cannot resolve method 'open()'
Instantiate Line and method
DBAdapter db = new DBAdapter(this);
db.open();
Main Class
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.ContentFrameLayout;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
final Context context = this;
private FloatingActionButton fab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DBAdapter db = new DBAdapter(this);
db.open();
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog_box);
dialog.setTitle("Add new Location!");
dialog.show();
final EditText NameEdit = (EditText) findViewById(R.id.NameInput);
final EditText LatEdit = (EditText) findViewById(R.id.LatInput);
final EditText LongEdit = (EditText) findViewById(R.id.LongInput);
final EditText PhoneEdit = (EditText) findViewById(R.id.PhoneInput);
final Button OkButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
final Button CancelButton = (Button) dialog.findViewById(R.id.dialogButtonCancel);
OkButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String RealName = NameEdit.getText().toString();
String Lat = LatEdit.getText().toString();
Float realLat = Float.parseFloat(Lat);
String Long = LongEdit.getText().toString();
Float realLong = Float.parseFloat(Long);
String Phone = PhoneEdit.getText().toString();
Double realPhone = Double.parseDouble(Phone);
//Use above to create a new Geofence
}
});
CancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
}
});
}
}
DBAdpater Class
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;
/**
* Created by Rory on 09/09/2016.
*/
public class DBAdapter {
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
//Database Version & name
private static final String DATABASE_NAME = "OpenSesame";
private static final int DATABASE_VERSION = 1;
private static final String TAG = "DBMain";
private static final String GEOTABLE = "geoTable";
private static final String KEY_ID = "_id";
private static final String KEY_NAME = "name";
private static final String KEY_LAT = "lat";
private static final String KEY_LONG = "long";
private static final String KEY_RADIUS = "radius";
private static final String KEY_PHONE = "phone";
private static final String CREATE_GEO_TABLE = "CREATE TABLE "
+ GEOTABLE + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTO INCREMENT,"
+ KEY_NAME + " TEXT,"
+ KEY_LAT + " FLOAT,"
+ KEY_LONG + " FLOAT,"
+ KEY_RADIUS + " INTEGER,"
+ KEY_PHONE + " INTEGER" + ")";
public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* Method to create each of the tables defined above
* #param db
*/
#Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(CREATE_GEO_TABLE);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Method for updating the database
* #param db
* #param newVersion
* #param oldVersion
*/
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public DatabaseHelper open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
public void close() {
DBHelper.close();
}
public Cursor DeleteGeo(String name) {
return db.rawQuery("delete from geoTable where name = " + name, null);
}
public long AddGeo(String name, float lat, float lon, double phone, int radius) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_LAT, lat);
initialValues.put(KEY_LONG, lon);
initialValues.put(KEY_PHONE, phone);
initialValues.put(KEY_RADIUS, radius);
return db.insert(GEOTABLE, null, initialValues);
}
public Cursor GetAllGeos() {
return db.rawQuery("select * from geoTable order by name ASC", null);
}
}
}
Your DBAdapter class does not have the open() method. It is the private inner class DatabaseHelper that has that method. You have two options to expose open() to be able to call it the way you are expecting.
Option 1: add an open() method to DBAdapter that calls DatabaseHelper's open() method
public void open() {
DBHelper.open();
}
Option 2: remove DatabaseHelper entirely, and have DBAdapter extends SQLiteOpenHelper instead
public class DBAdapter extends SQLiteOpenHelper {
...
public DBAdapter(Context ctx) {
this.context = ctx;
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// add all the code from inside DatabaseHelper below
/**
* Method to create each of the tables defined above
* #param db
*/
#Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(CREATE_GEO_TABLE);
} catch (SQLException e) {
e.printStackTrace();
}
}
// you will have to change this method to work
public DBAdapter open() throws SQLException
{
db = getWritableDatabase();
return this;
}
...
}
At first the app would just crash when I started it with an emulator, Not sure what I changed to get it to run but now it will run the onCreate method however, when I implement the addButtonClicked method the app just stalls and the Android Monitor displays "Suspending all threads" every few seconds and I'm not sure where to even begin debugging. Any pointers in the right direction would be greatly appreciated as I'm fairly new to Android development.
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText testInput;
TextView testText;
MyDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testInput = (EditText) findViewById(R.id.testInput);
testText = (TextView) findViewById(R.id.testText);
dbHandler = new MyDBHandler(this, null, null, 1);
printDatabase();
}
//Add product to database
public void addButtonClicked(View view){
Products product = new Products((testInput.getText().toString()));
dbHandler.addProduct(product);
printDatabase();
}
// Delete Items
public void deleteButtonClicked(View view){
String inputText = testText.getText().toString();
dbHandler.deleteProduct(inputText);
printDatabase();
}
public void printDatabase(){
String dbString = dbHandler.databaseToString();
testText.setText(dbString);
testInput.setText("");
}
}
Products.java
public class Products {
private int _id;
private String _productname;
public Products(){
}
public Products(String productname) {
this._productname = productname;
}
public void set_id(int _id) {
this._id = _id;
}
public void set_productname(String _productname) {
this._productname = _productname;
}
public int get_id() {
return _id;
}
public String get_productname() {
return _productname;
}
}
MyDBHandler.java
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import android.content.Context;
import android.content.ContentValues;
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 15;
private static final String DATABASE_NAME = "products.db";
public static final String TABLE_PRODUCTS = "products";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_PRODUCTNAME = "productname";
public MyDBHandler(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_PRODUCTS +"(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," +
COLUMN_PRODUCTNAME +" TEXT " +
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
onCreate(db);
}
//Add new row to the database
public void addProduct(Products product){
ContentValues values = new ContentValues();
values.put(COLUMN_PRODUCTNAME, product.get_productname());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_PRODUCTS, null, values);
db.close();
}
//Delete product from database
public void deleteProduct(String productName){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_PRODUCTS + " WHERE " + COLUMN_PRODUCTNAME + "=\"" + productName + "\";" );
}
//Print of DB as sting
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
//Cursor point to a location in your results
Cursor c = db.rawQuery(query, null);
//Move to the first row in your results
c.moveToFirst();
while (!c.isAfterLast()){
if(c.getString(c.getColumnIndex("productname"))!= null){
dbString += c.getString(c.getColumnIndex("productname"));
dbString += "\n";
}
}
db.close();
return dbString;
}
}
for your databaseToString method you are performing a retrieve operation. You should be doing a read operation in a thread other than UI thread. Try fetching in AsyncTask. It should work. Implementation for your databaseToString should be handled by AsyncTask.
Happy Coding..
I feel like this is a really simple fix but I am new the android and sqlite in general. I have a array that takes data from a database and then shows them in a list. However every time I restart the app the list adds the items once again into the list. How can I make it not do this?
package com.example.assignmenttracker;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.example.assignmenttracker.MySQLiteHelper;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.app.Activity;
public class MainActivity extends Activity {
private ListView ListView;
private Button addbutton;
public final static String ID_EXTRA="com.example.assignmenttracker._ID";
public static ArrayList<String> ArrayofName = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.addbutton = (Button)this.findViewById(R.id.button1);
this.addbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this, AddAssign.class);
startActivity(intent);
}
});
}
private void populateListView() {
MySQLiteHelper db = new MySQLiteHelper(this);
List<tasklist> contacts = db.getSometasklist();
for (tasklist cn : contacts) {
Log.d("Reading: ", "Reading all contacts..");
String log = "Id: "+cn.getID()+" ,Task: " + cn.getTask() + " ,Date: " + cn.getDate() + " ,Status: " + cn.getStatus();
Log.d("Name: ", log);
}
ListView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, ArrayofName);
ListView.setAdapter(adapter);
ListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Intent i = new Intent(MainActivity.this, ViewAssign.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);}
});
}
#Override
public void onResume() {
super.onResume();
populateListView();
}
}
here is the code of mysqlitehelper
package com.example.assignmenttracker;
import java.util.ArrayList;
import java.util.List;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import android.content.ContentValues;
import android.content.Context;
public class MySQLiteHelper extends SQLiteOpenHelper {
// Contacts Table Columns names
private static final String TABLE_CONTACTS = "tasklist1";
private static final String KEY_ID = "id";
private static final String KEY_TASK = "task";
private static final String KEY_DESC = "desc";
private static final String KEY_MOD = "module";
private static final String KEY_DATE = "date";
private static final String KEY_TYPE = "type";
private static final String KEY_STATUS = "status";
private static final int DATABASE_VERSION = 3;
private static final String DATABASE_NAME = "tasklist1";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
String CREATE_TASKLIST_TABLE = "CREATE TABLE tasklist1 ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"task TEXT, "+
"desc TEXT, "+
"module TEXT, "+
"date TEXT, "+
"type TEXT, "+
"status INTEGER )";
db.execSQL(CREATE_TASKLIST_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older task list table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// create fresh task list table
this.onCreate(db);
}
public void insertTask(tasklist tasklist){
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TASK, tasklist.getTask());
values.put(KEY_DESC, tasklist.getDesc());
values.put(KEY_MOD, tasklist.getModule());
values.put(KEY_DATE, tasklist.getDate());
values.put(KEY_TYPE, tasklist.getType());
values.put(KEY_STATUS, tasklist.getStatus());
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
public List<tasklist> getAlltasklist(int passedid) {
List<tasklist> tasklistList = new ArrayList<tasklist>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS +
" where id = " + passedid;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
tasklist contact = new tasklist();
contact.setTask(cursor.getString(1));
contact.setDesc(cursor.getString(2));
contact.setModule(cursor.getString(3));
contact.setDate(cursor.getString(4));
contact.setType(cursor.getString(5));
contact.setStatus(cursor.getInt(6));
String name = cursor.getString(1);
String desc =cursor.getString(2);
String module =cursor.getString(3);
String date = cursor.getString(4);
String type = cursor.getString(5);
int status = cursor.getInt(6);
ViewAssign.task= name;
ViewAssign.desc=desc;
ViewAssign.module=module;
ViewAssign.date=date;
ViewAssign.type=type;
ViewAssign.status=status;
// Adding contact to list
tasklistList.add(contact);
db.close();
} while (cursor.moveToNext());
}
return tasklistList;
}
public List<tasklist> getSometasklist() {
List<tasklist> tasklistList = new ArrayList<tasklist>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
tasklist contact = new tasklist();
contact.setTask(cursor.getString(1));
contact.setDate(cursor.getString(4));
String name = cursor.getString(1) +"\n"+ cursor.getString(4);
MainActivity.ArrayofName.add(name);
// Adding contact to list
tasklistList.add(contact);
db.close();
} while (cursor.moveToNext());
}
return tasklistList;
}
public void deleteTask(long row) {
// Deletes a row given its rowId, but I want to be able to pass
// in the name of the KEY_NAME and have it delete that row.
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + "=" + row, null);
db.close();
}
}
I suspect the culprint is this:
public static ArrayList<String> ArrayofName = new ArrayList<String>();
It is a static variable, meaning that in some circumstances, it will STILL have the objects you added on app first run when you run it second time.
Possible solutions:
remove "static" keyword, or
clear ArrayOfName before populating it, eg. ArrayOfName.clear()
I know I am late but maybe it will help someone else.
You need to split ArrayList into two parts
Place the following code in MainActivity
public static ArrayList<String> ArrayofName;
And place the following in onCreate() OR onResume() method
ArrayofName = new ArrayList<String>();
I've developed an app for Android which stores car filling information in an SQLite database. Everything seems to work fine on my 4.0.3 phone and my 4.0.3 AVD, but I would like it to also work in Jelly Bean and newer versions. The app really doesn't do anything very complicated. When I fire the app up in the emulated Jelly Bean device I get a FATAL EXCEPTION error:
09-05 01:45:40.311: W/dalvikvm(1062): threadid=1: thread exiting with uncaught exception >(group=0x414c4700)
09-05 01:45:40.331: E/AndroidRuntime(1062): FATAL EXCEPTION: main
09-05 01:45:40.331: E/AndroidRuntime(1062): java.lang.RuntimeException: Unable to start >activity ComponentInfo{ard.util.fueltracker/ard.util.fueltracker.TitleScreenActivity}: >java.lang.IllegalStateException: attempt to re-open an already-closed object: >SQLiteDatabase: /data/data/ard.util.fueltracker/databases/vehicleDatabase
09-05 01:45:40.331: E/AndroidRuntime(1062): at >android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
In my initial searches in Google I thought I had Instance issues somehow, so I followed Approach #1 here (http://www.androiddesignpatterns.com/2012/05/correctly-managing-your-sqlite-database.html), but this doesn't seem to make a difference. Still works in ICS with the changes too.
Here's the code from my TitleScreenActivity:
package ard.util.fueltracker;
import java.util.List;
import ard.util.fueltracker.util.SystemUiHider;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.content.Intent;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*
* #see SystemUiHider
*/
#SuppressLint("NewApi")
public class TitleScreenActivity extends Activity implements OnItemSelectedListener {
/**
* Whether or not the system UI should be auto-hidden after
* {#link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
*/
private static final boolean AUTO_HIDE = false;
/**
* If {#link #AUTO_HIDE} is set, the number of milliseconds to wait after
* user interaction before hiding the system UI.
*/
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
/**
* If set, will toggle the system UI visibility upon interaction. Otherwise,
* will show the system UI visibility upon interaction.
*/
private static final boolean TOGGLE_ON_CLICK = false;
/**
* The flags to pass to {#link SystemUiHider#getInstance}.
*/
//private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;
private static final int HIDER_FLAGS = 0;
/**
* The instance of the {#link SystemUiHider} for this activity.
*/
private SystemUiHider mSystemUiHider;
// Spinner element
Spinner spinner;
// Buttons
Button btnAdd;
Button btnLogo;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR); //new
getActionBar().hide(); //new
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_title_screen);
// Spinner element
spinner = (Spinner) findViewById(R.id.titleSelectionSpinner);
// buttons
btnAdd = (Button) findViewById(R.id.button_go);
btnLogo = (Button) findViewById(R.id.button_ard_logo);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Check for Add New Vehicle entry to create menu option in drop down list
checkAddNewVehicle();
// Loading spinner data from database
loadSpinnerData();
//"Go" button actions
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Starting a new Intent
Intent screenAddVehicle = new Intent(getApplicationContext(), AddVehicleActivity.class);
Intent screenRecordViewing = new Intent(getApplicationContext(), RecordViewing.class);
String SpinnerChoice = spinner.getSelectedItem().toString();
//Sending data to another Activity
//store value of vehicle label for Record Viewing screen
screenRecordViewing.putExtra("vehicleLabel", SpinnerChoice);
//interpret Spinner choice as Menu items
//"Add New Vehicle" always at Position 0
if (SpinnerChoice == spinner.getItemAtPosition(0).toString()) {
startActivity(screenAddVehicle);
} else {
//display value of selection if not "Add New Vehicle"
//Toast.makeText(spinner.getContext(), "Selection:" + SpinnerChoice, Toast.LENGTH_LONG).show();
//go to Record Viewing screen
startActivity(screenRecordViewing);
}
}
});
//"Logo" button - display program copyright
btnLogo.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(), "FuelTracker is Copyright 2013 by Authentic Ruby Designs", Toast.LENGTH_LONG).show();
}
});
final View controlsView = findViewById(R.id.fullscreen_content_controls);
final View contentView = findViewById(R.id.fullscreen_content);
// Set up an instance of SystemUiHider to control the system UI for
// this activity.
mSystemUiHider = SystemUiHider.getInstance(this, contentView,
HIDER_FLAGS);
mSystemUiHider.setup();
mSystemUiHider
.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
// Cached values.
int mControlsHeight;
int mShortAnimTime;
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void onVisibilityChange(boolean visible) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
// If the ViewPropertyAnimator API is available
// (Honeycomb MR2 and later), use it to animate the
// in-layout UI controls at the bottom of the
// screen.
if (mControlsHeight == 0) {
mControlsHeight = controlsView.getHeight();
}
if (mShortAnimTime == 0) {
mShortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
controlsView
.animate()
.translationY(visible ? 0 : mControlsHeight)
.setDuration(mShortAnimTime);
} else {
// If the ViewPropertyAnimator APIs aren't
// available, simply show or hide the in-layout UI
// controls.
controlsView.setVisibility(visible ? View.VISIBLE
: View.GONE);
}
if (visible && AUTO_HIDE) {
// Schedule a hide().
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
}
});
// Set up the user interaction to manually show or hide the system UI.
contentView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TOGGLE_ON_CLICK) {
mSystemUiHider.toggle();
} else {
mSystemUiHider.show();
}
}
});
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
findViewById(R.id.button_go).setOnTouchListener(
mDelayHideTouchListener);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
//delayedHide(100);
}
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
Handler mHideHandler = new Handler();
Runnable mHideRunnable = new Runnable() {
#Override
public void run() {
mSystemUiHider.hide();
}
};
/**
* Schedules a call to hide() in [delay] milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide(int delayMillis) {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
/**
* Function to check that Add New Vehicle is the first label in the DB table
*/
private void checkAddNewVehicle() {
// database handler
//DatabaseHandler db = new DatabaseHandler(getApplicationContext());
DatabaseHandler db = DatabaseHandler.getInstance(getApplicationContext());
// table data
List<String> labels = db.getAllLabels();
//Check for "Add New Vehicle" entry at first row of table
if (labels.isEmpty() ) {
db.insertLabel("Add New Vehicle");
}
}
/**
* Function to load the spinner data from SQLite database
* */
private void loadSpinnerData() {
// database handler
//DatabaseHandler db = new DatabaseHandler(getApplicationContext());
DatabaseHandler db = DatabaseHandler.getInstance(getApplicationContext());
// Spinner Drop down elements
List<String> labels = db.getAllLabels();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, labels);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
}
And here's my DatabaseHandler class:
package ard.util.fueltracker;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.TableLayout;
public class DatabaseHandler extends SQLiteOpenHelper {
//create static instance
private static DatabaseHandler mInstance = null;
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "vehicleDatabase";
// Labels table name
private static final String TABLE_LABELS = "labels";
// Fuel Data table name
private static final String TABLE_FUELDATA = "fuel_data";
// Labels Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
// Fuel Data Tables Columns names
private static final String KEY_ENTRY = "entry_id";
private static final String FIELD_VEHICLEID = "vehicle_id";
private static final String FIELD_DATE = "date";
private static final String FIELD_FTYPE = "fuel_type";
private static final String FIELD_BRAND = "brand";
private static final String FIELD_PRICE = "price";
private static final String FIELD_KMS = "kms";
private static final String FIELD_LITRES = "litres";
private static final String FIELD_LPER = "l_per";
private static final String FIELD_MPG = "mpg";
// Fuel Data Columns for display - query shorthand
private static final String[] fuelDataDisplayCols = { FIELD_DATE, FIELD_FTYPE, FIELD_BRAND, FIELD_PRICE,
FIELD_KMS, FIELD_LITRES, FIELD_LPER, FIELD_MPG };
public static DatabaseHandler getInstance(Context ctx) {
//Use the application context to avoid leaking Activity's context
if (mInstance == null) {
mInstance = new DatabaseHandler(ctx.getApplicationContext());
}
return mInstance;
}
private DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
// Category table create query
String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT)";
db.execSQL(CREATE_CATEGORIES_TABLE);
// Fuel Data table create query
String CREATE_FUELDATA_TABLE = "CREATE TABLE " + TABLE_FUELDATA + "("
+ KEY_ENTRY + " INTEGER PRIMARY KEY," + FIELD_VEHICLEID + " INTEGER,"
+ FIELD_DATE + " TEXT," + FIELD_FTYPE + " TEXT," + FIELD_BRAND +
" TEXT," + FIELD_PRICE + " REAL," + FIELD_KMS + " REAL,"
+ FIELD_LITRES + " REAL," + FIELD_LPER + " REAL," + FIELD_MPG +
" REAL)";
db.execSQL(CREATE_FUELDATA_TABLE);
db.close();
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FUELDATA);
// Create tables again
onCreate(db);
}
/**
* Inserting new label into Labels table
* */
public void insertLabel(String label){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, label);
// Inserting Row
db.insert(TABLE_LABELS, null, values);
db.close(); // Closing database connection
}
/**
* Inserting entry data into Fuel Data table
*/
//public void insertFuelData(int vehicleID, String date, String ftype, String brand,
// float price, float kms, float litres) {
public void insertFuelData(ArrayList<String> fuelEntryData) {
SQLiteDatabase dbWrite = this.getWritableDatabase();
ArrayList<String> fuelEntry = fuelEntryData;
ContentValues values = new ContentValues();
//turn array values into individual field values with correct datatype
int vehicleID = getVehicleID(fuelEntry.get(0));
String date = fuelEntry.get(1);
String ftype = fuelEntry.get(2);
String brand = fuelEntry.get(3);
double price = Double.parseDouble((fuelEntry.get(4)));
double kms = Double.parseDouble((fuelEntry.get(5)));
double litres = Double.parseDouble((fuelEntry.get(6)));
//values for calculations
double lper;
double mpg;
//Format calculations to round to one significant digit
DecimalFormat df = new DecimalFormat("###.#");
//calculate Liters/100Kilometres
lper = (100 / (kms / litres));
//calculate U.S. Miles Per Gallon
mpg = (kms / litres) * 2.35;
//Prepare data and Insert row into table
values.put(FIELD_VEHICLEID, vehicleID);
values.put(FIELD_DATE, date);
values.put(FIELD_FTYPE, ftype);
values.put(FIELD_BRAND, brand);
values.put(FIELD_PRICE, price);
values.put(FIELD_KMS, kms);
values.put(FIELD_LITRES, litres);
values.put(FIELD_LPER, df.format(lper));
values.put(FIELD_MPG, df.format(mpg));
dbWrite.insert(TABLE_FUELDATA, null, values);
dbWrite.close();
}
/**
* Getting all labels
* returns list of labels
* */
public List<String> getAllLabels(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
/**
* Get entries based on vehicle id
*/
public List<List<String>> getFuelData(int vehicleID) {
//List of Lists - each row/entry of data is a separate List
List<List<String>> fuelDataTable = new ArrayList<List<String>>();
List<String> fuelDataRow = new ArrayList<String>();
//Select Query
String selectQuery = "SELECT * FROM " + TABLE_FUELDATA +
" WHERE vehicle_id = ? ";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, new String[] { String.valueOf(vehicleID) });
// looping through all rows and 9 columns (not incl key) and adding to list
if (cursor.moveToFirst()) {
do {
for(int i = 1; i < 10; i++) {
//doesn't work with non-string values
//fuelDataRow.add(cursor.getString(i));
}
//add each row in its entirety to the List; multi-dimenionsal list
fuelDataTable.add(fuelDataRow);
//empty fuelDataRow
fuelDataRow.clear();
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
//return data
return fuelDataTable;
}
public List<String> getFuelDataRows(int vehicleID) {
List<String> fuelDataTable = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
//Get data from database table
Cursor c = db.query(TABLE_FUELDATA, fuelDataDisplayCols, " vehicle_id=? ", new String[] { String.valueOf(vehicleID) }, null, null, FIELD_DATE);
//Insert Header row into Array
fuelDataTable.add("Date");
fuelDataTable.add("Type");
fuelDataTable.add("Brand");
fuelDataTable.add("Price");
fuelDataTable.add("KMs");
fuelDataTable.add("Litres");
fuelDataTable.add("L/100");
fuelDataTable.add("MPG");
//Go to beginning of Cursor data and loop through
c.moveToFirst();
while (!c.isAfterLast()) {
//add each cell in the row to List array
fuelDataTable.add(c.getString(c.getColumnIndex(FIELD_DATE)));
fuelDataTable.add(c.getString(c.getColumnIndex(FIELD_FTYPE)));
fuelDataTable.add(c.getString(c.getColumnIndex(FIELD_BRAND)));
fuelDataTable.add(String.valueOf(c.getDouble(c.getColumnIndex(FIELD_PRICE))));
fuelDataTable.add(String.valueOf(c.getDouble(c.getColumnIndex(FIELD_KMS))));
fuelDataTable.add(String.valueOf(c.getDouble(c.getColumnIndex(FIELD_LITRES))));
fuelDataTable.add(String.valueOf(c.getDouble(c.getColumnIndex(FIELD_LPER))));
fuelDataTable.add(String.valueOf(c.getDouble(c.getColumnIndex(FIELD_MPG))));
c.moveToNext();
}
// Make sure to close the cursor
c.close();
db.close();
return fuelDataTable;
}
public int getVehicleID(String label) {
// set variables
SQLiteDatabase dbReader = this.getReadableDatabase();
String vLabel = label;
//Query String
String selectQuery = "SELECT " + KEY_ID + " FROM " + TABLE_LABELS +
" WHERE name = ? ";
Cursor c = dbReader.rawQuery(selectQuery, new String[] { vLabel });
//avoid out of bounds exception
c.moveToFirst();
//extract value as integer
int vID = c.getInt(c.getColumnIndex(KEY_ID));
c.close();
return vID;
}
}
Some of it probably looks ugly - this is my first app project and Eclipse auto-populated some of the methods upon creation - but it is working OK in Ice Cream Sandwich.
Thanks for any clues.
db.close() is not needed in public void onCreate(). This will probably fix your problem.