Populate TableLayout from SQLite-database - java

I want to display a simple list in a table view which I've created and included below but can't see how i capture the data which I'm getting back from my query to populate this.
I have a database adapter which i think is working:
public class DbAdapter {
public static final String KEY_ROWID = "id";
public static final String KEY_ITEM_NAME = "name";
public static final String KEY_ITEM_COST = "cost";
public static final String KEY_ITEM_PRICE_VALUE = "price";
public static final String KEY_ITEM_POSTAGE = "postage";
public static final String KEY_ACTUAL_PL = "profitloss";
private static final String TAG = "DbAdapter";
private static final String DATABASE_NAME = "eBaySalesDB";
private static final String DATABASE_TABLE = "actualSales";
private static final int DATABASE_VERSION = 1;
private DatabaseHelper mDbHelper;
private SQLiteDatabase db;
//private static final String DATABASE_CREATE = "create table if not exists"
// + DATABASE_TABLE + "(" + KEY_ROWID
// + "integer primary key autoincrement, " + KEY_ITEM_NAME
// + "text not null," + KEY_ITEM_COST + "text not null,"
// + KEY_ITEM_PRICE_VALUE + "text not null," + KEY_ITEM_POSTAGE
// + "text not null," + KEY_ACTUAL_PL + "text not null);";
private static final String DATABASE_CREATE = "create table if not exists "
+ DATABASE_TABLE + "(" + KEY_ROWID
+ " integer primary key autoincrement, " + KEY_ITEM_NAME
+ " text not null," + KEY_ITEM_COST + " text not null,"
+ KEY_ITEM_PRICE_VALUE + " text not null," + KEY_ITEM_POSTAGE
+ " text not null," + KEY_ACTUAL_PL + " text not null);";
private final Context mCtx;
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);
}
#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 " + DATABASE_TABLE);
onCreate(db);
}
}
/**
* constructor - takes the context to allow the database to be opened /
* created
*
* #param ctx
*/
public DbAdapter(Context ctx) {
this.mCtx = ctx;
}
/**
* open up the database. If it cannot be opened it will try to create a new
* instance of the database. if this can't be created it will throw an
* exception
*
* #return this (self reference)
* #throws SQLException
* (if the database can't be opened or closed.
*/
public DbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
db = mDbHelper.getWritableDatabase();
return this;
}
/**
* Method to close the code off to others
*/
public void close() {
mDbHelper.close();
}
/**
* method to insert a record into the database
*/
public long insertRecord(String name, String cost, String price,
String postage, String profitloss) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_ITEM_NAME, name);
initialValues.put(KEY_ITEM_COST, cost);
initialValues.put(KEY_ITEM_PRICE_VALUE, price);
initialValues.put(KEY_ITEM_POSTAGE, postage);
initialValues.put(KEY_ACTUAL_PL, profitloss);
return db.insert(DATABASE_TABLE, null, initialValues);
}
/**
* method to delete a record from the database
*/
public boolean deleteRecord(long id) {
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + id, null) > 0;
}
/**
* method to retrieve all the records
*/
public Cursor getAllRecords() {
return db.query(DATABASE_TABLE, new String[] { KEY_ROWID,
KEY_ITEM_NAME, KEY_ITEM_COST, KEY_ITEM_PRICE_VALUE,
KEY_ITEM_POSTAGE, KEY_ACTUAL_PL }, null, null, null, null,
null, null);
}
/**
* method to retrieve a particular record
*/
public Cursor getRecord(long id) throws SQLException {
Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
KEY_ROWID, KEY_ITEM_NAME, KEY_ITEM_COST, KEY_ITEM_PRICE_VALUE,
KEY_ITEM_POSTAGE, KEY_ACTUAL_PL }, KEY_ROWID + "=" + id, null,
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
/**
* method to update a record
*/
public boolean updateRecord(long id, String name, String cost,
String price, String postage, String profitloss) {
ContentValues args = new ContentValues();
args.put(KEY_ITEM_NAME, name);
args.put(KEY_ITEM_COST, cost);
args.put(KEY_ITEM_PRICE_VALUE, price);
args.put(KEY_ITEM_POSTAGE, postage);
args.put(KEY_ACTUAL_PL, profitloss);
return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + id, null) > 0;
}
}
I've also created an Activity to activate a button to view the data which a user can press. It's the third button, viewRecordsDB, which I'm having trouble getting to function....
public class ActualSalesTracker extends Activity implements OnClickListener {
DbAdapter db = new DbAdapter(this);
Button BtnSalesCal, BtnAddRecordDB, BtnViewRecordsDB;
EditText item_name, item_cost, item_price_value, item_postage, actual_pl;
SalesProfitLossCal actSalesCal = new SalesProfitLossCal();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actual_sales_tracker);
Button salesCalBtn = (Button) findViewById(R.id.BtnSalesCal);
// register the click event with the sales calculating profit/loss
// button
salesCalBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// get EditText by id to represent the value of the item stock
// cost and store it as a double
EditText itemCostString = (EditText) findViewById(R.id.item_cost);
String ic = itemCostString.getText().toString();
double itemCost = Double.valueOf(ic).doubleValue();
// get EditText by id to represent the value of the post and
// packaging cost and store it as a double
EditText itemPostageString = (EditText) findViewById(R.id.item_postage);
String ipapc = itemPostageString.getText().toString();
double itemPostage = Double.valueOf(ipapc).doubleValue();
// get EditText by id to represent the value of the selling
// price and store it as a double
EditText itemPriceValueString = (EditText) findViewById(R.id.item_price_value);
String sp = itemPriceValueString.getText().toString();
double itemPriceValue = Double.valueOf(sp).doubleValue();
double actTotalCost = actSalesCal.ActTotalCostCal(itemCost,
itemPostage, itemPriceValue);
double actualProfitLoss = actSalesCal
.calculateProfitLossGenerated(itemPriceValue,
actTotalCost);
String ActualProfitLossString = String.format(
"You made £ %.2f", actualProfitLoss);
TextView ActualProfitLossView = (TextView) findViewById(R.id.yourActualPL);
ActualProfitLossView.setText(ActualProfitLossString);
}
});
// activate the add record button
Button addRecordDB = (Button) findViewById(R.id.BtnAddRecordDB);
// register the click event with the add record button
addRecordDB.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText nameText = (EditText) findViewById(R.id.item_name);
String name = nameText.getText().toString();
EditText costText = (EditText) findViewById(R.id.item_cost);
String cost = costText.getText().toString();
EditText priceText = (EditText) findViewById(R.id.item_price_value);
String price = priceText.getText().toString();
EditText postageText = (EditText) findViewById(R.id.item_postage);
String postage = postageText.getText().toString();
TextView profitlossText = (TextView) findViewById(R.id.actual_pl);
String profitloss = profitlossText.getText().toString();
db.open();
long id = db.insertRecord(name, cost, price, postage,
profitloss);
db.close();
}
});
// activate the view record button
Button viewRecordsDB = (Button) findViewById(R.id.BtnViewRecordsDB);
// register the click event with the add record button
viewRecordsDB.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
db.open();
Cursor id = db.getAllRecords();
db.close();
// for (id.moveToFirst(); !id.moveToLast(); id.moveToNext()){
// id.getString(
// result = result +
// }
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
I wanted it to populate the following view file on xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TableLayout
android:id="#+id/table_sales"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TableRow android:id="#+id/tableRow1" >
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="#string/item_name"
android:layout_weight="1" >
</TextView>
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="#string/profit_loss"
android:layout_weight="1" >
</TextView>
</TableRow>
</TableLayout>
<TextView
android:id="#+id/sales_info"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="get info from database" >
</TextView>
</LinearLayout>
and i have a java file set up to activate this :
public class ViewSales extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_sales);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

