Android Studio Database Column Must be > 0 error - java

I'm working on an assignment for a college course. I'm really new to coding so I apologize if this is an obvious fix.
The assignment is:
Create an activity app with two forms. The main form should have a list view, an add button, an edit button, a view button, and a delete button. On the click of any button you should navigate the user to the second form that will be populated properly for the button action using data passed using an intent object. Your second form should be a layout to input a name and address. The form needs to contain First Name, Last Name, Street Address, Town, State, and Zip code. All your entry fields should be correctly labeled / Hinted so the user will know what to enter. In addition to the fields you will need an “OK”, "Cancel", and a “Clear” button. If the user clicks the “Clear” button you need to clear all the entries. If the user clicks the “OK” or “Cancel” buttons, you should return the button selection and form data to the main form using an intent object. The main activity should process the response and add, update, or delete the record. All records should be added, updated, or delete within a SQLite database that is automatically created by your application. Your program should generate an alert message that confirms the action completed.
I'm getting an error in the cursorToAddressAttributeGroup method saying that the value cursor.getColumnIndexshould be greater than 0. How do I set it to be greater than 0?
This is the class that is having the issue:
package com.example.program5;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.*;
import com.example.program5.AddressCollection.AddressCollectionDB;
public class AddressDatabaseHelper extends SQLiteOpenHelper
{
public static final String TABLE_ADDRESS = "address";
public static final String COLUMN_ID = "id";
public static final String COLUMN_FIRSTNAME = "firstName";
public static final String COLUMN_LASTNAME ="lastName";
public static final String COLUMN_STREET_ADDRESS = "streetAddress";
public static final String COLUMN_TOWN = "town";
public static final String COLUMN_STATE = "state";
public static final String COLUMN_ZIP ="zip";
private static final String DATABASE_NAME = "address.db";
private static final int DATABASE_VERSION = 1;
// Database creation SQL statement
private static final String DATABASE_CREATE_SQL = "create table "
+ TABLE_ADDRESS + "("
+ COLUMN_ID + " integer primary key autoincrement, "
+COLUMN_FIRSTNAME + " text not null, "
+COLUMN_LASTNAME + "text not null, "
+COLUMN_STREET_ADDRESS + "text not null, "
+COLUMN_TOWN + "text not null, "
+COLUMN_STATE + "text not null, "
+COLUMN_ZIP + "text not null);";
public AddressDatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//onCreate method creates table
#Override
public void onCreate(SQLiteDatabase database)
{
//directly executes SQl statement create table
database.execSQL(DATABASE_CREATE_SQL);
}
//onUpgrade method upgrades the table
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
//drops table if it exists
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ADDRESS);
//calls onCreate method and passes db as an argument
onCreate(db);
}
}
class AddressDataSource
{
private SQLiteDatabase database;
private final AddressDatabaseHelper dbHelper;
private String[] allColumns = { AddressDatabaseHelper.COLUMN_ID,
AddressDatabaseHelper.COLUMN_FIRSTNAME, AddressDatabaseHelper.COLUMN_LASTNAME,
AddressDatabaseHelper.COLUMN_STREET_ADDRESS, AddressDatabaseHelper.COLUMN_TOWN,
AddressDatabaseHelper.COLUMN_STATE, AddressDatabaseHelper.COLUMN_ZIP };
//AddressDataSource passes c as argument
public AddressDataSource(Context c)
{
super();
// dbHelper equals AddressDatabaseHelper passing c as parameter
dbHelper = new AddressDatabaseHelper(c);
}
//open method
public void open() throws SQLException {
//sets database equal to dbHelper.getWritableDatabase
database = dbHelper.getWritableDatabase();
}
//close method
public void close()
{
//closes dbHelper
dbHelper.close();
}
//createAddress method passes address as argument
public long createAddress(AddressAttributeGroup address)
{
//creates new ContentValues object called values
ContentValues values = new ContentValues();
//puts values of firstname and lastname into COLUMN_NAME
values.put(AddressDatabaseHelper.COLUMN_ID,address.id);
values.put(AddressDatabaseHelper.COLUMN_FIRSTNAME, address.firstName );
values.put(AddressDatabaseHelper.COLUMN_LASTNAME, address.lastName );
values.put(AddressDatabaseHelper.COLUMN_STREET_ADDRESS, address.streetAddress);
values.put(AddressDatabaseHelper.COLUMN_TOWN,
address.town);
values.put(AddressDatabaseHelper.COLUMN_STATE,address.state);
values.put(AddressDatabaseHelper.COLUMN_ZIP,address.zip);
/* returns insertId */
long insertId = database.insert(AddressDatabaseHelper.TABLE_ADDRESS,
null,
values);
return insertId;
// return database.insert(AddressDatabaseHelper.TABLE_ADDRESS,null,values);
}
//deleteAddress method passes address as argument
public void deleteAddress(AddressAttributeGroup address)
{ //sets id equal to address.id
long id = address.id;
//deletes the entry stored at address.id in the TABLE_ADDRESS table
database.delete(AddressDatabaseHelper.TABLE_ADDRESS,
AddressDatabaseHelper.COLUMN_ID + " = " + id, null);
}
//getAllAddresses method
public AddressCollectionDB getAllAddresses() throws Exception
{ AddressCollectionDB addresses = new AddressCollectionDB();
Cursor cursor = database.query(AddressDatabaseHelper.TABLE_ADDRESS,
allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast())
{
//adds address to addresses
addresses.addAddress(cursorToAddressAttributeGroup(cursor));
//and moves cursor to next entry
cursor.moveToNext();
}
//closes the cursor
cursor.close();
//returns addresses
return addresses;
}
private AddressAttributeGroup cursorToAddressAttributeGroup(Cursor cursor)
{
//error must be greater than 0. Figure out what is causing the error?
(cursor.getInt(cursor.getColumnIndex(AddressDatabaseHelper.COLUMN_ID)),
cursor.getString(cursor.getColumnIndex(AddressDatabaseHelper.COLUMN_FIRSTNAME)),
cursor.getString(cursor.getColumnIndex(AddressDatabaseHelper.COLUMN_LASTNAME)),
cursor.getString(cursor.getColumnIndex(AddressDatabaseHelper.COLUMN_STREET_ADDRESS)),
cursor.getString(cursor.getColumnIndex(AddressDatabaseHelper.COLUMN_TOWN)),
cursor.getString(cursor.getColumnIndex(AddressDatabaseHelper.COLUMN_STATE)),
cursor.getString(cursor.getColumnIndex(AddressDatabaseHelper.COLUMN_ZIP)));
}
}
Here are theother classes in the program for context:
AddressAttributeGroup Class:
package com.example.program5;
public class AddressAttributeGroup {
//declare Strings for name and address and a long for the id number
public long id;
public String firstName;
public String lastName;
public String streetAddress;
public String town;
public String state;
public String zip;
//constructor
public AddressAttributeGroup(long id, String firstName, String lastName, String streetAddress,
String town, String state, String zip) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.streetAddress = streetAddress;
this.town = town;
this.state = state;
this.zip = zip;
}
AddressCollection Class:
package com.example.program5;
import android.content.Context;
import java.util.ArrayList;
public class AddressCollection {
ArrayList<AddressAttributeGroup> addressList = new ArrayList<>();
final int MAXIMUM_ADDRESS_COUNT = 10;
//boolean that checks if amount of records in arrayList equal to or greater than limit
public boolean isAddressLimitReached()
{
return (addressList.size() >= MAXIMUM_ADDRESS_COUNT);
}
public int addAddress(AddressAttributeGroup address) throws Exception {
//if arrayList is full
if (isAddressLimitReached())
{
throw (new Exception("Maximum Address Reached."));
}
//adds new address to the arraylist addressList
addressList.add(address);
//returns the index of address
return addressList.indexOf(address);
}
public void setAddress(int addressIndex, AddressAttributeGroup address) {
addressList.set(addressIndex, address);
}
public void removeAddress(int addressIndex) {
//removes address at the index addressIndex
addressList.remove(addressIndex);
}
//
public AddressAttributeGroup getAddress(int addressIndex) {
return addressList.get(addressIndex);
}
static class AddressCollectionDB extends AddressCollection
{static public AddressDataSource addressData;
public static AddressCollectionDB AddressCollectionFactory(Context context)
{
AddressCollectionDB resultCode = new AddressCollectionDB();
addressData = new AddressDataSource(context);
try {
addressData.open();
resultCode = addressData.getAllAddresses();
addressData.close();
} catch (Exception e) {
e.printStackTrace();
}
return resultCode;
}
public int addAddress (AddressAttributeGroup address) throws Exception
{
if (isAddressLimitReached())
throw (new Exception("Maximum Address Reached."));
addressData.open();
address.id = addressData.createAddress(address);
addressData.close();
return super.addAddress(address);
}
public void setAddress ( int addressIndex, AddressAttributeGroup address)
{
addressData.open();
addressData.deleteAddress(getAddress(addressIndex));
address.id = addressData.createAddress(address);
addressData.close();
super.setAddress(addressIndex, address);
}
public void removeAddress ( int addressIndex)
{
addressData.open();
addressData.deleteAddress(getAddress(addressIndex));
addressData.close();
super.removeAddress(addressIndex);
}
}
}
AddressConsole class:
package com.example.program5;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.program5.StrongIntent.TypeOfAction;
import com.example.program5.AddressCollection.AddressCollectionDB;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class AddressConsole extends AppCompatActivity implements View.OnClickListener,
AdapterView.OnItemClickListener, AdapterView.OnItemSelectedListener {
Button cmdAdd;
Button cmdDelete;
Button cmdView;
Button cmdEdit;
TextView textAddressMessage;
EditText editRecordNumber;
ListView listOfAddresses;
final int ADDRESS_ENTRY = 1001;
AddressCollectionDB addresses;
//AddressCollection addresses = new AddressCollection();
AddressArrayAdapter addressAdapter;
int recordNumber = +1;
#Override
protected void onCreate(Bundle saveInstanceState)
{
super.onCreate(saveInstanceState);
setContentView(R.layout.address_console);
textAddressMessage = findViewById(R.id.textAddressMessage);
editRecordNumber = findViewById(R.id.editRecordNumber);
cmdAdd = findViewById(R.id.cmdAdd);
cmdAdd.setOnClickListener(this);
cmdEdit = findViewById(R.id.cmdEdit);
cmdEdit.setOnClickListener(this);
cmdDelete = findViewById(R.id.cmdDelete);
cmdDelete.setOnClickListener(this);
cmdView = findViewById(R.id.cmdView);
cmdView.setOnClickListener(this);
listOfAddresses = findViewById(R.id.listOfAddresses);
listOfAddresses.setOnItemClickListener (this);
listOfAddresses.setOnItemSelectedListener( this);
addresses = AddressCollectionDB.AddressCollectionFactory(this);
addressAdapter = new AddressArrayAdapter(this, R.layout.row_layout, addresses);
listOfAddresses.setAdapter(addressAdapter);
}
void displayError(Exception message) {
Toast.makeText(this,message.getMessage(),Toast.LENGTH_LONG).show();
}
void displayError(){
Toast.makeText(this, "Maximum Number Of Addresses Reached!",Toast.LENGTH_LONG).show();
}
void displayInfo(String message)
{
Toast.makeText(this, message,Toast.LENGTH_SHORT).show();
}
//hmm why is this never used?
void displayAddressMessage(AddressAttributeGroup address)
{//issue
textAddressMessage.setText("Address:" + address.firstName + " " + address.lastName + " " +
address.streetAddress + " "
+ address.town + "" + address.state + " " + address.zip);
}
void clearAddressMessage()
{
textAddressMessage.setText("");
}
#Override
public void onClick(View view) {
StrongIntent intent;
//if user clicks add button
if(cmdAdd.getId() == view.getId())
{
//if address limit has not been reached
if(!addresses.isAddressLimitReached())
{
//intent equals new Strong Intent
intent = new StrongIntent();
//intent action is equal to ADD
intent.action = TypeOfAction.ADD;
startActivityForResult(intent.getIntent(this, AddressEntry.class),ADDRESS_ENTRY);
}
//else
else
//calls display error message
displayError();
}
else
{
try {
{
AddressAttributeGroup address = addresses.getAddress(recordNumber);
//if user clicks edit
if(cmdEdit.getId() == view.getId())
{
//intent equals new StrongIntent passing address, typeOfAction and record number as arguments
intent = new StrongIntent(address,TypeOfAction.EDIT,recordNumber);
startActivityForResult(intent.getIntent(this,AddressEntry.class),ADDRESS_ENTRY);
}
//if user clicks delete button
if(cmdDelete.getId()==view.getId())
{
//intent equals StrongIntent passing address DELETE and record number as arguments
intent = new StrongIntent(address, TypeOfAction.DELETE,recordNumber);
startActivityForResult(intent.getIntent(this,AddressEntry.class),ADDRESS_ENTRY);
}
//if user clicks view
if(cmdView.getId() == view.getId())
{
//calls displayAddressMessage and passes address as an argument
displayAddressMessage(address);
}
}
//catch block
} catch (Exception ex) {
displayError(ex);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
StrongIntent addressIntent = new StrongIntent(data);
if (requestCode == ADDRESS_ENTRY) {
try {
//switch statement passes resultCode as argument
switch (resultCode) {
case RESULT_OK:
AddressAttributeGroup address = new AddressAttributeGroup(addressIntent.addressIndex,addressIntent.firstName, addressIntent.lastName,
addressIntent.streetAddress, addressIntent.town, addressIntent.state, addressIntent.zip);
switch (addressIntent.action) {
case ADD:
addresses.addAddress(address);
displayAddressMessage(address);
displayInfo("Added + Address:" + address.firstName + " " + address.lastName + " " + address.streetAddress + " "
+ address.town + "" + address.state + " " + address.zip);
break;
case DELETE:
addresses.removeAddress(addressIntent.addressIndex);
displayInfo("Address Deleted");
clearAddressMessage();
editRecordNumber.setText("");
recordNumber =-1;
break;
case EDIT:
addresses.setAddress(addressIntent.addressIndex,address);
displayAddressMessage(address);
displayInfo("Address Updated");
break;
}
addressAdapter.notifyDataSetChanged();
break;
case RESULT_CANCELED:
displayInfo("Cancelled");
break;
}
}
//catch block
catch(Exception ex)
{
displayError(ex);
}
}
super.onActivityResult(requestCode,resultCode,data);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
onItemSelected(parent, view, position,id);
AddressAttributeGroup address = addresses.getAddress(recordNumber);
displayAddressMessage(address);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
recordNumber = position;
editRecordNumber.setText(String.valueOf(recordNumber));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
class AddressArrayAdapter extends ArrayAdapter<AddressAttributeGroup> {
private final Context context;
private final AddressCollection addresses;
public AddressArrayAdapter(Context context, int resource, AddressCollection addresses) {
super(context, resource, addresses.addressList);
this.context = context;
this.addresses = addresses;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
AddressAttributeGroup address = addresses.getAddress(position);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView;
rowView = inflater.inflate(R.layout.row_layout, parent, false);
TextView firstNameTextView = rowView.findViewById(R.id.editFirstName);
TextView lastNameTextView = rowView.findViewById(R.id.editLastName);
TextView addressTextView = rowView.findViewById(R.id.editStreetAddress);
TextView townTextView;
townTextView = rowView.findViewById(R.id.editTown);
TextView stateTextView = rowView.findViewById(R.id.editState);
TextView zipTextView = rowView.findViewById(R.id.editZip);
firstNameTextView.setText(address.firstName);
lastNameTextView.setText(address.lastName);
addressTextView.setText(address.streetAddress);
townTextView.setText(address.town);
stateTextView.setText(address.state);
zipTextView.setText(address.zip);
return rowView;
}
}
}
Strong Intent Class:
package com.example.program5;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class StrongIntent
{
public String firstName;
public String lastName;
public String streetAddress;
public String town;
public String state;
public String zip;
public enum TypeOfAction
{
ADD,
EDIT,
DELETE
}
TypeOfAction action;
int addressIndex = +1;
Intent intent;
public StrongIntent(Intent intent)
{
Bundle bundle = intent.getExtras();
//try/catch block for retrieving key value pairs for intent bundle
try
{
firstName = bundle.getString("firstName");
lastName = bundle.getString("lastName");
streetAddress = bundle.getString("streetAddress");
town = bundle.getString("town");
state = bundle.getString("state");
zip = bundle.getString("zip");
//retrieves the action type chosen
action = TypeOfAction.values()[bundle.getInt("action",0)];
//gets address index
addressIndex = bundle.getInt("addressIndex");
}
//catch block
catch (Exception ex) {
ex.printStackTrace();
}
}
//constructor
public StrongIntent()
{ firstName = "";
lastName = "";
streetAddress = "";
town = "";
state= "";
zip = "";
}
//constructor which passes addressAttributes, action and addressIndex as arguments
public StrongIntent(AddressAttributeGroup addressAttributes, TypeOfAction action, int addressIndex)
{
firstName = addressAttributes.firstName;
lastName = addressAttributes.lastName;
streetAddress = addressAttributes.streetAddress;
town = addressAttributes.town;
state= addressAttributes.state;
zip = addressAttributes.zip;
this.action = action;
this.addressIndex = addressIndex;
}
//sets intent equal to null
public void clearIntent()
{
intent = null;
}
//adds data to intent bundle
void putExtras()
{
intent.putExtra("firstName",firstName);
intent.putExtra("lastName",lastName);
intent.putExtra("streetAddress",streetAddress);
intent.putExtra("town",town);
intent.putExtra("state",state);
intent.putExtra("zip",zip);
intent.putExtra("action",action.ordinal());
intent.putExtra("addressIndex",addressIndex);
}
public Intent getIntent()
{ //if intent is equal to null
if (intent == null)
//sets intent equal to new Intent
{ intent = new Intent();
//calls putExtras method
putExtras();
}
//returns intent
return intent;
}
public Intent getIntent(Activity addressEntry,
Class<AddressEntry> class1)
{
//if intent is equal to null
if (intent == null)
{
intent = new Intent(addressEntry,class1);
//calls putExtras method
putExtras();
}
//returns intent
return intent;
}
}
AddressEntry Class:
package com.example.program5;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class AddressEntry extends Activity implements View.OnClickListener{
Button cmdSave;
Button cmdClear;
Button cmdCancel;
EditText editFirstName;
EditText editLastName;
EditText editStreetAddress;
EditText editTown;
EditText editState;
EditText editZip;
int result;
StrongIntent stIntent;
#Override
public void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.address_entry);
editFirstName = findViewById(R.id.editFirstName);
editLastName = findViewById(R.id.editLastName);
editStreetAddress = findViewById(R.id.editStreetAddress) ;
editTown = findViewById(R.id.editTown);
editState = findViewById(R.id.editState);
editZip = findViewById(R.id.editZip);
cmdSave = findViewById(R.id.cmdSave);
cmdSave.setOnClickListener(this);
cmdClear = findViewById(R.id.cmdClear);
cmdClear.setOnClickListener(this);
cmdCancel = findViewById(R.id.cmdCancel);
cmdCancel.setOnClickListener(this);
stIntent = new StrongIntent(getIntent());
editFirstName.setText(stIntent.firstName);
editLastName.setText(stIntent.lastName);
editStreetAddress.setText(stIntent.streetAddress);
editTown.setText(stIntent.town);
editState.setText(stIntent.state);
editZip.setText(stIntent.zip);
//if the type of action is equal to DELETE
if (stIntent.action ==StrongIntent.TypeOfAction.DELETE)
//if user clicks Save sets text to Delete
cmdSave.setText(R.string.deleteString);
//enables action when delete is not selected
editFirstName.setEnabled(stIntent.action!=StrongIntent.TypeOfAction.DELETE);
editLastName.setEnabled(stIntent.action!=StrongIntent.TypeOfAction.DELETE);
editStreetAddress.setEnabled(stIntent.action != StrongIntent.TypeOfAction.DELETE);
editTown.setEnabled(stIntent.action != StrongIntent.TypeOfAction.DELETE);
editState.setEnabled(stIntent.action != StrongIntent.TypeOfAction.DELETE);
editZip.setEnabled(stIntent.action != StrongIntent.TypeOfAction.DELETE);
cmdClear.setEnabled(stIntent.action!=StrongIntent.TypeOfAction.DELETE);
}
#Override
public void onClick(View view)
{
//if Save is clicked
if(cmdSave.getId() == view.getId())
{
//result equals RESULT_OK
result = RESULT_OK;
//calls the finish method
finish();
}
//if Clear is clicked
if(cmdClear.getId() == view.getId())
//clears all values entered
{ editFirstName.setText("");
editLastName.setText("");
editStreetAddress.setText("");
editTown.setText("");
editState.setText("");
editZip.setText("");
}//if Cancel is clicked
if(cmdCancel.getId() == view.getId())
{ //result is equal to RESULT_CANCELED
result = RESULT_CANCELED;
//calls finish method
finish();
}
}
#Override
public void finish()
{ //clears intent
stIntent.clearIntent();
//sets firstName equal to editFirstName
stIntent.firstName= editFirstName.getText().toString();
//sets lastName equal to editLastName
stIntent.lastName = editLastName.getText().toString();
//sets streetAddress equal to editStreetAddress
stIntent.streetAddress =editStreetAddress.getText().toString();
//sets town equal to editTown
stIntent.town = editTown.getText().toString();
//sets state equal to editState
stIntent.state = editState.getText().toString();
//sets zip equal to editZip
stIntent.zip = editZip.getText().toString();
//sets result passing result and the intent as arguments
setResult(result, stIntent.getIntent());
//calls super.finish method
super.finish();
}
}

I believe that the cause is an issue with SDK 31.
The options to circumvent this is to do one of the following:-
Change to use SDK 30 in the build gradle.
Use #SuppressLint("Range") on the line before private AddressAttributeGroup cursorToAddressAttributeGroup(Cursor cursor)
Use getColumnIndexOrThrow instead of getColumnIndex
get the index prior to the get????
e.g.
int idx = cursor.getColumnIndex(AddressDatabaseHelper.COLUMN_ID);
cursor.getInt(idx);
You should also change :
// Database creation SQL statement
private static final String DATABASE_CREATE_SQL = "create table "
+ TABLE_ADDRESS + "("
+ COLUMN_ID + " integer primary key autoincrement, "
+COLUMN_FIRSTNAME + " text not null, "
+COLUMN_LASTNAME + "text not null, "
+COLUMN_STREET_ADDRESS + "text not null, "
+COLUMN_TOWN + "text not null, "
+COLUMN_STATE + "text not null, "
+COLUMN_ZIP + "text not null);";
to :-
// Database creation SQL statement
private static final String DATABASE_CREATE_SQL = "create table "
+ TABLE_ADDRESS + "("
+ COLUMN_ID + " integer primary key autoincrement, "
+COLUMN_FIRSTNAME + " text not null, "
+COLUMN_LASTNAME + " text not null, "
+COLUMN_STREET_ADDRESS + "text not null, " //<<<<< ADDED SPACE
+COLUMN_TOWN + " text not null, " //<<<<< ADDED SPACE
+COLUMN_STATE + " text not null, " //<<<<< ADDED SPACE
+COLUMN_ZIP + " text not null);"; //<<<<< ADDED SPACE
As otherwise the column names (those commented with //<<<<< ADDED SPACE) will be the expected column name suffixed with text and would then result in -1 being returned and a resultant column index error when run. e.g. Instead of lastname the column name would be lastnametext

Related

Creating a putExtra to another class won't work

So I am trying to pass data from my HomePage.class(my main activity) to my ContactHelper class but it just seems to crash.
This is the code that crashes the app:
Context context = view.getContext();
Intent i = new Intent(context, ContactHelper.class);
i.putExtra("name", displayName);
i.putExtra("phone", phone);
i.putExtra("email", contactEmail);
i.putExtra("amount", Amount);
i.putExtra("curDate", CurDate);
i.putExtra("dueDate", DueDate);
i.putExtra("curTime", TimeCur);
i.putExtra("timeDue", TimeDue);
//on below line we are starting a new activity,
context.startActivity(i);
Which is inside my getContacts function:
#SuppressLint("Range")
private void getContacts(View view) {
// this method is use to read contact from users device.
// on below line we are creating a string variables for
// our contact id and display name.
String contactId = "";
String displayName = "";
String phone = "";
String contactEmail = "";
String Amount = "0";
String CurDate = "11111111";
String DueDate = "99999999";
String TimeCur = "0";
String TimeDue = "0";
// on below line we are calling our content resolver for getting contacts
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
// on blow line we are checking the count for our cursor.
if (cursor.getCount() > 0) {
// if the count is greater than 0 then we are running a loop to move our cursor to next.
while (cursor.moveToNext()) {
// on below line we are getting the phone number.
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
// we are checking if the has phone number is > 0
// on below line we are getting our contact id and user name for that contact
contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// on below line we are calling a content resolver and making a query
Cursor phoneCursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{contactId},
null);
// on below line we are moving our cursor to next position.
if (phoneCursor.moveToNext()) {
// on below line we are getting the phone number for our users and then adding the name along with phone number in array list.
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactsModalArrayList.add(new ContactsModal(displayName, phoneNumber));
}
// on below line we are closing our phone cursor.
phoneCursor.close();
}
}
Context context = view.getContext();
Intent i = new Intent(context, ContactHelper.class);
i.putExtra("name", displayName);
i.putExtra("phone", phone);
i.putExtra("email", contactEmail);
i.putExtra("amount", Amount);
i.putExtra("curDate", CurDate);
i.putExtra("dueDate", DueDate);
i.putExtra("curTime", TimeCur);
i.putExtra("timeDue", TimeDue);
//on below line we are starting a new activity,
context.startActivity(i);
}
// on below line we are closing our cursor.
cursor.close();
// on below line we are hiding our progress bar and notifying our adapter class.
loadingPB.setVisibility(View.GONE);
contactRVAdapter.notifyDataSetChanged();
}
I am trying to pass the intent to the class below to a function named getContactInfo:
package com.example.myan;
import android.app.AlertDialog;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.provider.ContactsContract.RawContacts;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class ContactHelper extends AppCompatActivity {
static Context context;
static String number;
static String newName;
static String newNumber;
public static Cursor getContactCursor(ContentResolver contactHelper,
String startsWith) {
String[] projection = { ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER };
Cursor cur = null;
try {
if (startsWith != null && !startsWith.equals("")) {
cur = contactHelper.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " like \"" + startsWith + "%\"", null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " ASC");
} else {
cur = contactHelper.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, null, null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " ASC");
}
cur.moveToFirst();
} catch (Exception e) {
e.printStackTrace();
}
return cur;
}
public void getContactInfo(View view) {
Intent intent = getIntent();
String getName = intent.getStringExtra("name");
String getPhone = intent.getStringExtra("phone");
String getEmail = intent.getStringExtra("email");
String getAmount = intent.getStringExtra("amount");
String getCurDate = intent.getStringExtra("curDate");
String getDueDate = intent.getStringExtra("dueDate");
String getCurTime = intent.getStringExtra("curTime");
String getTimeDue = intent.getStringExtra("timeDue");
Integer getFirstDate4thValue = Integer.valueOf(String.valueOf(intent.getStringExtra(getCurDate).charAt(3)));
Integer getFirstDate3rdValue = Integer.valueOf(String.valueOf(intent.getStringExtra(getCurDate).charAt(2)));
String getFirstDateNumber = String.valueOf(getFirstDate3rdValue) + String.valueOf(getFirstDate4thValue);
Integer getSecondDate4thValue = Integer.valueOf(String.valueOf(intent.getStringExtra(getDueDate).charAt(3)));
Integer getSecondDate3rdValue = Integer.valueOf(String.valueOf(intent.getStringExtra(getDueDate).charAt(2)));
String getSecondDateNumber = String.valueOf(getSecondDate3rdValue) + String.valueOf(getSecondDate4thValue);
if (Integer.valueOf(String.valueOf(intent.getStringExtra(getAmount))) > 0) {
view.findViewById(R.id.txtfront).setVisibility(View.VISIBLE);
}
if (Integer.valueOf(String.valueOf(intent.getStringExtra(getAmount))) == 0) {
view.findViewById(R.id.txtfront).setVisibility(View.GONE);
}
if (Integer.valueOf(getFirstDateNumber) != Integer.valueOf(getSecondDateNumber)) {
view.findViewById(R.id.txtDueToday).setVisibility(View.GONE);
}
if (Integer.valueOf(getFirstDateNumber) == Integer.valueOf(getSecondDateNumber)) {
view.findViewById(R.id.txtLate).setVisibility(View.GONE);
view.findViewById(R.id.txtDueToday).setVisibility(View.VISIBLE);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setMessage(intent.getStringExtra(getName) + " owes you $" + intent.getStringExtra(getAmount) + ".00 today at " + intent.getStringExtra(getTimeDue) + " O'Clock.");
alertDialogBuilder.setIcon(R.drawable.ic_launcher_background);
alertDialogBuilder.setTitle("MYAN");
alertDialogBuilder.setNegativeButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
if (Integer.valueOf(getFirstDateNumber) > Integer.valueOf(getSecondDateNumber)) {
view.findViewById(R.id.txtLate).setVisibility(View.VISIBLE);
view.findViewById(R.id.txtDueToday).setVisibility(View.GONE);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setMessage(intent.getStringExtra(getName) + " is late and has owed you on " + intent.getStringExtra(getDueDate) + " and owes you $" + intent.getStringExtra(getAmount) + ".00");
alertDialogBuilder.setIcon(R.drawable.myanlogo);
alertDialogBuilder.setTitle("MYAN");
alertDialogBuilder.setNegativeButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
if (Integer.valueOf(getFirstDateNumber) < Integer.valueOf(getSecondDateNumber)) {
view.findViewById(R.id.txtLate).setVisibility(View.GONE);
}
}
public static long getContactID(ContentResolver contactHelper,
String phone) {
Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phone));
String[] projection = { PhoneLookup._ID };
Cursor cursor = null;
try {
cursor = contactHelper.query(contactUri, projection, null, null,
null);
if (cursor.moveToFirst()) {
int personID = cursor.getColumnIndex(PhoneLookup._ID);
return cursor.getLong(personID);
}
return -1;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
cursor = null;
}
}
return -1;
}
public static void deleteContact(ContentResolver contactHelper,
String number) {
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
String[] args = new String[] { String.valueOf(getContactID(
contactHelper, number)) };
ops.add(ContentProviderOperation.newDelete(RawContacts.CONTENT_URI)
.withSelection(RawContacts.CONTACT_ID + "=?", args).build());
try {
contactHelper.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}
}
}
Why would it be crashing?
My ultimate goal here is to have objects in my ContactsRVAdapter to become visible and not visible, and also text change, like current date and time.
[This is the FloatingActionButton which I am trying to manipulate][1]
Which is in a RecyclerView
But I cant seem to reach the items in my FloatingActionButton(ContactsRVAdapter) in any way.
Here is my ContactsRVAdapter class:
package com.example.myan;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import java.net.URISyntaxException;
import java.util.ArrayList;
class ContactRVAdapter extends RecyclerView.Adapter<ContactRVAdapter.ViewHolder> {
public static final String CHANNEL_1="CHANNEL1";
// creating variables for context and array list.
private Context context;
private ArrayList<ContactsModal> contactsModalArrayList;
private ContentResolver contactHelper;
private String number;
private TextView contactLate;
private View view;
private Intent intent;
// creating a constructor
public ContactRVAdapter(Context context, ArrayList<ContactsModal> contactsModalArrayList) {
this.context = context;
this.contactsModalArrayList = contactsModalArrayList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
// passing our layout file for displaying our card item
try {
return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.contacts_rv_item, parent, false));
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
// below method is use for filtering data in our array list
public void filterList(ArrayList<ContactsModal> filterlist) {
// on below line we are passing filtered
// array list in our original array list
contactsModalArrayList = filterlist;
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
// getting data from array list in our modal.
ContactsModal modal = contactsModalArrayList.get(position);
// on below line we are setting data to our text view.
holder.contactTV.setText(modal.getUserName());
ColorGenerator generator = ColorGenerator.MATERIAL; // or use DEFAULT
// generate random color
int color = generator.getRandomColor();
// below text drawable is a circular.
TextDrawable drawable2 = TextDrawable.builder().beginConfig()
.width(100) // width in px
.height(100) // height in px
.endConfig()
// as we are building a circular drawable
// we are calling a build round method.
// in that method we are passing our text and color.
.buildRound(modal.getUserName().substring(0, 1), color);
// setting image to our image view on below line.
holder.contactIV.setImageDrawable(drawable2);
// on below line we are adding on click listener to our item of recycler view.
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// on below line we are opening a new activity and passing data to it.
Intent i = new Intent(context, ContactDetailActivity.class);
i.putExtra("name", modal.getUserName());
i.putExtra("contact", modal.getContactNumber());
//on below line we are starting a new activity,
context.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return contactsModalArrayList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public ImageView contactLate;
public ImageView txtFront;
// on below line creating a variable
// for our image view and text view.
private ImageView contactIV;
private TextView contactTV;
private ImageView btnDeleteContact;
private ImageView textDueToday;
private Intent intent;
private String getName;
private String getPhone;
private String getEmail;
private String getAmount;
private String getCurDate;
private String getDateDue;
private String getCurTime;
private String getDueTime;
public ViewHolder(#NonNull View itemView) throws URISyntaxException {
super(itemView);
// initializing our image view and text view.
contactIV = itemView.findViewById(R.id.idIVContact);
contactTV = itemView.findViewById(R.id.idTVContactName);
//contactLate = itemView.findViewById(R.id.txtLate);
//txtFront = itemView.findViewById(R.id.txtfront);
//textDueToday = itemView.findViewById(R.id.txtDueToday);
}
}
}
So all I am trying to do is make it to where I can manipulate the objects inside ContactsRVAdapter class which is a Floating action button.
And my Logcat
FATAL EXCEPTION: main
Process: com.example.myan, PID: 1719
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myan/com.example.myan.HomePage}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.view.View.getContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3645)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3782)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:101)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2307)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7872)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.view.View.getContext()' on a null object reference
at com.example.myan.HomePage.getContacts(HomePage.java:286)
at com.example.myan.HomePage.access$200(HomePage.java:39)
at com.example.myan.HomePage$4.onPermissionsChecked(HomePage.java:159)
at com.karumi.dexter.DexterInstance$1.run(Unknown Source:43)
at com.karumi.dexter.MainThread.execute(Unknown Source:6)
at com.karumi.dexter.DexterInstance.checkMultiplePermissions(Unknown Source:71)
at com.karumi.dexter.DexterInstance.checkPermissions(Unknown Source:0)
at com.karumi.dexter.Dexter.check(Unknown Source:10)
at com.example.myan.HomePage.requestPermissions(HomePage.java:187)
at com.example.myan.HomePage.onCreate(HomePage.java:69)
at android.app.Activity.performCreate(Activity.java:8305)
at android.app.Activity.performCreate(Activity.java:8284)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1417)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3626)
try this code...
Intent i = new Intent(this, ContactHelper.class);
The crash is in your view. You are passing view of an activity, which doesn't exist or has been finished.
Context context = view.getContext();
In this function, pass context of existing activity.
private void getContacts(View view) {
...
}
Check the datatypes of the data that you are parsing in Another activities. It should be parcelable or serializable.

