2014-01-24 120 views
0

的Android調用頁面我有我從我所返回的JSON文本,但Java代碼Android應用程序調用一個aspx頁面下方突破這裏BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));返回JSON錯誤

,此錯誤。

錯誤android.os.NetworkOnMainThreadException

你能幫助plesae?由於

default.aspx return json 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 

public partial class _Default : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     Response.ContentType = "text/plain"; 

     //Write the message 
     Response.Write("{'testvar':'testtext'}"); 
     //End the response causing it to be sent 
     Response.End(); 
    } 
} 

的Android的Java

public void connectWCF() { 

     try { 
      URL json = new URL("http://localhost:50851/Default.aspx"); 

      URLConnection jc = json.openConnection(); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream())); 

      String line = reader.readLine(); 

      reader.close(); 

     } catch(Exception e){ 

     } 

鏈接在那裏我得到的代碼的想法從 http://wyousuf.wordpress.com/2012/03/01/android-with-wcf-services/ http://matijabozicevic.com/blog/android-development/android-with-wcf-service

+0

從的AsyncTask調用函數connectWCF(),東陽你不能在主線程服務器交互。 –

+0

http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception –

+0

爲什麼你的Android應用程序試圖連接到你的WCF服務**在手機上而不是在它的服務器上? –

回答

1

要放置在主線程上的網絡通信。您應該使用的AsyncTask

http://developer.android.com/reference/android/os/AsyncTask.html 

這裏是一個不錯的視頻,使用的AsyncTask解釋JSON解析。

http://www.youtube.com/watch?v=qcotbMLjlA4 

僅用於測試,您可以在主要活動中添加以下內容,但認爲這是不好的做法。

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
StrictMode.setThreadPolicy(policy); 
1

由於Android 3.0,你不能把在主線程網頁或類似的外部資源的任何電話(換句話說,活動的任何部分),除非你用的AsyncTask做到這一點,爲了避免應用程序在等待來自外部數據源的響應時看起來「鎖定」且無響應。因此,您需要使用和AsyncTask實現webservice調用。

實例類的AsyncTask:

import org.apache.http.HttpResponse; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.entity.StringEntity; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.util.EntityUtils; 
import org.json.JSONArray; 
import org.json.JSONObject; 

import android.content.Context; 
import android.os.AsyncTask; 
import android.util.Log; 




public class cargaDatosRest extends AsyncTask<Context, Void, Void> { 


    private Context c; 
    private boolean resul = false; 
    private String control = ""; 
    private String respStrS = ""; 

    public cargaDatosRest(Context C) 
    { 
     c = C;  
    } 

    public String getStr() 
    { 
     return respStrS; 
    } 

    public String getControl() 
    { 
     return control; 
    } 

    @Override 
    protected void onPreExecute() {  
     super.onPreExecute(); 
     //mProgressDialog.show(); 
    } 

    @Override 
    protected Void doInBackground(Context... params) {   

     HttpClient httpClient = new DefaultHttpClient(); 

     HttpGet get = new HttpGet("url");     
     HttpResponse resp; 

     get.setHeader("content-type", "application/json"); 

     try 
     { 

         /*resp contains the response from the webService. respStr and respJSON allows to read that resp in JSON format. Just delete them if you don't need them. You can asign the values returned by the webservice to local variables in the AsyncTask class and then read them with public methods, like the resul variable.*/ 

       resp = httpClient.execute(getUsuarios); 
      String respStr = EntityUtils.toString(resp.getEntity()); 

      JSONArray respJSON = new JSONArray(respStr);  

      this.resul = true; 
     } 
     catch(Exception ex) 
     {   
      Log.e("ServicioRest","Error!", ex); 
      this.resul = false; 
     }   

    }   
    public boolean getResul() 
    { 
     return this.resul; 
    } 

    protected void onProgressUpdate(String... progress) { 
     Log.d("ANDRO_ASYNC",progress[0]); 
     //mProgressDialog.setProgress(Integer.parseInt(progress[0])); 
    } 

    @Override 
    protected void onPostExecute(Void unused) { 
     //mProgressDialog.dismiss(); 
    } 
} 

//從活動調用的AsyncTask:

 CargaDatosRest CallRest = new CargaDatosRest(this.getApplicationContext()); 
     CallRest.execute();      
     Log.v("WebService", "Just trying "+arest.getResul()); 
+0

謝謝你能給我一個例子plesae –

+0

我加了一些例子代碼 –