Share
Explore

Android Pet Farm - Working with Android Kotlin Shared Preference

Creating a Virtual Pet Farm app with Kotlin in Android involves several components. We'll start by outlining the `MainActivity.kt` and `activity_main.xml` for adding pet records.
Then, I'll provide the contents for the `build.gradle.kts` file.
### MainActivity.kt (Screen A - Add Pet Records) This is a simplified version. You'll need another activity (Screen B) for displaying and editing the pet list.
```kotlin ​package com.example.peterapp1
import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.example.peterapp1.databinding.ActivityMainBinding import com.google.gson.Gson import com.google.gson.reflect.TypeToken
class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root)
binding.buttonAddPet.setOnClickListener { val name = binding.editTextPetName.text.toString() val description = binding.editTextPetDescription.text.toString() val pet = Pet(name, description) addPetToSharedPreferences(pet) }
binding.buttonViewPets.setOnClickListener { startActivity(Intent(this, PetListActivity::class.java)) } }
private fun addPetToSharedPreferences(pet: Pet) { val sharedPreferences = getSharedPreferences("PetPrefs", MODE_PRIVATE) val editor = sharedPreferences.edit()
val pets = getPetsFromSharedPreferences().toMutableList() pets.add(pet)
val gson = Gson() val json = gson.toJson(pets) editor.putString("pets", json) editor.apply() }
private fun getPetsFromSharedPreferences(): List<Pet> { val sharedPreferences = getSharedPreferences("PetPrefs", MODE_PRIVATE) val gson = Gson() val json = sharedPreferences.getString("pets", null) val type = object : TypeToken<List<Pet>>() {}.type return gson.fromJson(json, type) ?: emptyList() } }
data class Pet(val name: String, val description: String) ```
### activity_main.xml (Add Pet Record Layout) This file defines the user interface for adding a pet.
```xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp">
<EditText android:id="@+id/editTextPetName" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter pet name"/>
<EditText android:id="@+id/editTextPetDescription" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter pet description"/>
<Button android:id="@+id/buttonAddPet" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Add Pet"/>
<Button android:id="@+id/buttonViewPets" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="View Pets"/> </LinearLayout> ```
### build.gradle.kts (Module: app) This file configures your app's build settings. Make sure to include Gson for JSON serialization.
```kotlin plugins { id("com.android.application") kotlin("android") kotlin("android.extensions") }
android { compileSdkVersion(30) defaultConfig { applicationId = "com.example.peterapp1" minSdkVersion(21) targetSdkVersion(30) versionCode = 1 versionName = "1.0" }
buildTypes { getByName("release") { isMinifyEnabled = false proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") } }
compileOptions { sourceCompatibility(JavaVersion.VERSION_1_8) targetCompatibility(JavaVersion.VERSION_1_8) }
kotlinOptions { jvmTarget = "1.8" } }
dependencies { implementation("androidx.core:core-ktx:1.3.2") implementation("androidx.appcompat:appcompat:1.2.0") implementation("com.google.android.material:material:1.3.0") implementation("androidx.constraintlayout:constraintlayout:2.0.4") testImplementation("junit:junit:4.13.2") androidTestImplementation("androidx.test.ext:junit:1.1.2") androidTestImplementation("androidx.test.espresso:espresso-core:3.3.0") implementation("com.google.code.gson:gson:2.8.6") } ```
### Workflow Instructions: 1. **Setup Project**: Create a new Android project in Android Studio with the name `peterapp1` and package name `com.example.peterapp1`.
2. **Add Dependencies**: Include Gson in your `build.gradle.kts` file for JSON serialization.
3. **Implement Activities**: Create `MainActivity` and `activity_main.xml` as provided. Implement `PetListActivity` (Screen B) for displaying and editing pet records.
4. **Handling Data**: Use Shared Preferences to store pet records. Use Gson to serialize and deserialize the list of pets.
5. **Navigation**: Add functionality to navigate between `MainActivity` and `PetListActivity`.
6. **Testing**: Run the app and test adding, viewing, and editing pet records.
Remember, this is a basic structure. You may need to add more features or handle edge cases based on your requirements. Also, ensure your Android Studio and SDK tools are up to date to avoid compatibility issues.

Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.