Jacob Morris
Jacob Morris

Reputation: 500

Get JSON object from URL using HTTPURLConnection on android

I am currently trying to access a JSON object on my android application. However, I keep getting the following error:

android.os.NetworkOnMainThreadException

From researching it a bit, the only information I have currently is that I need to be doing this asynchronously(?)

Here is my code:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView dynamictext;
    dynamictext = (TextView) findViewById(R.id.dynamictext);
    dynamictext.setText(getJSON("my url here"));

}


public String getJSON(String url) {
    HttpURLConnection c = null;
    try {
        URL u = new URL(url);
        c = (HttpURLConnection) u.openConnection();
        c.connect();
        int status = c.getResponseCode();
        switch (status) {
            case 200:
            case 201:
                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line+"\n");
                }
                br.close();
                return sb.toString();
        }

    } catch (Exception ex) {
        return ex.toString();
    } finally {
        if (c != null) {
            try {
                c.disconnect();
            } catch (Exception ex) {
                //disconnect error
            }
        }
    }
    return null;
}
}

Thanks in advance

Upvotes: 6

Views: 14835

Answers (4)

alican akyol
alican akyol

Reputation: 288

private void taskPostExecute(String url)
{
     myTask2=(RequestTask)new RequestTask().execute(url);
}

class RequestTask extends AsyncTask<String, String, String> {
    @Override
    protected String doInBackground(String... uri) {
        try {
                postData(uri[0]);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return null;
    }
    @Override
    protected void onCancelled() {
        myTask2.cancel(true);

    }
    @Override
    protected void onPostExecute(String url) {
        LinearLayouts();
    }
}

public static String postData(String url) throws UnsupportedEncodingException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httppost = new HttpGet(url);
    String responseString = "";

    try {
        HttpResponse response = httpclient.execute(httppost);
        StatusLine statusLine = response.getStatusLine();
        InputStream inputStream = null;
        if(statusLine.getStatusCode() == HttpStatus.SC_OK){
            inputStream = response.getEntity().getContent();
            if(inputStream != null)
                responseString = convertInputStreamToString(inputStream);
            else
                responseString = "Did not work!";
            JSONObject reader = null;
            JSONArray sys  = null;
            try {
                reader = new JSONObject(responseString);
                String res_metar = reader.getString("TAG");

            } catch (JSONException e) {
                e.printStackTrace();
            }
            //a = responseString;

        } else{
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (ClientProtocolException e) {

    } catch (IOException e) {

        // process execption
    }
    return responseString;
}

private static String convertInputStreamToString(InputStream inputStream) throws IOException{
    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();
    return result;

}

You can try it, it works.

Upvotes: 0

Herin
Herin

Reputation: 141

To perform the time consuming task you need to implement Async task which will run on non UI thread as you can't do such operations on UI thread.

And you can execute the async task in onStart() method of your activity and and override the onPostMethod() of the async task to implement any changes you wish to do on the UI once the network operation check http://developer.android.com/reference/android/os/AsyncTask.html for the details about the Async task.

Upvotes: 0

LEETAEJUN
LEETAEJUN

Reputation: 186

i recommand to read this url https://stackoverflow.com/a/6343299/2530660



add AsyncTask;

public class TestAsyncTask extends AsyncTask<Void, Void, String> {
    private Context mContext;
    private String mUrl;

    public TestAsyncTask(Context context, String url) {
        mContext = context;
        mUrl = url;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dynamictext = (TextView) findViewById(R.id.dynamictext);
    }

    @Override
    protected String doInBackground(Void... params) {
        String resultString = null;
        resultString = getJSON(mUrl);

        return resultString;
    }

    @Override
    protected void onPostExecute(String strings) {
        super.onPostExecute(strings);
        dynamictext.setText(strings);
    }

    private String getJSON(String url) { ... }
}

use AsyncTask;

public class MainActivity ... {
    private TextView dynamictest;

    onCreate() {
        ...
        TestAsyncTask testAsyncTask = new TestAsyncTask(MainActivity.this, "my url here");
        testAsyncTask.execute();
    }
}

Upvotes: 7

timbillstrom
timbillstrom

Reputation: 1176

From Android 3 and above, network operations running on the UI thread is not allowed and therefore your application will crash caused by the NetworkOnMainThreadException.

Here you can find a simple example of a Asyntask which you will handle your code asynchronously: Android: AsyncTask to make an HTTP GET Request?

Upvotes: 0

Related Questions