2017-08-27 189 views
1

我綁閱讀我使用的XAMPP)從服務器的數據,但該數據是空 這是我的Connect活動:我的Android應用程序無法連接到服務器

public String link=""; 
public AsyncTaskConnect(String link){ 
    this.link=link; 
} 
@Override 
protected Object doInBackground(Object[] params) { 
    try{ 
     URL url=new URL(link); 
     URLConnection connection=url.openConnection(); 
     BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream())); 
     StringBuilder builder=new StringBuilder(); 
     String line=null; 
     while((line=reader.readLine())!=null){ 
      builder.append(line); 
     } 
     MainActivity.data=builder.toString(); 
    }catch (Exception e){ 
    } 
    return ""; 
} 

這是主要活動:

public static String data=""; 
TextView txthello; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    txthello=(TextView)findViewById(R.id.txthello); 
    new AsyncTaskConnect("http://192.168.1.2/digikala/test.php").execute(); 
    txthello.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Toast.makeText(MainActivity.this,data,Toast.LENGTH_LONG).show(); 
     } 
    }); 
} 

但它不起作用,我該怎麼辦?

+0

主要活動中的數據沒有值 – reza

+0

也沒有鏈接值 – LLL

+0

'execute()'做了什麼?你叫它,但你的代碼不在上面。 – axlj

回答

0

使用HttpURLConnection,它擴展了你的URLConnection,所以我只是改變了一點你的代碼。鑑於你在String變量link中有你的查詢,這應該工作得很好。

try { 
       URL url = new URL(link); 
       HttpURLConnection connection= (HttpURLConnection) url.openConnection(); 

       int responseCode = connection.getResponseCode(); 
       Log.i(TAG, "POST Response Code: " + responseCode); 

       //Takes data only if response from WebService is OK 
       if (responseCode == HttpURLConnection.HTTP_OK) { 
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
        String inputLine; 
        StringBuilder response = new StringBuilder(); 

        //Stores input line by line in response 
        while ((inputLine = in.readLine()) != null) { 
         response.append(inputLine); 
        } 
        in.close(); 
} catch (Exception e) { 
      e.printStackTrace(); 
} 

如果按照這個片段中,響應是包含了所有你從你的web服務獲得響應的,您可以進一步將其轉換爲JSON,如果你想要的字符串。

希望它的作品!

+0

該文檔還建議Volley –

+0

我的壞!我馬上編輯 –

+0

不,你的回答很好。它只是不是問題 –

0

但數據是空

由於執行不阻塞調用。

假設你可以真正到達服務器,MainActivity.data是一個空字符串,直到後的AsyncTask onPostExecute

您可以用排槍,Okhttp,改造等,以簡化您的網絡代碼

Comparison of Android networking libraries: OkHTTP, Retrofit, and Volley

或向您的Asynctask添加回調

How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

+0

坦克爲您的所有幫助 – reza

相關問題