AA's Weight Tracker

This is a discussion on AA's Weight Tracker within the LG Ally Hacking / Development forums, part of the LG Ally category; This is my 3rd tutorial and it covers some basic coding for using a SQLite database to store user input. As always, please view Getting ...

Results 1 to 3 of 3

Thread: AA's Weight Tracker

  1. #1
    Android Junkie allyAndroid's Avatar
    Join Date
    Jun 2010
    Location
    Ohio
    Posts
    1,413
    This is my 3rd tutorial and it covers some basic coding for using a SQLite database to store user input.



    As always, please view Getting Setup to Develop if you have not already done so.





    Prerequisites



    This tutorial does not cover setting up your computer to develop Android Apps. You must have installed JDK (Version 5 or 6), Android SDK, Eclipse (Version 3.5 or greater), and the Android Eclipse Plug-in. You must also be familiar with Java and using Eclipse.



    A New Project



    The first thing we want to do is to create a new project.

    • Open Eclipse.
    • Click on the File menu.
    • Select New -> Project.
    • In the New Project dialog box, select Android -> Android Project.
    • Click on the Next button.
    • Enter the project information:
      • Project Name: weightTracker
        • The project name will be used to create the folder that Eclipse will store all of the project's files in.
      • Build Target: Android 2.1
        • The build target is the version of Android that you want to use for the application.
        • Any device that uses an earlier version of Android may not be able to run the application.
      • Application Name: AA\'s Weight Tracker
        • The application name is what will appear in the application's title and is what the user will see.
      • Package Name: com.allyandroid.weighttracker
      • Create Activity: TrackWeight
        • The activity is the main activity that is ran when the application is opened.
      • Min SDK Version: 7
        • The min SDK is used to prevent older version of Android from being able to run the application.
        • If blank, any device can install the application even if they have an older version of Android.


    The Layout



    Next, we want to design the layout of the application. We want to add the following objects to the main layout:

    • Textbox - This is what the user will enter their weight.
    • Add Weight button - The button the user touches to add their weight.
    • View Weights button - The button the user touches to view all the weights entered.
    • Clear button - The button the user touches to clear the value from the textbox.
    • ImageView - This will hold a picture of a weight scale.


    In order to add these objects, we need to work with two separate files: strings.xml and main.xml. We will also need to create an image of a scale.

    • Open the strings.xml file.
      • The strings.xml file is located in this folder: /res/values/.
      • Change the code in the file to the following:
          • AA\'s Weight Tracker
          • Add Weight
          • addWeightHandler
          • View Weights
          • viewWeightHandler
          • Clear
          • clearHandler
      • Save the file.
    • Open the main.xml file.
      • The main.xml file is located in this folder: /res/layout/.
      • Change the code in the file to:
    [/list][/list] [/list] [/list] [/list] [/list] [/list][/list] [/list]
    • Save the file.
    [/list]
    • Create an image called weightscale.png.
      • Place the image in the \res\drawable-hdpi folder.


    The Menu



    We want to add a menu file that contains a Reset, Exit and About. A menu is what pops up when the user pushes the menu button. The menu file is not automatically created by Eclipse so we will need to create it.

    • Create the menu.xml file.
      • Create a new menu folder.
        • Right click on the res folder.
        • Select New -> Folder.
        • Enter menu for the folder name.
        • Click on the Finish button.
      • Create a new file called menu.xml.
        • Right click on the menu folder.
        • Select New -> File.
        • Enter menu.xml for the file name.
        • Click on the Finish button.
      • Open menu.xml.
        • Add the following code to the file:
      • Save the file.


    The Database Adapter



    We need to create a file that will allow us to use an SQLite database.

    • Create the DBAdapter.java file.
      • Create a new file called DBAdapter.java.
        • Right click on /src/com.allyandroid.weighttracker.
        • Select New -> File.
        • Enter DBAdapter.java for the file name.
        • Click on the finish button.
      • Open DBAdapter.java.
        • Add the following code to the file.
          • package com.allyandroid.weight.tracker;
          • // Add the following imports, if they are not already listed:
            • import java.util.ArrayList;
            • import java.util.List;
            • import android.content.Context;
            • import android.database.Cursor;
            • import android.database.sqlite.SQLiteDatabase;
            • import android.database.sqlite.SQLiteOpenHelper;
            • import android.database.sqlite.SQLiteStatement;
            • import android.util.Log;
          • // This is the main database class.
            • public class DataHelper {
              • private static final String DATABASE_NAME = "weight.db";
              • private static final int DATABASE_VERSION = 1;
              • private static final String TABLE_NAME = "weight";
              • private Context context;
              • private SQLiteDatabase db;
              • private SQLiteStatement insertStmt;
              • private static final String INSERT = "insert into " + TABLE_NAME + "(weight) values (?)";
              • public DataHelper(Context context) {
                • this.context = context;
                • OpenHelper openHelper = new OpenHelper(this.context);
                • this.db = openHelper.getWritableDatabase();
                • this.insertStmt = this.db.compileStatement(INSERT);
              • }
          • // Inserts a record into the database.
            • public long insert(String weight) {
              • this.insertStmt.bindString(1, weight);
    • return this.insertStmt.executeInsert();
    • }
    • // Deletes all records from the database.
      • public void deleteAll() {
        • this.db.delete(TABLE_NAME, null, null);
      • }
    • // Gets all records from the database.
      • public List selectAll() {
        • List list = new ArrayList();
        • Cursor cursor = this.db.query(TABLE_NAME, new String[] { "weight" },
          • null, null, null, null, null);
        • if (cursor.moveToFirst()) {
          • do {
            • list.add(cursor.getString(0));
          • } while (cursor.moveToNext());
        • }
        • if (cursor != null && !cursor.isClosed()) {
          • cursor.close();
        • }
        • return list;
      • }
    • // Returns the ten most recent records from the database.
      • public List selectTen() {
        • List list = new ArrayList();
        • Cursor cursor = this.db.query(TABLE_NAME, new String[] { "weight" },
          • null, null, null, null, null, "10");
        • if (cursor.moveToFirst()) {
          • do {
            • list.add(cursor.getString(0));
          • } while (cursor.moveToNext());
        • }
        • if (cursor != null && !cursor.isClosed()) {
          • cursor.close();
        • }
        • return list;
      • }
    • // Opens the database.
      • private static class OpenHelper extends SQLiteOpenHelper {
        • OpenHelper(Context context) {
          • super(context, DATABASE_NAME, null, DATABASE_VERSION);
        • }
    • // Creates a new database if it does not already exist.
      • @Override
      • public void onCreate(SQLiteDatabase db) {
        • db.execSQL("CREATE TABLE " + TABLE_NAME
          • + "(id INTEGER PRIMARY KEY, weight TEXT)");
      • }
    • // Used when the database needs to be upgraded. Change the value of DATABASE_VERSION to a higher number.
      • @Override
      • public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        • Log.w("Example", "Upgrading database, this will drop tables and recreate.");
        • db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        • onCreate(db);
      • }
      • }
    • }
    • Save the file.


    The Activity



    Now comes the fun part of programming the activities that will perform the calculations when a user enters a value, selects a radio button, and then clicks on the Calculate button. We will also create the handler activities and menu activities.

    • Open TrackWeight.java file.
      • The TrackWeight.java file is located in this folder: /src/com.allyandroid.weighttracker.
      • Change the code in the file to:
        • package com.allyandroid.weight.tracker;
        • // Add the following imports, if they are not already listed:
          • import java.util.List;
          • import android.app.Activity;
          • import android.os.Bundle;
          • import android.text.Editable;
          • import android.util.Log;
          • import android.view.Menu;
          • import android.view.MenuInflater;
          • import android.view.MenuItem;
          • import android.view.View;
          • import android.widget.EditText;
          • import android.widget.TextView;
          • import android.widget.Toast;
        • // This is the main class that was created when you created the project.
          • public class TrackWeight extends Activity {
            • private EditText myWeight;
            • private TextView output;
            • private DataHelper dh;
            • @Override
            • public void onCreate(Bundle savedInstanceState) {
              • super.onCreate(savedInstanceState);
              • setContentView(R.layout.main);
            • myWeight = (EditText) findViewById(R.id.EditText01);
            • output = (TextView) this.findViewById(R.id.TextView01);
            • dh = new DataHelper(this);
            • getTenRecords();
            • }
        • // This activity handles the menu when the menu button is pushed.
          • public boolean onCreateOptionsMenu(Menu menu) {
            • MenuInflater inflater = getMenuInflater();
            • inflater.inflate(R.menu.menu, menu);
            • return true;
          • }
        • // This activity handles the Exit or About menu when touched.
          • @Override
          • public boolean onOptionsItemSelected(MenuItem item) {
            • switch (item.getItemId()) {
            • case R.id.exit:
              • finish();
              • return true;
            • case R.id.about:
              • Toast.makeText(this,
              • break;
            • case R.id.reset:
              • this.dh.deleteAll();
              • viewWeightHandler(null);
              • Toast
                • .makeText(
                  • this,
                  • "The database has been reset and all records have been deleted.",
                  • Toast.LENGTH_LONG).show();
              • break;
            • }
            • return true;
          • }
        • // This activity handles the Add Weight button when touched.
          • public void clearHandler(View view) {
            • myWeight.setText("");
          • }
        • // This activity handles the Add Weight button when touched.
          • public void addWeightHandler(View view) {
            • Editable newWeight = myWeight.getText();
            • String weight = newWeight.toString();
            • if (myWeight.length() > 0) {
              • dh.insert(weight);
              • Toast.makeText(this, "Your weight has been added to the database.",
                • Toast.LENGTH_SHORT).show();
              • getTenRecords();
              • clearHandler(view);
            • } else {
              • Toast.makeText(this, "Your must enter a weight.",
                • Toast.LENGTH_SHORT).show();
            • }
          • }
        • // This activity handles the View Weight button when touched.
          • public void viewWeightHandler(View view) {
            • List weights = this.dh.selectAll();
            • StringBuilder sb = new StringBuilder();
            • sb.append("Previous Weights:\n");
            • for (String weight : weights) {
              • sb.append(weight + "\n");
            • }
            • Log.d("WEIGHT", "weight size - " + weights.size());
            • output.setText(sb.toString());
          • }
        • // Brings back only ten records.
          • public void getTenRecords(){
            • List weights = this.dh.selectTen();
            • StringBuilder sb = new StringBuilder();
            • sb.append("Recent Ten Weights:\n");
            • for (String weight : weights) {
              • sb.append(weight + "\n");
            • }
            • Log.d("WEIGHT", "weight size - " + weights.size());
            • output.setText(sb.toString());
          • }
        • }
      • Save the file.
    Motorola Droid 4

  2. Android.net is the premier Android Forum. Registered users do not see these ads. .

  3. #2
    Android Junkie allyAndroid's Avatar
    Join Date
    Jun 2010
    Location
    Ohio
    Posts
    1,413




    QR Code for the APK file
    Motorola Droid 4

  4. #3
    Android Junkie allyAndroid's Avatar
    Join Date
    Jun 2010
    Location
    Ohio
    Posts
    1,413
    Screenshots



    Motorola Droid 4

Remove Ads

http://www.scramblerducati.org/

Sponsored Links

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  

Search tags for this page

android weight tracker app

,

beginner insert user imput into sqlite database with android

,

create weight tracker android java

,

java for android ally

,

openhelper sqlite example

,

weight tracker android app using eclipse

,

weight tracker xml

Click on a term to search our sites for related topics.
Android Forum