Android: SQLite error in adding data - java

I'm working on a PiggyBank-like application wherein users can make wishlists of their wanted item and helps them save for that item. My app is still in prototype because i'm still learning android.
The problem i'm experiencing right now is every time i add a new data, it always returns false. Here's my code:
DatabaseHelper.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "people_table";
private static final String COL1 = "ID";
private static final String COL2 = "name";
private static final String COL3 = "price";
private static final String COL4 = "totalsavings";
private static final String COL5 = "duedate";
public DatabaseHelper(Context context) {
super(context, TABLE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL2 +" TEXT, " + COL3 + "TEXT, " + COL4 +"INTEGER)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
contentValues.put(COL3, item);
contentValues.put(COL4, item);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
/**
* Returns all the data from database
* #return
*/
public Cursor getData(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
/**
* Returns only the ID that matches the name passed in
* #param name
* #return
*/
public Cursor getItemID(String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT " + COL1 + " FROM " + TABLE_NAME +
" WHERE " + COL2 + " = '" + name + "'";
Cursor data = db.rawQuery(query, null);
return data;
}
/**
* Updates the name field
* #param newName
* #param id
* #param oldName
*/
public void updateName(String newName, int id, String oldName){
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE " + TABLE_NAME + " SET " + COL2 +
" = '" + newName + "' WHERE " + COL1 + " = '" + id + "'" +
" AND " + COL2 + " = '" + oldName + "'";
Log.d(TAG, "updateName: query: " + query);
Log.d(TAG, "updateName: Setting name to " + newName);
db.execSQL(query);
}
/**
* Delete from database
* #param id
* #param name
*/
public void deleteName(int id, String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + TABLE_NAME + " WHERE "
+ COL1 + " = '" + id + "'" +
" AND " + COL2 + " = '" + name + "'";
Log.d(TAG, "deleteName: query: " + query);
Log.d(TAG, "deleteName: Deleting " + name + " from database.");
db.execSQL(query);
}
}
MainActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
DatabaseHelper mDatabaseHelper;
private Button btnAdd, btnViewData;
private EditText editText, editText2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//for inputs
editText = (EditText) findViewById(R.id.editText);
editText2 =(EditText) findViewById(R.id.editText2);
//buttons
btnAdd = (Button) findViewById(R.id.btnAdd);
btnViewData = (Button) findViewById(R.id.btnView);
//call database
mDatabaseHelper = new DatabaseHelper(this);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = editText.getText().toString();
if (editText.length() != 0) {
AddData(newEntry);
editText.setText("");
} else {
toastMessage("You must put something in the text field!");
}
String newPriceEntry = editText2.getText().toString();
if (editText2.length() != 0) {
AddData(newPriceEntry);
editText2.setText("");
} else {
toastMessage("You must put something in the text field!");
}
}
});
btnViewData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ListDataActivity.class);
startActivity(intent);
}
});
}
public void AddData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
if (insertData) {
toastMessage("Data Successfully Inserted!");
} else {
toastMessage("Something went wrong");
}
}
/**
* customizable toast
* #param message
*/
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
ListDataActivity.java
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by User on 2/28/2017.
*/
public class ListDataActivity extends AppCompatActivity {
private static final String TAG = "ListDataActivity";
DatabaseHelper mDatabaseHelper;
private ListView mListView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_layout);
mListView = (ListView) findViewById(R.id.listView);
mDatabaseHelper = new DatabaseHelper(this);
populateListView();
}
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
//get the data and append to a list
Cursor data = mDatabaseHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()){
//get the value from the database in column 1
//then add it to the ArrayList
listData.add(data.getString(1));
}
//create the list adapter and set the adapter
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
mListView.setAdapter(adapter);
//set an onItemClickListener to the ListView
mListView.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 = mDatabaseHelper.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(ListDataActivity.this, EditDataActivity.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
startActivity(editScreenIntent);
}
else{
toastMessage("No ID associated with that name");
}
}
});
}
/**
* customizable toast
* #param message
*/
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
EditDataActivity.java
In this activity, the data will be displayed in an EditText (name), the savings goal (price). (I'm still working on the totalsavings).
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class EditDataActivity extends AppCompatActivity {
private static final String TAG = "EditDataActivity";
private TextView myGoal, mySavings;
private Button btnSave,btnDelete, btnDeposit;
private EditText editable_item, depositInput;
DatabaseHelper mDatabaseHelper;
private String selectedName, selectedPrice;
private int selectedID, selectedTotalSavings;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_data_layout);
myGoal = (TextView) findViewById(R.id.displayGoal);
mySavings = (TextView) findViewById(R.id.displayTotalSavings);
btnSave = (Button) findViewById(R.id.btnSave);
btnDelete = (Button) findViewById(R.id.btnDelete);
btnDeposit = (Button) findViewById(R.id.btnDeposit);
editable_item = (EditText) findViewById(R.id.editable_item);
mDatabaseHelper = new DatabaseHelper(this);
//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");
//now get the price we passed as an extra
selectedPrice = receivedIntent.getStringExtra("price");
//now we get the totalsavings we passed as an extra
selectedTotalSavings = receivedIntent.getIntExtra("totalsavings", -1);
//set the text to show the current selected name
editable_item.setText(selectedName);
//set the text to show the user's saving goal
myGoal.setText(selectedPrice);
//set text to show the user's total savings so far
mySavings.setText(selectedTotalSavings);
//-----------------------------------DIALOG BOX-----------------------------------------
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Enter Deposit");
builder.setMessage("Enter your deposit!");
depositInput= new EditText(this);
builder.setView(depositInput);
//SET POSITIVE BUTTON
builder.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String depositTxt=depositInput.getText().toString();
selectedTotalSavings = Integer.parseInt(selectedTotalSavings + depositTxt);
mySavings.setText(selectedTotalSavings);
Toast.makeText(getApplicationContext(),depositTxt, Toast.LENGTH_LONG).show();
}
});
//SET NEGATIVE BUTTON
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
//CREATE THE DIALOG
final AlertDialog depositPrompt=builder.create();
//--------------------------------------------------------------------------------------
//buttons
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String item = editable_item.getText().toString();
if(!item.equals("")){
mDatabaseHelper.updateName(item,selectedID,selectedName);
}else{
toastMessage("You must enter a name");
}
}
});
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDatabaseHelper.deleteName(selectedID,selectedName);
editable_item.setText("");
toastMessage("removed from database");
}
});
btnDeposit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0){
depositPrompt.show();
}
});
}
/**
* customizable toast
* #param message
*/
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
Here's the Sample Syntax
User enters details for name and price
User clicks add data
User can View Data and the data will be displayed on a ListView
User can edit and view data in the EditDataActivity
I'm not sure what the problem is.
UPDATE
so i found this code on the MainActivity Class. I'm trying to add the data from editText2 but i don't know how.
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = editText.getText().toString();
if (editText.length() != 0) {
AddData(newEntry);
editText.setText("");
} else {
toastMessage("You must put something in the text field!");
}
String newPriceEntry = editText2.getText().toString();
if (editText2.length() != 0) {
AddData(newPriceEntry);
editText2.setText("");
} else {
toastMessage("You must put something in the text field!");
}
}
});
btnViewData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ListDataActivity.class);
startActivity(intent);
}
});
}
public void AddData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
if (insertData) {
toastMessage("Data Successfully Inserted!");
} else {
toastMessage("Something went wrong");
}
}
Do i have to make a new AddData?