Use a ListView rather than a TableLayout. A TableLayout is usually used to display static, pre-defined content, while a ListView is much more dynamic and can directly handle the Cursor you get from the SQLite-db: Learn How to Create ListView From SQLite Database in Android Development

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.

Null pointer exception in Android prompt user input dialog box [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
This is my activity ,where I need to Add Category to the database,I used Android prompt user input dialog box to add that catgeory.I refer this link for the dialog box. http://www.mkyong.com/android/android-prompt-user-input-dialog-example/
But now it's giving null pointer exception when I pressing ADD(OK) button in dialog box.
public class budget extends Activity {
int selected_id;
ListView rldlist = null;
DBhelper helper;
String budget;
TextView menubtn;
Context context = this;
EditText txr;
Button btn1;
SQLiteDatabase db;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.budget);
helper = new DBhelper(this);
txr = (EditText) findViewById(R.id.add);
btn1 = (Button) findViewById(R.id.button);
menubtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// get prompts.xml view
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.addcategory, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("ADD",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ContentValues value = new ContentValues();
value.put(DBhelper.Name, txr.getText().toString());
db = helper.getWritableDatabase();
if (helper.checkIdExist(txr.getText().toString())) {
db.insert(DBhelper.TABLE1, null, value);
db.close();
} else {
Toast.makeText(getApplicationContext(), "Duplicate Category Name!", Toast.LENGTH_LONG).show();
}
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
This is my DB class..
public class DBhelper extends SQLiteOpenHelper{
static final String DATABASE = "wedding9.db";
static final int VERSION = 9;
static final String TABLE1 = "Category";
static final String TABLE2 = "Budget";
static final String TABLE3 = "Expenses";
static final String C_ID = "_id";
static final String Name = "name";
static final String B_ID = "_id";
static final String Description = "description";
static final String Amount = "amount";
public static final String ID1="_id";
public static final String DATE_T1="date1";
public static final String CATEGORY="category";
public static final String DETAIL="detail";
public static final String AMOUNT1="amount1";
public static final String STATUS="status";
public static final String EX_YEAR="exyear";
public static final String EX_MONTH="exmonth";
public DBhelper(Context context){
super(context, DATABASE, null, VERSION);
}
public void onCreate(SQLiteDatabase db){
db.execSQL("CREATE TABLE " + TABLE1+ "(" +C_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT," +Name+ " text unique not null)");
db.execSQL("CREATE TABLE " + TABLE2+ "(" +B_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT," +Description+ " text,"
+Amount+ " text, FOREIGN KEY ("+Description+") REFERENCES "+TABLE1+"("+Name+"));");
db.execSQL("CREATE TABLE " + TABLE3 + " ( "
+ ID1 + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ DATE_T1 + " text, "
+ CATEGORY + " text, "
+ DETAIL + " text, "
+ STATUS + " text, "
+ EX_YEAR + " text, "
+ EX_MONTH + " text, "
+ AMOUNT1 + " text, FOREIGN KEY ("+CATEGORY+") REFERENCES "+TABLE1+"("+Name+"));");
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table " + TABLE1);
onCreate(db);
}
public ArrayList<category> getCategories(){
ArrayList<category> arrayList = new ArrayList<category>();
SQLiteDatabase db = getReadableDatabase();
Cursor c = db.query(DBhelper.TABLE1, null, null, null, null, null, null);
while (c.moveToNext()) {
category cat = new category(c.getInt(0),c.getString(1));
arrayList.add(cat);
}
return arrayList;
}
public boolean checkIdExist(String name) {
SQLiteDatabase db = getReadableDatabase();
Cursor c = db.query(DBhelper.TABLE1, null, null, null, null, null, null);
while (c.moveToNext()) {
if(c.getString(1).equals(name))
return false;
}
return true;
}
}
10-25 13:56:21.179 16248-16248/com.example.username.weddingplanning
E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.username.weddingplanning.budget$1$2.onClick(budget.java:83)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:185)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5299)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Here:
Context context = this;
Initializing context before creating Activity which probably causing issue.
Initialize context in onCreate method :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.budget);
context=this;//<<<<
....
}
If add EditText is inside addcategory layout then initialize it using promptsView as in onClick method:
View promptsView = li.inflate(R.layout.addcategory, null);
txr = (EditText)promptsView. findViewById(R.id.add);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);

