Home > Back-end >  Passing a Class Variable Globally in Android (Java)
Passing a Class Variable Globally in Android (Java)

Time:11-26

So in my Java code for my app I have a class called Pet. A variable of this is created in one of my activities further in my app.

I've so far been able to successfully create an instance of this class and get variables from it in the same activity.

Now I would like to pass that newly created Class variable (pet1) to the rest of my application and use functions like the getPetName() function in my other activities to set the string displayed on buttons and other elements of the application.

This is the Pet class

package com.example.myapplication;
import java.time.format.DateTimeFormatter;

public class Pet {

    // Variable Declarations
    private String name;
    private String species;
    private int birthday;
    private String notes = "Notes: ";
    // Replace with a clock
    // Find a way to calculate age based on time-birthday
    private int currentTime;
    //Create an array of medications

    // Creation Function
    public Pet(String petName, String petSpecies, String petBirthDay, String petNotes, String petMedication, int petDosage, String petDosageUnit){
        setPetName(petName);
        setSpecies(petSpecies);
        setBirthDay(petBirthDay);
        addNotes(petNotes);
        addMeds(petMedication, petDosage, petDosageUnit);
    }

    // Set name Function
    private void setPetName(String petName){
        name = petName;
    }

    // Get name Function
    public String getPetName(){
        return name;
    }

    // Set species Function
    private void setSpecies(String petSpecies) {
        species = petSpecies;
    }

    // Get species Function
    public String getSpecies(){
        return species;
    }

    // Set birthday Function
    private void setBirthDay(String petBirthDay) {
        // Convert Birthday to integer
        //birthday = petBirthDay;
    }

    // Get age Function
    public int getAge(){
        // We calculate the age by taking the BirthDay and subtracting the current time
        return (currentTime - birthday);
    }

    // Add notes Function
    public void addNotes(String newNotes){
        // There are no current notes
        if (notes == "Notes: ") {
            notes = notes   newNotes;
        }
        // Make a new line and append the new notes
        else {
            notes = notes   "\n"   newNotes;
        }
    }

    // Get notes Function
    public String getNotes(){
        return notes;
    }

    // Combine Medication Information and add to Array
    public void addMeds(String medName, int medDosage, String unit){
        String medInfo = medName   " : "   medDosage   unit;
    }
    

}