You need to insert the right type of values as mentioned below :
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
contentValues.put(COL3, item);
contentValues.put(COL4, item); // pass an integer instead of a String as you have mentioned its datatype as INTEGER or parse it using Integer.parseInt()
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}

The problem I think is in the CREATE TABLE query.
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + COL2 +" TEXT, " + COL3 + "TEXT, " + COL4 +"INTEGER)";
There is no space between COL3 and "TEXT" (same for COL4 and "INTEGER"). So just add a space like so.
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + COL2 +" TEXT, " + COL3 + " TEXT, " + COL4 +" INTEGER)";

Problem is in your addData() method. COL4 holds INTEGER value.
Try this:
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
contentValues.put(COL3, item);
contentValues.put(COL4, Integer.parseInt(item));
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}

The return of db.insert() is a long and you're comparing it to an int. Change
if (result == -1) {
return false;
} else {
return true;
}
To
return (int)result == -1;

Related

How to populate ListView with SQLite table where int value matches column in table

I am new to android development and can't get this to work. I am trying to populate a listview in my AdminActivity with the int value that I am passing from a previous list view. That int value then needs to be used to populate the ListView with the users that match the int value in the booking column of the users table.
Here is the DBHelper class:
package com.example.shashank.fffffffffffffffffffffffffff;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class DBHelper extends SQLiteOpenHelper {
public static final String DBNAME = "Login.db";
public static final String FLIGHTS = "FLIGHTS";
public static final String COLUMN_ID = "ID";
public static final String COLUMN_DESTINATION = "DESTINATION";
public static final String COLUMN_PRICE = "PRICE";
public static final String COLUMN_DEPARTURE_TIME = "DEPARTURE_TIME";
public static final String COLUMN_ARRIVAL_TIME = "ARRIVAL_TIME";
public static final String COLUMN_DURATION = "DURATION";
public static final String COLUMN_AVAILABLE_SEATS = "AVAILABLE_SEATS";
public static final String USERS = "users";
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
public static final String EMAIL = "email";
public static final String BALANCE = "balance";
public static final String BOOKING = "booking";
public DBHelper(Context context) {
super(context, "Login.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase MyDB) {
String createTable1 = ("create Table " + USERS + "(" + USERNAME + " TEXT primary key, " + PASSWORD + " TEXT, " + EMAIL + " TEXT UNIQUE, " + BALANCE + " REAL, " + BOOKING + " INTEGER)");
MyDB.execSQL(createTable1);
MyDB.execSQL("CREATE TABLE " + FLIGHTS + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_DESTINATION + " TEXT, " + COLUMN_PRICE + " REAL, " + COLUMN_DEPARTURE_TIME + " TEXT, " + COLUMN_ARRIVAL_TIME + " TEXT, " + COLUMN_DURATION + " TEXT, " + COLUMN_AVAILABLE_SEATS + " INTEGER)");
ContentValues insertValues = new ContentValues();
insertValues.put(COLUMN_DESTINATION, "Johannesburg");
insertValues.put(COLUMN_PRICE, 1200);
insertValues.put(COLUMN_DEPARTURE_TIME, "12:00");
insertValues.put(COLUMN_ARRIVAL_TIME, "14:15");
insertValues.put(COLUMN_DURATION, "2:15");
insertValues.put(COLUMN_AVAILABLE_SEATS, 10);
MyDB.insert(FLIGHTS, null, insertValues);
ContentValues insertValues2 = new ContentValues();
insertValues2.put(COLUMN_DESTINATION, "Johannesburg");
insertValues2.put(COLUMN_PRICE, 1000);
insertValues2.put(COLUMN_DEPARTURE_TIME, "16:00");
insertValues2.put(COLUMN_ARRIVAL_TIME, "18:15");
insertValues2.put(COLUMN_DURATION, "2:15");
insertValues2.put(COLUMN_AVAILABLE_SEATS, 22);
MyDB.insert(FLIGHTS, null, insertValues2);
ContentValues insertValues3 = new ContentValues();
insertValues3.put(COLUMN_DESTINATION, "Durban");
insertValues3.put(COLUMN_PRICE, 800);
insertValues3.put(COLUMN_DEPARTURE_TIME, "12:00");
insertValues3.put(COLUMN_ARRIVAL_TIME, "14:00");
insertValues3.put(COLUMN_DURATION, "2:00");
insertValues3.put(COLUMN_AVAILABLE_SEATS, 2);
MyDB.insert(FLIGHTS, null, insertValues3);
ContentValues insertValues4 = new ContentValues();
insertValues4.put(COLUMN_DESTINATION, "Port Elizabeth");
insertValues4.put(COLUMN_PRICE, 700);
insertValues4.put(COLUMN_DEPARTURE_TIME, "08:00");
insertValues4.put(COLUMN_ARRIVAL_TIME, "09:10");
insertValues4.put(COLUMN_DURATION, "1:10");
insertValues4.put(COLUMN_AVAILABLE_SEATS, 0);
MyDB.insert(FLIGHTS, null, insertValues4);
ContentValues insertValues5 = new ContentValues();
insertValues5.put(COLUMN_DESTINATION, "Port Elizabeth");
insertValues5.put(COLUMN_PRICE, 700);
insertValues5.put(COLUMN_DEPARTURE_TIME, "12:00");
insertValues5.put(COLUMN_ARRIVAL_TIME, "13:10");
insertValues5.put(COLUMN_DURATION, "1:10");
insertValues5.put(COLUMN_AVAILABLE_SEATS, 22);
MyDB.insert(FLIGHTS, null, insertValues5);
ContentValues insertValues6 = new ContentValues();
insertValues6.put(COLUMN_DESTINATION, "Durban");
insertValues6.put(COLUMN_PRICE, 900);
insertValues6.put(COLUMN_DEPARTURE_TIME, "14:00");
insertValues6.put(COLUMN_ARRIVAL_TIME, "16:00");
insertValues6.put(COLUMN_DURATION, "2:00");
insertValues6.put(COLUMN_AVAILABLE_SEATS, 11);
MyDB.insert(FLIGHTS, null, insertValues6);
}
#Override
public void onUpgrade(SQLiteDatabase MyDB, int i, int i1) {
MyDB.execSQL("drop Table if exists " + USERS);
MyDB.execSQL("drop Table if exists " + FLIGHTS);
onCreate(MyDB);
}
public Boolean insertData(String username, String password, String email, Double balance){
SQLiteDatabase MyDB = this.getWritableDatabase();
ContentValues contentValues= new ContentValues();
contentValues.put(USERNAME, username);
contentValues.put(PASSWORD, password);
contentValues.put(EMAIL, email);
contentValues.put(BALANCE, balance);
long result = MyDB.insert(USERS, null, contentValues);
if(result==-1) return false;
else
return true;
}
public Boolean checkusername(String username) {
SQLiteDatabase MyDB = this.getWritableDatabase();
Cursor cursor = MyDB.rawQuery("Select * from " + USERS + " where " + USERNAME + " = ?", new String[]{username});
if (cursor.getCount() > 0)
return true;
else
return false;
}
public Boolean checkusernamepassword(String username, String password){
SQLiteDatabase MyDB = this.getWritableDatabase();
Cursor cursor = MyDB.rawQuery("Select * from " + USERS + " where " + USERNAME + " = ? and " + PASSWORD + " = ?", new String[] {username,password});
if(cursor.getCount()>0)
return true;
else
return false;
}
public List<FlightsModel> getEveryone(){
List<FlightsModel> returnList = new ArrayList<>();
String queryString = "SELECT * FROM " + FLIGHTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(queryString, null);
if(cursor.moveToFirst()){
do {
int id = cursor.getInt(0);
String destination = cursor.getString(1);
double price = cursor.getDouble(2);
String departure = cursor.getString(3);
String arrival = cursor.getString(4);
String duration = cursor.getString(5);
int space = cursor.getInt(6);
FlightsModel newFlight = new FlightsModel(id, destination, price, departure, arrival, duration, space);
returnList.add(newFlight);
}while (cursor.moveToNext());
}
else{
}
cursor.close();
db.close();
return returnList;
}
#SuppressLint("Range") // suppress Bug/issue with getColumnIndex
public FlightsModel getFlightById(int id) {
FlightsModel rv;
SQLiteDatabase db = this.getWritableDatabase();
// Uses the query convenience method rather than raw query
Cursor csr = db.query(FLIGHTS,null,COLUMN_ID+"=?",new String[]{String.valueOf(id)},null,null,null);
if (csr.moveToFirst()) {
rv = new FlightsModel(
csr.getInt(csr.getColumnIndex(COLUMN_ID)),
csr.getString(csr.getColumnIndex(COLUMN_DESTINATION)),
csr.getDouble(csr.getColumnIndex(COLUMN_PRICE)),
csr.getString(csr.getColumnIndex(COLUMN_DEPARTURE_TIME)),
csr.getString(csr.getColumnIndex(COLUMN_ARRIVAL_TIME)),
csr.getString(csr.getColumnIndex(COLUMN_DURATION)),
csr.getInt(csr.getColumnIndex(COLUMN_AVAILABLE_SEATS))
);
} else {
rv = new FlightsModel();
}
csr.close();
// No need to close the database (inefficient to keep opening and closing db)
return rv;
}
#SuppressLint("Range")
public UsersModel getPasswordByName(String name){
UsersModel rv;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cr = db.query(USERS, null, USERNAME+"=?", new String[]{name}, null, null, null);
if (cr.moveToFirst()) {
rv = new UsersModel(
cr.getString(cr.getColumnIndex(USERNAME)),
cr.getString(cr.getColumnIndex(PASSWORD)),
cr.getString(cr.getColumnIndex(EMAIL)),
cr.getDouble(cr.getColumnIndex(BALANCE)),
cr.getInt(cr.getColumnIndex(BOOKING))
);
} else rv = new UsersModel();
cr.close();
return rv;
}
public int setBookingByUserName(int bookingAmount, String userName) {
ContentValues cv = new ContentValues();
cv.put(BOOKING,bookingAmount);
return this.getWritableDatabase().update(USERS,cv,USERNAME+"=?",new String[]{userName});
}
public double makingPayment(double balance, String userName){
ContentValues cv = new ContentValues();
cv.put(BALANCE,balance);
return this.getWritableDatabase().update(USERS,cv,USERNAME+"=?",new String[]{userName});
}
public int setAvailableSeatsAfterPayment(int seats, int flightID){
ContentValues cv = new ContentValues();
cv.put(COLUMN_AVAILABLE_SEATS,seats);
return this.getWritableDatabase().update(FLIGHTS,cv,COLUMN_ID+"=?",new String[]{String.valueOf(flightID)});
}
public int cancelBooking(int bookingAmount, String userName){
ContentValues cv = new ContentValues();
cv.put(BOOKING,bookingAmount);
return this.getWritableDatabase().update(USERS,cv,USERNAME+"=?",new String[]{String.valueOf(userName)});
}
#SuppressLint("Range")
public UsersModel getUsersModelByName(String userName) {
UsersModel rv = new UsersModel();
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(USERS,null,USERNAME+"=?", new String[]{userName},null,null,null);
if (csr.moveToFirst()) {
rv = new UsersModel(
csr.getString(csr.getColumnIndex(USERNAME)),
csr.getString(csr.getColumnIndex(PASSWORD)),
csr.getString(csr.getColumnIndex(EMAIL)),
csr.getDouble(csr.getColumnIndex(BALANCE)),
csr.getInt(csr.getColumnIndex(BOOKING))
);
}
csr.close();
return rv;
}
public boolean makeBooking(String userName, int bookingId) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(BOOKING,bookingId);
return db.update(USERS,cv,USERNAME + "=?", new String[]{userName}) > 0;
}
public String makeBookReceiptFile(String userName, Context context) {
String rcpts_directory = "receipts";
String rv = "";
SQLiteDatabase db = this.getWritableDatabase();
UsersModel currentUser = getUsersModelByName(userName);
FlightsModel currentFlightsModel = new FlightsModel();
if (currentUser.booking > 0) {
currentFlightsModel = getFlightById(currentUser.booking);
if (currentFlightsModel.getId() < 1) {
rv = "INVALID - unable to extract booking for id " + currentUser.booking;
}
} else {
rv = "INVALID - unable to extract user who's name is " + userName;
}
if (rv.length() > 0) return rv;
String rcpt_filename =
currentUser.getName() + "-" +
currentFlightsModel.getDestination() + "-" +
currentFlightsModel.getDeparture_time() + "-" +
currentFlightsModel.getArrival_time()
;
File rcpt = new File(context.getFilesDir().getPath() + File.separatorChar + rcpts_directory + File.separatorChar + rcpt_filename);
rcpt.getParentFile().mkdirs();
try {
FileWriter fw = new FileWriter(rcpt);
fw.write("Invoice for flight:" + "\n" +
"\n" + "-----------------------------------------------" +
"\n" + "User: " + userName +
"\n" + "Destination: " + currentFlightsModel.getDestination()+
"\n" + "Departure time at: " + currentFlightsModel.getDeparture_time() +
"\n" + "Arrival time at: " + currentFlightsModel.getArrival_time() +
"\n" + "Duration of flight: " + currentFlightsModel.getDuration() +
"\n" + "Amount paid: " + "R" + currentFlightsModel.getPrice()
);
fw.flush();
fw.close();
rv = rcpt.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
rv = "IOERROR - " + e.getMessage();
}
return rv;
}
}
Here is the usersmodel class:
package com.example.shashank.fffffffffffffffffffffffffff;
public class UsersModel {
private String name, password, email;
private double balance;
int booking;
public UsersModel(String name, String password, String email, double balance, int booking) {
this.name = name;
this.password = password;
this.email = email;
this.balance = balance;
this.booking = booking;
}
public UsersModel() {
}
public int getBooking() {
return booking;
}
public void setBooking(int booking) {
this.booking = booking;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
return "UsersModel{" +
"name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}
Here is the AdminActivity:
package com.example.shashank.fffffffffffffffffffffffffff;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;
public class AdminActivity extends AppCompatActivity {
ListView userList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
userList = findViewById(R.id.userList);
int intValue;
Intent mIntent = getIntent();
intValue = mIntent.getIntExtra("intVariableName", 0);
intValue = intValue + 1;
Toast.makeText(AdminActivity.this, Integer.toString(intValue), Toast.LENGTH_SHORT).show();
}
}
I want to use the intValue and populate the list with all the users where the intValue matches the int value in their booking column.
Any help will be appreciated thank you
First Add a method to DBHelper to get the list of users as a Cursor by the int (BOOKING) such as :-
public Cursor getUsersByBookingNumber(int bookingNumber) {
SQLiteDatabase MyDB = this.getWritableDatabase();
/* return cursor with ALL columns AND a column called _ID which has the rowid */
return MyDB.query(USERS, new String[]{"*","rowid AS " + BaseColumns._ID},BOOKING+"=?",new String[]{String.valueOf(bookingNumber)},null,null,null);
}
Note that Cursor Adapters MUST have a column name _id (BaseColumns._ID resolves to _id) so this is achieved by getting the rowid column AS _id.
A ListView requires an adapter, Cursor Adapters are designed for use with Cursors so SimpleCursorAdapter is used.
An adapter requires a layout that will be used to display each item in the list (an item can consist of multiple views). In this case the stock layout simple_list_item2 will be used (you would probably want to create your own layout). You setup the adapter and then tell the ListView what adapter to use.
All of the above is done in the respective activity. To demonstrate MainActivity has been used, it is :-
public class MainActivity extends AppCompatActivity {
DBHelper dbHelper;
Cursor userListViewCursor; /* The Cursor to be used for the ListView */
SimpleCursorAdapter sca; /* The adapter for the ListView */
ListView userListView; /* The ListView */
int currentBookingNumber; /* the int */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userListView = this.findViewById(R.id.activity_admin);
/* Prepare Database */
dbHelper = new DBHelper(this);
/* Add some test data */
dbHelper.insertData("Fred","password","fred#email",0.00);
dbHelper.insertData("Mary","password","mary#email",0.00);
dbHelper.insertData("Jane","password","jane#email",0.00);
dbHelper.insertData("Tom","password","tom#email",0.00);
dbHelper.insertData("Sue","password","sue#email",0.00);
dbHelper.insertData("Bob","password","bob#email",0.00);
dbHelper.makeBooking("Fred",1);
dbHelper.makeBooking("Mary",2);
dbHelper.makeBooking("Sue",3);
dbHelper.makeBooking("Jane",1);
dbHelper.makeBooking("Tom",2);
dbHelper.makeBooking("Bob",1);
currentBookingNumber = 1; /*(mimic getting the booking number)*/
/* setup the ListView as the adapter will be null */
setupOrRefreshLIstView(currentBookingNumber);
}
private void setupOrRefreshLIstView(int bookingNumber) {
userListViewCursor = dbHelper.getUsersByBookingNumber(bookingNumber);
if (sca == null) {
sca = new SimpleCursorAdapter(
this,
/* The layout for each item in the ListView */
android.R.layout.simple_list_item_2,
userListViewCursor,
/* Columns in the Cursors */
new String[]{DBHelper.USERNAME,DBHelper.EMAIL},
/* id of the View in the ListView's item layout that corresponds with the column in the Cursor*/
/* NOTE 1st column corresponds to first id and so on so :- */
/* USERNAME column value is placed into text1 View, EMAIl column into text2 */
/* simple list item has 2 TextViews with ids text1 and text2 */
new int[]{android.R.id.text1,android.R.id.text2},
0
);
/* Tie the adapter sca to the ListView userListView */
userListView.setAdapter(sca);
/* set listeners here if required e.g. */
userListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#SuppressLint("Range")
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l /* will be the value of _id column */) {
Toast.makeText(view.getContext(),
"You clicked on the row with _id " + l
+ " the user is " + userListViewCursor.getString(userListViewCursor.getColumnIndex(DBHelper.USERNAME))
+ " the email is " + userListViewCursor.getString(userListViewCursor.getColumnIndex(DBHelper.EMAIL))
/* even though balance etc is not shown as the values are in the cursor they can be retrieved */
+ " the balance is " + userListViewCursor.getDouble(userListViewCursor.getColumnIndex(DBHelper.BALANCE))
,
Toast.LENGTH_SHORT).show();
}
});
} else {
sca.swapCursor(userListViewCursor);
}
}
/* if the activity is resumed then refresh the ListView just in case the data has changed */
#Override
protected void onResume() {
super.onResume();
setupOrRefreshLIstView(currentBookingNumber);
}
#Override
protected void onDestroy() {
super.onDestroy();
userListViewCursor.close(); /*should always close a cursor when done with it */
}
}
Note that some testing data is generated and loaded to demonstrate.
An onItemClickListener has been added, this will toast the details of the clicked item.
Running the above results in :-

