Pergunta

I have a local broadcast inside an intentService which sends a message to an activity. the problem is am getting a null pointer exception. any help is appreciated :)

LogCat Error

01-22 17:57:15.461: I/Arrival(16592): This is instantated
01-22 17:57:16.859: D/sender(16592): Broadcasting message
01-22 17:57:16.867: D/AndroidRuntime(16592): Shutting down VM
01-22 17:57:16.867: W/dalvikvm(16592): threadid=1: thread exiting with uncaught exception (group=0x4110d930)
01-22 17:57:16.875: E/AndroidRuntime(16592): FATAL EXCEPTION: main
01-22 17:57:16.875: E/AndroidRuntime(16592): java.lang.NullPointerException
01-22 17:57:16.875: E/AndroidRuntime(16592):    at android.support.v4.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:297)
01-22 17:57:16.875: E/AndroidRuntime(16592):    at android.support.v4.content.LocalBroadcastManager.access$000(LocalBroadcastManager.java:46)
01-22 17:57:16.875: E/AndroidRuntime(16592):    at android.support.v4.content.LocalBroadcastManager$1.handleMessage(LocalBroadcastManager.java:116)
01-22 17:57:16.875: E/AndroidRuntime(16592):    at android.os.Handler.dispatchMessage(Handler.java:99)
01-22 17:57:16.875: E/AndroidRuntime(16592):    at android.os.Looper.loop(Looper.java:175)
01-22 17:57:16.875: E/AndroidRuntime(16592):    at android.app.ActivityThread.main(ActivityThread.java:5279)
01-22 17:57:16.875: E/AndroidRuntime(16592):    at java.lang.reflect.Method.invokeNative(Native Method)
01-22 17:57:16.875: E/AndroidRuntime(16592):    at java.lang.reflect.Method.invoke(Method.java:511)
01-22 17:57:16.875: E/AndroidRuntime(16592):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
01-22 17:57:16.875: E/AndroidRuntime(16592):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
01-22 17:57:16.875: E/AndroidRuntime(16592):    at dalvik.system.NativeStart.main(Native Method)

Receiver Class (Activity)

package com.user;

public class Arrival_List extends Activity {


    SqlHandler sqlHandler;
    ListView lvCustomList, listView;
    EditText IconBearing, BusName, DistanceInfo;
    Button btnGetData;

    MediaPlayer mp;
    String SENDER_ID = "616159599278";
    static final String TAG = "GCMDemo";
    GoogleCloudMessaging gcm;
    TextView mDisplay;
    Context context;
    String regid;
     private BroadcastReceiver mMessageReceiver;

    ArrayList<ContactListItems> contactList = new ArrayList<ContactListItems>();
    ContactListAdapter contactListAdapter = new ContactListAdapter(this,
            contactList);

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_arrival);

        sqlHandler = new SqlHandler(this);
        btnMap = (Button) findViewById(R.id.OPEN_MAP);
        RelativeLayout listViewHolder = (RelativeLayout) findViewById(R.id.listViewHolder);
        lvCustomList = new ListView(getApplication());
        listViewHolder.addView(lvCustomList);
        Log.i("Arrival", "This is instantated");

        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
                  new IntentFilter("custom-event-name"));


            // Our handler for received Intents. This will be called whenever an Intent
            // with an action named "custom-event-name" is broadcasted.
             mMessageReceiver = new BroadcastReceiver() {
              @Override
              public void onReceive(Context context, Intent intent) {
                // Get extra data included in the Intent
                String message = intent.getStringExtra("message");
                Log.i("receiver", "Got message: " + message);

              }
            };

    }

    @Override
    protected void onDestroy() {
      // Unregister since the activity is about to be closed.
      LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
      super.onDestroy();
    }


}

Sender Class (Service)

public class Get_Distane_Data extends IntentService {

    SqlHandler sqlHandler;
    ListView lvCustomList, listView;
    EditText IconBearing, BusName, DistanceInfo;
    Button btnGetData;
    JSONParser jsonParser = new JSONParser();
    JSONArray products = null;
    MediaPlayer mp;
    String SENDER_ID = "616159599278";
    static final String TAG = "GCMDemo";
    GoogleCloudMessaging gcm;

    TextView mDisplay;
    Context context;
    String regid;
    private static String URL_Distance = "http://vu2150.admin.studentswebprojects.ritaj.ps/Distance_Send_Receive/Get_Distance_From_Database.php";
    ArrayList<ContactListItems> contactList = new ArrayList<ContactListItems>();
    ContactListAdapter contactListAdapter = new ContactListAdapter(this,
            contactList);

    public Get_Distane_Data() {
        super("Get_Distane_Data");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        sqlHandler = new SqlHandler(this);
        // TODO Auto-generated method stub
        String RegistrartionID = RegisID();

        List<NameValuePair> params = new ArrayList<NameValuePair>();

        params.add(new BasicNameValuePair("RegistrartionID", RegistrartionID));

        Log.i("RegistrartionID", RegistrartionID);

        JSONObject json = jsonParser.makeHttpRequest(URL_Distance, "POST",
                params);
        String query = "DELETE FROM GPS_INFORMATION;";
        sqlHandler.executeQuery(query);

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt("success");

            if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray("products");

                // looping through All Products
                for (int i = 0; i < products.length(); i++) {
                    JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable

                    String Bus_Distance = c.getString("Bus_Distance");

                    String Bus_Bearing = c.getString("Bus_Bearing");
                    String Bus_Long = c.getString("Bus_Long");
                    String Bus_Lat = c.getString("Bus_Lat");
                    String BusName = c.getString("Bus_Name");

                    Log.i("Bus_Distance", Bus_Distance);
                    Log.i("Bus_Bearing", Bus_Bearing);
                    Log.i("Bus_Long", Bus_Long);
                    Log.i("Bus_Lat", Bus_Lat);
                    Log.i("BusName", BusName);

                    try {
                        String query0 = "INSERT INTO GPS_INFORMATION(Bus_Name,Distance_Info,Icon_Bearing,Bus_Lat,Bus_Long) values ('"
                                + Bus_Bearing
                                + "','"
                                + BusName
                                + "','"
                                + Bus_Distance
                                + "','"
                                + Bus_Lat
                                + "','"
                                + Bus_Long + "')";
                        sqlHandler.executeQuery(query0);

                        sendMessage();

                    } catch (Exception e) {
                        Log.i("error", "this is where the error happens");
                    }

                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }



    private void sendMessage() {
        Log.d("sender", "Broadcasting message");
        Intent intent = new Intent("custom-event-name");
        intent.putExtra("message", "This is my message!");
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }

}
Foi útil?

Solução

in line

LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
              new IntentFilter("custom-event-name"));

mMessageReceiver is null, it is assigned below, you must initialize before registerReceiver

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top