Android Studio: Database search functions fine but unable to display all records via button

Much like the title says. I have followed my class tutorials but chunks seem to be missing and it gets a bit confusing flicking between video lectures and pdf's when you're not too well versed in such.
When the app is executed the user can search for a song by year, or display all records within the database. However, originally all records would display from clicking the search by year button instead of the display all button. The search function works as intended but the display all button I cannot seem to figure out, despite following my lecturer's tutorials.
The first section of code is "MainActivity.java" and the second is "OpenDatabse.java"
package com.example.dbcopyexample1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MainActivity extends AppCompatActivity
{
private static String DATABASE_PATH_AND_NAME;
private static String CHECK_DATABASES_FOLDER;
//private static final String DATABASE_NAME = "music.db";
private static final String LOG_TAG = "MUSIC_DB";
Context ctx;
OpenDatabase sqh;
SQLiteDatabase sqdb;
// Control Objects
EditText searchByYearEditText;
Button searchButton;
TextView numRecordTextView;
Button displayAllRecordsButton;
TextView resultsTextView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupDatabaseStrings();
setUpDatabase();
InitDataBase(); // open the music.db for reading and writing
//sqh.DisplayRecords( sqdb ); // Display the songtable records to the run window
setupControls();
numRecordTextView.setText( Integer.toString( sqh.numberOfRecordsInSongtable( sqdb ) ) );
} // protected void onCreate(Bundle savedInstanceState)
protected void setupControls()
{
searchByYearEditText = findViewById(R.id.searchByYearEditText);
searchButton = findViewById(R.id.searchButton);
searchButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
resultsTextView.setText( sqh.searchByYearInSongtable( sqdb,
searchByYearEditText.getText().toString()) );
}
});
numRecordTextView = findViewById(R.id.numRecordTextView);
displayAllRecordsButton = findViewById(R.id.displayAllRecordsButton);
displayAllRecordsButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
}
});
resultsTextView = findViewById(R.id.resultsTextView);
} // protected void setupControls()
protected void setupDatabaseStrings()
{
// Full path to where we will copy music.db to on the emulator!
DATABASE_PATH_AND_NAME = "/data/data/" + getApplicationContext().getPackageName() +
"/databases/" + OpenDatabase.DATABASE_NAME;
// Used to check if the "databases" folder exists
CHECK_DATABASES_FOLDER = "/data/data/" + getApplicationContext().getPackageName() +
"/databases";
// Debug information
Log.i("DATABASE_PATH_AND_NAME","DATABASE_PATH_AND_NAME = " + DATABASE_PATH_AND_NAME);
Log.i("CHECK_DATABASES_FOLDER","CHECK_DATABASES_FOLDER = " + CHECK_DATABASES_FOLDER);
} // protected void setupDatabaseStrings()
protected void setUpDatabase()
{
ctx = this.getBaseContext();
Log.w("CTX","ctx = " + ctx);
Log.w("getBaseContext()","getBaseContext = " + getBaseContext());
try
{
CopyDataBaseFromAsset();
}
catch (IOException e)
{
e.printStackTrace();
}
} // protected void setUpDatabase()
protected void CopyDataBaseFromAsset() throws IOException
{
Log.w( LOG_TAG , "Starting copying...");
String outputFileName = DATABASE_PATH_AND_NAME;
File databaseFolder = new File( CHECK_DATABASES_FOLDER );
// databases folder exists ? No - Create it and copy !!!
if ( !databaseFolder.exists() )
{
databaseFolder.mkdir();
// Open the sqlite database "music.db" found in the assets folder
InputStream in = ctx.getAssets().open(OpenDatabase.DATABASE_NAME);
OutputStream out = new FileOutputStream(outputFileName);
byte[] buffer = new byte[1024];
int length;
while ( (length = in.read(buffer)) > 0 )
{
out.write(buffer,0,length);
} // while ( (length = in.read(buffer)) > 0 )
out.flush();
out.close();
in.close();
Log.w(LOG_TAG, "Completed.");
} // if ( !databaseFolder.exists() )
} // protected void CopyDataBaseFromAsset() throws IOException
public void InitDataBase()
{
// Init the SQLite Helper Class
sqh = new OpenDatabase(this);
// RETRIEVE A READABLE AND WRITEABLE DATABASE
sqdb = sqh.getWritableDatabase();
} // public void InitDataBase()
public void DisplayRecords()
{
Cursor c = sqdb.rawQuery("SELECT * FROM songtable", null);
if (c != null)
{
if (c.moveToFirst())
{
do
{
String id = c.getString(0);
String songtitle = c.getString(1);
String year = c.getString(2);
String artist = c.getString(3);
String album = c.getString(4);
Log.w("SONG_TABLE", "ID = " + id + " Songtitle = " + songtitle);
} while (c.moveToNext());
}
}
c.close();
} // public void DisplayRecords()
} // public class MainActivity extends AppCompatActivity
package com.example.dbcopyexample1;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class OpenDatabase extends SQLiteOpenHelper
{
public static final String DATABASE_NAME = "music.db";
// TOGGLE THIS NUMBER FOR UPDATING TABLES AND DATABASE
private static final int DATABASE_VERSION = 1;
OpenDatabase(Context context)
{
super( context, DATABASE_NAME, null, DATABASE_VERSION );
} // OpenDatabase(Context context)
#Override
public void onCreate(SQLiteDatabase db)
{
} // public void onCreate(SQLiteDatabase db)
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
} // public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
public String searchByYearInSongtable(SQLiteDatabase sqdb, String searchYear)
{
String result = "";
Cursor c = sqdb.rawQuery("SELECT * FROM songtable where year = '" + searchYear + "'",
null);
if (c != null) {
if (c.moveToFirst()) {
do {
String id = c.getString(0);
result = result + id + ",";
String songtitle = c.getString(1);
result = result + songtitle + ",";
String year = c.getString(2);
result = result + year + ",";
String artist = c.getString(3);
result = result + artist + ",";
String album = c.getString(4);
result = result + album + "\n"; // new line control character
Log.w("SONG_TABLE", "ID = " + id + " Songtitle = " + songtitle);
} while (c.moveToNext());
} else
{
result = "No Records Found for the Search Year = " + searchYear;
}
}
c.close();
return result;
} // public String allRecordsInSongtable(SQLiteDatabase sqdb)
public int numberOfRecordsInSongtable(SQLiteDatabase sqdb)
{
int count = 0;
Cursor c = sqdb.rawQuery("SELECT count(*) FROM songtable", null);
if (c != null)
{
if (c.moveToFirst())
{
do
{
String id = c.getString(0);
count = Integer.parseInt( id );
} while (c.moveToNext());
}
}
c.close();
return count;
} // public int numberOfRecordsInSongtable(SQLiteDatabase sqdb)
} // public class OpenDatabase extends SQLiteOpenHelper
You have not called your DisplayRecords() function to display records on tap of displayAllRecordsButton.
displayAllRecordsButton = findViewById(R.id.displayAllRecordsButton);
displayAllRecordsButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
DisplayRecords();
}
});
Also, in the DisplayRecords() method, you need to set text to the text view.
Below is your code I edited to display records.
public void DisplayRecords()
{
String result = "";
Cursor c = sqdb.rawQuery("SELECT * FROM songtable", null);
if (c != null)
{
if (c.moveToFirst())
{
do
{
String id = c.getString(0);
String songtitle = c.getString(1);
String year = c.getString(2);
String artist = c.getString(3);
String album = c.getString(4);
Log.w("SONG_TABLE", "ID = " + id + " Songtitle = " + songtitle);
result = result + "ID = " + id + "Song Title = " + songtitle + "Artist = " + artist + "Album = " + album + "Year = " + year + "\n";
} while (c.moveToNext());
}
}
c.close();
resultsTextView.setText(result);
} // public void DisplayRecords()

