我们正在一个android应用程序中使用4版本,我们需要一个mysql连接。我们使用的是一个php文件,该文件返回数据库结果。下面的代码工作正常,因为如果我们调试项目,我们可以在System.out.println中看到正确的数据库结果。线路。但是,如果我们试图更改应用程序中的一个文本,以反映数据库的结果,我们的应用程序无法正确运行,错误出现在t.setText(txt);行中。
有人能帮我解决这个问题吗?您是否有其他的想法来进行数据库连接,或者这是正确的方式?
非常感谢。
我的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//FUNCIONA NO BORRAR
final httpHandler handler = new httpHandler();
Thread thread = new Thread()
{
@Override
public void run() {
try {
if(true) {
sleep(1000);
String txt = handler.post("http://www.golftipp.com/pruebas_android/app.php");
TextView t = (TextView) findViewById(R.id.textView2);
t.setText(txt);
System.out.println(txt);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}错误
05-30 02:42:50.331 1276-1291/es.softline.connexiodb.app E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-87
Process: es.softline.connexiodb.app, PID: 1276
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6094)
at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:824)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:352)
at android.view.View.requestLayout(View.java:16431)
at android.widget.TextView.checkForRelayout(TextView.java:6600)
at android.widget.TextView.setText(TextView.java:3813)
at android.widget.TextView.setText(TextView.java:3671)
at android.widget.TextView.setText(TextView.java:3646)
at es.softline.connexiodb.app.MainActivity$1.run(MainActivity.java:33)发布于 2014-05-30 07:06:53
非UI线程无法访问视图,请使用runOnUiThread():
Thread thread = new Thread()
{
@Override
public void run() {
try {
if(true) {
sleep(1000);
String txt = handler.post("http://www.golftipp.com/pruebas_android/app.php");
TextView t = (TextView) findViewById(R.id.textView2);
runOnUiThread(new Runnable() {
@Override
public void run() {
// do UI updates here
t.setText(txt);
}
});
System.out.println(txt);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start(); https://stackoverflow.com/questions/23948906
复制相似问题