This is the activity that creates an instance of the class

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class AddPetScreen extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
    private Button addPetButton;

    private EditText petNameText;
    private EditText petBirthdayText;
    private EditText petNotesText;

    private Spinner petSpeciesSpinner;
    private String speciesChoice;

    private String petNameTextVal;
    private String petBDayTextVal;
    private String petNotesTextVal;

    public Pet pet1;
    //public static final Pet GLOBAL_PET = "com.example.myapplication.GLOBAL_PET";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_pet_screen);

        petNameText = (EditText)findViewById(R.id.addPetNameField);
        petBirthdayText = (EditText)findViewById(R.id.addPetBirthdayField);
        petNotesText = (EditText) findViewById(R.id.addPetNotesField);

        petSpeciesSpinner = findViewById(R.id.addPetSpeciesSpinner);

        ArrayAdapter<CharSequence> speciesAdapter = ArrayAdapter.createFromResource(this, R.array.Species, android.R.layout.simple_spinner_dropdown_item);
        speciesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        petSpeciesSpinner.setAdapter(speciesAdapter);
        petSpeciesSpinner.setOnItemSelectedListener(this);


        // Button to create Pet in Pet Class and Add
        addPetButton = (Button) findViewById(R.id.addPetAddPetButton);
        addPetButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addPet();
            }
        });
    }

    // Function to create Pet in Pet class and Add
    public void addPet() {
        // Need to parse variables from text boxes and spinner
        petNameTextVal = petNameText.getText().toString();
        petNotesTextVal = petNotesText.getText().toString();
        petBDayTextVal = petBirthdayText.getText().toString();
        // NOTE: Do not pass in medication, since that is the Veterinarians Job

        // Check for empty parameters
        if (petNameText.getText().toString().isEmpty()) {
            Toast.makeText(getApplicationContext(), "Please Enter a Pet Name", Toast.LENGTH_SHORT).show();
        }
        else if (petBirthdayText.getText().toString().isEmpty()){
                Toast.makeText(getApplicationContext(),"Please Enter a Birth Date (YYYY/MM/DD)",Toast.LENGTH_SHORT).show();
        }
        // All necessary values are given
        else {
            if (checkBirthdayValidity() == false){
                Toast.makeText(getApplicationContext(), "Date Incorrect", Toast.LENGTH_SHORT).show();
            }
            else {
                // If there are no notes, set it to the empty string
                if (petNotesText.getText().toString().isEmpty()) {
                    petNotesTextVal = "";
                }
                // Create Pet
                pet1 = new Pet(petNameTextVal, speciesChoice, petBDayTextVal, petNotesTextVal, "", 0, "");
                Toast.makeText(getApplicationContext(), "Success! "   pet1.getPetName()   " was added", Toast.LENGTH_SHORT).show();

            }
        }
    }

    // Check if the birthday is in YYYY/MM/DD format
    public boolean checkBirthdayValidity(){
        petBDayTextVal = petBirthdayText.getText().toString();
        String year;
        year = petBDayTextVal.substring(0, 4);

        // Check that the birthday is a valid input
        if(petBDayTextVal.length() != 10){
            Toast.makeText(getApplicationContext(),"Incorrect Date, Please check your input",Toast.LENGTH_SHORT).show();
            return false;
        }
        else if (petBDayTextVal.substring(0, 4).matches("-?\\d ") == false) {
            Toast.makeText(getApplicationContext(), "Incorrect Year input", Toast.LENGTH_SHORT).show();
            return false;
        }
        else if (Integer.valueOf(petBDayTextVal.substring(0, 4)) <= 1989 || Integer.valueOf(petBDayTextVal.substring(0, 4)) >= 2022){
            Toast.makeText(getApplicationContext(), "Incorrect Year input: Please input a Year between 1990 and 2021", Toast.LENGTH_SHORT).show();
            return false;
        }
        // Year has been checked, now check Month
        else if (petBDayTextVal.substring(4, 5).contains("/") == false){
            Toast.makeText(getApplicationContext(),"Forgot the / after Year",Toast.LENGTH_SHORT).show();
            return false;
        }
        else if (petBDayTextVal.substring(5, 7).matches("-?\\d ") == false){
            Toast.makeText(getApplicationContext(), "Incorrect Month input", Toast.LENGTH_SHORT).show();
            return false;
        }
        else if (Integer.valueOf(petBDayTextVal.substring(5, 7)) <= 0 || Integer.valueOf(petBDayTextVal.substring(5, 7)) >= 13){
            Toast.makeText(getApplicationContext(), "Incorrect Month input: Please input a Month between 01 and 12", Toast.LENGTH_SHORT).show();
            return false;
        }
        // Month has been checked, now check Day
        else if (petBDayTextVal.substring(7, 8).contains("/") == false){
            Toast.makeText(getApplicationContext(), "Forgot the / after Month", Toast.LENGTH_SHORT).show();
            return false;
        }
        else if (petBDayTextVal.substring(8, 10).matches("-?\\d ") == false){
            Toast.makeText(getApplicationContext(), "Incorrect Day input", Toast.LENGTH_SHORT).show();
            return false;
        }
        // Check for 31 Day Months
        else if (Integer.valueOf(petBDayTextVal.substring(5, 7)) == 1 || Integer.valueOf(petBDayTextVal.substring(5, 7)) == 3 || Integer.valueOf(petBDayTextVal.substring(5, 7)) == 5 || Integer.valueOf(petBDayTextVal.substring(5, 7)) == 7 || Integer.valueOf(petBDayTextVal.substring(5, 7)) == 8 || Integer.valueOf(petBDayTextVal.substring(5, 7)) == 10 || Integer.valueOf(petBDayTextVal.substring(5, 7)) == 12){
            if (Integer.valueOf(petBDayTextVal.substring(8, 10)) <= 0 || Integer.valueOf(petBDayTextVal.substring(8, 10)) >= 32) {
                Toast.makeText(getApplicationContext(), "Incorrect Date for Month input: Please input a Date between 01 and 31", Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        // Check for 30 Day Months
        else if (Integer.valueOf(petBDayTextVal.substring(5, 7)) == 4 || Integer.valueOf(petBDayTextVal.substring(5, 7)) == 6 || Integer.valueOf(petBDayTextVal.substring(5, 7)) == 9 || Integer.valueOf(petBDayTextVal.substring(5, 7)) == 11){
            if (Integer.valueOf(petBDayTextVal.substring(8, 10)) <= 0 || Integer.valueOf(petBDayTextVal.substring(8, 10)) >= 31) {
                Toast.makeText(getApplicationContext(), "Incorrect Date for Month input: Please input a Date between 01 and 30", Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        // Check for February
        else if (Integer.valueOf(petBDayTextVal.substring(5, 7)) == 2 && (Integer.valueOf(petBDayTextVal.substring(8, 10)) >= 0 || Integer.valueOf(petBDayTextVal.substring(8, 10)) >= 29)){
            Toast.makeText(getApplicationContext(), "Incorrect Date for Month input: Please input a Date between 01 and 28\n NOTE: Input 28 if Pet was born on a leap year 29th", Toast.LENGTH_SHORT).show();
            return false;
        }
        // All checks have been passed: Birthday is correct format
        return true;
    }

    // Set Species based on what is selected
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        speciesChoice = parent.getItemAtPosition(position).toString();
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}

And this is the screen where I want the Pet name to display as the text of the button. Note I have it currently set as a string that says Placeholder. Since this screen also comes before the creation of the Class variable.

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class SelectPetScreen extends AppCompatActivity {
    // Button Declarations
    private Button addPetButton;
    private Button selectPetButton;
    private Button pet1Button;
    private String selectPetButtonText;


    //Pet pet1 = getResources().getPet();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_pet_screen);

        addPetButton = (Button)findViewById(R.id.selectPetPet1Button);

        // Set the Pet's name from the class here
        // When there is an instance of the Pet class use getPetName() to set the name to the Button text
        addPetButton.setText("Placeholder name");

        // Button to navigate to Add a Pet
        addPetButton = (Button) findViewById(R.id.selectPetAddPetButton);
        addPetButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openAddPetScreen();
            }
        });
    }

    // Function to open Add Pet Screen
    public void openAddPetScreen() {
        Intent intent = new Intent(this, AddPetScreen.class);
        startActivity(intent);
    }
}

I've searched a lot and all I can find is stuff pertaining to simple variables like strings and ints

CodePudding user response:

Make Pet a member of your Application class so you can access it anywhere and don't need to pass it around between activities.

CodePudding user response:

What you want seems to be a Singleton: a class that only has a single instance and can be used globally across the app.

But a more appropriate solution would be to pass the required data to the activity. That can be achieved by using the Intent itself:

public void openAddPetScreen() {
    Intent intent = new Intent(this, AddPetScreen.class);
    intent.putExtra(SelectPetScreen.EXTRA_PET_NAME, petName);
    startActivity(intent);
}

And then get the data in the SelectPetScreen activity:

public static final String EXTRA_PET_NAME = "extra_name";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent intent = getIntent();
    if(intent != null) {
        String petName = intent.getExtra(EXTRA_PET_NAME);
        if (petName != null) {
            // do logic with the petName
        }
    }
}

If you require to pass the whole Pet object, then you can make it extend Parcelable and pass it using intent.putParcelableExtra

  • Related