Search code examples
androidserializationandroid-asynctaskdeserializationobjectinputstream

ObjectInputStream is giving NullPointerException error inside the AsyncTask in Android


My purpose is to deserialize a binary file inside the AsyncTask since it is a heavy process that freezes my Android GUI.

Web Service serializes the Weka Classifier class. Then, I am getting a binary file through Web Service and I am going to deserialize the binary file so that I can continue to process other Weka calculations.

I have achieved to receive the serialized binary file and deserialize in my Android App. Then, I realized that deserialization and reading process takes time. Therefore, I have decided to show Progress Dialog to the user by using AsyncTask.

And, here comes the issue. When I implement the deserialization process inside the doInBackground method, I get a NullPointerException error.

Android Code:

public class MatlabMainWindow extends AppCompatActivity {

private Button treeButton;
private Button positionButton;
private TextView textViewTree;
private PositionDetector positionDetector;
private String treeHolder;
private Classifier j48ClassifierHolder;

File sdcardFile = Environment.getExternalStorageDirectory();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_matlab_main_window);

    treeButton = (Button) findViewById(R.id.button_tree);
    positionButton = (Button) findViewById(R.id.button_position);
    textViewTree = (TextView) findViewById(R.id.textView_tree);


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

            BackgroundTask task = new BackgroundTask(MatlabMainWindow.this);
            task.execute();

        }
    });

    positionButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                String positionString = positionDetector.calculateThePosition();

                AlertDialog.Builder alert = new AlertDialog.Builder(MatlabMainWindow.this);
                alert.setTitle("Position Prediction");
                alert.setMessage(positionString);
                alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub

                    }
                });
                alert.show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

}

private class BackgroundTask extends AsyncTask<Void, Void, Void> {

    private ProgressDialog dialog;

    public BackgroundTask(MatlabMainWindow activity) {
        dialog = new ProgressDialog(activity);
    }

    @Override
    protected void onPreExecute() {
        dialog.setMessage("Doing something, please wait.");
        dialog.show();

    // getting the binary file through web service
    ...
    ...

        Volley.newRequestQueue(MatlabMainWindow.this).add(binaryHttpRequest);
    }

    @Override
    protected void onPostExecute(Void result) {
        textViewTree.setMovementMethod(new ScrollingMovementMethod());
        textViewTree.setText(treeHolder);
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    @Override
    protected Void doInBackground(Void... params) {
        try {
            // deserialize model
            ObjectInputStream ois = new ObjectInputStream(
                    new FileInputStream(sdcardFile.getAbsolutePath() + "/Weka/dataset_RFKON/j48.model"));

                j48ClassifierHolder = (Classifier) ois.readObject();
                ois.close();
        }
        catch (Exception ex){
            ex.printStackTrace();
        }

        //try {
        //
        //        treeHolder = j48ClassifierHolder.toString();
        //    } catch (Exception e) {
        //        e.printStackTrace();
        //    }


        return null;
    }
  }
}

Error:

W/System.err:     at inovasyonwebservice.com.gezkonwebservice.Matlab.MatlabMainWindow$BackgroundTask.doInBackground(MatlabMainWindow.java:250)
W/System.err:     at inovasyonwebservice.com.gezkonwebservice.Matlab.MatlabMainWindow$BackgroundTask.doInBackground(MatlabMainWindow.java:155)
W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:292)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W/System.err:     at java.lang.Thread.run(Thread.java:818)
W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
W/System.err:     at inovasyonwebservice.com.gezkonwebservice.Matlab.MatlabMainWindow$BackgroundTask.doInBackground(MatlabMainWindow.java:264)
W/System.err:     at inovasyonwebservice.com.gezkonwebservice.Matlab.MatlabMainWindow$BackgroundTask.doInBackground(MatlabMainWindow.java:155)
W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:292)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worke

Note: There is no problem about deserialization process, file location or file permisssion because it runs in MatlabMainWindow class perfectly

EDIT1: I have just commented the toString() part to investage reading part closer, the main error that I was getting actually is this one:

W/System.err: java.io.EOFException
W/System.err:     at libcore.io.Streams.readFully(Streams.java:83)
W/System.err:     at java.io.DataInputStream.readLong(DataInputStream.java:147)

Thanks in advance, guys!


Solution

  • OK guys, I have figured out what went wrong. There are main 3 part in my doInBackground() method, which are getting the binary file through Web Service, reading and deserializing the binary file and converting my object into a string.

    I found out that getting the binary file and converting deserilized object into a string confuses readObject() method somehow. Thus, I isolated these 2 process by placing the Web Service part into onCreate() and placing also the string conversion part in to onPostExecute().

    Here is the final code:

    public class MatlabMainWindow extends AppCompatActivity {
    
    private Button treeButton;
    private Button positionButton;
    private TextView textViewTree;
    private PositionDetector positionDetector;
    private String treeHolder;
    private Classifier j48ClassifierHolder;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_matlab_main_window);
    
        treeButton = (Button) findViewById(R.id.button_tree);
        positionButton = (Button) findViewById(R.id.button_position);
        textViewTree = (TextView) findViewById(R.id.textView_tree);
    
        BinaryHttpRequest binaryHttpRequest = new BinaryHttpRequest(....)
    
        Volley.newRequestQueue(MatlabMainWindow.this).add(binaryHttpRequest);
    
        treeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
    
                BackgroundTask task = new BackgroundTask(MatlabMainWindow.this);
                task.execute();
            }
        });
    
        positionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    String positionString = positionDetector.calculateThePosition();
    
                    AlertDialog.Builder alert = new AlertDialog.Builder(MatlabMainWindow.this);
                    alert.setTitle("Position Prediction");
                    alert.setMessage(positionString);
                    alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
    
                        }
                    });
                    alert.show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    
    }
    
    private class BackgroundTask extends AsyncTask<Void, Void, Void> {
    
        private ProgressDialog dialog;
    
        public BackgroundTask(MatlabMainWindow activity) {
            dialog = new ProgressDialog(activity);
        }
    
        @Override
        protected void onPreExecute() {
            dialog.setMessage("Doing something, please wait.");
            dialog.show();
        }
    
        @Override
        protected void onPostExecute(Void result) {
            try {
                treeHolder = positionDetector.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
            textViewTree.setMovementMethod(new ScrollingMovementMethod());
            textViewTree.setText(treeHolder);
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
    
    
        }
    
        @Override
        protected Void doInBackground(Void... params) {
    
            positionDetector = new PositionDetector();
                try {
            // reading the binary file here 
                    positionDetector.getTrainData();
                } catch (Exception e) {
                    e.printStackTrace();
                }
    
                return null;
        }
    }
    }