2015-08-13 2 views
0

В методе doInBackground, который возвращает массив ссылок на YouTube, я регистрирую значение массива прямо перед его возвратом, чтобы убедиться, что он не равен нулю. Однако, когда я пытаюсь использовать его в методе onPostExecute (используя переменную «result»), я получаю ошибку с нулевым массивом. Я не могу для жизни меня найти объяснение. Вот мой код:AsyncTask - результат OnPostExecute равен нулю, я полностью потерял то, почему

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]); 
    } 

В приложения, а в журналах я сначала «попытался read from null array "исключение в строке, принадлежащей методу onPostExecute. Затем я получаю правильный журнал «До возвращения: YouTubeLink».

Любые предложения?

Edit:

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) 

Извините, что так долго, мой интернет вышел.

Line 105 является декларирование AsyncTask:

public class FetchMovieInfoTask extends AsyncTask<String, Void, String[]> { 

И линия 258 является линией внутри onPostExecute:

+2

Должно быть исключение в' getTrailerDataFromJson' - пожалуйста, поделитесь его кодом, а также логарифмом Положите, что показывает, что вы смогли напечатать 'Before return: ...' –

+3

Это потому, что вы возвращаете 'null' в блок' finally' – Lal

+0

, пожалуйста, проверьте мой ответ // @Bensas – Lal

ответ

-1

Заменить метод и посмотреть на завершающем журнал «окончательный массив возврата прицеп "

@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; 
} 
+0

Вы проверили код –

Смежные вопросы