我正在編寫Android應用程序。在某個時候,應用程序被要求從我在Heroku上的Web服務中檢索數據。 包含使用這些數據的方法來檢索數據和類的方法不同。 我想通過接口將數據從AsyncTask的onPostExecute()傳遞給其他類;但是我得到一個惱人的NullPointerException,我不理解這個原因!Android JAVA - 使用NullPointerException和接口字段
我的 「主」 類:
public class Details extends AppCompatActivity implements ResponseFromWebService.AsyncResponse {
@Override
public void processFinish(String output){
System.out.println(output);
}
//Other Stuff
}
我ResponseFromWebService類:
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);
}
}
}
的NPE發生在最後一行,當有delegate.processFinish(s);
真正需要幫助的呼叫!
使用調試器...... –