There are many ways to do this, if you wanna use the AsyncTask the code inside your class should be the following
public class JSONrequest extends AsyncTask<String, Void, JSONObject> {
// First you'll need an interface that'll call requestDone() for the JSONobject you wanna listen
public interface JSONListener{
void requestDone(JSONObject jsonObject);
}
private JSONListener jListener;
//Your class will need a constructor. Basic Java.
public JSONrequest(JSONListener jListener){
this.jListener = jListener;
}
@Override
//You'll be required to implement this method because of the extension and
//here's where the logic of your handler class goes
protected JSONObject doInBackground(String... strings) {
// First try to retrieve the url
JSONObject result = null; //initializing the result we'll return
try{
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
InputStream is = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String currentLine = "";
while((currentLine = br.readLine()) != null){
Log.d("JSON REQUEST", currentLine); //a little log so you can see what's going on
sb.append(currentLine);
}
result = new JSONObject(sb.toString());
}
}catch (Exception e){
e.printStackTrace();
}
return result;
return null;
}
}
If you're gonna fetch your JSON from a server it's very important that you give your app the permission to use Internet.
To do this, you add the following line to the Android Manifest:
<uses-permission android:name="android.permission.INTERNET" />
I hope this solves your problem.
Good luck.