2016-11-06 85 views
0

當我運行我的應用程序我看不到我的JSON數據。 它拋出一個異常,它說這個JSON對象不工作/ conecting

Toast.makeText(this, "can't execute http request", Toast.LENGTH_LONG).show();

public class IsstatusActivity extends AppCompatActivity { 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.isstatus); 
     TextView latCor = (TextView) findViewById(R.id.Coordinates); 
     latCor.setText(getJson()); 

    } 

    public String getJson() { 
     String quoteUrl = "https://api.wheretheiss.at/v1/satellites"; 
     DefaultHttpClient httpclient = new DefaultHttpClient(); 
     HttpGet httpget = new HttpGet(quoteUrl); 

     httpget.setHeader("Content-type", "application/json"); 

     InputStream inputStream = null; 
     String result = null; 
     String aJsonString1 = null; 
     try { 
      HttpResponse response = httpclient.execute(httpget); 

      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"); 
      }  TextView latCor = (TextView) findViewById(R.id.Coordinates); 


      result = sb.toString(); 
      JSONObject jObject = new JSONObject(result); 
      aJsonString1 = jObject.getString("latitude"); 
      latCor.setText(aJsonString1); 

     } catch (Exception e) { 
      Toast.makeText(this, "can't execute http request", Toast.LENGTH_LONG).show(); 
     } finally { 
      try { 
       if (inputStream != null) inputStream.close(); 
      } catch (Exception squish) { 
      } 
     } 

     return aJsonString1; 
    } 
} 
+2

你能發佈異常嗎?這可能是因爲你試圖在主線程上進行HTTP調用。 – vkislicins

+0

你能否詳細說明更多張貼堆棧跟蹤? –

回答

0

vkislicins似乎是正確的。

網絡問題後,您還會遇到另一個異常,即從https://api.wheretheiss.at/v1/satellites返回的響應是JSONArray,但您試圖將其解析爲JSONObject。你需要通過解析迴應

String latitude = null; 
JSONArray jsonArray = new JSONArray(result); 
if (jsonArray.length() > 0) { 
    latitude = jsonArray.optJSONObject(0).optString("latitude"); 
}