-1

So I am trying to show a certien depending on what item is selected in the spinner. But when i remove a view from the original layout replace it then try to reference it in any way it gives me a null object reference.

Code:

if(subjectSpinner.getSelectedItem().toString().equals("All")){

                allSelected();

            } else {

                if(taskList == null){
                    Log.i("SQL", "task list id null");
                    taskList = (RecyclerView) findViewById(R.id.tasks_list);
                }

//error points at this line
                if(taskList.getParent() == null){

                    TextView textView = (TextView) findViewById(R.id.textView10);

                    baseView.removeAllViews();

                    baseView.addView(appBarLayout);
                    baseView.addView(subjectSpinner);
                    baseView.addView(taskList);
                    baseView.addView(textView);

                }

The allSelected() method:

void allSelected (){
    subjectSpinner = (Spinner) findViewById(R.id.tasks_list_spinner);
    taskList = (RecyclerView) findViewById(R.id.tasks_list);
    baseView = (RelativeLayout) findViewById(R.id.activity_view_tasks);

    baseView.removeView(taskList);

    ScrollView           scrollView    = new ScrollView(getApplicationContext());
    LinearLayout         linearLayout  = new LinearLayout(getApplicationContext());
    List <TextView>      subjectText   = new ArrayList <>();
    List <RecyclerView>  recyclerViews = new ArrayList <>();
    List <CustomAdaptor> adaptor       = new ArrayList <>();

    RelativeLayout.LayoutParams scrollViewParams =
            new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                            ViewGroup.LayoutParams.MATCH_PARENT);
    scrollViewParams.addRule(RelativeLayout.BELOW, R.id.textView10);

    RelativeLayout.LayoutParams linearLayoutParams =
            new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                                            RelativeLayout.LayoutParams.WRAP_CONTENT);

PS. these are not the full code but I am doing nothing else with the taskList recyclerView outside of these snippets.

Logcat:

 Process: com.example.user.timetable_test, PID: 12685
 java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.ViewParent android.support.v7.widget.RecyclerView.getParent()' on a null object reference
     at com.example.user.timetable_test.ViewTasks$1.onItemSelected(ViewTasks.java:225)
     at android.widget.AdapterView.fireOnSelected(AdapterView.java:1165)
     at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:1154)
     at android.widget.AdapterView.access$300(AdapterView.java:59)
     at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:1121)
     at android.os.Handler.handleCallback(Handler.java:739)
     at android.os.Handler.dispatchMessage(Handler.java:95)
     at android.os.Looper.loop(Looper.java:158)
     at android.app.ActivityThread.main(ActivityThread.java:7225)

                                                                                     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

The .xml file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_view_tasks"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.user.timetable_test.ViewTasks"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar_viewTasks"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/appbar_padding_top"
        android:theme="@style/AppTheme.AppBarOverlay">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar3"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay" android:layout_weight="1"/>
    </android.support.design.widget.AppBarLayout>

    <Spinner
        android:layout_width="200dp"
        android:layout_height="wrap_content" android:id="@+id/tasks_list_spinner"
        android:layout_below="@+id/appbar_viewTasks" android:layout_alignParentEnd="true"
        android:layout_marginEnd="@dimen/activity_vertical_margin"
        android:layout_marginTop="@dimen/activity_horizontal_margin"/>

    <TextView
        android:text="@string/subject"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:id="@+id/textView10"
        android:textAppearance="@style/TextAppearance.AppCompat.Headline"
        android:layout_below="@+id/appbar_viewTasks" android:layout_alignParentStart="true"
        android:layout_marginStart="@dimen/activity_vertical_margin"
        android:layout_marginTop="@dimen/activity_horizontal_margin"/>

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent" android:id="@+id/tasks_list"
        android:fitsSystemWindows="true" android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:layout_marginStart="@dimen/activity_vertical_margin"
        android:layout_marginEnd="@dimen/activity_vertical_margin"
        android:layout_below="@+id/textView10"
        android:layout_marginBottom="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"/>
</RelativeLayout>

So does someone know why am I getting this error and how to fix it?

BTW this is not a duplicate of What is a NullPointerException, and how do I fix it?. Yes it is about null pointer exception, but it doesn't ask what is a null pointer exception, but rather how did I get a null pointer exception in this code?

Since I am editing the question and can't post an answer, let me say that I fixed the error by not removing the views, instead making them invisible. It is a work around and not really a fix. If you have a similar problem, hope this helps :)

Omar
  • 75
  • 1
  • 3
  • 11
  • Your taskList etc. are class variables? Why are you assigning them every time you change the spinner selection? – kristyna Dec 31 '16 at 13:02
  • @kristyna I thought that I need to reassign them every time, hence the null error. – Omar Dec 31 '16 at 13:39
  • Try to assign these vies only once. I see no reason why to assign them again and again... Maybe this should help you with that nullpointer – kristyna Dec 31 '16 at 14:45

2 Answers2

0

The problem is that even if the null check fails for tasklist you still call getParent for it. You should wrap the rest of the code inside else for the if (tasklist ==null) part like this:

if(subjectSpinner.getSelectedItem().toString().equals("All")){

                allSelected();

            } else {

                if(taskList == null){
                    Log.i("SQL", "task list id null");
                    taskList = (RecyclerView) findViewById(R.id.tasks_list);
                }

//add else here
               else{
                if(taskList.getParent() == null){

                    TextView textView = (TextView) findViewById(R.id.textView10);

                    baseView.removeAllViews();

                    baseView.addView(appBarLayout);
                    baseView.addView(subjectSpinner);
                    baseView.addView(taskList);
                    baseView.addView(textView);

                }
        }
akash93
  • 1,582
  • 1
  • 10
  • 18
  • wouldn't that skip `baseView.removeAllViews();` if taskList was null? – Omar Dec 31 '16 at 13:46
  • yes it would.. But the reason your exception was occurring was because it was trying to evaluate `getParent` for a null object. Also looking at your layout xml the parent of the RecyclerView is baseView so if it is null then calling `removeAllViews` inside that block doesn't make sense either – akash93 Dec 31 '16 at 14:04
  • it is because there are other views inside the layout, added in code, that i want to remove them to add the recycler view on a clean slate. On another point, I will try, instead of removing the recycler view, to change the visibility depending on whether I want it or not. – Omar Dec 31 '16 at 14:23
  • It would be better if you change visibility instead of removing views since redrawing them is expensive and should be avoided i – akash93 Jan 01 '17 at 03:17
0

The error code says:

Attempt to invoke virtual method 'android.view.ViewParent android.support.v7.widget.RecyclerView.getParent()' on a null object reference

Which means taskList is null.

Possible mistake in your code:

  • Check setContentView(R.layout.your_layout) or inflated layout - is tasks_list id really in your_layout.xml or inflated layout?
kristyna
  • 1,240
  • 23
  • 40
  • I assume you are asking me if the referenced id is in the inflated layout, I posted an edit giving the .xml file of the layout – Omar Dec 31 '16 at 13:43