线程代码中的NullPointerException导致线程终止

时间:2014-01-16 16:12:14

标签: java android multithreading nullpointerexception handler

我在我的Asynctask中有以下代码:

public DialogoAlerta dialogo;
    public FileOutputStream fos;
    public int size;
    public byte[] buf;
    public int byteRead;
    public int bytesDownloaded;
    public InputStream inputStream;
    public int time;
    public Thread hilo;

    @Override
    protected Boolean doInBackground(Void... arg0) {

        readXML();

        db = bdhelper.getWritableDatabase();

        if(db != null)
        {
            Log.d("Tamaño de la lista", buttonsList.size()+"");

for(int i=0; i<buttonsList.size(); i++)
            {
                String[] campos = new String[] {"local"};
                String[] args = new String[] {buttonsList.get(i).getImageurl().toString()};
                Cursor c = db.query("Imagenes", campos, "url=?", args, null, null, null);
                Cursor c2 = db.rawQuery("SELECT url, local FROM Imagenes WHERE url='"+args+"' AND local='imagemissing.png'", null);
                Log.d("El valor de la consulta es: ", "valor "+c.moveToFirst());
                if (!c.moveToFirst() || (c.moveToFirst() && c2.moveToFirst())){
                    if(isOnline()){
                    //Generamos los datos
                        Random generator = new Random();
                        int n = 10000;
                        n = generator.nextInt(n);

                        String url = buttonsList.get(i).getImageurl().toString();
                        String local = "Imagen" + n;
                        try {
                            URL direccion = new URL(url);
                            File myDir =  new File(Environment.getExternalStorageDirectory () +"/Aspaceimages/");

                            if(!myDir.exists()){
                                myDir.mkdirs();
                                Log.v("", "Se crea la ruta "+myDir);
                            }

                            File file = new File (myDir, local+".jpg");
                            while(file.exists()){
                                local = local + n;
                                file = new File(myDir, local+".jpg");
                            }

                            URLConnection ucon = direccion.openConnection();
                            inputStream = null;
                            HttpURLConnection httpConn = (HttpURLConnection)ucon;
                            httpConn.setRequestMethod("GET");
                            httpConn.connect();
                            Log.d("Peso de la imagen en Bytes (header): ", httpConn.getContentLength()+"");


                          if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                           inputStream = httpConn.getInputStream();
                          }

                            fos = new FileOutputStream(file);
                            size = 1024*1024;
                            buf = new byte[size];
                            bytesDownloaded = 0;

                            hilo = new Thread(new Runnable() {

                                @Override
                                public void run() {
                                    // TODO Auto-generated method stub
                                    try {
                                        Log.i("ID DEL HILO", hilo.getId()+"****************************");
                                        while (((byteRead = inputStream.read(buf)) != -1)) {
                                            fos.write(buf, 0, byteRead);
                                            bytesDownloaded += byteRead;
                                            Log.d("leyendo imagen", "descargando imagen del servidor");
                                        }
                                        Log.d("peso de la imagen descargada", ""+bytesDownloaded);
                                        fos.close();
                                        Message msg = new Message();
                                          msg.what = IMAGE_DOWNLOADED;
                                          mHandler.sendMessage(msg);
                                    } catch (IOException e) {
                                        Log.e("Error", "not downloading");
                                        e.printStackTrace();
                                    }

                                }
                            });
                            hilo.start();   



                            //Compruebo si hay conexión accediendo al tipo de contenido
                                if(!httpConn.getContentType().toString().contains("image")){
                                    db.execSQL("DROP TABLE Imagenes");
                                    Log.d("Eliminada: ", "Base de datos eliminada");
                                    db.execSQL("CREATE TABLE IF NOT EXISTS Imagenes (url TEXT, local TEXT)");
                                    deleteDirectory(myDir);
                                    return false;   
                                }




                        } catch (MalformedURLException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }catch (Exception e) {
                            e.printStackTrace();                            
                        }

                        if(!c.moveToFirst()){
                            //Insertamos los datos en la tabla Usuarios
                            db.execSQL("INSERT INTO Imagenes (url, local) " +
                                       "VALUES ('" + url + "', '" + local+".jpg" +"')");
                            Log.i("Inserta en la base de datos", "Inserta");
                        } else if (c.moveToFirst() && c2.moveToFirst()){
                            //Actualizamos el registro en la base de datos
                            db.execSQL("UPDATE Imagenes SET local='"+local+".jpg' WHERE url='"+url+"'");
                            Log.i("Actualiza en la base de datos", "Actualiza");
                        }
                        publishProgress((100/buttonsList.size())*(i+1));
                    } else {
                        Log.d(tag, "error");
                        db.execSQL("DROP TABLE Imagenes");
                        Log.d("Eliminada: ", "Base de datos eliminada");
                        db.execSQL("CREATE TABLE IF NOT EXISTS Imagenes (url TEXT, local TEXT)");
                        return false;
                    }
                } else {
                    try {
                        Thread.sleep(100);
                    } catch(InterruptedException e) {}
                    publishProgress((100/buttonsList.size())*(i+1));
                }
            }

我的经纪人

public Handler mHandler = new Handler() {
        public void handleMessage(Message msg){
            switch (msg.what){
                case IMAGE_DOWNLOADED : {
                    Log.d("Imagen descargada", "entró al handler");
                    try {
                        Thread.sleep(2000);
                    } catch(InterruptedException e) {}
                    break;
                }
                default : {
                    break;
                }
            }
        }
    };

当我运行我的应用程序时,日志显示我:

01-16 16:39:27.941: W/dalvikvm(14273): threadid=14: thread exiting with uncaught exception (group=0x41850ba8)
01-16 16:39:27.951: E/AndroidRuntime(14273): FATAL EXCEPTION: Thread-415
01-16 16:39:27.951: E/AndroidRuntime(14273): Process: com.example.aspace, PID: 14273
01-16 16:39:27.951: E/AndroidRuntime(14273): java.lang.NullPointerException
01-16 16:39:27.951: E/AndroidRuntime(14273):    at com.example.aspace.SplashActivity$MiTareaAsincrona$2.run(SplashActivity.java:312)
01-16 16:39:27.951: E/AndroidRuntime(14273):    at java.lang.Thread.run(Thread.java:841)

我有一个NullPointer,但我不知道为什么,我跟踪输入流,fos,大小,buf的值,但没有人为null,nullpointer出现在第二次迭代,特别是在这一行:

while (((byteRead = inputStream.read(buf)) != -1)) {

我跟踪了read方法并且没有返回null,我做错了什么?我想我没有好好使用Thread ...有什么建议吗?对不起我的长代码并感谢你的时间

3 个答案:

答案 0 :(得分:1)

  

while (((byteRead = inputStream.read(buf)) != -1)) {

     

我跟踪了read方法并且没有返回null,我做错了什么?

在我看来inputStream为空。看完代码后我看到了:

inputStream = null;
...
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
    inputStream = httpConn.getInputStream();
}
...
// thread does the read

所以我怀疑响应代码不是200.如果响应代码不是HTTP_OK那么你应该退出你的方法而分叉一个线程来读取响应。

将来,您可以像调整其他应用程序一样轻松调试线程应用程序。您可以在NPE附近放置断点,然后测试相关字段。调试可以搞砸线程程序的计时,但仍然有用。

答案 1 :(得分:0)

正如@Gray已经说过的那样,您将inputStream创建为null,并且仅在响应为200时为其设置值。然后,您尝试在代码的另一个点访问此对象。

假设您的响应总是 200不是一个好习惯,因为每次运行任务时,您都依赖于连接的成功响应。

你应该为它添加一些错误处理代码,这样你不仅可以避免空指针,还可以在出现问题时给予用户适当的反馈。

我想补充的另一件事是,在使用它之前,您并不需要将inputStream设置为null,因为每个Java对象都已初始化为null。

答案 2 :(得分:0)

谢谢你的时间......

通过删除以下行解决了问题:

inputStream = null;

这是一个线程问题,我创建了多个线程,我正在初始化inputstream var而其他线程正在运行...

感谢您的帮助和建议!