ListView doesn't show anything in Android app - java

Ok so here is the whole code
This is MainActivity.java
package com.gobtron.database_test;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class MainActivity extends ActionBarActivity {
DBAdapter myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
openDB();
populateListView();
}
#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_main, menu);
return true;
}
private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
}
public void onClick_ViewData (View v){
openDB();
populateListView();
}
#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 populateListView() {
Cursor cursor = myDb.getAllRows();
// DatabaseUtils.dumpCursor(cursor);
String[] fromFieldNames = new String[] {DBAdapter.KEY_ROWID, DBAdapter.KEY_NOM};
int[] toViewIDs = new int[] {R.id.textView2, R.id.textView3};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.item_layout, cursor, fromFieldNames, toViewIDs, cursor.getCount());
ListView myList = (ListView) findViewById(R.id.listView);
myList.setAdapter(myCursorAdapter);
}
}
And this is the DPAdapter class code:
package com.gobtron.database_test;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
private static final String TAG = "DBAdapter"; //used for logging database version changes
// Field Names:
public static final String KEY_ROWID = "_id";
public static final String KEY_MORPH = "'morph'";
public static final String KEY_LONGFRONDE = "'long_fronde'";
public static final String KEY_FORMELIMBE = "'forme_limbe'";
public static final String KEY_DISPOSFRONDE = "'dispos_fronde'";
public static final String KEY_DESC = "'description'";
public static final String KEY_DESCHOIX = "'desc_choix'";
public static final String KEY_DESCHOIX2 = "'desc_choix2'";
public static final String KEY_NOM = "'nom'";
public static final String[] ALL_KEYS ={KEY_ROWID, KEY_MORPH, KEY_LONGFRONDE, KEY_FORMELIMBE, KEY_DISPOSFRONDE, KEY_DESC, KEY_DESCHOIX, KEY_DESCHOIX2, KEY_NOM};
public static final String[] ALL_KEYS2 = {"_id", "'long_fronde'"};
// Column Numbers for each Field Name:
public static final int COL_ROWID = 0;
public static final int COL_MORPH = 1;
public static final int COL_LONGFRONDE = 2;
public static final int COL_FORMELIMBE = 3;
public static final int COL_DISPOSFRONDE = 4;
public static final int COL_DESC = 5;
public static final int COL_DESCHOIX = 6;
public static final int COL_DESCHOIX2 = 7;
public static final int COL_NOM = 8;
// DataBase info:
public static final String DATABASE_NAME = "fougeres_db";
public static final String DATABASE_TABLE = "mono_dimo";
public static final int DATABASE_VERSION = 3; // The version number must be incremented each time a change to DB structure occurs.
//SQL statement to create database
private static final String DATABASE_CREATE_SQL =
"CREATE TABLE " + DATABASE_TABLE
+ " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_NOM + " TEXT NOT NULL, "
+ KEY_DESC + " TEXT"
+ ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
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 be inserted into the database.
public long insertRow(String task, String date) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NOM, task);
initialValues.put(KEY_MORPH, date);
// Insert the data 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(DATABASE_TABLE, ALL_KEYS, where, null, null, null, null);
DatabaseUtils.dumpCursor(c);
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 task, String date) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_NOM, task);
newValues.put(KEY_MORPH, date);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
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);
}
}
}
I don't get why my cursor is empty... I think it opens the database correctly, and the table too.
Well... I'm new to java so it is probably something stupid i'm missing.

You are trying to insert a value with key KEY_MORTH, however there is no field with this Key in your table
this:
"CREATE TABLE " + DATABASE_TABLE
+ " (" + KEY_ROWID + " INTEGER PRIMARY KEY , "
+ KEY_NOM + " TEXT NOT NULL, "
+ KEY_DESC + " TEXT"
+ ");";
needs to be
"CREATE TABLE " + DATABASE_TABLE
+ " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_NOM + " TEXT NOT NULL, "
+ KEY_DESC + " TEXT, "
+ KEY_MORTH + " TEXT "
+ ");";
You will need to update your db version or clear your data for this to take effect

Ok, turns out that my database was simply put in the wrong place. I needed to open the Android Device Monitor, then go the File Explorer, then put my existing database to /data/data/my package name/databases/

Related

How to Retrieve Multiple data when clicked on listview?

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.

add more fields to DBAdapter class