Getting -1 for one of my columns in SQLiteDatabase

Creating an app for seeing pets in the store, where I've created a database and a table called shelter.db and pets respectively. I've created a contract class to store all the constants related to the database, a class called PetDbHelper that extends SQLiteOpenHelper. I have two activities CatalogActivity and EditorActivity. In CatalogActivity, I'm trying to read the table and here I tried to get the column indices of each column but the last column named 'weight' returns -1 which means as you may know 'no column exists' and in EditorActivity, I'm trying to insert pets in the table. I've checked everything but have no clue what's wrong with my code.
Here's the PetContract class:
package com.example.android.pets.data;
import android.provider.BaseColumns;
public final class PetsContract {
public static final class PetEntry implements BaseColumns {
// CONSTANTS FOR TABLE AND COLUMN NAMES
public static final String TABLE_NAME = "pets";
public static final String _ID = BaseColumns._ID;
public static final String COLUMN_PET_NAME = "name";
public static final String COLUMN_PET_BREED = "breed";
public static final String COLUMN_PET_GENDER = "gender";
public static final String COLUMN_PET_WEIGHT = " weight";
// CONSTANTS FOR GENDER
public static final int GENDER_UNKNOWN = 0;
public static final int GENDER_MALE = 1;
public static final int GENDER_FEMALE = 2;
}
}
Here's the PetDbHelper that extends SQLiteOpenHelper class:
package com.example.android.pets.data;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class PetDbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "shelter.db";
private static final int DATABASE_VERSION = 1;
public PetDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + PetsContract.PetEntry.TABLE_NAME
+ " (" + PetsContract.PetEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ PetsContract.PetEntry.COLUMN_PET_NAME + " TEXT NOT NULL, "
+ PetsContract.PetEntry.COLUMN_PET_BREED + " TEXT, "
+ PetsContract.PetEntry.COLUMN_PET_GENDER + " INTEGER NOT NULL, "
+ PetsContract.PetEntry.COLUMN_PET_WEIGHT + " INTEGER NOT NULL DEFAULT 0);";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
Here's the code of CatalogActivity.java that is related to database:
/**
* Displays list of pets that were entered and stored in the app.
*/
public class CatalogActivity extends AppCompatActivity {
private PetDbHelper mDbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catalog);
mDbHelper = new PetDbHelper(this);
private void displayDatabaseInfo() {
// To access our database, we instantiate our subclass of
SQLiteOpenHelper
// and pass the context, which is the current activity.
// CREATE AND/OR OPEN A DATABASE TO READ FROM IT
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// String[] projection = {PetEntry._ID, PetEntry.COLUMN_PET_NAME, PetEntry.COLUMN_PET_BREED, PetEntry.COLUMN_PET_GENDER, PetEntry.COLUMN_PET_WEIGHT};
Cursor cursor = db.query(PetEntry.TABLE_NAME, null, null, null, null, null, null);
//Cursor cursor = db.rawQuery("SELECT * FROM pets", null);
TextView displayView = (TextView) findViewById(R.id.text_view_pet);
try {
// Create a header in the Text View that looks like this:
//
// The pets table contains <number of rows in Cursor> pets.
// _id - name - breed - gender - weight
//
// In the while loop below, iterate through the rows of the cursor and display
// the information from each column in this order.
displayView.setText("The pets table contains " + cursor.getColumnCount() + " pets.\n\n");
displayView.append(PetEntry._ID + " - " +
PetEntry.COLUMN_PET_NAME + " - " +
PetEntry.COLUMN_PET_BREED + " - " +
PetEntry.COLUMN_PET_GENDER + " - " +
PetEntry.COLUMN_PET_WEIGHT );
// Figure out the index of each column
int idColumnIndex = cursor.getColumnIndex(PetEntry._ID);
int nameColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_NAME);
int breedColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_BREED);
int genderColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_GENDER);
int weightColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_WEIGHT);
Toast.makeText(this,
"weight_index ?" + weightColumnIndex + "\n"
+ "id_index" + idColumnIndex + "\n"
+ "name_index" + nameColumnIndex + "\n"
+ "breed_index" + breedColumnIndex + "\n"
+ "gender_index" + genderColumnIndex , Toast.LENGTH_LONG).show();
} finally {
// Always close the cursor when you're done reading from it. This releases all its
// resources and makes it invalid.
cursor.close();
}
}
#Override
protected void onStart() {
super.onStart();
displayDatabaseInfo();
}
I know that's a lot of code, and here's the last piece of code of EditorActivity.java class: (excluded the code related to spinner object)
**
* Allows user to create a new pet or edit an existing one.
*/
public class EditorActivity extends AppCompatActivity {
/** EditText field to enter the pet's name */
private EditText mNameEditText;
/** EditText field to enter the pet's breed */
private EditText mBreedEditText;
/** EditText field to enter the pet's weight */
private EditText mWeightEditText;
/** EditText field to enter the pet's gender */
private Spinner mGenderSpinner;
/**
* Gender of the pet. The possible values are:
* 0 for unknown gender, 1 for male, 2 for female.
*/
private int mGender = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editor);
// Find all relevant views that we will need to read user input from
mNameEditText = (EditText) findViewById(R.id.edit_pet_name);
mBreedEditText = (EditText) findViewById(R.id.edit_pet_breed);
mWeightEditText = (EditText) findViewById(R.id.edit_pet_weight);
mGenderSpinner = (Spinner) findViewById(R.id.spinner_gender);
}
private void addPet() {
String name = mNameEditText.getText().toString().trim();
String breed = mBreedEditText.getText().toString().trim();
int weight = Integer.parseInt(mWeightEditText.getText().toString().trim());
ContentValues values = new ContentValues();
values.put(COLUMN_PET_NAME, name);
values.put(COLUMN_PET_BREED, breed);
values.put(COLUMN_PET_GENDER, mGender);
values.put(COLUMN_PET_WEIGHT, weight);
PetDbHelper mDbHelper = new PetDbHelper(this);
SQLiteDatabase db = mDbHelper.getWritableDatabase();
long result = db.insert(TABLE_NAME, null, values);
if (result != -1) {
Toast.makeText(this, "Pet saved with id: " + result, Toast.LENGTH_SHORT).show();
} else {Toast.makeText(this, "Error with saving pet", Toast.LENGTH_SHORT).show();}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu options from the res/menu/menu_editor.xml file.
// This adds menu items to the app bar.
getMenuInflater().inflate(R.menu.menu_editor, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// User clicked on a menu option in the app bar overflow menu
switch (item.getItemId()) {
// Respond to a click on the "Save" menu option
case R.id.action_save:
// Save pet into the database
addPet();
// Exit the activity
finish();
return true;
// Respond to a click on the "Delete" menu option
case R.id.action_delete:
// Do nothing for now
return true;
// Respond to a click on the "Up" arrow button in the app bar
case android.R.id.home:
// Navigate back to parent activity (CatalogActivity)
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Leading whitespace is ignored in SQL but it matters in map keys - column names and their indices are essentially stored in a map you can access with getColumnIndex().
public static final String COLUMN_PET_WEIGHT = " weight";
Remove the leading whitespace here.

Data not being stored in SQLite database for some reason? Errors

i'm trying to store some data within a new my sql database and am getting logcat errors saying the table does not exist despite me creating a method to do this. Here is my code!
DataBaseHelper2.java -
package com.example.david.myview3;
/**
* Created by David on 23/03/2017.
*/
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataBaseHelper2 extends SQLiteOpenHelper {
public DataBaseHelper2(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
}
// Called when no database exists in disk and the helper class needs
// to create a new one.
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE1);
_db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE2);
_db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE3);
_db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE4);
_db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE5);
}
// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
#Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) {
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " + _oldVersion + " to " + _newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new version. Multiple
// previous versions can be handled by comparing _oldVersion and _newVersion
// values.
// The simplest case is to drop the old table and create a new one.
_db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");
// Create a new one.
onCreate(_db);
}
}
SurveyDataBaseAdapter -
package com.example.david.myview3;
/**
* Created by David on 23/03/2017.
*/
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class SurveyDataBaseAdapter {
static final String DATABASE_NAME = "survey.db";
static final int DATABASE_VERSION = 1;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
// SQL Statement to create a new database.
static final String DATABASE_CREATE1 = "create table " + "USER" +
"( " + "ID" + " integer primary key autoincrement," + "ID int,NAME text); ";
static final String DATABASE_CREATE2 = "create table " + "QUESTION" +
"( " + "ID2" + " integer primary key autoincrement," + "QUESTION text,ANSWER1 text, ANSWER2 text, ANSWER3 text); ";
static final String DATABASE_CREATE3 = "create table " + "RESPONSE" +
"( " + "ID3" + " integer primary key autoincrement," + "ID int,QUESTION text, ANSWER int); ";
// Variable to hold the database instance
public SQLiteDatabase db2;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper2 dbHelper2;
public SurveyDataBaseAdapter(Context _context) {
context = _context;
dbHelper2= new DataBaseHelper2(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public SurveyDataBaseAdapter open() throws SQLException {
db2 = dbHelper2.getWritableDatabase();
return this;
}
public void close() {
db2.close();
}
public SQLiteDatabase getDatabaseInstance() {
return db2;
}
public void insertQuestion(String question, String answerOne, String answerTwo, String answerThree) {
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("QUESTION", question);
newValues.put("ANSWER1", answerOne);
newValues.put("ANSWER2", answerTwo);
newValues.put("ANSWER3", answerThree);
// Insert the row into your table
db2.insert("QUESTION", null, newValues);
///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}
//new try
public void insertEntry2(String question, String answer) {
ContentValues newValues2 = new ContentValues();
// Assign values for each row.
newValues2.put("QUESTION", question);
newValues2.put("ANSWER", answer);
// Insert the row into your table
db2.insert("SURVEY1", null, newValues2);
///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}
public int deleteEntry(String UserName) {
//String id=String.valueOf(ID);
String where = "USERNAME=?";
int numberOFEntriesDeleted = db2.delete("LOGIN", where, new String[]{UserName});
// Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
return numberOFEntriesDeleted;
}
public String[] getQuestion() {
final String TABLE_NAME = "QUESTION";
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getDatabaseInstance();
Cursor cursor = db2.rawQuery(selectQuery, null);
String[] data = null;
if(cursor.moveToFirst()) {
do {
// get the data into the array, or class variable
}while (cursor.moveToNext());
}
cursor.close();
return data;
}
public String getSingleEntry()
{
Cursor cursor=db2.query("QUESTION", null, null, null, null, null, null);
cursor.moveToFirst();
String question= cursor.getString(cursor.getColumnIndex("QUESTION"));
cursor.close();
return question;
}
public void updateEntry(String userName, String password) {
// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
updatedValues.put("USERNAME", userName);
updatedValues.put("PASSWORD", password);
String where = "USERNAME = ?";
db2.update("LOGIN", updatedValues, where, new String[]{userName});
}
}
CreateSurveyActivity.java
package com.example.david.myview3;
/**
* Created by David on 23/03/2017.
*/
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.content.Context;
import android.view.inputmethod.InputMethodManager;
public class CreateSurveyActivity extends DashBoardAppActivity {
EditText editQuestion, editAnswer1, editAnswer2, editAnswer3;
Button btnNext, btnComplete;
SurveyDataBaseAdapter SurveyDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photoalbum);
// get Instance of Database Adapter
SurveyDataBaseAdapter = new SurveyDataBaseAdapter(this);
SurveyDataBaseAdapter = SurveyDataBaseAdapter.open();
// Get References of Views
editQuestion = (EditText) findViewById(R.id.editTextQuestion);
editAnswer1 = (EditText) findViewById(R.id.editTextAnswer1);
editAnswer2 = (EditText) findViewById(R.id.editTextAnswer2);
editAnswer3 = (EditText) findViewById(R.id.editTextAnswer3);
// Get Refs of buttons
btnComplete = (Button) findViewById(R.id.buttonSignUP);
}
public void createSurvey(View V){
final Dialog dialog = new Dialog(CreateSurveyActivity.this);
dialog.setContentView(R.layout.photoalbum);
dialog.setTitle("Create");
// get the Refferences of views
final EditText editQuestion=(EditText)dialog.findViewById(R.id.editTextQuestion);
editQuestion.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
final EditText editAnswer1=(EditText)dialog.findViewById(R.id.editTextAnswer1);
editAnswer1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
final EditText editAnswer2=(EditText)dialog.findViewById(R.id.editTextAnswer2);
editAnswer2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
final EditText editAnswer3=(EditText)dialog.findViewById(R.id.editTextAnswer3);
editAnswer3.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
// Set On ClickListener
Button btnNext = (Button) dialog.findViewById(R.id.buttonNext);
btnNext.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String question = editQuestion.getText().toString();
String answer1 = editAnswer1.getText().toString();
String answer2 = editAnswer2.getText().toString();
String answer3 = editAnswer3.getText().toString();
// check if any of the fields are vaccant
if (question.equals("") || answer1.equals("") || answer2.equals("") || answer3.equals("")) {
Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
return;
}
{
// Save the Data in Database
SurveyDataBaseAdapter.insertQuestion(question, answer1, answer2, answer3);
Toast.makeText(getApplicationContext(), "Question Successfully Created ", Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
// try to send home on complete button press
//*
//btnNext = (Button) findViewById(R.id.buttonNext);
// btnNext.setOnClickListener(new View.OnClickListener() {
// final Intent intent = new Intent(context, DashHomeActivity.class);
//
// });
}
public void hideKeyboard(View view){
InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
SurveyDataBaseAdapter.close();
}
}
logcat -
04-17 20:26:41.408 14322-14322/com.example.david.myview3 E/SQLiteLog: (1) no such table: QUESTION
04-17 20:26:41.408 14322-14322/com.example.david.myview3 E/SQLiteDatabase: Error inserting ...
android.database.sqlite.SQLiteException: no such table: QUESTION (code 1): , while compiling: INSERT INTO QUESTION(QUESTION,ANSWER3,ANSWER2,ANSWER1) VALUES (?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:919)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:530)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1547)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1404)
at com.example.david.myview3.SurveyDataBaseAdapter.insertQuestion(SurveyDataBase Adapter.java:59)
at com.example.david.myview3.CreateSurveyActivity$5.onClick(CreateSurveyActivity .java:117)
at android.view.View.performClick(View.java:4785)
at android.view.View$PerformClick.run(View.java:19869)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:10 28)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
Use SurveyDataBaseAdapter.DATABASE_CREATE1 instead of LoginDataBaseAdapter.DATABASE_CREATE1.
In your DataBaseHelper2.java, update onCreate() method as below:
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(SurveyDataBaseAdapter.DATABASE_CREATE1);
_db.execSQL(SurveyDataBaseAdapter.DATABASE_CREATE2);
_db.execSQL(SurveyDataBaseAdapter.DATABASE_CREATE3);
}
In your SurveyDataBaseAdapter , update SQL table create statement as below:
static final String DATABASE_CREATE1 = "CREATE TABLE " + "USER" + "( " +
"ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"ID1 INTEGER, " + "NAME TEXT " + ")";
static final String DATABASE_CREATE2 = "CREATE TABLE " + "QUESTION" + "( " +
"ID2 INTEGER PRIMARY KEY AUTOINCREMENT, " +
"QUESTION TEXT, " + "ANSWER1 TEXT, " + "ANSWER2 TEXT, " + "ANSWER3 TEXT " + ")";
static final String DATABASE_CREATE3 = "CREATE TABLE " + "RESPONSE" + "( " +
"ID3 INTEGER PRIMARY KEY AUTOINCREMENT, " +
"ID INTEGER, " + "QUESTION TEXT, " + "ANSWER INTEGER " + ")";

