-1

I have a activity where you select a number in a spinner(dropdown-list in AndroidStudio) and sends it to a new activity/another class, before it is sent to a server. The array-adapter works fine, but using the getExtra Intent in the receiving activity is a lot of trouble for me. The app crashes and logcat give this message:

NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference.
MainActivity.(MainActivity.java:76)

Line 76 in MainActivity String avd_nr= getIntent().getStringExtra("getData");

This is my code for passing the array value, and the line Log.i("data",avd); posts the spinner value(avd) in the logcat.

btnAvdeling.setOnClickListener(new View.OnClickListener()
            {
                final String avd = dropdown.getSelectedItem().toString();
                @Override
                public void onClick(View v)
                {
                    Intent i = new Intent(getApplicationContext(), MainActivity.class);
                    i.putExtra("getData",avd.toString());
                    startActivity(i);
                    Log.i("data",avd);
                }
            }

This is my code where I receive data

String avd_nr= getIntent().getStringExtra("getData");

private SurveyResponse fillInResponsData(Integer answer) {
    surveyResponse.setAvdeling(avd_nr);
    return surveyResponse;
}

Please give some help on what i need to add or change

Jens
  • 168
  • 2
  • 13
  • Is `String avd_nr= getIntent().getStringExtra("getData");` outside a method? As in, is `avd_nr` a field in the class, rather than a local variable? – Andy Turner Apr 07 '17 at 18:52
  • 1
    write `String avd_nr= getIntent().getStringExtra("getData");` inside `onCreate()`... – rafsanahmad007 Apr 07 '17 at 18:52
  • @rafsanahmad007 or at least `avd_nr = getIntent().getStringExtra(...)`. You can still declare the variable outside the method. – Andy Turner Apr 07 '17 at 18:53
  • Thanks, but how can I acces *avd_nr* from *onCreate()* method in my *fillInResponsData* method? – Jens Apr 07 '17 at 20:24
  • 1
    Possible duplicate of [how to handle a getIntent() method with java nullpointerexception](http://stackoverflow.com/questions/21236245/how-to-handle-a-getintent-method-with-java-nullpointerexception) – Jens Apr 19 '17 at 08:05

2 Answers2

0

in onCreate() Method put the following :

 String avd_nr =getIntent.getExtras("getData");
0
 String avd_nr =getIntent.getExtras("getData");

Its should be on onCreate() method

Farmaan Elahi
  • 1,620
  • 16
  • 18
  • I see, but how can I make *avd_nr* in the onCreate() method available for the fillInResponsData method ? – Jens Apr 07 '17 at 20:15