JSON对象无法正常工作/正在进行

时间:2016-11-06 15:02:26

标签: java android json xml

当我运行我的应用程序时,我无法看到我的JSON数据。 它引发了一个异常,它说明了这个

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 个答案:

答案 0 :(得分:0)

在没有看到异常的情况下很难判断,但我的猜测是,你正在尝试在main线程上进行HTTP调用,这是不允许的。我建议您熟悉Android如何处理长时间运行的任务。您可能会发现以下资源非常有用:

https://www.youtube.com/watch?v=jtlRNNhane0 https://developer.android.com/training/basics/network-ops/index.html http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html

答案 1 :(得分: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");
}