How to display database fields in seperate textViews

I have created a database film app where a user can search for films, the search results then display in a scroll view. The user can then click on a film result which will lead to another activity which will display the full film details (film, actors, directors). How would I retrieve the database fields and display these in separate textViews?
MainActivity:
public void search(View v){
EditText search = (EditText)findViewById(R.id.edtSearch);
String searchresult = "%" + search.getText().toString() + "%";
db = new DbHelper(this).getReadableDatabase();
String[] tblColumns = {"*"};
String where = "film LIKE ? OR actor LIKE ? OR actor2 LIKE ? OR director LIKE ?";
String[] args = {searchresult, searchresult, searchresult, searchresult};
Cursor results = db.query("FILMTABLE", tblColumns, where, args, null, null, null);
film(results);
}
public void film (Cursor c){
c.moveToFirst();
int titleint = c.getColumnIndex("film");
int id= c.getColumnIndex("id");
String title = c.getString(titleint);
int filmID = c.getInt(id);
TextView txt = new TextView(getApplicationContext());
txt.setId(filmID);
txt.setText(title);
txt.setTextColor(Color.BLACK);
txt.setTextSize(15);
txt.setClickable(true);
txt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity4.class);
intent.putExtra("FILM_ID_KEY", String.valueOf(v.getId()));
startActivity(intent);
}
});
ScrollView scrollView = (ScrollView)findViewById(R.id.scrolLView);
scrollView.addView(txt);
}
MainActivity4:
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
public class MainActivity4 extends ActionBarActivity {
String filmId;
protected SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
Intent intent = getIntent();
filmId = intent.getStringExtra(MainActivity.FILM_ID_KEY);
}
}
DbHelper:
public class DbHelper extends SQLiteOpenHelper {
private static final String ID = "id";
private static final String FILM = "film";
private static final String ACTOR = "actor";
private static final String ACTOR2 = "actor2";
private static final String DIRECTOR = "director";
private static final String DESCRIPTION = "description";
private static final String TABLE_NAME = "FILMTABLE";
private static final String DATABASE_NAME = "filmdatabase3";
private static final int DATABASE_VERSION = 1;
private static final boolean FAVOURITE = false;
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
FILM + " TEXT NOT NULL, " +
ACTOR + " TEXT NOT NULL, " +
ACTOR2 + " TEXT NOT NULL, " +
DIRECTOR + " TEXT NOT NULL, " +
FAVOURITE + " BOOLEAN, " +
DESCRIPTION + " TEXT NOT NULL);"
);
Cursor countRows = db.rawQuery("SELECT count(*) FROM FILMTABLE", null);
countRows.moveToFirst();
int NumRows = countRows.getInt(0);
countRows.close();
if (NumRows == 0) {
ContentValues values = new ContentValues();
values.put("film", "Wolf of Wall Street");
values.put("actor", "Leonardo Dicaprio");
values.put("actor2", "Jonah Hill");
values.put("director", "Martin Scorses");
values.put("description", "Description");
db.insert("FILMTABLE", null, values);
values.clear();
values.put("film", "Captain Philips");
values.put("actor", "Tom Hanks");
values.put("actor2", "Catherine Keener");
values.put("director", "Paul Greengrass");
values.put("description", "Description");
db.insert("FILMTABLE", null, values);
values.clear();
}
}
The answer to this question lies in the use of ListViews (https://developer.android.com/reference/android/widget/ListView.html). Basically you should create an ArrayAdapter which takes in a List of FilmObjects you retrieve from the database. In this adapter you will define how you want this data shown for each row. When you attach the adapter to the listview Android will take care of the visualization of the each row.
This tutorial will definitely help:http://developer.android.com/guide/topics/ui/layout/listview.html
I would advice to get rid of the seperate Strings that make up a movie but instead make a class that contains all these fields. This allows for much easier data handling.

Database using Eclipse

I am making a login screen which is connected to the database shown below, I have the class called DatabaseHelper which contains all my tables and functions, and the main.java contains the codes below, and the register.java contains the following codes :
package DatabaseHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
//get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "ExpenseManager";
// Table Names
private static final String TABLE_user = "user";
private static final String TABLE_income = "income";
private static final String TABLE_store = "store";
// Common column names
private static final String KEY_ID = "uid";
// user Table - column names
public static final String KEY_username = "username";
public static final String KEY_password = "password";
private static final String KEY_email = "email";
private static final String KEY_url = "url";
private static final String KEY_amountalert = "amountalert";
private static final String KEY_currency = "currency";
// income Table - column names
private static final String KEY_IID = "iid";
private static final String KEY_INCOMEDATE = "Incomedate";
private static final String KEY_AMOUNT = "amount";
private static final String KEY_INCOMETYPE = "Incometype";
// store Table - column names
private static final String KEY_EID = "eid";
private static final String KEY_ITEM = "item";
private static final String KEY_PRICE = "price";
private static final String KEY_TYPE = "type";
private static final String KEY_DATE = "date";
private static final String KEY_PLACE = "place";
// Table Create Statements
// user table create statement
private static final String CREATE_TABLE_user = "CREATE TABLE "
+ TABLE_user + "(" + KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_username + " TEXT," + KEY_password + " TEXT," + KEY_email
+ " TEXT, " + KEY_url + " TEXT," + KEY_amountalert + " FLOAT,"
+ KEY_INCOMETYPE + " TEXT," + KEY_currency + " TEXT," + ")";
// income table create statement
private static final String CREATE_TABLE_income = "CREATE TABLE "
+ TABLE_income + "(" + KEY_IID + " INTEGER PRIMARY KEY,"
+ KEY_AMOUNT + " TEXT," + KEY_ID + " INTEGER," + KEY_INCOMEDATE
+ " DATETIME," + KEY_INCOMETYPE + " TEXT, " + "FOREIGN KEY ("
+ KEY_ID + ") REFERENCES TABLE_user(uid))";
// store table create statement
private static final String CREATE_TABLE_store = "CREATE TABLE "
+ TABLE_store + "(" + KEY_EID + " INTEGER PRIMARY KEY," + KEY_ITEM
+ " TEXT," + KEY_PRICE + " FLOAT," + KEY_TYPE + " TEXT, "
+ KEY_PLACE + " TEXT, " + KEY_DATE + " DATETIME, " + KEY_ID
+ " INTEGER," + "FOREIGN KEY (" + KEY_ID
+ ") REFERENCES TABLE_user(uid))";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// creating required tables
db.execSQL(CREATE_TABLE_user);
db.execSQL(CREATE_TABLE_income);
db.execSQL(CREATE_TABLE_store);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + TABLE_user);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_income);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_store);
// create new tables
onCreate(db);
}
public DatabaseHelper open() {
return this;
}
public void close() {
db.close();
}
public void Login(String username,String password){
ContentValues values = new ContentValues();
String un = (String) values.get(username);
String ps = (String) values.get(password);
db.close();
}
public void insertEntry(String username,String password, String email, String url, String amountAlert){
ContentValues values = new ContentValues();
// Assign values for each row.
values.put("KEY_username", username);
values.put("KEY_password",password);
values.put("KEY_email",email);
values.put(KEY_url, url);
values.put(KEY_amountalert, amountAlert);
// Insert the row into your table
db.insert(TABLE_user, null, values);
db.close();
}
}
package com.example.dailyexpensemanager;
import info.androidhive.sqlite.model.user;
public class Main extends Activity {
private EditText username;
private EditText password;
private TextView attempts;
private Button login;
int counter = 3;
private DatabaseHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
username = (EditText) findViewById(R.id.editText1);
password = (EditText) findViewById(R.id.editText2);
attempts = (TextView) findViewById(R.id.textView5);
attempts.setText(Integer.toString(counter));
login = (Button) findViewById(R.id.button1);
TextView registerScreen = (TextView) findViewById(R.id.sign);
final String getUsername=username.getText().toString();
final String getPassword=password.getText().toString();
// Listening to register new account link
registerScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Switching to Register screen
Intent i = new Intent(getApplicationContext(),RegisterActivity.class);
startActivity(i);
}
});
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dbHelper = new DatabaseHelper(getBaseContext());
dbHelper.open();
dbHelper.Login(getUsername, getPassword);
if ((getUsername.equals(DatabaseHelper.KEY_username)) && (getPassword.equals(DatabaseHelper.KEY_password))) {
Toast.makeText(getApplicationContext(),"Redirecting...",Toast.LENGTH_SHORT).show();
Intent in=new Intent(Main.this,home.class);
startActivity(in);
} else {
Toast.makeText(Main.this, "Login failed", Toast.LENGTH_SHORT).show();
attempts.setBackgroundColor(Color.RED); counter--;
attempts.setText(Integer.toString(counter));
if(counter==0){
login.setEnabled(false); }
}
dbHelper.close();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
package com.example.dailyexpensemanager;
public class RegisterActivity extends Activity {
private EditText username;
private EditText password;
private EditText passwordc;
private EditText email;
private EditText bank;
private EditText amount;
Button btnRegister;
DatabaseHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
//Fill the spin
String array_spinner[];
array_spinner = new String[3];
array_spinner[0] = "Lebanese Lira (L.L)";
array_spinner[1] = "Dollar ($)";
array_spinner[2] = "Euro (€)";
Spinner s = (Spinner) findViewById(R.id.spin);
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, array_spinner);
s.setAdapter(adapter);
//end spin filling
// Get References of Views
username=(EditText)findViewById(R.id.reg_fullname);
password=(EditText)findViewById(R.id.reg_password);
passwordc=(EditText)findViewById(R.id.reg_passwordc);
email=(EditText)findViewById(R.id.reg_email);
bank=(EditText)findViewById(R.id.bank);
amount=(EditText)findViewById(R.id.amount);
btnRegister=(Button)findViewById(R.id.btnRegister);
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String getUsername=username.getText().toString();
String getPassword=password.getText().toString();
String getconfirmPassword=passwordc.getText().toString();
String getEmail=email.getText().toString();
String getBank =bank.getText().toString();
String getAmount=amount.getText().toString();
dbHelper = new DatabaseHelper(getBaseContext());
dbHelper.open();
dbHelper.insertEntry(getUsername, getPassword, getEmail, getBank, getAmount);
// check if any of the fields are vacant
if(getUsername.equals("")||getPassword.equals("")||getconfirmPassword.equals("")||getEmail.equals("")
||getBank.equals("")||getAmount.equals(""))
{
Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if(!getPassword.equals(getconfirmPassword))
{
Toast.makeText(getApplicationContext(), "Password does not match", Toast.LENGTH_LONG).show();
return;
}
else
{
// Save the Data in Database
dbHelper.insertEntry(getUsername, getPassword, getEmail , getBank , getAmount );
Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show();
}
dbHelper.close();
}
});
}
}
When running the application, it runs normally, my problem is, when pressing on login or on register button, the application will stop unexpectally. Please I want a solution for this problem .
There's an error here:
KEY_currency + " TEXT," + ")";
Please remove the extra comma:
KEY_currency + " TEXT" + ")";
[EDIT]
Here's another error (it occurs twice in your code)
REFERENCES TABLE_user(uid))";
It should be
REFERENCES user(uid))";

