For the app I am making I need to get data (a CSV or JSON file) from a specific URL, but I can't get it to work. It seems that I have to make the request in another thread (NetworkOnMainThreadException) but I don't know how to do that. What is the correct way to make a request to a webpage and retrieve the data?
Asked
Active
Viewed 1.7k times
2
-
Do you have the URL to fetch data ? – tahsinRupam Mar 07 '17 at 16:01
-
1Possible duplicate of [Make an HTTP request with android](http://stackoverflow.com/questions/3505930/make-an-http-request-with-android) – Wasim K. Memon Mar 07 '17 at 16:02
-
Possible duplicate of [NetworkOnMainThreadException](http://stackoverflow.com/questions/5150637/networkonmainthreadexception) – petey Mar 07 '17 at 16:04
2 Answers
4
Even though it's a duplicate I am going to answear. The best way to do this is to use asynchronous method:
class MyTask extends AsyncTask<Integer, Integer, String> {
@Override
protected String doInBackground(Integer... params) {
for (; count <= params[0]; count++) {
try {
Thread.sleep(1000);
publishProgress(count);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
JSONObject response = getJSONObjectFromURL("your http link"); // calls method to get JSON object
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return "Task Completed.";
}
@Override
protected void onPostExecute(String result) {
progressBar.setVisibility(View.GONE);
}
@Override
protected void onPreExecute() {
txt.setText("Task Starting...");
}
@Override
protected void onProgressUpdate(Integer... values) {
txt.setText("Running..."+ values[0]);
progressBar.setProgress(values[0]);
}
}
And here is the class to get JSON from http and parse it. When calling the method pass in the url you wish to get the json object from.
public static JSONObject getJSONObjectFromURL(String urlString) throws IOException, JSONException {
HttpURLConnection urlConnection = null;
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setDoOutput(true);
urlConnection.connect();
BufferedReader br=new BufferedReader(new InputStreamReader(url.openStream()));
char[] buffer = new char[1024];
String jsonString = new String();
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
jsonString = sb.toString();
System.out.println("JSON: " + jsonString);
urlConnection.disconnect();
return new JSONObject(jsonString);
}

kPieczonka
- 394
- 1
- 14
-
What is `char[] buffer = new char[1024];` for? It looks unused to me. – cges30901 Jun 27 '21 at 06:46
-
2
Use AsyncTask and put all your Network Actions into "doInBackground" and work with yout result-data in "onPostExecute".
for a example you can check this post https://stackoverflow.com/a/18827536/2377961