i try to save current date values when button get clicked....i use DBAdapter for save parameters to sqlite and it was fine when used for 2 fields like example of DBAdapter but when i edited DBAdapter for 6 fields this doesnt work.where is my problem?
DBAdapter.java
import java.io.StringReader;
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
private static final String TAG = "DBAdapter"; //used for logging database version changes
// Field Names:
public static final String KEY_ROWID = "_id";
public static final String KEY_YEAR = "year";
public static final String KEY_MONTH = "month";
public static final String KEY_DAY = "day";
public static final String KEY_HOUR = "hour";
public static final String KEY_MINUTE = "minute";
public static final String KEY_SECOND = "second";
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_YEAR, KEY_MONTH, KEY_DAY, KEY_HOUR, KEY_MINUTE, KEY_SECOND};
// Column Numbers for each Field Name:
public static final int COL_ROWID = 0;
public static final int COL_TASK = 1;
public static final int COL_DATE = 2;
// DataBase info:
public static final String DATABASE_NAME = "dbToDo12";
public static final String DATABASE_TABLE = "mainToDo12";
public static final int DATABASE_VERSION = 2; // The version number must be incremented each time a change to DB structure occurs.
//SQL statement to create database
private static final String DATABASE_CREATE_SQL =
"CREATE TABLE " + DATABASE_TABLE
+ " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_YEAR + " TEXT NOT NULL, "
+ KEY_MONTH + " TEXT"
+ KEY_DAY + " TEXT"
+ KEY_HOUR + " TEXT"
+ KEY_MINUTE + " TEXT"
+ KEY_SECOND + " TEXT"
+ ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
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 be inserted into the database.
public long insertRow(String year, String month,String day, String hour,String minute,String second) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_YEAR, year);
initialValues.put(KEY_MONTH, month);
initialValues.put(KEY_DAY, day);
initialValues.put(KEY_HOUR, hour);
initialValues.put(KEY_MINUTE, minute);
initialValues.put(KEY_SECOND, second);
// Insert the data 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 year, String month,long day, String hour, String minute,long second) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_YEAR, year);
newValues.put(KEY_MONTH, month);
newValues.put(KEY_DAY, day);
newValues.put(KEY_HOUR, hour);
newValues.put(KEY_YEAR, year);
newValues.put(KEY_MINUTE, minute);
newValues.put(KEY_SECOND, second);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
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);
}
}
}
MainActivity.java
import android.content.Context;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.view.View;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
Button plus;
int second,minute,houre,day,mounth,year;
DBAdapter mDb = new DBAdapter(this);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
ViewGroup.LayoutParams superparams =
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.MATCH_PARENT);
LinearLayout table = new LinearLayout(this);
plus = new Button(this);
plus.setText("+");
table.addView(plus);
setContentView(table);
plus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Calendar c = Calendar.getInstance();
second = c.get(Calendar.SECOND);
minute = c.get(Calendar.MINUTE);
houre = c.get(Calendar.HOUR);
day = c.get(Calendar.DAY_OF_MONTH);
mounth = c.get(Calendar.MONTH);
year = c.get(Calendar.YEAR);
mDb.open();
mDb.insertRow(Integer.toString(year), Integer.toString (mounth),Integer.toString(day), Integer.toString(houre),Integer.toString(minute), Integer.toString(second));
mDb.close();
mDb.open();
Cursor g=mDb.getRow(2);
DisplayContact(g);
mDb.close();
}
});
}
public void DisplayContact(Cursor c)
{
Toast.makeText(this,"id: "+c.getString(0)+"\n"+
"year: "+c.getString(1)+"\n"+
"month: "+c.getString(2),
Toast.LENGTH_LONG).show();
}
}
You're missing commas , between your column specifications here:
+ KEY_MONTH + " TEXT"
+ KEY_DAY + " TEXT"
+ KEY_HOUR + " TEXT"
+ KEY_MINUTE + " TEXT"
After adding the missing commas, either uninstall your app or increment the schema version to get the table recreated.

Error parsing XML - not well formed (invalid token)

