2015-11-04 55 views
0

enter image description here我用Asp.net MVC創建一個API,它返回JSON。現在我想在我的Android應用程序中接收JSON,但它有錯誤。如何獲取Json在android

我返回[{"id":22,"Name":"2","Family":"1"}],我的瀏覽器顯示在http://192.168.1.100/api/people

這裏是我的Android代碼:

public class ReteriveFormWebActivity extends Activity { 

    private static String  url  = "http://192.168.1.100/api/people"; 

    //JSON Node Names 


    JSONArray     user  = null; 


    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams()); 
     HttpPost httppost = new HttpPost(url); 
     // Depends on your web service 
     httppost.setHeader("Content-type", "application/json"); 

     InputStream inputStream = null; 
     String result = null; 
     try { 
      HttpResponse response = httpclient.execute(httppost); 
      HttpEntity entity = response.getEntity(); 

      inputStream = entity.getContent(); 
      // json is UTF-8 by default 
      BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); 
      StringBuilder sb = new StringBuilder(); 

      String line = null; 
      while ((line = reader.readLine()) != null) 
      { 
       sb.append(line + "\n"); 
      } 
      result = sb.toString(); 
      Log.i("re", result); 
     } 
     catch (Exception e) { 
      // Oops 
     } finally { 
      try { 
       if (inputStream != null) 
        inputStream.close(); 
      } 
      catch (Exception squish) {} 
     } 
    } 
} 

在日誌中顯示錯誤eccurred:爲什麼呢?

+1

'在日誌中顯示錯誤eccurred'哪個錯誤?顯示應用程序崩潰時的logcat結果 –

+0

請有人幫我 – aliyousefian

+0

在日誌中顯示錯誤eccurred哪個錯誤?顯示應用程序崩潰時的logcat結果 –

回答

0

獲取NPE由於:

.... 
TextView txts = (TextView) findViewById(R.id.txt); 
txts.setText(result); //<<<< 
.... 

線造成的問題,因爲txtsnull

爲什麼null

因爲沒有要求通過傳遞佈局ID中的TextView與txtonCreate提供setContentView方法。

做得一樣:

@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_layout_file_name); 
    ... your code here 
} 

注: Currenlty做在主UI線程與網絡有關的任務,這將導致ANR對話框。因此在後臺線程中使用AsyncTask做網絡相關的作業。

+0

這不是答案我現在用我的textview和log.i如何一個錯誤消息發生我的問題是得到JSON不是UI setContentView(R.layout.activity_layout_file_name); – aliyousefian

+0

@ user3480060:夥計。如果你評論這個Log.i(「resss」,e.toString());'line,那麼你仍然會遇到問題,因爲由於'txts'爲'null',程序將進入catch catch try/catch塊。如果你知道什麼是問題,那麼爲什麼不修理它而不是提問呢? –

+0

對不起,先生。但我刪除所有textview如果JSON張貼在logcat中必須顯示我的JSON,但顯示一個錯誤ECACTRE爲什麼? – aliyousefian

0

將所有httprequests放入新線程中。您不能在ui線程中執行httprequests。