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
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 .
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 .
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With