2015-10-16 122 views
1

尝试在空对象上调用虚方法'void java.io.BufferedReader.close()'引用此例外是抛出由JRE请帮助!尝试在空对象上调用虚方法'void java.io.BufferedReader.close()'参考

这里是类

package com.example.MovieMania.fragmentTv; 


import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.URL; 

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 





import com.example.MovieMania.R; 

import android.app.Activity; 
import android.content.Context; 
import android.content.Intent; 
import android.os.AsyncTask; 
import android.util.Log; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.GridView; 
import android.widget.AdapterView.OnItemClickListener; 

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

    final String DEF_BASE_URL = "http:api.themoviedb.org/3/tv/popular?[api_key]"; 

    private final Context context; 

    public BackgroundTaskTv(Context context) { 
     this.context = context; 
    } 

    public static String JsonStr; // so that JSONstring can be used by other activities 

    private String[] jsonParse(String movieJsonStr) throws JSONException { 

     final String POSTER_PATH = "poster_path"; // JSON STRING PARSING AND 
                // RETURN 
                // POSTER PATHS 

     JSONObject jsonObj = new JSONObject(movieJsonStr); 
     JSONArray resultArray = jsonObj.getJSONArray("results"); 

     int len =resultArray.length(); 
     String[] posters = new String[len]; 
     for (int i = 0; i < len; i++) { 
      posters[i] = resultArray.getJSONObject(i).getString(POSTER_PATH); 
     } 

     for (String res : posters) 
      Log.v(POSTER_PATH, res); 

     return posters; 

    } 

    @Override 
    protected String[] doInBackground(String... params) { 



     String movieJsonStr = null; 
     InputStream inputStream = null; 


     String FINAL_URL=DEF_BASE_URL; 
     ImageAdapterTv.poster_paths.clear(); 

     BufferedReader reader = null; 
     HttpURLConnection urlConnection = null; // READ THE INPUTSTREAM AND 
               // GET THE JSONSTRING 
     try { 
      URL url = new URL(FINAL_URL); 
      urlConnection = (HttpURLConnection) url.openConnection(); 
      urlConnection.setRequestMethod("GET"); 
      urlConnection.connect(); 

      // Read the input stream into a String 
      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; 
      } 

      movieJsonStr = buffer.toString(); 
      JsonStr=movieJsonStr; 

      Log.v("Tv string: ", movieJsonStr); 
     } catch (Throwable e) { 
      Log.e("backgroundtask", "EXCEPTION", e); 
     } finally { 
      urlConnection.disconnect(); 
      try { 
       reader.close(); 
       inputStream.close(); 
      } catch (IOException e) { 
       Log.e("READER.CLOSE()", e.toString()); 
      } 
     } 

     try { 
      return jsonParse(movieJsonStr); 
     } catch (JSONException e) { 
      Log.e("BACKGROUNDTASK", "EXCEPTION FROM jsonParse()", e); 
     } 

     return null; 
    } 

    @Override 
    protected void onPostExecute(String[] result) { 
     if (ImageAdapterTv.poster_paths.isEmpty()) { 
      for (String s : result) { 
       ImageAdapterTv.poster_paths.add(s); 
      } 
     } 

     final Activity activity = (Activity) context; 
     activity.runOnUiThread(new Runnable() { 
      @Override 
      // this code is written so that the grid view is populated after 
      // backgroundTask 
      public void run() { // produce results so that there is no blank 
           // screen on launch 
       GridView grid = (GridView) activity.findViewById(R.id.gridview_tv); 
       grid.setAdapter(new ImageAdapterTv(context)); 

       grid.setOnItemClickListener(new OnItemClickListener() { 
        @Override 
        public void onItemClick(AdapterView<?> parent, View view, 
          int position, long id) { 
         String path=ImageAdapterTv.poster_paths.get(position); 
         Intent intent=new Intent(context,DetailActivityTv.class); 
         intent.putExtra("poster", path); 
         intent.putExtra("POSITION", position); 
         activity.startActivity(intent); 
         } 
       }); 

       } 
     }); 
    } 

} 

这是这是越来越从一个API 我不知道为什么这个异常被抛出JSON响应后台线程。

+0

为什么不移除围绕BufferedReader初始化的try catch,并查看它的崩溃。 –

回答

3

如果异常初始化在读者面前发生就会导致这个错误,因为阅读器.close()放在finally块中。这是很好的做法,终于

if(reader != null) 
    reader.close(); 
if(inputStream != null) 
    inputStream.close(); 
+0

感谢它的工作,但现在它引发了另一个异常引起:java.lang.NullPointerException:试图调用虚拟方法'int java.lang.String.length()'在一个空对象引用我现在做什么? –

+0

这不是一个好方法。你应该检查null,是的。但在此之前,请检查你为什么变为空。 –

1

你需要检查最后的“空”。发生了一些事情,而读者没有创建。

  try { 
       if (reader != null) reader.close(); 
       if (inputStream!= null) inputStream.close(); 
      } catch (IOException e) { 
       Log.e("READER.CLOSE()", e.toString()); 
      } 

你做return null,但最后完成。并在其中BufferedReader reader = null;。见例如

public static void main(String[] args){ 
    System.out.println(0); 
    Object o = get(); 
    System.out.println(2); 
} 

public static Object get(){ 
    try { 
     System.out.println(1); 
     return null; 
    } catch (Exception e){ 

    } finally { 
     System.out.println("finally"); 
    } 
    return null; 
} 

输出:

终于
+0

感谢它的工作,但现在它抛出了另一个异常引起:java.lang.NullPointerException:试图调用虚拟方法'int java.lang.String.length()'null对象引用我现在做什么? –

+0

我回答了第一个问题,并且您选择了正确的答案。大声笑。可怕的世界......在我看来,你不明白最终如何工作。它总是令人满意。 – user2413972

1

关闭资源之前总是检查空它也许造成的,因为在你的URLConnection异常或您的InputStream为null。

if (inputStream == null) 
return null; 

如果抛出异常或从inputstream空值检查调用返回值,您的代码将最终阻塞。

从不创建使用inputstream创建的读取器对象。所以当你尝试close()方法时,它会抛出空指针异常。

在流和读者,作者使用close()方法之前,您应该始终使用空检查。

+0

感谢它的工作,但现在它抛出另一个异常引起:java.lang.NullPointerException:尝试调用空对象引用虚拟方法'int java.lang.String.length()'现在我该怎么做? –

+0

我无法找到您想要在后台任务中访问字符串长度的位置。异常可能导致在应用程序的其他部分。 – Sudheer

1

因为它是从详细描述可见,当你试图关闭BufferedReader reader对象在finally块,因为它是null在那一刻出现异常。发生这种情况是因为在初始化读取器之前或因为调用return语句而导致try块中出现其他异常,Ë某处这段代码:

 URL url = new URL(FINAL_URL); 
     urlConnection = (HttpURLConnection) url.openConnection(); 
     urlConnection.setRequestMethod("GET"); 
     urlConnection.connect(); 

     // Read the input stream into a String 
     inputStream = urlConnection.getInputStream(); 
     StringBuffer buffer = new StringBuffer(); 
     if (inputStream == null) { 
      // Nothing to do. 
      return null; 
     } 

为了避免这种情况,你应该检查你的nullreaderinputStream封似在此之前:

if(reader != null) { 
    reader.close; 
    reader = null; 
} 
if(inputStream != null) { 
    inputStream.close; 
    inputStream = null; 
} 

除了看看这篇文章关于捕Throwables: Is it a bad practice to catch Throwable?

无论如何,我想你应该知道为什么这个流程发生,因为它不是你想要的,只要我能理解第二

为什么你感动的代码块的第一try-catch外:

try { 
     return jsonParse(movieJsonStr); 
    } catch (JSONException e) { 
     Log.e("BACKGROUNDTASK", "EXCEPTION FROM jsonParse()", e); 
    } 

您可以从一个try{}赶上多种类型的异常,你只需要指定逐一。 如上所述,当出现错误(并且确实如此)时,在创建读取器之前以及之后的所有内容之前,您正在完成之前的try-catch块。因此在这个地方你的movieJsonStr也是null,并且你正在向前传递它以创建一个JSONOblect。这是您的下一个异常来自哪里。将return jsonParse(movieJsonStr);字符串移到您确定它是您要处理的字符串的位置。

相关问题