Skip to content

Instantly share code, notes, and snippets.

@Nouman16
Last active November 6, 2016 18:49
Show Gist options
  • Save Nouman16/a4eb412d164e83179cd3b1de48aa657c to your computer and use it in GitHub Desktop.
Save Nouman16/a4eb412d164e83179cd3b1de48aa657c to your computer and use it in GitHub Desktop.
AsyncTask class to get JSON Response from web API
public class ConnectTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
StringBuilder stringBuilder = new StringBuilder();
// params stores url of the API in string format that is needed to be convert in URL it comes from your MainActivity from where you execute asynctask.
try {
//String of API converting in URL
URL url = new URL(http://api.openweathermap.org/data/2.5/weather?q="+params[0]+"&units="+params[1]+"&APPID=947cbe6c1905b31b4df44f41c09659d1);
// HttpURLConnection is kind of browser that is needed to open or established connection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Reading stream coming from our connection with API using bufferreader
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
// This loop will read one line from our bufferreader and check its null or not and append every line in our stringbuilder
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
bufferedReader.close();
// myResponse is global variable to store the all the response comes from API.
myResponse = stringBuilder.toString();
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return myResponse;
}
protected void onPostExecute(String response) {
try {
if(response.equals("")){
//Toast for no response coming from API might be due to some network connection problem
}
else {
// convert our response String in JSONObject
JSONObject rootObject = new JSONObject(response);
// Parse further JSON to get your desired values
}
} catch (JSONException e) {
e.printStackTrace();
}
catch (NullPointerException e){
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment