在返回YouTube链接数组的doInBackground
方法中,我在返回之前记录数组的值,以确保它不为空。但是,当我尝试在onPostExecute
方法中使用它时(使用'result'变量),我得到一个空数组错误。我不能为我的生活找到解释。这是我的代码:
doInBackground:
@Override
protected String[] doInBackground(String... params) {
// If there's no parameter, there's nothing to look up. Verify size of params.
if (params.length == 0) {
return null;
}
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String rawJsonStr = null;
try {
// Construct the URL for the TMDb query
//Define strings for creating the url:
final String BASE_URL = "http://api.themoviedb.org/3/movie/";
final String PARAM_API_KEY = "?api_key=----"; //REMEMBER NOT TO LEAVE YOUR KEYS HERE!
final String TRAILER_REVIEWS_APPEND = "&append_to_response=trailers,reviews";
URL url = new URL(BASE_URL + movieId + PARAM_API_KEY + TRAILER_REVIEWS_APPEND);
// Create the request to TMDb, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
rawJsonStr = buffer.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
return null;
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try{
getMovieDataFromJson(rawJsonStr);
Log.d(LOG_TAG, "Before returning: " + getTrailerDataFromJson(rawJsonStr)[0]);
return getTrailerDataFromJson(rawJsonStr);
} catch (JSONException e) {
e.printStackTrace();
Log.e(LOG_TAG, "Coudn't return trailer array");
}
return null;
}
注意:是的,我在调用AsyncTask
onPostExecute:
@Override
protected void onPostExecute(String[] result) {
Log.d(LOG_TAG, "After returning: " + result[0]);
}
应用程序崩溃,在日志中,我首先在属于onPostExecute方法的行中获得“尝试从空数组中读取”异常。然后,我得到了正确的“返回之前:YouTubeLink”日志。
有什么建议吗?
编辑:
getTrailerData方法:
private String[] getTrailerDataFromJson(String rawJsonData)
throws JSONException {
final String TMDb_TRAILERS = "trailers";
//Get the object corresponding to the movie
JSONObject movieData = new JSONObject(rawJsonData);
//Create trailer objects
JSONObject trailerData = movieData.getJSONObject(TMDb_TRAILERS);
JSONArray youtubeTrailers = trailerData.getJSONArray("youtube");
String[] trailerLinks = new String[youtubeTrailers.length()];
//Get trailers
for (int i = 0; i < youtubeTrailers.length(); i++){
if (!youtubeTrailers.isNull(i)){
JSONObject trailer = youtubeTrailers.getJSONObject(i);
trailerLinks[i] = "https://www.youtube.com/watch?v=" + trailer.getString("source");
}
else{
noTrailers = true;
break;
}
}
return trailerLinks;
}
日志错误如下:
08-13 14:30:54.422 17240-17240/com.mightybarbet.quickmovieinfo E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.mightybarbet.quickmovieinfo, PID: 17240
java.lang.NullPointerException: Attempt to read from null array
at com.mightybarbet.quickmovieinfo.DetailActivityFragment$FetchMovieInfoTask.onPostExecute(DetailActivityFragment.java:258)
at com.mightybarbet.quickmovieinfo.DetailActivityFragment$FetchMovieInfoTask.onPostExecute(DetailActivityFragment.java:105)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
抱歉,我花了这么长时间,我的网络已经用完了。
第105行是AsyncTask的声明:
public class FetchMovieInfoTask extends AsyncTask<String, Void, String[]> {
第258行是onPostExecute里面的一行:
Log.d(LOG_TAG, "After returning: " + result[0]);
答案 0 :(得分:-1)
替换您的方法并查看最终日志&#34;最终返回预告片阵列&#34;
@Override
protected String[] doInBackground(String... params)
{
// If there's no parameter, there's nothing to look up. Verify size of params.
if (params.length == 0) {
return null;
}
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String rawJsonStr = null;
String[] resultArray = null;
try {
// Construct the URL for the TMDb query
//Define strings for creating the url:
final String BASE_URL = "http://api.themoviedb.org/3/movie/";
final String PARAM_API_KEY = "?api_key=----"; //REMEMBER NOT TO LEAVE YOUR KEYS HERE!
final String TRAILER_REVIEWS_APPEND = "&append_to_response=trailers,reviews";
URL url = new URL(BASE_URL + movieId + PARAM_API_KEY + TRAILER_REVIEWS_APPEND);
// Create the request to TMDb, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
rawJsonStr = buffer.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try{
getMovieDataFromJson(rawJsonStr);
Log.d(LOG_TAG, "Before returning: " + getTrailerDataFromJson(rawJsonStr)[0]);
resultArray = getTrailerDataFromJson(rawJsonStr);
} catch (JSONException e) {
e.printStackTrace();
Log.e(LOG_TAG, "Couldn't return trailer array");
}
Log.e(LOG_TAG, "final return trailer array"+resultArray;);
return resultArray;
}