2017-07-22 64 views
0

我试着创建一个公共类来尝试从一个活动向另一个活动传输数据。但是当我尝试设置这个类的信息时,我设法得到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; 
    } 
} 
+0

正在创建的对象可以使用辛格尔顿,让您的CurrentCar类的静态和看得见的CarActivity。或者您可以实施parcelable以在活动之间传递您的汽车物件。希望能帮助到你 –

回答

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

,然后在文本视图设置这些值。

0

我CarActivity要创建新的对象:CurrentCar currentcar = new CurrentCar();

因此,如果调用name.setText(currentcar.getName());那么它将简单的返回null,因为字符串默认为空。

只是使用我的MainActivity

相关问题