Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 978
Jacob Morris Avatar asked Oct 14 '15 01:10

Jacob Morris


People also ask

How can I get JSON data from URL?

Get JSON From URL Using jQuerygetJSON(url, data, success) is the signature method for getting JSON from an URL. In this case, the URL is a string that ensures the exact location of data, and data is just an object sent to the server. And if the request gets succeeded, the status comes through the success .

What is JSONObject in android?

org.json.JSONObject. A modifiable set of name/value mappings. Names are unique, non-null strings. Values may be any mix of JSONObjects , JSONArrays , Strings, Booleans, Integers, Longs, Doubles or NULL .


1 Answers

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();
    }
}
like image 71
LEETAEJUN Avatar answered Oct 13 '22 00:10

LEETAEJUN