I'm coding an Android App. At a certain point, the App is asked to retrieve data from a Web Service that I have on Heroku. The class that contains the methods that retreive data and the class with the methods that use those data are different. I'm trying to pass the data from an AsyncTask's onPostExecute() to my other class using an interface; however I'm getting an annoying NullPointerException and I'm not understanding the reason of this!
My "main" class:
public class Details extends AppCompatActivity implements ResponseFromWebService.AsyncResponse {
@Override
public void processFinish(String output){
System.out.println(output);
}
//Other Stuff
}
My ResponseFromWebService class:
public class ResponseFromWebService {
public void getData (String Name) {
new JSONTask().execute("censored-URL");
}
public interface AsyncResponse {
void processFinish(String output);
}
public class JSONTask extends AsyncTask<String, String, String> {
AsyncResponse delegate = null;
@Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
StringBuffer buffer = new StringBuffer();
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject finalObject = new JSONObject(finalJson);
String Desc = finalObject.getString("desc");
return Desc;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
delegate.processFinish(s);
}
}
}
The NPE occurs at the last line, when there is a call to delegate.processFinish(s);
Really need help!