-3

I have an activity 'B'. I have 2 more activities A and C. Both the activities lead to B. But i pass different Data from A and C. So while fetching

String dataFromA = getIntent.getStringExtra("SomethingA");
String dataFromC = getIntent.getStringExtra("SomethingC");

How to not get an error. I wont know from where the user is getting to activity B So how do i add an If statement or seomthing to not get an error while fetching as Either line A or C will get a NullPOinterException

Markus Kauppinen
  • 3,025
  • 4
  • 20
  • 30

3 Answers3

3

You can use hasExtra method to check if that String exists.

if (getIntent().hasExtra("SomethingA")) {
    String dataFromA = getIntent.getStringExtra("SomethingA");
} else if (getIntent().hasExtra("SomethingC")) {
    String dataFromC = getIntent.getStringExtra("SomethingC");
}
Madis R
  • 121
  • 5
0

You can try this code.

        Bundle arguments = getArguments();
        if (arguments != null){
           if (arguments.containsKey("SomethingA")) {
               String somethingA = arguments.getString("SomethingA");
               if (TextUtils.isEmpty(somethingA)){
                   // Your codes comes here
               }
           }
        }

Bundle (arguments) can be null if there is no data passed.

Emre Aktürk
  • 3,306
  • 2
  • 18
  • 30
-1

To check if string is empty or not use below code :

if(TextUtils.isEmpty(yourString))
 {
 // String empty
 }
 else
 {
   // string not empty
  }

In your case you check it as :

  if (getIntent()!=null && getIntent().getStringExtra!=null )
    {
        if (getIntent().hasExtra("SomethingA") && getIntent().hasExtra("SomethingB"))
        String dataFromA = getIntent.getStringExtra("SomethingA");
        String dataFromB = getIntent.getStringExtra("SomethingB");

    }
Rishav Singla
  • 485
  • 4
  • 10