Question: Android Programming in Android Studio Exercise 13-4 Add a database to the Tip Calculator app In this exercise, youll create a database that you can

Android Programming in Android Studio

Exercise 13-4 Add a database to the Tip Calculator app

In this exercise, youll create a database that you can use with the Tip Calculator app.

Add a database class

Start Android Studio and open the project named ch13_ex4_TipCalculator.

Review the code. Note that it includes a Tip class that you can use to store the data for a tip.

Add a database class that creates a table with these column names and data types:

_id INTEGER bill_date INTEGER bill_amount REAL tip_percent REAL

When the database class creates the database, it should also insert two rows of test data. (You can use 0 for the bill date values, but make up some bill amount and tip percent values such as 40.60 and .15.)

Add a public getTips method that returns an ArrayList object that contains all columns and rows from the database table.

Switch to the activity class. Then, add code to its onResume method that calls the getTips method and loops through all saved tips. For each saved tip, this code should use LogCat logging to send the bill date milliseconds, the bill amount, and the tip percent to the LogCat view.

Run the app. At this point, it should create the database, add two rows of test data, and print the data for each row to the LogCat view.

Save tip calculations

Switch to the database class and add a method that saves tip calculations.

In the layout for the activity, add a Save button below the other widgets.

In the class for the activity, add code that saves the current bill amount and tip percent to the database when the user clicks the Save button. This code should also clear the bill amount from the user interface.

Run the app and test the Save button. To do that, you can execute the onResume method by navigating away from the app and navigating back to it. Then, you can check the LogCat view to make sure the data is saved when you click on the Save button.

Display the date and time of the last saved tip

Switch to the database class and add a method that returns a Tip object for the last tip that was saved.

Add code to the onResume method that displays the date and time of the last saved tip in the LogCat view. This date and time should be in this format:

Sep 4 2016 15:54:00

You can use a method of the Tip class to return this format.

Execute the onResume method again. Then, check the LogCat view to make sure the data is displayed correctly.

Set default tip percent to average tip percent

Switch to the database class and add a method that gets the average tip percent. To do that, you can provide an array of strings for the columns parameter like this:

String columns[] = {"AVG(" + TIP_PERCENT + ")"};

(This assumes the TIP_PERCENT constant contains the name of the column that stores the tip percent.)

Add code to the onResume method that displays the average tip percent in the LogCat view.

Execute the onResume method again by navigating away from the app and navigating back to it. Then, check the LogCat view to make sure the average tip percent is displayed correctly.

Modify the code for the Save button so it sets the tip percent to the average tip percent. That way, after you click the Save button, it should set the tip percent to the average tip percent.

TipCalculatorActivity.java

package com.murach.tipcalculator;

import java.text.NumberFormat;

import android.os.Bundle;

import android.preference.PreferenceManager;

import android.view.KeyEvent;

import android.view.View;

import android.view.View.OnClickListener;

import android.view.inputmethod.EditorInfo;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import android.widget.TextView.OnEditorActionListener;

import android.app.Activity;

import android.content.SharedPreferences;

import android.content.SharedPreferences.Editor;

public class TipCalculatorActivity extends Activity

implements OnEditorActionListener, OnClickListener {

// define variables for the widgets

private EditText billAmountEditText;

private TextView percentTextView;

private Button percentUpButton;

private Button percentDownButton;

private TextView tipTextView;

private TextView totalTextView;

// define instance variables that should be saved

private String billAmountString = "";

private float tipPercent = .15f;

// set up preferences

private SharedPreferences prefs;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_tip_calculator);

// get references to the widgets

billAmountEditText = (EditText) findViewById(R.id.billAmountEditText);

percentTextView = (TextView) findViewById(R.id.percentTextView);

percentUpButton = (Button) findViewById(R.id.percentUpButton);

percentDownButton = (Button) findViewById(R.id.percentDownButton);

tipTextView = (TextView) findViewById(R.id.tipTextView);

totalTextView = (TextView) findViewById(R.id.totalTextView);

// set the listeners

billAmountEditText.setOnEditorActionListener(this);

percentUpButton.setOnClickListener(this);

percentDownButton.setOnClickListener(this);

// get default SharedPreferences object

prefs = PreferenceManager.getDefaultSharedPreferences(this);

}

@Override

public void onPause() {

// save the instance variables

Editor editor = prefs.edit();

editor.putString("billAmountString", billAmountString);

editor.putFloat("tipPercent", tipPercent);

editor.commit();

super.onPause();

}

@Override

public void onResume() {

super.onResume();

// get the instance variables

billAmountString = prefs.getString("billAmountString", "");

tipPercent = prefs.getFloat("tipPercent", 0.15f);

// set the bill amount on its widget

billAmountEditText.setText(billAmountString);

// calculate and display

calculateAndDisplay();

}

public void calculateAndDisplay() {

// get the bill amount

billAmountString = billAmountEditText.getText().toString();

float billAmount;

if (billAmountString.equals("")) {

billAmount = 0;

}

else {

billAmount = Float.parseFloat(billAmountString);

}

// calculate tip and total

float tipAmount = billAmount * tipPercent;

float totalAmount = billAmount + tipAmount;

// display the other results with formatting

NumberFormat currency = NumberFormat.getCurrencyInstance();

tipTextView.setText(currency.format(tipAmount));

totalTextView.setText(currency.format(totalAmount));

NumberFormat percent = NumberFormat.getPercentInstance();

percentTextView.setText(percent.format(tipPercent));

}

@Override

public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

if (actionId == EditorInfo.IME_ACTION_DONE ||

actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {

calculateAndDisplay();

}

return false;

}

@Override

public void onClick(View v) {

switch (v.getId()) {

case R.id.percentDownButton:

tipPercent = tipPercent - .01f;

calculateAndDisplay();

break;

case R.id.percentUpButton:

tipPercent = tipPercent + .01f;

calculateAndDisplay();

break;

}

}

}

Tip.java

package com.murach.tipcalculator;

import android.annotation.SuppressLint;

import java.text.NumberFormat;

import java.text.SimpleDateFormat;

import java.util.Date;

public class Tip {

private long id;

private long dateMillis;

private float billAmount;

private float tipPercent;

public Tip() {

setId(0);

setDateMillis(System.currentTimeMillis());

setBillAmount(0);

setTipPercent(.15f);

}

public Tip(long id, long dateMillis, float billAmount, float tipPercent) {

this.setId(id);

this.setDateMillis(dateMillis);

this.setBillAmount(billAmount);

this.setTipPercent(tipPercent);

}

public long getId() {

return id;

}

public void setId(long id) {

this.id = id;

}

public long getDateMillis() {

return dateMillis;

}

@SuppressLint("SimpleDateFormat")

public String getDateStringFormatted() {

// set the date with formatting

Date date = new Date(dateMillis);

SimpleDateFormat sdf = new SimpleDateFormat("MMM d yyyy HH:mm:ss");

return sdf.format(date);

}

public void setDateMillis(long dateMillis) {

this.dateMillis = dateMillis;

}

public float getBillAmount() {

return billAmount;

}

public String getBillAmountFormatted() {

NumberFormat currency = NumberFormat.getCurrencyInstance();

return currency.format(billAmount);

}

public void setBillAmount(float billAmount) {

this.billAmount = billAmount;

}

public float getTipPercent() {

return tipPercent;

}

public String getTipPercentFormatted() {

NumberFormat percent = NumberFormat.getPercentInstance();

return percent.format(tipPercent);

}

public void setTipPercent(float tipPercent) {

this.tipPercent = tipPercent;

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!