2

I'm using Parse.com for push notifications. When I receive a push notification, this class executes:

public class MyCustomReceiver extends BroadcastReceiver {

    protected ObjetoMensaje DatosObjecto;
    protected SerializacionDeDatos Sdd;
    protected String alert, fecha, name, tipo;
    private static final String TAG = "MyCustomReceiver";

  @Override
  public void onReceive(Context context, Intent intent) {
    try {

        DatosObjecto = new ObjetoMensaje();
        Sdd = new SerializacionDeDatos();

      String action = intent.getAction();
      String channel = intent.getExtras().getString("com.parse.Channel");
      JSONObject json = new JSONObject(intent.getExtras().getString("com.parse.Data"));

      Log.d(TAG, "got action " + action + " on channel " + channel + " with:");
      Iterator<?> itr = json.keys();
      Log.i("","");

      while (itr.hasNext()) {
        String key = (String) itr.next();
        Log.d(TAG, "..." + key + " => " + json.getString(key));
        Log.d(TAG,"");
       }

      alert = json.getString("alert").toString();
      name = json.getString("name").toString();
      tipo = json.getString("tipo").toString();

      DatosObjecto.setAlert(alert);
      DatosObjecto.setName(name);
      DatosObjecto.setTipo(tipo);

      Sdd.Serializa(DatosObjecto); //this line, I use for call the class "SerializacionDeDatos"

    } catch (JSONException e) {
      Log.d(TAG, "JSONException: " + e.getMessage());
    }
  }
}

These lines:

 alert = json.getString("alert").toString();
  name = json.getString("name").toString();
  tipo = json.getString("tipo").toString();

  DatosObjecto.setAlert(alert);
  DatosObjecto.setName(name);
  DatosObjecto.setTipo(tipo);

When I receive the push, I'm extracting the values of "alert", "name" and "tipo". I put them in an ObjetoMensaje Object. Code:

public class ObjetoMensaje extends Activity implements Serializable{ 

private static final long serialVersionUID = 5680898935329497057L; 
private String  alert, name, tipo; 
protected String filename = "datos.dat";

public ObjetoMensaje(){}; 

public ObjetoMensaje(String alert, String name, String tipo){ 
    super(); 
    this.alert = alert;
    this.name = name;
    this.tipo = tipo; 
    }

public String getAlert(){
    return alert;
}

public void setAlert(String alert){
    this.alert = alert;
    Log.i("Set Alert", "Excitoso");
}

public String getName(){
    return name;
}

public void setName(String name){
    this.name = name;
    Log.i("Set Name", "Excitoso");
}

public String getTipo(){
    return tipo;
}

public void setTipo(String tipo){
    this.tipo = tipo;
    Log.i("Set tipo", "Excitoso");
}
}

I want to serialize the values "alert", "name", and "tipo", so I've created a class for serialization:

public class SerializacionDeDatos extends Activity{

protected String filename = "datos.dat";
protected void Serializa(ObjetoMensaje DatosObjecto){
            FileOutputStream fos;
            try {
                fos = openFileOutput(filename, Context.MODE_PRIVATE);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                oos.writeObject(DatosObjecto);
                oos.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } 
            catch (IOException e) {
                e.printStackTrace();
            }
    }
}

When I call the class, I get this error:

08-08 13:15:32.976: W/dalvikvm(8360): threadid=1: thread exiting with uncaught exception (group=0x4001c578)
08-08 13:15:33.070: E/AndroidRuntime(8360): FATAL EXCEPTION: main
08-08 13:15:33.070: E/AndroidRuntime(8360): java.lang.RuntimeException: Unable to start receiver mx.nivel9.apps.MyCustomReceiver: java.lang.NullPointerException
08-08 13:15:33.070: E/AndroidRuntime(8360):     at android.app.ActivityThread.handleReceiver(ActivityThread.java:1809)
08-08 13:15:33.070: E/AndroidRuntime(8360):     at android.app.ActivityThread.access$2400(ActivityThread.java:117)
08-08 13:15:33.070: E/AndroidRuntime(8360):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:985)
08-08 13:15:33.070: E/AndroidRuntime(8360):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-08 13:15:33.070: E/AndroidRuntime(8360):     at android.os.Looper.loop(Looper.java:130)
08-08 13:15:33.070: E/AndroidRuntime(8360):     at android.app.ActivityThread.main(ActivityThread.java:3687)
08-08 13:15:33.070: E/AndroidRuntime(8360):     at java.lang.reflect.Method.invokeNative(Native Method)
08-08 13:15:33.070: E/AndroidRuntime(8360):     at java.lang.reflect.Method.invoke(Method.java:507)
08-08 13:15:33.070: E/AndroidRuntime(8360):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
08-08 13:15:33.070: E/AndroidRuntime(8360):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
08-08 13:15:33.070: E/AndroidRuntime(8360):     at dalvik.system.NativeStart.main(Native Method)
08-08 13:15:33.070: E/AndroidRuntime(8360): Caused by: java.lang.NullPointerException
08-08 13:15:33.070: E/AndroidRuntime(8360):     at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:158)
08-08 13:15:33.070: E/AndroidRuntime(8360):     at mx.nivel9.apps.SerializacionDeDatos.Serializa(SerializacionDeDatos.java:23)
08-08 13:15:33.070: E/AndroidRuntime(8360):     at mx.nivel9.apps.MyCustomReceiver.onReceive(MyCustomReceiver.java:50)
08-08 13:15:33.070: E/AndroidRuntime(8360):     at android.app.ActivityThread.handleReceiver(ActivityThread.java:1798)
08-08 13:15:33.070: E/AndroidRuntime(8360):     ... 10 more

