为什么没有安卓连接到我的Web服务器
问题描述:
package com.mohd.tryapp;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends ActionBarActivity {
public static int flag;
TextView view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
view=(TextView)findViewById(R.id.textvi);
getFlag var=new getFlag();
var.execute();
if(flag==1)
view.setText("true");
else
view.setText("false");
}
class getFlag extends AsyncTask<Void, Void, Void> {
private Exception exception;
@Override
protected Void doInBackground(Void... params) {
try{
String url="http://mohdgadi.netai.net/Register.php";
int timeout=15*1000;
URL myUrl = new URL(url);
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(timeout);
connection.connect();
flag=1;
} catch (Exception e) {
e.printStackTrace();
flag=0;
}
return null;
}
}
}
所以这是我想连接到我的000webhost的网站,我的主要活动代码,但连接总是显示false.I甚至试图改变URL来http://mohdgadi.netai.net/Register但似乎没有工作可能是什么问题,因为结果总是显示错误为什么没有安卓连接到我的Web服务器
答
这是因为,如果你看到日志,你会注意到你的代码会抛出一个NetworkOnMainThreadException。这意味着Android不允许您在主线程上进行网络通话。因此,移动你的代码到AsyncTask。
你可以看到一个例子here。
您应该使用get()
来等待结果填充,但最好在doInBackground
返回后使用onPostExecute
来执行您的代码。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
view=(TextView)findViewById(R.id.textvi);
getFlag var=new getFlag();
var.execute();
var.get();
if(flag==1)
view.setText("true");
else
view.setText("false");
}
行,所以我修改了我的代码为u说,看我的编辑代码,但它仍然给我假 –
这是因为你设置的标志之前访问值。我编辑了我的答案,看看它。 –
还是假的为什么不能我连接:( –