Certainly! Let's architect and implement a sophisticated plant management Android application using Java and Android Studio, adhering closely to your specified requirements. Below is a comprehensive guide covering the app's architecture, UI design, data management, notification handling, and error handling to ensure a user-centric, high-performance application.
1. Project Setup
1.1. Create a New Android Project
- Name: PlantManager
- Language: Java
- Minimum SDK: API 21 (Android 5.0 Lollipop) to ensure broad device compatibility
- Activities: Start with an empty activity
1.2. Add Required Dependencies
Open build.gradle (Module: app) and add the following dependencies:
dependencies {
// Room components
implementation "androidx.room:room-runtime:2.5.2"
annotationProcessor "androidx.room:room-compiler:2.5.2"
// RecyclerView
implementation 'androidx.recyclerview:recyclerview:1.3.0'
// Glide for image loading
implementation 'com.github.bumptech.glide:glide:4.15.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.15.1'
// Material Design
implementation 'com.google.android.material:material:1.9.0'
// WorkManager for background tasks
implementation "androidx.work:work-runtime:2.8.1"
// Other necessary dependencies
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
}
2. Database Design with Room
2.1. Define the Plant Entity
Create a Plant.java file under com.example.plantmanager.model:
package com.example.plantmanager.model;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
@Entity(tableName = "plants")
public class Plant {
@PrimaryKey(autoGenerate = true)
private int id;
private String name;
private String species;
private String notes;
private String tags;
private String imageUri; // URI as String
private long wateringFrequency; // in milliseconds
private long fertilizingFrequency;
private long repottingFrequency;
private boolean isWateringActive;
private boolean isFertilizingActive;
private boolean isRepottingActive;
// Constructors, Getters, and Setters
// ... (Omitted for brevity)
}
2.2. Create the DAO Interface
Create PlantDao.java under com.example.plantmanager.data:
package com.example.plantmanager.data;
import androidx.lifecycle.LiveData;
import androidx.room.*;
import com.example.plantmanager.model.Plant;
import java.util.List;
@Dao
public interface PlantDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(Plant plant);
@Update
void update(Plant plant);
@Delete
void delete(Plant plant);
@Query("SELECT * FROM plants ORDER BY name ASC")
LiveData<List<Plant>> getAllPlants();
@Query("SELECT * FROM plants WHERE name LIKE :search OR species LIKE :search OR tags LIKE :search")
LiveData<List<Plant>> searchPlants(String search);
}
2.3. Initialize the Room Database
Create PlantDatabase.java under com.example.plantmanager.data:
package com.example.plantmanager.data;
import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import com.example.plantmanager.model.Plant;
@Database(entities = {Plant.class}, version = 1)
public abstract class PlantDatabase extends RoomDatabase {
private static PlantDatabase instance;
public abstract PlantDao plantDao();
public static synchronized PlantDatabase getInstance(Context context) {
if (instance == null) {
instance = Room.databaseBuilder(context.getApplicationContext(),
PlantDatabase.class, "plant_database")
.fallbackToDestructiveMigration()
.build();
}
return instance;
}
}
2.4. Create a Repository and ViewModel
Implementing MVVM architecture enhances code maintainability.
PlantRepository.java
package com.example.plantmanager.repository;
import android.app.Application;
import android.os.AsyncTask;
import androidx.lifecycle.LiveData;
import com.example.plantmanager.data.PlantDao;
import com.example.plantmanager.data.PlantDatabase;
import com.example.plantmanager.model.Plant;
import java.util.List;
public class PlantRepository {
private PlantDao plantDao;
private LiveData<List<Plant>> allPlants;
public PlantRepository(Application application) {
PlantDatabase database = PlantDatabase.getInstance(application);
plantDao = database.plantDao();
allPlants = plantDao.getAllPlants();
}
public void insert(Plant plant) {
new InsertPlantAsyncTask(plantDao).execute(plant);
}
public void update(Plant plant) {
new UpdatePlantAsyncTask(plantDao).execute(plant);
}
public void delete(Plant plant) {
new DeletePlantAsyncTask(plantDao).execute(plant);
}
public LiveData<List<Plant>> getAllPlants() {
return allPlants;
}
public LiveData<List<Plant>> searchPlants(String query) {
return plantDao.searchPlants("%" + query + "%");
}
// AsyncTasks for database operations
private static class InsertPlantAsyncTask extends AsyncTask<Plant, Void, Void> {
private PlantDao plantDao;
private InsertPlantAsyncTask(PlantDao plantDao) {
this.plantDao = plantDao;
}
@Override
protected Void doInBackground(Plant... plants) {
plantDao.insert(plants[0]);
return null;
}
}
private static class UpdatePlantAsyncTask extends AsyncTask<Plant, Void, Void> {
private PlantDao plantDao;
private UpdatePlantAsyncTask(PlantDao plantDao) {
this.plantDao = plantDao;
}
@Override
protected Void doInBackground(Plant... plants) {
plantDao.update(plants[0]);
return null;
}
}
private static class DeletePlantAsyncTask extends AsyncTask<Plant, Void, Void> {
private PlantDao plantDao;
private DeletePlantAsyncTask(PlantDao plantDao) {
this.plantDao = plantDao;
}
@Override
protected Void doInBackground(Plant... plants) {
plantDao.delete(plants[0]);
return null;
}
}
}
PlantViewModel.java
package com.example.plantmanager.viewmodel;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;
import com.example.plantmanager.model.Plant;
import com.example.plantmanager.repository.PlantRepository;
import java.util.List;
public class PlantViewModel extends AndroidViewModel {
private PlantRepository repository;
private LiveData<List<Plant>> allPlants;
public PlantViewModel(@NonNull Application application) {
super(application);
repository = new PlantRepository(application);
allPlants = repository.getAllPlants();
}
public void insert(Plant plant) {
repository.insert(plant);
}
public void update(Plant plant) {
repository.update(plant);
}
public void delete(Plant plant) {
repository.delete(plant);
}
public LiveData<List<Plant>> getAllPlants() {
return allPlants;
}
public LiveData<List<Plant>> searchPlants(String query) {
return repository.searchPlants(query);
}
}
3. User Interface Design
We'll design two main screens:
- Main Screen: Displays the list/grid of plants.
- Add/Edit Plant Screen: Allows users to add or modify plant details.
3.1. Main Activity Layout
File: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!-- Toolbar with Search -->
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:title="Plant Manager"
app:titleTextColor="@android:color/white"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
</com.google.android.material.appbar.AppBarLayout>
<!-- RecyclerView for Plant Entries -->
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerViewPlants"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="8dp"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
android:paddingBottom="80dp"/>
<!-- Floating Action Button to Add Plant -->
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fabAddPlant"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="Add Plant"
android:src="@drawable/ic_add"
app:backgroundTint="@color/colorPrimary"
app:layout_anchor="@id/recyclerViewPlants"
app:layout_anchorGravity="bottom|end"
android:layout_margin="16dp"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
3.2. Plant RecyclerView Item Layout
File: item_plant.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="8dp"
android:layout_margin="8dp"
card_view:cardElevation="4dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="120dp">
<ImageView
android:id="@+id/imageViewPlant"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="10dp"
android:scaleType="centerCrop"
android:src="@drawable/ic_plant_placeholder" />
<TextView
android:id="@+id/textViewPlantName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="@id/imageViewPlant"
android:layout_marginStart="10dp"
android:text="Plant Name"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textViewPlantSpecies"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textViewPlantName"
android:layout_toEndOf="@id/imageViewPlant"
android:layout_marginStart="10dp"
android:text="Species"
android:textSize="14sp"
android:textColor="@color/gray" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
3.3. Add/Edit Plant Activity Layout
File: activity_add_edit_plant.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".AddEditPlantActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Image View for Plant Photo -->
<ImageView
android:id="@+id/imageViewPlantPhoto"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_gravity="center"
android:scaleType="centerCrop"
android:src="@drawable/ic_plant_placeholder"
android:contentDescription="Plant Photo" />
<!-- Button to Capture/Select Photo -->
<Button
android:id="@+id/buttonCapturePhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Photo"
android:layout_gravity="center"
android:layout_marginTop="8dp"/>
<!-- Plant Name Input -->
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Plant Name"
android:layout_marginTop="16dp">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/editTextPlantName"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</com.google.android.material.textfield.TextInputLayout>
<!-- Species Input -->
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Species"
android:layout_marginTop="8dp">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/editTextSpecies"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</com.google.android.material.textfield.TextInputLayout>
<!-- Notes Input -->
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Notes"
android:layout_marginTop="8dp">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/editTextNotes"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:lines="3"/>
</com.google.android.material.textfield.TextInputLayout>
<!-- Tags Input -->
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Tags (comma separated)"
android:layout_marginTop="8dp">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/editTextTags"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</com.google.android.material.textfield.TextInputLayout>
<!-- Notification Settings -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Care Reminders"
android:textSize="16sp"
android:textStyle="bold"
android:layout_marginTop="16dp"/>
<!-- Watering Reminder -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:layout_marginTop="8dp">
<CheckBox
android:id="@+id/checkBoxWatering"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Watering" />
<EditText
android:id="@+id/editTextWateringFrequency"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:hint="Frequency in days"
android:inputType="number"
android:enabled="false"
android:layout_marginStart="8dp"/>
</LinearLayout>
<!-- Fertilizing Reminder -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:layout_marginTop="8dp">
<CheckBox
android:id="@+id/checkBoxFertilizing"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fertilizing" />
<EditText
android:id="@+id/editTextFertilizingFrequency"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:hint="Frequency in weeks"
android:inputType="number"
android:enabled="false"
android:layout_marginStart="8dp"/>
</LinearLayout>
<!-- Repotting Reminder -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:layout_marginTop="8dp">
<CheckBox
android:id="@+id/checkBoxRepotting"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Repotting" />
<EditText
android:id="@+id/editTextRepottingFrequency"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:hint="Frequency in months"
android:inputType="number"
android:enabled="false"
android:layout_marginStart="8dp"/>
</LinearLayout>
<!-- Save Button -->
<Button
android:id="@+id/buttonSavePlant"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Save"
android:layout_marginTop="16dp"/>
</LinearLayout>
</ScrollView>
3.4. Implementing Dynamic UI Behavior
In the AddEditPlantActivity, enable/disable frequency EditText fields based on CheckBox states.
4. Implementing the Main Activity
4.1. MainActivity.java
package com.example.plantmanager;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.example.plantmanager.adapter.PlantAdapter;
import com.example.plantmanager.model.Plant;
import com.example.plantmanager.viewmodel.PlantViewModel;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private PlantViewModel plantViewModel;
private RecyclerView recyclerView;
private PlantAdapter adapter;
public static final int ADD_PLANT_REQUEST = 1;
public static final int EDIT_PLANT_REQUEST = 2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerViewPlants);
adapter = new PlantAdapter();
recyclerView.setAdapter(adapter);
plantViewModel = new ViewModelProvider(this).get(PlantViewModel.class);
plantViewModel.getAllPlants().observe(this, new Observer<List<Plant>>() {
@Override
public void onChanged(@Nullable List<Plant> plants) {
adapter.setPlants(plants);
}
});
FloatingActionButton buttonAddPlant = findViewById(R.id.fabAddPlant);
buttonAddPlant.setOnClickListener(v -> {
Intent intent = new Intent(MainActivity.this, AddEditPlantActivity.class);
startActivityForResult(intent, ADD_PLANT_REQUEST);
});
adapter.setOnItemClickListener(new PlantAdapter.OnItemClickListener() {
@Override
public void onItemClick(Plant plant) {
Intent intent = new Intent(MainActivity.this, AddEditPlantActivity.class);
intent.putExtra(AddEditPlantActivity.EXTRA_ID, plant.getId());
intent.putExtra(AddEditPlantActivity.EXTRA_NAME, plant.getName());
intent.putExtra(AddEditPlantActivity.EXTRA_SPECIES, plant.getSpecies());
intent.putExtra(AddEditPlantActivity.EXTRA_NOTES, plant.getNotes());
intent.putExtra(AddEditPlantActivity.EXTRA_TAGS, plant.getTags());
intent.putExtra(AddEditPlantActivity.EXTRA_IMAGE_URI, plant.getImageUri());
// Add other extras as needed
startActivityForResult(intent, EDIT_PLANT_REQUEST);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Handle results from AddEditPlantActivity
if (requestCode == ADD_PLANT_REQUEST && resultCode == RESULT_OK) {
// Extract data and insert into database
// Not shown for brevity
Toast.makeText(this, "Plant saved", Toast.LENGTH_SHORT).show();
} else if (requestCode == EDIT_PLANT_REQUEST && resultCode == RESULT_OK) {
// Extract data and update existing plant
// Not shown for brevity
Toast.makeText(this, "Plant updated", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Plant not saved", Toast.LENGTH_SHORT).show();
}
}
// Implement Search in Toolbar
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
// Implement SearchView here if needed
// Not shown for brevity
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle menu item clicks
// Not shown for brevity
return super.onOptionsItemSelected(item);
}
}
4.2. PlantAdapter.java
Create an adapter package and add PlantAdapter.java:
package com.example.plantmanager.adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.example.plantmanager.R;
import com.example.plantmanager.model.Plant;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
public class PlantAdapter extends RecyclerView.Adapter<PlantAdapter.PlantHolder> {
private List<Plant> plants = new ArrayList<>();
private OnItemClickListener listener;
@Override
public PlantHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_plant, parent, false);
return new PlantHolder(itemView);
}
@Override
public void onBindViewHolder(PlantHolder holder, int position) {
Plant currentPlant = plants.get(position);
holder.textViewName.setText(currentPlant.getName());
holder.textViewSpecies.setText(currentPlant.getSpecies());
// Load image using Glide
if (currentPlant.getImageUri() != null && !currentPlant.getImageUri().isEmpty()) {
Glide.with(holder.imageViewPlant.getContext())
.load(currentPlant.getImageUri())
.placeholder(R.drawable.ic_plant_placeholder)
.into(holder.imageViewPlant);
} else {
holder.imageViewPlant.setImageResource(R.drawable.ic_plant_placeholder);
}
}
@Override
public int getItemCount() {
return plants.size();
}
public void setPlants(List<Plant> plants) {
this.plants = plants;
notifyDataSetChanged();
}
class PlantHolder extends RecyclerView.ViewHolder {
private ImageView imageViewPlant;
private TextView textViewName;
private TextView textViewSpecies;
public PlantHolder(View itemView) {
super(itemView);
imageViewPlant = itemView.findViewById(R.id.imageViewPlant);
textViewName = itemView.findViewById(R.id.textViewPlantName);
textViewSpecies = itemView.findViewById(R.id.textViewPlantSpecies);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = getAdapterPosition();
if (listener != null && position != RecyclerView.NO_POSITION) {
listener.onItemClick(plants.get(position));
}
}
});
}
}
public interface OnItemClickListener {
void onItemClick(Plant plant);
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
}
5. Add/Edit Plant Activity Implementation
5.1. AddEditPlantActivity.java
package com.example.plantmanager;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import android.Manifest;
import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.*;
import com.bumptech.glide.Glide;
import com.example.plantmanager.model.Plant;
import com.example.plantmanager.viewmodel.PlantViewModel;
import com.google.android.material.textfield.TextInputEditText;
import java.io.IOException;
import java.util.Calendar;
public class AddEditPlantActivity extends AppCompatActivity {
public static final String EXTRA_ID = "com.example.plantmanager.EXTRA_ID";
public static final String EXTRA_NAME = "com.example.plantmanager.EXTRA_NAME";
public static final String EXTRA_SPECIES = "com.example.plantmanager.EXTRA_SPECIES";
public static final String EXTRA_NOTES = "com.example.plantmanager.EXTRA_NOTES";
public static final String EXTRA_TAGS = "com.example.plantmanager.EXTRA_TAGS";
public static final String EXTRA_IMAGE_URI = "com.example.plantmanager.EXTRA_IMAGE_URI";
// Add other extras as needed
private static final int REQUEST_IMAGE_CAPTURE = 100;
private static final int PICK_IMAGE_REQUEST = 101;
private static final int CAMERA_PERMISSION_REQUEST = 102;
private ImageView imageViewPlantPhoto;
private Button buttonCapturePhoto;
private TextInputEditText editTextName, editTextSpecies, editTextNotes, editTextTags;
private CheckBox checkBoxWatering, checkBoxFertilizing, checkBoxRepotting;
private EditText editTextWateringFrequency, editTextFertilizingFrequency, editTextRepottingFrequency;
private Button buttonSavePlant;
private Uri imageUri;
private PlantViewModel plantViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_edit_plant);
imageViewPlantPhoto = findViewById(R.id.imageViewPlantPhoto);
buttonCapturePhoto = findViewById(R.id.buttonCapturePhoto);
editTextName = findViewById(R.id.editTextPlantName);
editTextSpecies = findViewById(R.id.editTextSpecies);
editTextNotes = findViewById(R.id.editTextNotes);
editTextTags = findViewById(R.id.editTextTags);
checkBoxWatering = findViewById(R.id.checkBoxWatering);
checkBoxFertilizing = findViewById(R.id.checkBoxFertilizing);
checkBoxRepotting = findViewById(R.id.checkBoxRepotting);
editTextWateringFrequency = findViewById(R.id.editTextWateringFrequency);
editTextFertilizingFrequency = findViewById(R.id.editTextFertilizingFrequency);
editTextRepottingFrequency = findViewById(R.id.editTextRepottingFrequency);
buttonSavePlant = findViewById(R.id.buttonSavePlant);
plantViewModel = new ViewModelProvider(this).get(PlantViewModel.class);
// Handle CheckBox logic
handleCheckBoxes();
// Handle Capture Photo Button
buttonCapturePhoto.setOnClickListener(v -> {
// Check for camera permission
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST);
} else {
dispatchTakePictureIntent();
}
});
// Save Button Click Listener
buttonSavePlant.setOnClickListener(v -> savePlant());
// If editing, populate fields
Intent intent = getIntent();
if (intent.hasExtra(EXTRA_ID)) {
setTitle("Edit Plant");
editTextName.setText(intent.getStringExtra(EXTRA_NAME));
editTextSpecies.setText(intent.getStringExtra(EXTRA_SPECIES));
editTextNotes.setText(intent.getStringExtra(EXTRA_NOTES));
editTextTags.setText(intent.getStringExtra(EXTRA_TAGS));
String imgUriStr = intent.getStringExtra(EXTRA_IMAGE_URI);
if (imgUriStr != null && !imgUriStr.isEmpty()) {
imageUri = Uri.parse(imgUriStr);
Glide.with(this).load(imageUri).into(imageViewPlantPhoto);
}
// Populate notification settings if needed
// Not shown for brevity
} else {
setTitle("Add Plant");
}
}
private void handleCheckBoxes() {
checkBoxWatering.setOnCheckedChangeListener((buttonView, isChecked) -> {
editTextWateringFrequency.setEnabled(isChecked);
if (!isChecked) {
editTextWateringFrequency.setText("");
}
});
checkBoxFertilizing.setOnCheckedChangeListener((buttonView, isChecked) -> {
editTextFertilizingFrequency.setEnabled(isChecked);
if (!isChecked) {
editTextFertilizingFrequency.setText("");
}
});
checkBoxRepotting.setOnCheckedChangeListener((buttonView, isChecked) -> {
editTextRepottingFrequency.setEnabled(isChecked);
if (!isChecked) {
editTextRepottingFrequency.setText("");
}
});
}
private void savePlant() {
String name = editTextName.getText().toString().trim();
String species = editTextSpecies.getText().toString().trim();
String notes = editTextNotes.getText().toString().trim();
String tags = editTextTags.getText().toString().trim();
String imgUriStr = imageUri != null ? imageUri.toString() : "";
if (name.isEmpty()) {
editTextName.setError("Name is required");
editTextName.requestFocus();
return;
}
Plant plant = new Plant();
plant.setName(name);
plant.setSpecies(species);
plant.setNotes(notes);
plant.setTags(tags);
plant.setImageUri(imgUriStr);
// Handle reminders
if (checkBoxWatering.isChecked()) {
String wateringFreqStr = editTextWateringFrequency.getText().toString().trim();
if (!wateringFreqStr.isEmpty()) {
int days = Integer.parseInt(wateringFreqStr);
plant.setWateringFrequency(days * 24 * 60 * 60 * 1000L);
plant.setIsWateringActive(true);
// Schedule watering notification
scheduleNotification(plant, "Watering", plant.getWateringFrequency());
}
}
if (checkBoxFertilizing.isChecked()) {
String fertilizingFreqStr = editTextFertilizingFrequency.getText().toString().trim();
if (!fertilizingFreqStr.isEmpty()) {
int weeks = Integer.parseInt(fertilizingFreqStr);
plant.setFertilizingFrequency(weeks * 7 * 24 * 60 * 60 * 1000L);
plant.setIsFertilizingActive(true);
// Schedule fertilizing notification
scheduleNotification(plant, "Fertilizing", plant.getFertilizingFrequency());
}
}
if (checkBoxRepotting.isChecked()) {
String repottingFreqStr = editTextRepottingFrequency.getText().toString().trim();
if (!repottingFreqStr.isEmpty()) {
int months = Integer.parseInt(repottingFreqStr);
plant.setRepottingFrequency(months * 30 * 24 * 60 * 60 * 1000L);
plant.setIsRepottingActive(true);
// Schedule repotting notification
scheduleNotification(plant, "Repotting", plant.getRepottingFrequency());
}
}
Intent data = new Intent();
data.putExtra(EXTRA_NAME, name);
data.putExtra(EXTRA_SPECIES, species);
data.putExtra(EXTRA_NOTES, notes);
data.putExtra(EXTRA_TAGS, tags);
data.putExtra(EXTRA_IMAGE_URI, imgUriStr);
// Add other extras as needed
int id = getIntent().getIntExtra(EXTRA_ID, -1);
if (id != -1) {
plant.setId(id);
plantViewModel.update(plant);
// Update notifications accordingly
} else {
plantViewModel.insert(plant);
// Schedule notifications accordingly
}
setResult(RESULT_OK, data);
finish();
}
private void scheduleNotification(Plant plant, String type, long frequency) {
// Implement notification scheduling using AlarmManager or WorkManager
// Placeholder for implementation
}
// Handle Camera Intent
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure there's a camera activity
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
} else {
Toast.makeText(this, "No camera application found", Toast.LENGTH_SHORT).show();
}
}
// Handle Image Selection Result
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imageUri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), imageBitmap, "PlantPhoto", null));
Glide.with(this).load(imageUri).into(imageViewPlantPhoto);
} else if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
imageUri = data.getData();
Glide.with(this).load(imageUri).into(imageViewPlantPhoto);
}
}
// Handle Permission Result
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == CAMERA_PERMISSION_REQUEST){
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
dispatchTakePictureIntent();
} else {
Toast.makeText(this, "Camera permission is required to take photos", Toast.LENGTH_SHORT).show();
}
}
}
}
Note: For image selection from the gallery, consider adding another button or enabling the existing one to pick images. Due to brevity, only camera capture is showcased.
5.2. Handling Notifications
Implementing notifications requires careful scheduling to ensure reliability.
5.2.1. Using WorkManager for Notifications
Using WorkManager is preferred over AlarmManager for its robustness across different device states.
Add ReminderWorker.java
Create workers package and add ReminderWorker.java:
package com.example.plantmanager.workers;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;
import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import androidx.work.*;
import com.example.plantmanager.R;
public class ReminderWorker extends Worker {
public static final String CHANNEL_ID = "plant_manager_channel";
public ReminderWorker(@NonNull Context context, @NonNull WorkerParameters params) {
super(context, params);
}
@NonNull
@Override
public Result doWork() {
// Extract data from input
String plantName = getInputData().getString("plantName");
String reminderType = getInputData().getString("reminderType");
// Create Notification
createNotificationChannel();
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Plant Care Reminder")
.setContentText("Time to " + reminderType + " your plant: " + plantName)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true);
NotificationManager manager = (NotificationManager) getApplicationContext()
.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify((int) System.currentTimeMillis(), builder.build());
return Result.success();
}
private void createNotificationChannel(){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
CharSequence name = "Plant Manager Channel";
String description = "Channel for plant care reminders";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,name,importance);
channel.setDescription(description);
NotificationManager manager = getApplicationContext().getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
}
}
5.2.2. Scheduling Work with WorkManager
Modify AddEditPlantActivity.java to schedule reminders.
private void scheduleNotification(Plant plant, String type, long frequency) {
Data data = new Data.Builder()
.putString("plantName", plant.getName())
.putString("reminderType", type)
.build();
// Schedule periodic work
PeriodicWorkRequest workRequest = new PeriodicWorkRequest.Builder(ReminderWorker.class,
frequency,
TimeUnit.MILLISECONDS)
.setInputData(data)
.build();
WorkManager.getInstance(this).enqueueUniquePeriodicWork(
plant.getId() + "_" + type, // unique name
ExistingPeriodicWorkPolicy.REPLACE,
workRequest
);
}
Notes:
- Frequency Conversion: Ensure that frequency is converted appropriately from days/weeks/months to the required
TimeUnit.
- Unique Work Names: This ensures that reminders for the same plant and type don't stack.
5.2.3. Canceling Work
When a plant or a specific reminder is deleted or disabled, cancel the associated work:
private void cancelNotification(Plant plant, String type) {
WorkManager.getInstance(this).cancelUniqueWork(plant.getId() + "_" + type);
}
Call this method appropriately in your update/delete logic.
6. Data Handling and Storage
6.1. Image Storage
Storing images efficiently is crucial for performance:
- Option 1: Store image URIs pointing to images saved in the device's storage.
- Option 2: Compress and save images as byte arrays in the database.
Implementation Choice: Store image URIs to minimize database size and leverage Android's optimized image handling.
Handling Image Permissions:
- Camera: Already handled with runtime permissions.
- Gallery Access: If implemented, ensure
READ_EXTERNAL_STORAGE permission is managed.
6.2. Efficient Data Retrieval and Sorting
Implement search functionality in MainActivity to allow users to filter plants by name, species, or tags.
Example: Implementing a SearchView in Toolbar
Modify main_menu.xml:
Create res/menu/main_menu.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_search"
android:title="Search"
android:icon="@drawable/ic_search"
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="androidx.appcompat.widget.SearchView" />
</menu>
Modify MainActivity.java to Handle Search:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
androidx.appcompat.widget.SearchView searchView = (androidx.appcompat.widget.SearchView) searchItem.getActionView();
searchView.setQueryHint("Search Plants");
searchView.setOnQueryTextListener(new androidx.appcompat.widget.SearchView.OnQueryTextListener(){
@Override
public boolean onQueryTextSubmit(String query){
searchPlants(query);
return false;
}
@Override
public boolean onQueryTextChange(String newText){
searchPlants(newText);
return false;
}
});
return true;
}
private void searchPlants(String query){
String searchQuery = "%" + query + "%";
plantViewModel.searchPlants(searchQuery).observe(this, new Observer<List<Plant>>() {
@Override
public void onChanged(List<Plant> plants) {
adapter.setPlants(plants);
}
});
}
7. Notifications and Reminders Handling
7.1. Ensuring Persistency of Reminders
Use WorkManager, as it handles device reboot and app restarts.
Handle Device Reboot:
To ensure that reminders persist after a device reboot, create a BroadcastReceiver that listens for BOOT_COMPLETED and reschedules all reminders.
Add Permission in AndroidManifest.xml:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
Create BootReceiver.java:
package com.example.plantmanager.receivers;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import androidx.work.WorkManager;
import com.example.plantmanager.viewmodel.PlantViewModel;
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())){
// Re-initialize WorkManager schedules
PlantViewModel plantViewModel = new PlantViewModel((Application) context.getApplicationContext());
// Fetch all plants and reschedule reminders
plantViewModel.getAllPlants().observeForever(plants -> {
for(Plant plant: plants){
if(plant.isWateringActive()){
// schedule watering
// Implement scheduling logic here
}
if(plant.isFertilizingActive()){
// schedule fertilizing
// Implement scheduling logic here
}
if(plant.isRepottingActive()){
// schedule repotting
// Implement scheduling logic here
}
}
});
}
}
}
Register Receiver in AndroidManifest.xml:
<receiver
android:name=".receivers.BootReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
Note: The above BootReceiver should be optimized to prevent memory leaks. Using a Service or other mechanisms might be more appropriate for production.
8. Error Handling and User Experience Enhancements
8.1. Handling Missing Permissions
Already handled camera permissions in AddEditPlantActivity.java. Similarly:
- Gallery Permissions: If implemented, handle
READ_EXTERNAL_STORAGE similarly.
- Notification Permissions: Since Android 13 requires runtime notification permissions, handle accordingly.
8.2. Handling Image Save Failures
Provide user feedback using Snackbar or Toast messages when image capture or saving fails.
Example:
catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Failed to save image", Toast.LENGTH_SHORT).show();
}
8.3. Handling Notification Setup Issues
Notify users if scheduling a reminder fails.
Example:
In scheduleNotification(), wrap scheduling logic with try-catch:
try {
// Scheduling logic
} catch (Exception e) {
Toast.makeText(this, "Failed to schedule reminder", Toast.LENGTH_SHORT).show();
}
8.4. Providing User Feedback
Use Snackbar for quick messages or Dialogs for critical issues.
Example: Using Snackbar:
Snackbar.make(findViewById(R.id.coordinatorLayout), "Plant saved successfully", Snackbar.LENGTH_LONG).show();
8.5. Optimizing Performance
- Image Loading: Use Glide's built-in caching and image optimization features.
- Database Operations: Ensure asynchronous operations and avoid main thread blocking.
- RecyclerView Optimization:
- Use
ListAdapter with DiffUtil for efficient list updates.
- Implement view holder patterns properly.
Example: Updating PlantAdapter to use ListAdapter
public class PlantAdapter extends ListAdapter<Plant, PlantAdapter.PlantHolder> {
// Implementation using DiffUtil
}
9. Final Touches and Testing
9.1. Material Design Alignment
Ensure all UI components adhere to Material Design guidelines:
- Consistent Coloring: Use a consistent color palette aligned with plant and nature themes.
- Typography: Use readable fonts and appropriate text sizes.
- Animations: Implement subtle animations for better user experience.
9.2. Testing
Conduct thorough testing:
- Unit Testing: Test ViewModel and Repository components.
- UI Testing: Use Espresso to test UI flows.
- Beta Testing: Release to a small user group to gather feedback.
9.3. Deployment Preparation
- Icons and Branding: Design app icons and branding assets.
- Privacy Policy: If storing user data, ensure compliance with privacy standards.
- App Bundle Optimization: Use ProGuard/R8 for code optimization and obfuscation.
Conclusion
By following the above comprehensive guide, you can build a sophisticated plant management app that offers users an intuitive and visually appealing experience. The app will efficiently handle plant documentation, image management, and care reminders with robust error handling and performance optimizations. Remember to iterate based on user feedback to continually enhance the app's functionality and user experience.