我尝试创建一个公共类来尝试将数据从一个活动传输到另一个活动。但是当我尝试完全设置这个类的信息时,我设法得到Int变量而不是String,当我试图获取这些数据时它是空白的。
这是我的主要活动
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;
}
}
答案 0 :(得分:2)
如果要将数据从一个活动传递到另一个活动,请将其与意图一起附加。 实施例 -
在MainActivity中 -
Bundle bundle= new Bundle();
bundle.putString("name", "A");
bundle.putString("speed", "100");
Intent intent= new Intent(MainActivity.this,CarActivity.class);
intent.putExtras(bundle);
startActivity(intent);
在carActivity中 -
Bundle bundle=getIntent().getExtras();
String name=bundle.getString("name");
String speed=bundle.getString("speed");
然后在文本视图中设置这些值。
答案 1 :(得分:0)
在我的CarActivity 中,您正在创建新对象:CurrentCar currentcar = new CurrentCar();
所以如果你调用name.setText(currentcar.getName());
那么它只会返回null,因为字符串default是null。
只使用我的主要活动
中创建的对象