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?
3
-
Do you have the URL to fetch data ?tahsinRupam– tahsinRupam2017-03-07 16:01:55 +00:00Commented Mar 7, 2017 at 16:01
-
1Possible duplicate of Make an HTTP request with androidWasim K. Memon– Wasim K. Memon2017-03-07 16:02:50 +00:00Commented Mar 7, 2017 at 16:02
-
Possible duplicate of NetworkOnMainThreadExceptionpetey– petey2017-03-07 16:04:55 +00:00Commented Mar 7, 2017 at 16:04
Add a comment
|
2 Answers
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);
}
2 Comments
cges30901
What is
char[] buffer = new char[1024]; for? It looks unused to me.Caner Burc BASKAYA
AsyncTasks are now deprecated in Android unfortunately.
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