I have already checked the other XML files for errors, however this is the file that the error message is saying the error is in. There is also a message that pops up whenever I try to run the app that says, "Files under the build folder are generated and should not be edited".
package com.example.drive.drivercorder;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
private static final String TAG = "DBAdapter";
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
public static final String KEY_DRIVETIME = "Drive Time";
public static final String KEY_NIGHTORDAY = "Time of Day";
public static final int COL_DRIVETIME = 1;
public static final int COL_NIGHTORDAY = 2;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_DRIVETIME, KEY_NIGHTORDAY, };
public static final String DATABASE_NAME = "MyDb";
public static final String DATABASE_TABLE = "mainTable";
public static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_DRIVETIME + " integer not null, "
+ KEY_NIGHTORDAY + " text not null "
+ ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
public void close() {
myDBHelper.close();
}
public long insertRow(int drivetime, String nightorday) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_DRIVETIME, Drive Time);
initialValues.put(KEY_NIGHTORDAY, Time of Day);
return db.insert(DATABASE_TABLE, null, initialValues);
}
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();
}
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;
}
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;
}
public boolean updateRow(long rowId, String drivetime, String nightorday) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_DRIVETIME, Drive Time);
newValues.put(KEY_NIGHTORDAY, Time of Day);
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
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!");
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(_db);
}
}
}
There is also a message that pops up whenever I try to run the app that says, "Files under the build folder are generated and should not be edited".
I think you are changing the .class file in debug/DDMS mode or something like that. Please check and make sure to edit your .java file instead.
Posting your relevant logcat messages and also the XML file in question might help understand the problem.

NullPointerException at this.getReadableDatabase();

