1

I am writing unit testing for a function using roboelectric and facing null pointer exception but I have already assigned the variable. I'm pretty new to this so if any mistake please pardon me.

@Before
public void setup() {

    intent = new Intent(context, Xyz.class);
    intent.putExtra("abc", "abc");

    xyz = Robolectric.buildActivity(Xyz.class, intent)
            .create().start().get();
}

@Test
public void onConfigurationChanged() {
    int currentOrientation = xyz.getRequestedOrientation();
    RelativeLayouot gifframe = xyz.findViewById(R.id.gif_frame);
    assertNotNull(gifframe);
    assertEquals(gifframe.getVisibility(), VISIBLE);
    }
}

I expect thee gifframe to be able to get the visibility but gifframe is returning a null value. everywhere I searched a solution to this is to assign the value before calling it. I have assigned the value in the previous line.

Pritam
  • 339
  • 3
  • 22
anirudh
  • 23
  • 7
  • 1
    It just means that ```xyz.findViewById(R.id.gif_frame);``` returns null, thus there is no ```view``` in ```xyz``` that has the ```id``` of ```R.id.gif_frame```. So make sure you to check what is the value of ```R.id.gif_frame``` and check if ther is a ```view``` in ```xyz``` that has that ```id```. Use debugger for this – Mark Melgo Apr 02 '19 at 05:07
  • You've assigned *something*. Clearly that something was `null`. – user207421 Apr 02 '19 at 05:29
  • Yup the value im assigning R.id.gif_frame is null but i'am not understanding why is it null. – anirudh Apr 02 '19 at 05:53

2 Answers2

0

Looks like findViewById is returning null. Basically there is no view available with given Id. That is the right place to debug.

I'd suggest you to attach a debugger and see what is the view that is getting loaded and check if it has the desired views.

Hope this helps.

AskNilesh
  • 58,437
  • 15
  • 99
  • 129
krisnik
  • 1,283
  • 10
  • 15
0

When you do

 RelativeLayouot gifframe = xyz.findViewById(R.id.gif_frame);

Make sure you did setContentView(R.layout.thefilewhichhas_gif_frame)

Meaning make sure it knows where it needs to go look for gif_frame.

AskNilesh
  • 58,437
  • 15
  • 99
  • 129
ajg
  • 13
  • 4
  • I tried this but it is giving android.view.InflateException: XML file /home/anirudh/proj/app/build/intermediates/merged-not-compiled-resources/debug/layout/gifframe.xml line #-1 – anirudh Apr 02 '19 at 05:37
  • show us your xml file – ajg Apr 02 '19 at 17:28