我试图将我在异步任务类中获得的字符串传递回我的主要活动,但是当我传递字符串结果时(我知道它不是null,因为在将字符串传递给接口之前将其记录下来)输出它应该的东西),我得到一个nullPointerException,它说我不能将null对象传递给接口方法。
这是AsyncTask类,
public class APICalls extends AsyncTask<String,Void, String> {
public AsyncResponse delegate;
protected String doInBackground(String... zipcodes){
String zipcode = zipcodes[0];
String apikey = "6562c36e87ba41f6bc887104d1e82eb8";
String baseURL = "https://congress.api.sunlightfoundation.com";
String zipCodeAddition = "/legislators/locate?apikey="+apikey + "&zip=" + zipcode;
String url = baseURL + zipCodeAddition;
String results = "";
URL apiurl = null;
try {
apiurl = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpsURLConnection urlConnection = null;
try {
urlConnection = (HttpsURLConnection) apiurl.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
int data = in.read();
while(data != -1){
results += String.valueOf((char) data);
data = in.read();
}
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
return results;
}
protected void onPostExecute(String result){
String results = result;
try {
delegate.processFinish(results);
} catch (IOException e) {
e.printStackTrace();
}
}
}
行delegate.processFinish(results);中发生错误。当我记录结果字符串时,它不是null。界面是:
public interface AsyncResponse {
void processFinish(String output) throws IOException;
}
然后在主要活动中我实现了接口并使用方法:
public void processFinish(String output) throws IOException {
Log.v("++++++++", output);
}
答案 0 :(得分:1)
您获得NPE不是因为output
是null
,而是因为delegate
。你永远不会初始化它。