【发布时间】:2017-02-26 14:27:01
【问题描述】:
我正在编写一个 Android 应用程序。在某个时刻,应用程序被要求从我在 Heroku 上的 Web 服务中检索数据。 包含检索数据的方法的类和具有使用这些数据的方法的类是不同的。 我正在尝试使用接口将数据从 AsyncTask 的 onPostExecute() 传递到我的其他类;但是我得到了一个烦人的 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);
}
}
}
当调用delegate.processFinish(s);时,NPE 发生在最后一行
真的需要帮助!
【问题讨论】:
-
使用调试器...
标签: java android android-asynctask nullpointerexception