What am I doing wrong?

JoshDM
  • 4,939
  • 7
  • 43
  • 72
Robert
  • 1,192
  • 1
  • 10
  • 20

2 Answers2

1

The error comes from your code line 23 in the SerializacionDeDatos class. You are invoking a method on an object that has not been initialized yet - meaning you created a variable for an object, but did not use the "new" operator to create the object or the initialization returned null.

This line could probably the problem if "filename" is not valid.

fos = openFileOutput(filename, Context.MODE_PRIVATE);

Onfortunately there are no line numbers in your code snippet, so I cannot tell where exactly the error comes from.

Philipp Jahoda
  • 50,880
  • 24
  • 180
  • 187
0

These lines in your exception log:

08-08 13:15:33.070: E/AndroidRuntime(8360):     at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:158)
08-08 13:15:33.070: E/AndroidRuntime(8360):     at mx.nivel9.apps.SerializacionDeDatos.Serializa(SerializacionDeDatos.java:23)

tells us the exception is being thrown from

 fos = openFileOutput(filename, Context.MODE_PRIVATE);

in SerializacionDeDatos class, or more notably the call to openFileOutput, which means it is likely there is a fundamental problem with the file you are referring to (permissions, existence, etc.)

Unless you're doing something specific to each type of Exception, you should just add a general catch for (Exception e) to your try in your Serializa method, and print the stack trace to find out what's wrong as follows:

        try {

            fos = openFileOutput(filename, Context.MODE_PRIVATE);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(DatosObjecto);
            oos.close();

        } catch (Exception e) {

            e.printStackTrace();
        } 

Of further note, you're not closing your FileOutputStream. Best practices are to initialize it outside the try with null, then call the close() method in your finally block, as follows:

        FileOutputStream fos = null;
        ObjectOutputStream oos = null;

        try {

            fos = openFileOutput(filename, Context.MODE_PRIVATE);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(DatosObjecto);

        } catch (Exception e) {

            e.printStackTrace(); // NOW this should now tell us what's going wrong.

        } finally {

            try {

                oos.close();

            } catch (Exception e) {

                e.printStackTrace();
            }

            try {

                fos.close();

            } catch (Exception e) {

                e.printStackTrace();
            }
        }

UPDATE: You have noted in the comments below that you are receiving a NullPointerException. This is a very common problem when calling Activity.openFileOutput().

Check to see if your answer is on any of these links:

Community
  • 1
  • 1
JoshDM
  • 4,939
  • 7
  • 43
  • 72
  • I did that you say and throw many system.err, the first three are: `W/System.err(10893): java.lang.NullPointerException W/System.err(10893): at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:158) W/System.err(10893): at mx.nivel9.apps.SerializacionDeDatos.Serializa(SerializacionDeDatos.java:23)` – Robert Aug 08 '13 at 19:56
  • Your call to `Activity.openFileOutput` is throwing a `NullPointerException`. This is a common problem. Check to see if your answer is here: http://stackoverflow.com/questions/10259421/nullpointerexception-at-openfileoutput-in-activity or here http://stackoverflow.com/questions/6282313/nullpointer-exception-in-contextwrapper – JoshDM Aug 08 '13 at 20:12
  • and I will not need IOException and the FileNotFoundException? – Robert Aug 08 '13 at 20:19
  • That's your call. Basic Java 101. If you need to differentiate between how you handle an `IOException` and how you handle a `FileNotFoundException`, then differentiate, otherwise, both extend `Exception`, so they'll be caught. – JoshDM Aug 08 '13 at 20:21
  • You still have to resolve the underlying issue: why is this method `openFileOutput` throwing a `NullPointerException`. You should edit your original question and include the entire NEW stack trace you're receiving. – JoshDM Aug 08 '13 at 20:27