我试着创建一个公共类来尝试从一个活动向另一个活动传输数据。但是当我尝试设置这个类的信息时,我设法得到Int变量而不是String,并且当我试图获取这些数据时它是空白的。我将如何使用公共课程将数据从一项活动转移到另一项活动?
这是我的MainActivity
public void toyota_yaris(View view) {
CurrentCar currentcar = new CurrentCar();
currentcar.setInfo("Toyota Yaris",130,8,1160,7);
Intent switchScreen = new Intent(MainActivity.this,CarActivity.class);
MainActivity.this.startActivity(switchScreen);
}
这是我的CarActivity
CurrentCar currentcar = new CurrentCar();
TextView name = (TextView) findViewById(R.id.name);
name.setText(currentcar.getName());
TextView speed = (TextView) findViewById(R.id.speed);
speed.setText(String.valueOf(currentcar.getSpeed()));
这是我的CurrentCar类(getter和setter类)
public class CurrentCar {
private String mName;
private int mSpeed;
private int mAge;
private int mMileage;
private int mSeats;
public void setInfo(String Name,int Speed,int Age,int Mileage,int Seats) {
mName = Name;
mSpeed = Speed;
mAge = Age;
mMileage = Mileage;
mSeats = Seats;
}
public String getName() {
return mName;
}
public int getSpeed() {
return mSpeed;
}
public int getAge() {
return mAge;
}
public int getMileage() {
return mMileage;
}
public int getSeats() {
return mSeats;
}
}
正在创建的对象可以使用辛格尔顿,让您的CurrentCar类的静态和看得见的CarActivity。或者您可以实施parcelable以在活动之间传递您的汽车物件。希望能帮助到你 –