Can't add more than one record, ID not autoincrimenting

I'm trying to add site details to a database and then after I insert a row, output the result to a TextView. The record is being inserted into the database because it's being shown in a TextView, however I can only insert one record and I'm not sure why. I'm been using the tutorial here and modifying it to meet my needs.
Here is my DBAdapter:
public class DBAdapter {
// ///////////////////////////////////////////////////////////////////
// Constants & Data
// ///////////////////////////////////////////////////////////////////
// For logging:
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_NAME = "name";
public static final String KEY_ADDRESS = "address";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_PORT = "port";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_ADDRESS = 2;
public static final int COL_USERNAME = 3;
public static final int COL_PASSWORD = 4;
public static final int COL_PORT = 5;
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_NAME,
KEY_ADDRESS, KEY_USERNAME, KEY_PASSWORD, KEY_PORT };
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "Sites";
public static final String DATABASE_TABLE = "SiteTable";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_SQL = "create table "
+ DATABASE_TABLE
+ " ("
+ KEY_ROWID
+ " integer primary key autoincrement, "
/*
* CHANGE 2:
*/
// TODO: Place your fields here!
// + KEY_{...} + " {type} not null"
// - Key is the column name you created above.
// - {type} is one of: text, integer, real, blob
// (http://www.sqlite.org/datatype3.html)
// - "not null" means it is a required field (must be given a
// value).
// NOTE: All must be comma separated (end of line!) Last one must
// have NO comma!!
+ KEY_NAME + " string not null, " + KEY_ADDRESS
+ " string not null, " + KEY_USERNAME + " string not null, "
+ KEY_PASSWORD + " string not null, " + KEY_PORT
+ " integer not null"
// Rest of creation:
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
// ///////////////////////////////////////////////////////////////////
// Public methods:
// ///////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String name, String address, String username,
String password, int port) {
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_ADDRESS, address);
initialValues.put(KEY_USERNAME, username);
initialValues.put(KEY_PASSWORD, password);
initialValues.put(KEY_PORT, port);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String name, String address,
String username, String password, String port) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, name);
newValues.put(KEY_ADDRESS, address);
newValues.put(KEY_USERNAME, username);
// newValues.put(KEY_PASSWORD, password);
// newValues.put(KEY_PORT, port);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
// ///////////////////////////////////////////////////////////////////
// Private Helper Classes:
// ///////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading. Used to
* handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version "
+ oldVersion + " to " + newVersion
+ ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
I'm querying the database here:
public class FTPConnector extends Activity {
DBAdapter myDb;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.ftp);
status = (TextView) findViewById(R.id.status);
editAddress = (EditText) findViewById(R.id.editAddress);
editUser = (EditText) findViewById(R.id.editUsername);
editPassword = (EditText) findViewById(R.id.editPassword);
addsiteBtn = (Button) findViewById(R.id.addsiteBtn);
addsiteBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
siteManager();
}
});
openDb();
}
private void openDb() {
myDb = new DBAdapter(this);
myDb.open();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
closeDb();
}
private void closeDb() {
myDb.close();
}
//Where the insertRecord() happens
public void siteManager() {
final AlertDialog customDialog = new AlertDialog.Builder(this).create();
LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.site_manager, null);
final EditText tmpname = (EditText) view
.findViewById(R.id.dialogsitename);
final EditText tmpaddress = (EditText) view
.findViewById(R.id.dialogaddress);
final EditText tmpuser = (EditText) view
.findViewById(R.id.dialogusername);
final EditText tmppass = (EditText) view
.findViewById(R.id.dialogpassword);
final EditText tmpport = (EditText) view.findViewById(R.id.dialogport);
final TextView tmpsites = (TextView) view.findViewById(R.id.textView6);
final CheckBox tmppassive = (CheckBox) view
.findViewById(R.id.dialogpassive);
final Button tmpclose = (Button) view.findViewById(R.id.closeBtn);
final Button tmptestBtn = (Button) view.findViewById(R.id.testBtn);
final Button tmpsavetsite = (Button) view.findViewById(R.id.saveSite);
customDialog.setView(tmpclose);
customDialog.setView(tmptestBtn);
customDialog.setView(tmpname);
customDialog.setView(tmpaddress);
customDialog.setView(tmpuser);
customDialog.setView(tmppass);
customDialog.setView(tmpport);
customDialog.setView(tmppassive);
customDialog.setView(tmpsavetsite);
customDialog.setView(tmpsites);
tmpclose.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
}
});
tmptestBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_name = tmpname.getText().toString();
_address = tmpaddress.getText().toString();
_user = tmpuser.getText().toString();
_pass = tmppass.getText().toString();
_port = Integer.parseInt(tmpport.getText().toString());
_passive = false;
if (tmppassive.isChecked()) {
_passive = true;
}
boolean status = ftpConnect(_address, _user, _pass, _port);
if (status == true) {
Toast.makeText(FTPConnector.this, "Connection Succesful",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(FTPConnector.this,
"Connection Failed:" + status, Toast.LENGTH_LONG)
.show();
}
}
});
tmpsavetsite.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
tmpsites.setText("");
String msg = "!";
_name = tmpname.getText().toString();
_address = tmpaddress.getText().toString();
_user = tmpuser.getText().toString();
_pass = tmppass.getText().toString();
_port = Integer.parseInt(tmpport.getText().toString());
long newId = myDb.insertRow(_name, _address, _user, _pass, 21);
Cursor c = myDb.getAllRows();
if (c.moveToFirst()) {
int id = c.getInt(0);
String _name = c.getString(1);
String _address = c.getString(2);
String _user = c.getString(3);
String _pass = c.getString(4);
int _port = c.getInt(5);
msg += "id=" + id + "\n";
msg += ", name=" + _name + "\n";
msg += ", address=" + _address + "\n";
msg += ", username=" + _user + "\n";
msg += ", password=" + _pass + "\n";
msg += ", port=" + _port + "\n";
while (c.moveToNext());
}
c.close();
// displayText(msg);
tmpsites.setText(msg);
}
});
customDialog.setView(view);
customDialog.show();
}
Why can't I add more than one record?
In here :
while (c.moveToNext()); //<<<
currently you are not using any loop like do-while for iterating through cursor(you forget to add do block with while). get all data from cursor as using for loop:
//more to the first row
c.moveToFirst();
//iterate over rows
for (int i = 0; i < c.getCount(); i++) {
// get all data here from current row..
//move to the next row
c.moveToNext();
}
//close the cursor
c.close();
and using do-while you can get all values from current row as:
c.moveToFirst(); //more to the first row
do {
// get all data here from current row..
} while (c.moveToNext());

Categories