Using integer value to get SQLite database table row data of row index in order to display said data in textviews in new activity

I am trying to display my FLIGHTS table row data depending on the index in a activity using textviews. How do I get the index of the table row and display the table rows columns in textviews in an activity.
Here is my activity where I am trying to display the data in textviews:
package com.example.shashank.fffffffffffffffffffffffffff;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class BookingActivity extends AppCompatActivity {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking);
textView = findViewById(R.id.textView);
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0);
textView.setText(Integer.toString(intValue));
}
}
the intValue variable I am getting from another activity which represents the position being clicked on a listview.
I am then trying to use that variable to display the row index of the FLIGHTS table into textviews.
Here is my DBHelper class:
package com.example.shashank.fffffffffffffffffffffffffff;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class DBHelper extends SQLiteOpenHelper {
public static final String DBNAME = "Login.db";
public static final String FLIGHTS = "FLIGHTS";
public static final String COLUMN_ID = "ID";
public static final String COLUMN_DESTINATION = "DESTINATION";
public static final String COLUMN_PRICE = "PRICE";
public static final String COLUMN_DEPARTURE_TIME = "DEPARTURE_TIME";
public static final String COLUMN_ARRIVAL_TIME = "ARRIVAL_TIME";
public static final String COLUMN_DURATION = "DURATION";
public static final String COLUMN_AVAILABLE_SEATS = "AVAILABLE_SEATS";
public DBHelper(Context context) {
super(context, "Login.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase MyDB) {
String createTable1 = "create Table users(username TEXT primary key, password TEXT)";
MyDB.execSQL(createTable1);
MyDB.execSQL("CREATE TABLE " + FLIGHTS + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_DESTINATION + " TEXT, " + COLUMN_PRICE + " REAL, " + COLUMN_DEPARTURE_TIME + " TEXT, " + COLUMN_ARRIVAL_TIME + " TEXT, " + COLUMN_DURATION + " TEXT, " + COLUMN_AVAILABLE_SEATS + " INTEGER )");
ContentValues insertValues = new ContentValues();
insertValues.put(COLUMN_DESTINATION, "Cape Town");
insertValues.put(COLUMN_PRICE, 500);
insertValues.put(COLUMN_DEPARTURE_TIME, "1200");
insertValues.put(COLUMN_ARRIVAL_TIME, "1400");
insertValues.put(COLUMN_DURATION, "2");
insertValues.put(COLUMN_AVAILABLE_SEATS, 10);
MyDB.insert(FLIGHTS, null, insertValues);
ContentValues insertValues2 = new ContentValues();
insertValues2.put(COLUMN_DESTINATION, "Johannesburg");
insertValues2.put(COLUMN_PRICE, 1000);
insertValues2.put(COLUMN_DEPARTURE_TIME, "1400");
insertValues2.put(COLUMN_ARRIVAL_TIME, "1600");
insertValues2.put(COLUMN_DURATION, "2");
insertValues2.put(COLUMN_AVAILABLE_SEATS, 22);
MyDB.insert(FLIGHTS, null, insertValues2);
}
#Override
public void onUpgrade(SQLiteDatabase MyDB, int i, int i1) {
MyDB.execSQL("drop Table if exists users");
MyDB.execSQL("drop Table if exists " + FLIGHTS);
onCreate(MyDB);
}
public Boolean insertData(String username, String password){
SQLiteDatabase MyDB = this.getWritableDatabase();
ContentValues contentValues= new ContentValues();
contentValues.put("username", username);
contentValues.put("password", password);
long result = MyDB.insert("users", null, contentValues);
if(result==-1) return false;
else
return true;
}
public Boolean checkusername(String username) {
SQLiteDatabase MyDB = this.getWritableDatabase();
Cursor cursor = MyDB.rawQuery("Select * from users where username = ?", new String[]{username});
if (cursor.getCount() > 0)
return true;
else
return false;
}
public Boolean checkusernamepassword(String username, String password){
SQLiteDatabase MyDB = this.getWritableDatabase();
Cursor cursor = MyDB.rawQuery("Select * from users where username = ? and password = ?", new String[] {username,password});
if(cursor.getCount()>0)
return true;
else
return false;
}
public List<FlightsModel> getEveryone(){
List<FlightsModel> returnList = new ArrayList<>();
String queryString = "SELECT * FROM " + FLIGHTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(queryString, null);
if(cursor.moveToFirst()){
do {
int id = cursor.getInt(0);
String destination = cursor.getString(1);
double price = cursor.getDouble(2);
String departure = cursor.getString(3);
String arrival = cursor.getString(4);
String duration = cursor.getString(5);
int space = cursor.getInt(6);
FlightsModel newFlight = new FlightsModel(id, destination, price, departure, arrival, duration, space);
returnList.add(newFlight);
}while (cursor.moveToNext());
}
else{
}
cursor.close();
db.close();
return returnList;
}
}
add the following method to the DBHelper class
:-
#SuppressLint("Range") // suppress Bug/issue with getColumnIndex
public FlightsModel getFlightById(int id) {
FlightsModel rv;
SQLiteDatabase db = this.getWritableDatabase();
// Uses the query convenience method rather than raw query
Cursor csr = db.query(FLIGHTS,null,COLUMN_ID+"=?",new String[]{String.valueOf(id)},null,null,null);
if (csr.moveToFirst()) {
rv = new FlightsModel(
csr.getInt(csr.getColumnIndex(COLUMN_ID)),
csr.getString(csr.getColumnIndex(COLUMN_DESTINATION)),
csr.getDouble(csr.getColumnIndex(COLUMN_PRICE)),
csr.getString(csr.getColumnIndex(COLUMN_DEPARTURE_TIME)),
csr.getString(csr.getColumnIndex(COLUMN_ARRIVAL_TIME)),
csr.getString(csr.getColumnIndex(COLUMN_DURATION)),
csr.getInt(csr.getColumnIndex(COLUMN_AVAILABLE_SEATS))
);
} else {
rv = new FlightsModel();
}
csr.close();
// No need to close the database (inefficient to keep opening and clsoing db)
return rv;
}
note that getWritableDatabase has been used, it doesn't really matter which is used as getReadableDatabase will, unless the database can only be read, get a writeable database. i.e. getReadableDatabase will not protect against writes.
it is better to use getColumnIndex than hard code column indexes. Thus irrespective of the position of the column the column will be found, thus reducing potential maintenance issues.
Change the BookingActivity to retrieve the respective FlightsModel
:-
public class BookingActivity extends AppCompatActivity {
TextView textView;
DBHelper dbHelper; //<<<<< ADDED
FlightsModel flightsModel; //<<<<< ADDED
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking);
dbHelper = new DBHelper(this); //<<<<< ADDED
textView = findViewById(R.id.textView);
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0);
flightsModel = dbHelper.getFlightById(intValue); //<<<<< get the flightModel from the database
if (flightsModel.id > 1) {
// set the appropriate textviews
} else {
// do something here to indicate no FlightsModel found in database
}
textView.setText(Integer.toString(intValue));
}
}

