[英]Passing a Class Variable Globally in Android (Java)
因此,在我的应用程序的 Java 代码中,我有一个名为Pet的 class 。 这个变量是在我的应用程序中的一个活动中创建的。
到目前为止,我已经能够成功地创建这个 class 的实例,并在同一个活动中从中获取变量。
现在我想将新创建的 Class 变量 ( pet1 ) 传递给我的应用程序的 rest 并使用getPetName() function 之类的按钮在我的其他活动中显示的字符串和其他元素。
这是宠物 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;
}
}
这是创建 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) {
}
}
这是我希望宠物名称显示为按钮文本的屏幕。 请注意,我当前将其设置为表示占位符的字符串。 由于此屏幕也出现在 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);
}
}
我搜索了很多,我能找到的只是与字符串和整数等简单变量有关的东西
让Pet
成为您的应用程序class 的成员,这样您就可以在任何地方访问它,而无需在活动之间传递它。
您想要的似乎是Singleton :一个 class 只有一个实例,可以在整个应用程序中全局使用。
但更合适的解决方案是将所需的数据传递给活动。 这可以通过使用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
object,那么您可以使其扩展Parcelable 并使用intent.putParcelableExtra
传递它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.