我已经编写了一个Android应用程序,它可以检查互联网连接到谷歌(通过Socket,我猜)!当我从我的Networking-Thread(检查方法)得到答案时,我尝试用setText更新我的textview,但是我得到了一个nullpointerexception!它可能是我代码中一个安静的容易出错的错误,但我根本就没有得到它。
这是我的MainActivity:
package at.springsits.michi.hostchecker;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Main extends Activity implements OnClickListener {
TextView connection_internet;
Button pingbutton;
Networking net;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connection_internet = (TextView) findViewById(R.id.connection);
pingbutton = (Button) findViewById(R.id.ping_button);
pingbutton.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
`enter code here`net.connectionToGoogle = Networking.testPingToGoogle();
runOnUiThread(new Runnable() {
public void run() {
connection_internet.setText(String
.valueOf(net.connectionToGoogle));
}
});
}
}).start();
}
}
logcat的:
06-26 16:38:00.030: D/libEGL(2756): loaded /system/lib/egl/libEGL_adreno200.so
06-26 16:38:00.030: D/libEGL(2756): loaded /system/lib/egl/libGLESv1_CM_adreno200.so
06-26 16:38:00.030: D/libEGL(2756): loaded /system/lib/egl/libGLESv2_adreno200.so
06-26 16:38:00.030: I/Adreno200-EGL(2756): <eglInitialize:269>: EGL 1.4 QUALCOMM build: Nondeterministic AU_full_mako_PARTNER-ANDROID/JB-MR1-DEV_CL2961380_release_AU (CL2961380)
06-26 16:38:00.030: I/Adreno200-EGL(2756): Build Date: 12/10/12 Mon
06-26 16:38:00.030: I/Adreno200-EGL(2756): Local Branch:
06-26 16:38:00.030: I/Adreno200-EGL(2756): Remote Branch: m/partner-android/jb-mr1-dev
06-26 16:38:00.030: I/Adreno200-EGL(2756): Local Patches: NONE
06-26 16:38:00.030: I/Adreno200-EGL(2756): Reconstruct Branch: NOTHING
06-26 16:38:00.070: D/OpenGLRenderer(2756): Enabling debug mode 0
06-26 16:38:03.414: W/dalvikvm(2756): threadid=11: thread exiting with uncaught exception (group=0x40bf9930)
06-26 16:38:03.414: E/AndroidRuntime(2756): FATAL EXCEPTION: Thread-6549
06-26 16:38:03.414: E/AndroidRuntime(2756): java.lang.NullPointerException
06-26 16:38:03.414: E/AndroidRuntime(2756): at at.springsits.michi.hostchecker.Main$1.run(Main.java:37)
06-26 16:38:03.414: E/AndroidRuntime(2756): at java.lang.Thread.run(Thread.java:856)
答案 0 :(得分:0)
net
为空。您正在尝试在实例化之前访问其中一个字段。
你在这里声明:
Networking net
然后尝试在onClick()
net.connectionToGoogle = Networking.testPingToGoogle()
但在此阶段net
为null
。在尝试使用它之前,请在onCreate()
或类似内容中实例化它:
net = new Networking();