From a827fcdcdcf17550901cabc11af52cea70c34b5b Mon Sep 17 00:00:00 2001 From: Priyanshu Jain Date: Fri, 27 Aug 2021 10:26:24 +0530 Subject: [PATCH] After Lesson 2 --- README.md | 2 +- app/src/main/AndroidManifest.xml | 2 +- .../example/android/pets/CatalogActivity.java | 124 +++++++++++++++--- .../example/android/pets/EditorActivity.java | 54 +++++++- .../android/pets/data/PetContract.java | 24 ++++ .../android/pets/data/PetDbHelper.java | 44 +++++++ app/src/main/res/values/strings.xml | 4 +- 7 files changed, 230 insertions(+), 24 deletions(-) create mode 100644 app/src/main/java/com/example/android/pets/data/PetContract.java create mode 100644 app/src/main/java/com/example/android/pets/data/PetDbHelper.java diff --git a/README.md b/README.md index 861a484..4825b13 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ Pets App =================================== -This app displays a list of pets and their related data that the user inputs. +This app displays a list of pets and their related com.example.android.pets.data that the user inputs. Used in a Udacity course in the Android Basics Nanodegree by Google. Pre-requisites diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 7b6a691..e4c474c 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -32,7 +32,7 @@ android:label="@string/editor_activity_title_new_pet" android:theme="@style/EditorTheme" android:parentActivityName=".CatalogActivity" > - + diff --git a/app/src/main/java/com/example/android/pets/CatalogActivity.java b/app/src/main/java/com/example/android/pets/CatalogActivity.java index 2fde624..3b5bde8 100644 --- a/app/src/main/java/com/example/android/pets/CatalogActivity.java +++ b/app/src/main/java/com/example/android/pets/CatalogActivity.java @@ -1,33 +1,27 @@ -/* - * Copyright (C) 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ package com.example.android.pets; +import android.content.ContentValues; import android.content.Intent; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; +import android.widget.TextView; + +import com.example.android.pets.data.PetContract.PetEntry; +import com.example.android.pets.data.PetDbHelper; /** * 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); @@ -42,6 +36,87 @@ public void onClick(View view) { startActivity(intent); } }); + + mDbHelper = new PetDbHelper(this); + } + + @Override + protected void onStart() { + super.onStart(); + displayDatabaseInfo(); + } + + /** + * Temporary helper method to display information in the onscreen TextView about the state of + * the pets database. + */ + private void displayDatabaseInfo() { + // To access our database, we instantiate our subclass of SQLiteOpenHelper + // and pass the context, which is the current activity. +// PetDbHelper mDbHelper = new PetDbHelper(this); + + // Create and/or open a database to read from it + SQLiteDatabase db = mDbHelper.getReadableDatabase(); + + + String[] projections = { + PetEntry._ID, + PetEntry.COLUMN_PET_NAME, + PetEntry.COLUMN_PET_BREED, + PetEntry.COLUMN_PET_GENDER, + PetEntry.COLUMN_PET_WEIGHT }; +// String selection = " WHERE "; + // Perform this raw SQL query "SELECT * FROM pets" + // to get a Cursor that contains all rows from the pets table. + Cursor cursor = db.query( + PetEntry.TABLE_NAME, projections, + null, + null, + null, + null, + null, + null ); + + TextView textViewPet = (TextView) findViewById(R.id.text_view_pet); + + try + { + textViewPet.setText("The pets table contains "+cursor.getCount()+" pets.\n\n"); + int idIndex = cursor.getColumnIndex(PetEntry._ID); + int nameIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_NAME); + int breedIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_BREED); + int genderIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_GENDER); + int weightIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_WEIGHT); + + textViewPet.append(PetEntry._ID +" - " + +PetEntry.COLUMN_PET_NAME +" - " + +PetEntry.COLUMN_PET_BREED +" - " + +PetEntry.COLUMN_PET_GENDER +" - " + +PetEntry.COLUMN_PET_WEIGHT+ "\n\n"); + + while(cursor.moveToNext()) + { + int id = cursor.getInt(idIndex); + String name = cursor.getString(nameIndex); + String breed = cursor.getString(breedIndex); + int gender = cursor.getInt(genderIndex); + int weight = cursor.getInt(weightIndex); + + textViewPet.append( + id + " - "+ + name + " - " + + breed + " - " + + gender + " - " + + weight ); + textViewPet.append("\n"); + } + } + finally + { + // Always close the cursor when you're done reading from it. This releases all its + // resources and makes it invalid. + cursor.close(); + } } @Override @@ -59,6 +134,8 @@ public boolean onOptionsItemSelected(MenuItem item) { // Respond to a click on the "Insert dummy data" menu option case R.id.action_insert_dummy_data: // Do nothing for now + insertPet(); + displayDatabaseInfo(); return true; // Respond to a click on the "Delete all entries" menu option case R.id.action_delete_all_entries: @@ -67,4 +144,19 @@ public boolean onOptionsItemSelected(MenuItem item) { } return super.onOptionsItemSelected(item); } -} + + private void insertPet() + { +// PetDbHelper mDbHelper = new PetDbHelper(this); + SQLiteDatabase db = mDbHelper.getWritableDatabase(); + + ContentValues values = new ContentValues(); +// values.put(PetEntry._ID, 1); + values.put(PetEntry.COLUMN_PET_NAME, "Toto"); + values.put(PetEntry.COLUMN_PET_BREED, "Terrier"); + values.put(PetEntry.COLUMN_PET_GENDER, PetEntry.GENDER_MALE); + values.put(PetEntry.COLUMN_PET_WEIGHT, 7); + + long id = db.insert(PetEntry.TABLE_NAME, null, values); + } +} \ No newline at end of file diff --git a/app/src/main/java/com/example/android/pets/EditorActivity.java b/app/src/main/java/com/example/android/pets/EditorActivity.java index 320d69d..6e6fe3b 100644 --- a/app/src/main/java/com/example/android/pets/EditorActivity.java +++ b/app/src/main/java/com/example/android/pets/EditorActivity.java @@ -15,6 +15,8 @@ */ package com.example.android.pets; +import android.content.ContentValues; +import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v4.app.NavUtils; import android.support.v7.app.AppCompatActivity; @@ -26,6 +28,11 @@ import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; +import android.widget.Toast; + +import com.example.android.pets.data.PetContract; +import com.example.android.pets.data.PetContract.*; +import com.example.android.pets.data.PetDbHelper; /** * Allows user to create a new pet or edit an existing one. @@ -44,6 +51,8 @@ public class EditorActivity extends AppCompatActivity { /** EditText field to enter the pet's gender */ private Spinner mGenderSpinner; +// private PetDbHelper mDbhelper; + /** * Gender of the pet. The possible values are: * 0 for unknown gender, 1 for male, 2 for female. @@ -55,6 +64,8 @@ protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_editor); +// mDbhelper = new PetDbHelper(this); + // 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); @@ -86,11 +97,11 @@ public void onItemSelected(AdapterView parent, View view, int position, long String selection = (String) parent.getItemAtPosition(position); if (!TextUtils.isEmpty(selection)) { if (selection.equals(getString(R.string.gender_male))) { - mGender = 1; // Male + mGender = PetEntry.GENDER_MALE; // Male } else if (selection.equals(getString(R.string.gender_female))) { - mGender = 2; // Female + mGender = PetEntry.GENDER_FEMALE; // Female } else { - mGender = 0; // Unknown + mGender = PetEntry.GENDER_UNKNOWN; // Unknown } } } @@ -111,13 +122,48 @@ public boolean onCreateOptionsMenu(Menu menu) { return true; } + private void insertPet() + { + String nameString = mNameEditText.getText().toString().trim(); + String breedString = mBreedEditText.getText().toString().trim(); + String weightString = mWeightEditText.getText().toString().trim(); + int weight = Integer.parseInt(weightString); + + + PetDbHelper mDbHelper = new PetDbHelper(this); + SQLiteDatabase db = mDbHelper.getWritableDatabase(); + + ContentValues values = new ContentValues(); + values.put(PetEntry.COLUMN_PET_NAME, nameString); + values.put(PetEntry.COLUMN_PET_BREED, breedString); + values.put(PetEntry.COLUMN_PET_GENDER, mGender); + values.put(PetEntry.COLUMN_PET_WEIGHT, weight); + + long newRowId = db.insert(PetEntry.TABLE_NAME, null, values); + + if (newRowId == -1) + { + // If the row ID is -1, then there was an error with insertion. + Toast.makeText(this, "Error with saving pet", Toast.LENGTH_SHORT).show(); + } + else + { + // Otherwise, the insertion was successful and we can display a toast with the row ID. + Toast.makeText(this, "Pet saved with row id: " + newRowId, Toast.LENGTH_SHORT).show(); + } + + } + @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: - // Do nothing for now + // Insert the pet into the database + insertPet(); + //Finish the Activity + finish(); return true; // Respond to a click on the "Delete" menu option case R.id.action_delete: diff --git a/app/src/main/java/com/example/android/pets/data/PetContract.java b/app/src/main/java/com/example/android/pets/data/PetContract.java new file mode 100644 index 0000000..1309ca3 --- /dev/null +++ b/app/src/main/java/com/example/android/pets/data/PetContract.java @@ -0,0 +1,24 @@ +package com.example.android.pets.data; + +import android.provider.BaseColumns; + +public final class PetContract +{ + private PetContract() {} + + public static final class PetEntry implements BaseColumns + { + 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"; + + public static final int GENDER_MALE = 1; + public static final int GENDER_FEMALE = 2; + public static final int GENDER_UNKNOWN = 0; + + } +} diff --git a/app/src/main/java/com/example/android/pets/data/PetDbHelper.java b/app/src/main/java/com/example/android/pets/data/PetDbHelper.java new file mode 100644 index 0000000..0ab2679 --- /dev/null +++ b/app/src/main/java/com/example/android/pets/data/PetDbHelper.java @@ -0,0 +1,44 @@ +package com.example.android.pets.data; + +import android.content.Context; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; +import android.util.Log; + +import com.example.android.pets.data.PetContract.*; + +public class PetDbHelper extends SQLiteOpenHelper +{ + private static final int DATABASE_VERSION = 1; + private static final String DATABASE_NAME = "shelter.db"; + + public PetDbHelper(Context context) + { + super(context, DATABASE_NAME, null, DATABASE_VERSION); + } + + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { +// db.execSQL(DELETE_ALL_ENTRIES); +// onCreate(db); + } + + @Override + public void onCreate(SQLiteDatabase db) + { + String SQL_CREATE_ENTRIES = "CREATE TABLE "+ PetEntry.TABLE_NAME +" (" + + PetEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + + PetEntry.COLUMN_PET_NAME + " TEXT NOT NULL ," + + PetEntry.COLUMN_PET_BREED+ " TEXT," + + PetEntry.COLUMN_PET_GENDER+ " INTEGER NOT NULL ," + +PetEntry.COLUMN_PET_WEIGHT+ " INTEGER NOT NULL DEFAULT 0" + + ");"; + Log.d("In onCreate", SQL_CREATE_ENTRIES); + db.execSQL(SQL_CREATE_ENTRIES); + } + + + + public static final String DELETE_ALL_ENTRIES = "DROP TABLE IF EXISTS " + PetEntry.TABLE_NAME; + +} diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index c086a8e..1a34964 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -14,10 +14,10 @@ Pets - + Insert Dummy Data - + Delete All Pets