Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the putExtra exist?

I have a diagram as follows

Activity 1 --send data--> Service1
                            ^
                            |
Open app--------------------
                            ^
                            |
Activity 2------------------

It means the activity 1 will send the data to a Service 1. The service 1 is a running background service with return in onStartCommand() is START_STICKY. Currently, I am using putExtra() function to exchange the data. And in the service I will getExtra data as follows steps:

In Activity 1

Intent start_service = new Intent(getContext(), ConnectService.class);
start_service.putExtra("data", "123");
getContext().startService(start_service);

In onStartCommand() of Service 1

 String data=null;
 if(intent.hasExtra("data")){
    Bundle bundle = intent.getExtras();
    if(!bundle.getString("data").equals(null)){
        data= bundle.getString("data");
    }
  }
  else
       data="0";

I used the hasExtra function to check whether data is set or not. In my purpose, the case 1 is that the Service 1 can receive data from the Activity 1 . In the case 2, if we do not start from the Activity 1, for example, when I clean all running app, the phone will be open the Service 1 automatically due to START_STICKY, the Service 1 will set data equal "0". Hence, my issue is from second case, the application is crash because it cannot check the Extra exist or not.

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.content.Intent.hasExtra(java.lang.String)' on a null object reference

How could I fix the issue? Thank all

like image 302
Jame Avatar asked Dec 11 '25 05:12

Jame


1 Answers

 String data=null;
 if(getIntent()!=null && getIntent().getExtras()!=null){
    Bundle bundle = getIntent().getExtras();
    if(!bundle.getString("data").equals(null)){
        data= bundle.getString("data");
    }
 }
 else
 data="0";

try this,notice the change in if condition

like image 54
Ak9637 Avatar answered Dec 13 '25 19:12

Ak9637



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!