我有一个程序如下,谁能告诉我什么是获得NPE的原因。这为什么会导致NullPointerException?
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
secondClass x = new secondClass();
x.sText("Test Spring");
}
}
public class secondClass extends MainActivity {
public void sText(String s) {
TextView text = (TextView) findViewById(R.id.text);
text.setText(s);
}
}
Mainfest
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
...
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:id="@+id/text"
/>
</RelativeLayout>
logcat的
08-16 01:31:11.320 15032-15032/? E/Trace: error opening trace file: No such file or directory (2)
08-16 01:31:11.420 836-987/? E/EmbeddedLogger: App crashed! Process: com.example.myapplication
08-16 01:31:11.420 836-987/? E/EmbeddedLogger: App crashed! Package: com.example.myapplication v1 (1.0)
08-16 01:31:11.420 836-987/? E/EmbeddedLogger: Application Label: My Application
08-16 01:31:11.420 15032-15032/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java)
at android.app.ActivityThread.access$600(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java)
at android.os.Handler.dispatchMessage(Handler.java)
at android.os.Looper.loop(Looper.java)
at android.app.ActivityThread.main(ActivityThread.java)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:110)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java)
at com.example.myapplication.secondClass.sText(secondClass.java:13)
at com.example.myapplication.MainActivity.onCreate(MainActivity.java:14)
at android.app.Activity.performCreate(Activity.java)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java)
据我了解,这应该实例化和初始化然后二等对象调用其STEXT()方法。然后,sText方法应该在TextView中存储一个引用。接下来它调用TextView上的setText()方法,它将TextView中的文本更改为传递到sText()中的文本。
logcat说它会抛出一个NullPointerException,但我不完全确定为什么。如果这是一个新秀的错误,那是因为我是一名新秀。谢谢。
为什么你需要'secondClass'? – 2013-08-16 05:32:34
你可以发布你的logcat,可能有帮助 – bidluo
你能分享更多的细节你想要存档什么。有两个活动实例是非常罕见的情况,以及访问另一个不是如何工作的方式 –