从android中的超类继承数据
问题描述:
这里是我的继承活动的例子。由于日志显示我无法从我的超类中获取正确的数据。从android中的超类继承数据
我的超类
public class MainActivity extends Activity {
public String exampleString;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.NewButton);
button.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
exampleString = "Test and test";
Log.e("Mytag", "here "+ exampleString);
Intent intent = new Intent();
intent.setClass(getBaseContext(), Activity2.class);
startActivity(intent);
}
});
}
}
我的子类
public class Activity2 extends MainActivity {
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.layout2);
Log.e("Mytag", "here "+ exampleString);
}
}
我的日志
08-28 13:27:05.908: D/gralloc_goldfish(889): Emulator without GPU emulation detected.
08-28 13:27:08.677: E/Mytag(889): here Test and test
08-28 13:27:09.408: E/Mytag(889): here null
为什么子类获得exampleString空值? 任何身体可以帮助吗?谢谢
答
因为当你实例化你的超类或它的任何子类时,你会得到一个新的实例exampleString
。
使变量静态,然后类将共享它。
public static String exampleString;
但是在你的榜样,它看起来像你只需要一个字符串发送到另一个这样的活动:在你的其他类
Intent intent = new Intent();
intent.putExtra("myString", "my example argument");
intent.setClass(getBaseContext(), Activity2.class);
startActivity(intent);
,并接受它:
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.layout2);
Bundle args = getIntent().getExtras();
String example = args.getString("myString");
Log.e("Mytag", "here " + example);
}
活性2将输出:here my example argument
答
你正在设置onClick的exampleString变量方法。
当您在onClick方法中调用新活动时,实际上是在创建一个Activity2的新实例。为什么这个新实例在exampleString中有一个值,如果你从来没有设置它的话?
继承是一种将功能和数据从超类扩展到子类的好方法,但决不允许单独的实例共享相同的数据。
由于在第二个实例中您从不设置exampleText,因此您的日志打印输出显示为空。
+0
谢谢。有想法。 – WenhaoWu 2014-08-28 13:56:01
就是这样。我完全是java的新手。谢谢队友 – WenhaoWu 2014-08-28 13:43:46
@文豪武请阅读更新的答案。 – Simas 2014-08-28 13:46:00
再次感谢您。是的,这样可以节省继承时间。 – WenhaoWu 2014-08-28 13:55:43