2015-12-03 103 views
0
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服務器

回答

2

這是因爲,如果你看到日誌,你會注意到你的代碼會拋出一個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"); 


    } 
+0

行,所以我修改了我的代碼爲u說,看我的編輯代碼,但它仍然給我假 –

+0

這是因爲你設置的標誌之前訪問值。我編輯了我的答案,看看它。 –

+0

還是假的爲什麼不能我連接:( –

相關問題