Total price using rawQuery in android [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I've been trying to get the price value from the database and try to make a grand total. I used the rawQuery but always crashed.I think theres a problem in my rawQuery..i still cant get the total after many times i've tried..
this is the code:
DBAdapter
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;
// ------------------------------------ DBAdapter.java ---------------------------------------------
// TO USE:
// Change the package (at top) to match your project.
// Search for "TODO", and make the appropriate changes.
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_QUANTITY = "studentnum";
public static final String KEY_PRICE = "favcolour";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_QUANTITY = 2;
public static final int COL_PRICE = 3;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME, KEY_QUANTITY, KEY_PRICE};
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "MyDb";
public static final String DATABASE_TABLE = "mainTable";
// 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 + " text not null, "
+ KEY_QUANTITY + " integer not null, "
+ KEY_PRICE + " string 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 studentNum, String favColour) {
/*
* 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_QUANTITY, studentNum);
initialValues.put(KEY_PRICE, favColour);
// 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 Cursor getTotalPrice() {
Cursor c = db.rawQuery("SELECT SUM("+ KEY_PRICE +")from " + DATABASE_TABLE, null);
return c;
}
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, int studentNum, String favColour) {
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_QUANTITY, studentNum);
newValues.put(KEY_PRICE, favColour);
// 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);
}
}
}
Listprice:
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
/**
* Created by User on 6/2/2015.
*/
public class Listprice extends ActionBarActivity {
DBAdapter myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listprice);
openDB();
TextView textView = (TextView) findViewById(R.id.order90);
TextView textView1 = (TextView) findViewById(R.id.quan90);
TextView textView2 = (TextView) findViewById(R.id.price90);
TextView textView3 = (TextView) findViewById(R.id.totalprice);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String newText = extras.getString("firstmessage");
String newText1 = extras.getString("secondmessage");
String newText2 = extras.getString("thirdmessage");
if (newText != null) {
textView.setText(newText);
}
if (newText1 != null) {
textView1.setText(newText1);
}
if (newText2 != null) {
textView2.setText(newText2);
}
}
String num1 = textView.getText().toString().trim();
int num2 = Integer.parseInt(textView1.getText().toString());
int num3 = Integer.parseInt(textView2.getText().toString());
int num4 = num2 * num3;
registerListClickCallBack();
myDb.insertRow(num1, "Quantity = " + num2, ""+num4);
populateListViewFromDB();
Cursor sum=myDb.getTotalPrice();
textView3.setText(""+sum);
}
private void populateListViewFromDB() {
Cursor cursor = myDb.getAllRows();
//Query for the record we just added.
//Use the ID:
startManagingCursor(cursor);
String[] fromFieldNames = new String[]
{DBAdapter.KEY_NAME, DBAdapter.KEY_QUANTITY, DBAdapter.KEY_PRICE};
int[] toViewIDs = new int[]
{R.id.item_name, R.id.quantities, R.id.pricest};
SimpleCursorAdapter myCursorAdapter =
new SimpleCursorAdapter(
this,
R.layout.item_layout,
cursor,
fromFieldNames,
toViewIDs
);
// Set the adapter for the list view
ListView myList = (ListView) findViewById(R.id.listViewFromDB);
myList.setAdapter(myCursorAdapter);
}
private void openDB(){
myDb = new DBAdapter(this);
myDb.open();
}
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}
private void closeDB() {
myDb.close();
}
private void registerListClickCallBack() {
ListView myList = (ListView) findViewById(R.id.listViewFromDB);
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long idInDB) {
updateItemForId(idInDB);
}
});
}
private void updateItemForId(final long idInDB) {
final Cursor cursor = myDb.getRow(idInDB);
if (cursor.moveToFirst()) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Listprice.this);
// Setting Dialog Title
alertDialog.setTitle("Confirm Delete...");
// Setting Dialog Message
alertDialog.setMessage("Are you sure you want delete this?");
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to invoke YES event
Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show();
myDb.deleteRow(idInDB);
populateListViewFromDB();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
cursor.close();
populateListViewFromDB();
}
public void clear(View view) {
myDb.deleteAll();
populateListViewFromDB();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#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);
}
public void addFood(View view) {
Intent gotofood = new Intent(this, food.class);
startActivity(gotofood);
}
public void addDrinks(View view) {
Intent gotodrinks = new Intent(this, drink.class);
startActivity(gotodrinks);
}
public void gotomainmaenu(View view) {
Intent gotomain = new Intent(this, MainActivity.class);
startActivity(gotomain);
}
}
It sounds like you want the sum of each item's price multiplied by that item's quantity. If so, this should work:
public double getTotalPrice() {
String sql = "select sum(" + KEY_QUANTITY + " * " + KEY_PRICE + ") from "
+ DATABASE_TABLE;
Cursor cursor = db.rawQuery(sql, null);
if (cursor.moveToFirst()) {
return cursor.getDouble(0);
}
return 0;
}

Categories

Resources