在Android(Java)中全局传递类变量



因此,在我的应用程序Java代码中,我有一个名为Pet的类。在我的应用程序中,在我的一个活动中创建了一个这样的变量。

到目前为止,我已经能够成功地创建这个类的实例,并在同一活动中从中获取变量。

现在,我想将新创建的Class变量(pet1(传递给我的应用程序的其余部分,并在我的其他活动中使用类似getPetName((函数的函数来设置应用程序的按钮和其他元素上显示的字符串。

这是宠物级

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;
}

}

这是创建类实例的活动

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 28n 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) {
}
}

这就是我想要宠物名字显示为按钮文本的屏幕。注意,我目前将它设置为一个字符串,上面写着Placeholder。因为这个屏幕也是在创建Class变量之前出现的。

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);
}
}

我搜索了很多,我能找到的都是与字符串和int 等简单变量有关的东西

您想要的似乎是Singleton:一个只有一个实例并且可以在整个应用程序中全局使用的类。

但更合适的解决方案是将所需的数据传递给活动。这可以通过使用Intent本身来实现:

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

然后获取SelectPetScreen活动中的数据:

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
}
}
}

如果您需要传递整个Pet对象,那么您可以使其扩展Parcelable并使用intent.putParcelableExtra传递它

使Pet成为应用程序类的成员,这样您就可以在任何地方访问它,而不需要在活动之间传递它。

最新更新