Heyhey :)
I looked at several Questions to the same topic, but I found no solution to my problem.
A NullPointerException at this.getReadableDatabase(); appears...
Here's my Code:
public class DatabaseHandler extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "TODO_APP";
/*--------------------------- TABLE ITEMS START ---------------------------*/
private static final String TABLE_ITEMS = "items";
private static String KEY_ID_ITEMS = "id_items";
private static final String KEY_CATEGORY_ITEMS = "category";
private static final String KEY_DATETIME_ITEMS = "datetime";
private static String KEY_NAME_ITEMS = "name";
private static final String KEY_DESCRIPTION_ITEMS = "description";
private static final String KEY_ALARM_ITEMS = "alarm";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// create table ITEMS
String CREATE_ITEMS_TABLE = "CREATE TABLE " + TABLE_ITEMS + "("
+ KEY_ID_ITEMS + " INTEGER PRIMARY KEY," + KEY_CATEGORY_ITEMS
+ " INTEGER," + KEY_DATETIME_ITEMS
+ " TIMESTAMP DEFAULT CURRENT_TIMESTAMP," + KEY_NAME_ITEMS
+ " TEXT," + KEY_DESCRIPTION_ITEMS + " TEXT," + KEY_ALARM_ITEMS
+ " INTEGER" + ");";
db.execSQL(CREATE_ITEMS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ITEMS);
// Create tables again
this.onCreate(db);
}
public void addItem(DB_Item item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_CATEGORY_ITEMS, item.getCategory());
values.put(KEY_NAME_ITEMS, item.getName());
values.put(KEY_DESCRIPTION_ITEMS, item.getDescription());
values.put(KEY_ALARM_ITEMS, item.getAlarm());
// Inserting Row
db.insert(TABLE_ITEMS, null, values);
db.close(); // Closing database connection
}
public DB_Item getItem(String name) {
//!!!!! Here is one problem !!!!!
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_ITEMS, new String[] { KEY_ID_ITEMS,
KEY_CATEGORY_ITEMS, KEY_DATETIME_ITEMS, KEY_NAME_ITEMS,
KEY_DESCRIPTION_ITEMS, KEY_ALARM_ITEMS },
KEY_NAME_ITEMS = " = ?", new String[] { String.valueOf(name) },
null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
// DB_Item (int category, String name, String description, int
// alarm)
DB_Item item = new DB_Item(cursor.getInt(1), cursor.getString(3),
cursor.getString(4), cursor.getInt(5));
return item;
}
public List<DB_Item> getAllItems() {
List<DB_Item> itemList = new ArrayList<DB_Item>();
// SELECT ALL
String selectQuery = "SELECT * FROM " + TABLE_ITEMS;
//!!!!!!!!!! here is the other Problem
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
// go through all rows and then adding to list
if (cursor.moveToFirst()) {
do {
DB_Item item = new DB_Item();
item.setCategory(Integer.parseInt(cursor.getString(0)));
// TODO
// adding to list
itemList.add(item);
} while (cursor.moveToNext());
}
return itemList;
}
[and so on, didn't copy the whole code]
Hope you can help me...
The error appears definitely at SQLiteDatabase db = this.getReadableDatabase();
Output:
09-03 08:34:17.863: E/AndroidRuntime(7074): java.lang.RuntimeException: Unable to start activity ComponentInfo{todo.todo_list/todo.view.StartApp}: java.lang.NullPointerException
09-03 08:34:17.863: E/AndroidRuntime(7074): at todo.database.DatabaseHandler.getAllItems(DatabaseHandler.java:144)
09-03 08:34:17.863: E/AndroidRuntime(7074): at todo.helper.SortItems.sortItemsCategory(SortItems.java:16)
09-03 08:34:17.863: E/AndroidRuntime(7074): at todo.view.StartApp.onCreate(StartApp.java:36)
chnage you class to something like this:
package com.mhp.example;
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 {
/*--------------------------- TABLE ITEMS START ---------------------------*/
private static final String TABLE_ITEMS = "items";
private static String KEY_ID_ITEMS = "id_items";
private static final String KEY_CATEGORY_ITEMS = "category";
private static final String KEY_DATETIME_ITEMS = "datetime";
private static String KEY_NAME_ITEMS = "name";
private static final String KEY_DESCRIPTION_ITEMS = "description";
private static final String KEY_ALARM_ITEMS = "alarm";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "dbname";
private static final int DATABASE_VERSION = 1;
tring CREATE_ITEMS_TABLE = "CREATE TABLE " + TABLE_ITEMS + "("
+ KEY_ID_ITEMS + " INTEGER PRIMARY KEY," + KEY_CATEGORY_ITEMS
+ " INTEGER," + KEY_DATETIME_ITEMS
+ " TIMESTAMP DEFAULT CURRENT_TIMESTAMP," + KEY_NAME_ITEMS
+ " TEXT," + KEY_DESCRIPTION_ITEMS + " TEXT," + KEY_ALARM_ITEMS
+ " INTEGER" + ");";
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)
{
try {
db.execSQL(CREATE_ITEMS_TABLE);
} catch (SQLException e) {
e.printStackTrace();
}
}
#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);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
public void addItem(DB_Item item) {
ContentValues values = new ContentValues();
values.put(KEY_CATEGORY_ITEMS, item.getCategory());
values.put(KEY_NAME_ITEMS, item.getName());
values.put(KEY_DESCRIPTION_ITEMS, item.getDescription());
values.put(KEY_ALARM_ITEMS, item.getAlarm());
// Inserting Row
db.insert(TABLE_ITEMS, null, values);
}
public DB_Item getItem(String name) {
Cursor cursor = db.query(TABLE_ITEMS, new String[] { KEY_ID_ITEMS,
KEY_CATEGORY_ITEMS, KEY_DATETIME_ITEMS, KEY_NAME_ITEMS,
KEY_DESCRIPTION_ITEMS, KEY_ALARM_ITEMS },
KEY_NAME_ITEMS = " = ?", new String[] { String.valueOf(name) },
null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
// DB_Item (int category, String name, String description, int
// alarm)
DB_Item item = new DB_Item(cursor.getInt(1), cursor.getString(3),
cursor.getString(4), cursor.getInt(5));
return item;
}
public List<DB_Item> getAllItems() {
List<DB_Item> itemList = new ArrayList<DB_Item>();
// SELECT ALL
String selectQuery = "SELECT * FROM " + TABLE_ITEMS;
Cursor cursor = db.rawQuery(selectQuery, null);
// go through all rows and then adding to list
if (cursor.moveToFirst()) {
do {
DB_Item item = new DB_Item();
item.setCategory(Integer.parseInt(cursor.getString(0)));
// TODO
// adding to list
itemList.add(item);
} while (cursor.moveToNext());
}
return itemList;
}
}
NOTE: when you create object from DBAdapter,you should open() db and after your work close() it.
DBAdapter db = new DBAdapter(contex);
db.open();
//do you work
db.close();
Just use getReadableDatabase() without this.

Updating specific column using a spinner widget

I am trying to update current credits column of the only row in the database using a drop down spinner which gets values from an arraylist. Very unsure about how to go about doing this operation. Thank you for any help in advance.
My database code:
package com.example.parkangel;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class UDbHelper extends SQLiteOpenHelper
{
public static final String KEY_ROWID = "_id";
public static final String KEY_PFNAME = "payeeFname";
public static final String KEY_PSNAME = "payeeSname";
public static final String KEY_CARD = "card";
public static final String KEY_CREDITS = "credits";
private static final String DATABASE_NAME = "UserData.db";
private static final String DATABASE_TABLE = "UserTable";
private static final int DATABASE_VERSION = 1;
//private UDbHelper dbHelper;
//private final Context ourContext;
private static UDbHelper instance;
private SQLiteDatabase ourDatabase;
public UDbHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static UDbHelper getInstance(Context context)
{
if (instance == null)
{
instance = new UDbHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_PFNAME + " TEXT NOT NULL, " + KEY_PSNAME + "
TEXT NOT NULL, " +
KEY_CARD + " TEXT NOT NULL, " + KEY_CREDITS + " TEXT
NOT NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
public synchronized UDbHelper open() throws SQLException
{
System.out.println ("running open");
if(ourDatabase == null || !ourDatabase.isOpen())
ourDatabase = getWritableDatabase();
return this;
}
public String getData()
{
// TODO Auto-generated method stub
String[] columns = new String[] {KEY_ROWID, KEY_PFNAME, KEY_PSNAME,
KEY_CARD, KEY_CREDITS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null,
null, null, null);
String result = " ";
int iRow = c.getColumnIndexOrThrow(KEY_ROWID);
int iPFname = c.getColumnIndexOrThrow(KEY_PFNAME);
int iPSname = c.getColumnIndexOrThrow(KEY_PSNAME);
int iCard = c.getColumnIndexOrThrow(KEY_CARD);
int iCredits = c.getColumnIndexOrThrow(KEY_CREDITS);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " +
c.getString(iPFname) + " " +
c.getString(iPSname)
+ " " + c.getString(iCard) + " " +
c.getString(iCredits) + "\n";
}
return result;
}
}
My main activity code I will be doing the operation through:
package com.example.parkangel;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class Balance extends Activity{
Button add;
TextView display;
Spinner spinner3;
String[] money = {"Select amount", "£1", "£2", "£5", "£10"};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.balance_layout);
TextView tv = (TextView) findViewById(R.id.firstn);
UDbHelper db = new UDbHelper(this);
db.open();
String data = db.getData();
db.close();
tv.setText(data);
ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(Balance.this,
android.R.layout.simple_spinner_item, money);
spinner3 = (Spinner) findViewById (R.id.moneytoadd);
spinner3.setAdapter(adapter3);
add = (Button) findViewById(R.id.topup);
}
public void onClick(View arg0)
{
}
public void updateActivity(View view){
Intent book = new Intent(Balance.this, BookTicket.class);
startActivity(book);
}
public void addBalance(View view){
Intent addB = new Intent(Balance.this, Balance.class);
startActivity(addB);
}
public void doUpdate(View view){
Intent upd = new Intent(Balance.this, UpdateTicket.class);
startActivity(upd);
}
}
Your question is fairly compound, getting selected field from spinner, updating database... I'm not going to provide a complete answer, but this should get you started:
This is how you would get the selected field from the spinner, which you can then use to update your database. One word of warning, I believe setOnItemSelectedListener is called when it is initially set, so you may need to ignore the first call.
Spinner spinner;
spinner.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View view, int arg2,
long arg3) {
if(! (view instanceof TextView)){
// view is probably a textview, but record type if not.
System.out.println("incorrect view type " + view.getClass().getSimpleName());
return;
}
EditText et = (EditText) view;
String fieldName = et.getText().toString().trim();
//Now we got selected name, send name
//to a function that updates our database.
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
I didn't find the problem but I can tell you that your code is VERY INEFFICIENT. You are using String to build your result in the getData method. Each time you try to append the new data (Row) to the old one you are creating a new string to hold the new data. If you are retrieving 1000 row from the database, this means that you are creating 1000 string to build the final one. I recommend using StringBuilder instead as following:
StringBuilder strBuilder= new StringBuilder();
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
strBuilder.append( c.getString(iRow) + " " +
c.getString(iPFname) + " " +
c.getString(iPSname)
+ " " + c.getString(iCard) + " " +
c.getString(iCredits) + "\n");
}
return str= strBuilder.toString();
Here is an example of how to insert into your DB:
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_PFNAME , editText1.getText().toString());
values.put(KEY_PSNAME , stringArrayList.get(position));
values.put(KEY_CARD , "12345677");
values.put(KEY_CREDITS , "55");
// Inserting Row
db.insert(DATABASE_TABLE, null, values);
db.close(); // Closing database connection

Categories