How to skip "Email" in login form so i can login.There's "Email" in register form and database but i dont want to delete it

In android studio im using SQLite
There's username,email,password in Register form
But there's only username and password i want to input in Login Form
to make it login into layout activity_home in activity : HomeActivity.java
the error's in this code (need 3 string):
private void login(){
String username = etUsername.getText().toString();
String pass = etPass.getText().toString();
if(db.getUser(username,pass)){
session.setLoggedin(true);
startActivity(new Intent(LoginActivity.this, HomeActivity.class));
finish();
}else{
Toast.makeText(getApplicationContext(), "Wrong email/password",Toast.LENGTH_SHORT).show();
}
}
}
Full Code :
DBHelper.java
package com.demo.androidgudang;
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;
/**
* Created by Administrator on 5/5/2016.
*/
public class DbHelper extends SQLiteOpenHelper {
public static final String TAG = DbHelper.class.getSimpleName();
public static final String DB_NAME = "myapp.db";
public static final int DB_VERSION = 1;
public static final String USER_TABLE = "users";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_USERNAME = "username";
public static final String COLUMN_EMAIL = "email";
public static final String COLUMN_PASS = "password";
/*
create table users(
id integer primary key autoincrement,
email text,
password text);
*/
public static final String CREATE_TABLE_USERS = "CREATE TABLE " + USER_TABLE + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_USERNAME + " TEXT,"
+ COLUMN_EMAIL + " TEXT,"
+ COLUMN_PASS + " TEXT);";
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_USERS);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + USER_TABLE);
onCreate(db);
}
/**
* Storing user details in database
* */
public void addUser(String username, String email, String password) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_USERNAME, username);
values.put(COLUMN_EMAIL, email);
values.put(COLUMN_PASS, password);
long id = db.insert(USER_TABLE, null, values);
db.close();
Log.d(TAG, "user inserted" + id);
}
public boolean getUser(String username, String email, String pass){
//HashMap<String, String> user = new HashMap<String, String>();
String selectQuery = "select * from " + USER_TABLE + " where " +
COLUMN_USERNAME + " = " + "'"+username+"'" + " and " + COLUMN_EMAIL + " = " + "'"+email+"'" + " and " + COLUMN_PASS + " = " + "'"+pass+"'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
return true;
}
cursor.close();
db.close();
return false;
}
}
HomeActivity.java
package com.demo.androidgudang;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class HomeActivity extends AppCompatActivity {
private Button btnLogout;
private Session session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
session = new Session(this);
if(!session.loggedin()){
logout();
}
btnLogout = (Button)findViewById(R.id.btnLogout);
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logout();
}
});
}
private void logout(){
session.setLoggedin(false);
finish();
startActivity(new Intent(HomeActivity.this,LoginActivity.class));
}
}
Session.java
package com.demo.androidgudang;
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by Administrator on 5/5/2016.
*/
public class Session {
SharedPreferences prefs;
SharedPreferences.Editor editor;
Context ctx;
public Session(Context ctx){
this.ctx = ctx;
prefs = ctx.getSharedPreferences("myapp", Context.MODE_PRIVATE);
editor = prefs.edit();
}
public void setLoggedin(boolean logggedin){
editor.putBoolean("loggedInmode",logggedin);
editor.commit();
}
public boolean loggedin(){
return prefs.getBoolean("loggedInmode", false);
}
}
RegisterActivity.java
package com.demo.androidgudang;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{
TextView LoginDisini;
private Button reg;
private EditText etUsername, etEmail, etPass;
private DbHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
db = new DbHelper(this);
reg = (Button)findViewById(R.id.btnReg);
etUsername = (EditText)findViewById(R.id.etUsername);
etEmail = (EditText)findViewById(R.id.etEmail);
etPass = (EditText)findViewById(R.id.etPass);
reg.setOnClickListener(this);
LoginDisini = (TextView)findViewById(R.id.LoginDisini);
LoginDisini.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent loginHere = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(loginHere);
}
});
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnReg:
register();
break;
default:
}
}
private void register(){
String username = etUsername.getText().toString();
String email = etEmail.getText().toString();
String pass = etPass.getText().toString();
if(username.isEmpty() && email.isEmpty() && pass.isEmpty()){
displayToast("Username/password field empty");
}else{
db.addUser(username,email,pass);
displayToast("User registered");
finish();
}
}
private void displayToast(String message){
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
}
LoginActivity.java
package com.demo.androidgudang;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
private Button login;
private EditText etUsername, etPass;
private DbHelper db;
private Session session;
TextView RegisterDisini;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
db = new DbHelper(this);
session = new Session(this);
login = (Button)findViewById(R.id.btnLogin);
etUsername = (EditText)findViewById(R.id.etUsername);
etPass = (EditText)findViewById(R.id.etPass);
login.setOnClickListener(this);
RegisterDisini = (TextView) findViewById(R.id.RegisterDisini);
RegisterDisini.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent registerHere = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(registerHere);
}
});
if(session.loggedin()){
startActivity(new Intent(LoginActivity.this,HomeActivity.class));
finish();
}
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnLogin:
login();
break;
default:
}
}
private void login(){
String username = etUsername.getText().toString();
String pass = etPass.getText().toString();
if(db.getUser(username,pass)){
session.setLoggedin(true);
startActivity(new Intent(LoginActivity.this, HomeActivity.class));
finish();
}else{
Toast.makeText(getApplicationContext(), "Wrong email/password",Toast.LENGTH_SHORT).show();
}
}
}
In the getUser method, add a null check for the selectQuery variable. First append the username and the password. Next if the email is given, append it to your query like following:
String selectQuery = "select * from " + USER_TABLE + " where " +
COLUMN_USERNAME + " = " + "'"+username+"'" + " and " + COLUMN_PASS + " = " + "'"+pass+"'";
if(email != null)
selectQuery += "and " + COLUMN_EMAIL + " = " + "'"+email+"'";
Then you can call the getUser by db.getUser(username,null,pass).

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.

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