简体   繁体   中英

Android - java.lang.NullPointerException when loading files for the second time

In my app I have to load data contained in different files in a folder. It works well the first time, but it forces closes the second time I want to load the files (after I have modified them)

01-07 14:55:51.034: W/dalvikvm(3650): threadid=1: thread exiting with uncaught exception (group=0x40018560)
01-07 14:55:51.044: E/AndroidRuntime(3650): FATAL EXCEPTION: main
01-07 14:55:51.044: E/AndroidRuntime(3650): java.lang.NullPointerException
01-07 14:55:51.044: E/AndroidRuntime(3650):     at com.hangin.around.Modele.<init>(Modele.java:27)
01-07 14:55:51.044: E/AndroidRuntime(3650):     at com.hangin.around.MainActivity$5.onClick(MainActivity.java:386)
01-07 14:55:51.044: E/AndroidRuntime(3650):     at android.view.View.performClick(View.java:2506)
01-07 14:55:51.044: E/AndroidRuntime(3650):     at android.view.View$PerformClick.run(View.java:9112)
01-07 14:55:51.044: E/AndroidRuntime(3650):     at android.os.Handler.handleCallback(Handler.java:587)
01-07 14:55:51.044: E/AndroidRuntime(3650):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-07 14:55:51.044: E/AndroidRuntime(3650):     at android.os.Looper.loop(Looper.java:130)
01-07 14:55:51.044: E/AndroidRuntime(3650):     at android.app.ActivityThread.main(ActivityThread.java:3835)
01-07 14:55:51.044: E/AndroidRuntime(3650):     at java.lang.reflect.Method.invokeNative(Native Method)
01-07 14:55:51.044: E/AndroidRuntime(3650):     at java.lang.reflect.Method.invoke(Method.java:507)
01-07 14:55:51.044: E/AndroidRuntime(3650):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
01-07 14:55:51.044: E/AndroidRuntime(3650):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
01-07 14:55:51.044: E/AndroidRuntime(3650):     at dalvik.system.NativeStart.main(Native Method)

Here is where I load the code in MainActivity :

...
    @Override
    protected void onCreate(Bundle savedInstanceState) {

    ...

        startButton.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {

                ...

                // Checking if storage is available
                String storageState = Environment.getExternalStorageState();

                if (storageState.equals(Environment.MEDIA_MOUNTED)){
                    // Listing the files contained in the folder
                    listFiles = listFiles(new File(Environment.getExternalStorageDirectory(), "HanginAround" + File.separator + "modeles" ));

                    // Creating models
                    if (!(listFiles == null)){
                        listeModeles = new Modele[NB_MODELES];
                        for (int i = 0; i < listFiles.length ; i++){
                            listeModeles[i] = new Modele(listFiles[i]); 
                        } // for
                    }// if (listFiles != 0)
                }// if (MEDIA_MOUNTED)
                else {
                    // If storage is unavailable, then show a popup indicating it's not available
                    ...
                }

                ...

            }
        });

        ...

    }

    public File[] listFiles(File directory) {
        // This function return all *.csv files contained in the folder specified in the parameters

        // Listing all files in the folder
        File[] list = directory.listFiles();
        ArrayList<File> arrayListOfFiles = new ArrayList<File>();

        if(!(list == null)) {
            for (int i = 0; i < list.length; i++) 
            {
               if (list[i].isFile() && ( (list[i].getName().endsWith(".csv")) || (list[i].getName().endsWith(".CSV")) ) ) 
               {
                   Log.d(TAG, "MainActivity : " + list[i].getName());
                   arrayListOfFiles.add(list[i]);
                   NB_MODELES += 1;
               } // if ( *.csv )
            } // for ( i < list.length )
        } // if (!(list == null))

        if (NB_MODELES == 0){
            // Showing a popup indicating there's no models in the directory
            ...
        }
        else {
            File[] listOfFiles = new File[NB_MODELES];

            Iterator<File> it =  arrayListOfFiles.iterator();
            int i = 0;

            while (it.hasNext()){
                listOfFiles[i] = (File) it.next();
                i++;
            }

            return listOfFiles; 
        }
        return null;
    }

And here is my class Modele :

package com.hangin.around;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

import android.util.Log;

public class Modele {

    private  String nom;

    private Queue<double[]> fifo = new LinkedList<double[]>();

    private File file ;
    private final static String TAG = "Modele";

    public Modele(File parFile)
    {
        file = parFile;
        // Cutting off the extention from the file name
        String strLine = file.getName();
        StringTokenizer string = new StringTokenizer(strLine, ".");
        nom = string.nextToken();

        // Reading the file
        try{
            // Open the file that is the first 
            // command line parameter
            FileInputStream fstream = new FileInputStream(file);
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            strLine = "";
            //Read File Line By Line
            while ((strLine = br.readLine()) != null)   {
                // Add each value into a table
                StringTokenizer stringTokenizer = new StringTokenizer(strLine, ";");
                double values[] = new double[3];
                int i=0;

                while (stringTokenizer.hasMoreTokens()) {
                    values[i]= Double.parseDouble(stringTokenizer.nextToken());                 
                    i++;        
                }
                // Adding the tab into the Queue
                fifo.add(values);               
            }

            // Close the input stream
            in.close();
        }catch (Exception e){// Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }

    }

    // Class's getters and setters
    public void setNom(String parNom)
    {
        nom=parNom;
    }

    public void setFifo(Queue<double[]> parFifo)
    {
        fifo=parFifo;
    }

    public void setFile(File parFile)
    {
        file=parFile;
    }

    public String getNom()
    {
        return nom;     
    }

    public Queue<double[]> getFifo()
    {
        return fifo;        
    }

    public File getFile()
    {
        return file;        
    }

}

I can't see where the error comes from, can you help me ? Thanks in advance ;)

EDIT :

Line 27 in Modele.java is

String strLine = file.getName(); 

And line 386 in MainActitivy.java is

listeModeles[i] = new Modele(listFiles[i]); 

Seems that you didn't reset NB_MODELES to 0 before re-reading the files and so you array of files is too big (with null at the end).

Please note that there are simple methods to create array from a list. See here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM