Reputation: 349
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?
Upvotes: 2
Views: 18476
Reputation: 404
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);
}
Upvotes: 4
Reputation: 4991
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
Upvotes: 2