Home » Android » Cant get Json info on the app [duplicate]

Cant get Json info on the app [duplicate]

Posted by: admin November 1, 2017 Leave a comment

Questions:

This question already has an answer here:

Answers:

A exception is thrown when an application attempts to perform a networking operation on its main thread. Hence the network call wouldn’t take place in your case as you are making a network call on main thread and it would directly throw a NetworkOnMainThreadException instead of making a network call. Run your code in AsyncTask

Questions:
Answers:

well doing any network operation on main thread is crime in Android. You will be punished with network_operation_on_main_thread exception. You need take help from AsyncTask.

please try below code

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text);
new LongOperation().execute("");
}


private class LongOperation extends AsyncTask<String, Void, String> {
   String data = "input stream empty";
    @Override
    protected String doInBackground(String... params) {
        try {
    URL url = new URL("https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&minlatitude=4&maxlatitude=5");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    is = new BufferedInputStream(connection.getInputStream());

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));

    StringBuilder builder = new StringBuilder();

    while((line=reader.readLine())!=null){
        builder.append(line);
    }
    if(builder.toString().equals(""))
    {
        data = "no work builder empty";
    }

    line=builder.toString();
    JSONObject object = new JSONObject(line);
    JSONArray fea = object.getJSONArray("features");
    JSONObject QUAKE = fea.getJSONObject(0);
    JSONObject pro = QUAKE.getJSONObject("properties");
    int mag = pro.getInt("mag");
    data = mag+"";



} catch (Exception e) {
    e.printStackTrace();
}
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
     textView.setText(data);
    }

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected void onProgressUpdate(Void... values) {
    }
}