Attempt to read from field 'android.view.View android.support.v7.widget.RecyclerView$ViewHolder.itemView'











up vote
0
down vote

favorite












I am trying to select recyclerview item randomly with delay.I need to start random selection method after fragment load without any user interaction,But getting the following error. Afterward I put it on ImageView click to check but again I am getting same exception.Will anybody here tell me where I am making a mistake,or what else could be better way to achieve this.Below is my code



    package com.apponative.bjja.fragments;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.apponative.bjja.R;
import com.apponative.bjja.adapters.AttackGridAdapter;

import java.util.Random;

public class Fragment_AttackGrid extends Fragment {

View v;
RecyclerView grid_attack;
AttackGridAdapter attackGridAdapter;
Bundle b;
int itemCount;
Handler randomHandler;
Runnable randomRunnable;
Random rand;
int randomNum = 0;
long emptyTime;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

v = inflater.inflate(R.layout.fragment_attack_grid, container, false);

setUpViews();

return v;
}

void setUpViews() {

b = getArguments();
itemCount = b.getInt(getString(R.string.item_count));
rand = new Random();
randomHandler = new Handler();

grid_attack = (RecyclerView) v.findViewById(R.id.attack_grid);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(), 4);

grid_attack.setLayoutManager(layoutManager);
attackGridAdapter = new AttackGridAdapter(getActivity(), itemCount);
grid_attack.setAdapter(attackGridAdapter);

v.findViewById(R.id.belt_black).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
selectRandomly();
}
});
}

void selectRandomly() {

for (int i = 0; i < itemCount; i++) {
emptyTime = emptyTime+1000;
randomRunnable = new Runnable() {
@Override
public void run() {
grid_attack.findViewHolderForAdapterPosition(randomNum).itemView.setSelected(false);
randomNum = rand.nextInt((itemCount - 0) + 1) + 0;
grid_attack.findViewHolderForAdapterPosition(randomNum).itemView.setSelected(true);
}
};
randomHandler.postDelayed(randomRunnable, emptyTime);

}
emptyTime = emptyTime+2000;
randomRunnable = new Runnable() {
@Override
public void run() {
grid_attack.findViewHolderForAdapterPosition(randomNum).itemView.performClick();
}
};
randomHandler.postDelayed(randomRunnable, emptyTime);
}

@Override
public void onResume() {
super.onResume();
// selectRandomly();
}
}


At start I put




selectRandomly()




at




onResume()




method and I was getting an exception:



01-27 18:28:44.969 19041-19041/com.apponative.bjja E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.apponative.bjja, PID: 19041
java.lang.NullPointerException: Attempt to read from field 'android.view.View android.support.v7.widget.RecyclerView$ViewHolder.itemView' on a null object reference at com.apponative.bjja.fragments.Fragment_AttackGrid$2.run(Fragment_AttackGrid.java:77)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)


According to fragment lifecycle at Fragment LifeCycle onResume() and onStart() methods are called after view has been created. I tried putting my method there too, But no success.










share|improve this question




























    up vote
    0
    down vote

    favorite












    I am trying to select recyclerview item randomly with delay.I need to start random selection method after fragment load without any user interaction,But getting the following error. Afterward I put it on ImageView click to check but again I am getting same exception.Will anybody here tell me where I am making a mistake,or what else could be better way to achieve this.Below is my code



        package com.apponative.bjja.fragments;

    import android.os.Bundle;
    import android.os.Handler;
    import android.support.annotation.Nullable;
    import android.support.v4.app.Fragment;
    import android.support.v7.widget.GridLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;

    import com.apponative.bjja.R;
    import com.apponative.bjja.adapters.AttackGridAdapter;

    import java.util.Random;

    public class Fragment_AttackGrid extends Fragment {

    View v;
    RecyclerView grid_attack;
    AttackGridAdapter attackGridAdapter;
    Bundle b;
    int itemCount;
    Handler randomHandler;
    Runnable randomRunnable;
    Random rand;
    int randomNum = 0;
    long emptyTime;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    v = inflater.inflate(R.layout.fragment_attack_grid, container, false);

    setUpViews();

    return v;
    }

    void setUpViews() {

    b = getArguments();
    itemCount = b.getInt(getString(R.string.item_count));
    rand = new Random();
    randomHandler = new Handler();

    grid_attack = (RecyclerView) v.findViewById(R.id.attack_grid);
    RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(), 4);

    grid_attack.setLayoutManager(layoutManager);
    attackGridAdapter = new AttackGridAdapter(getActivity(), itemCount);
    grid_attack.setAdapter(attackGridAdapter);

    v.findViewById(R.id.belt_black).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    selectRandomly();
    }
    });
    }

    void selectRandomly() {

    for (int i = 0; i < itemCount; i++) {
    emptyTime = emptyTime+1000;
    randomRunnable = new Runnable() {
    @Override
    public void run() {
    grid_attack.findViewHolderForAdapterPosition(randomNum).itemView.setSelected(false);
    randomNum = rand.nextInt((itemCount - 0) + 1) + 0;
    grid_attack.findViewHolderForAdapterPosition(randomNum).itemView.setSelected(true);
    }
    };
    randomHandler.postDelayed(randomRunnable, emptyTime);

    }
    emptyTime = emptyTime+2000;
    randomRunnable = new Runnable() {
    @Override
    public void run() {
    grid_attack.findViewHolderForAdapterPosition(randomNum).itemView.performClick();
    }
    };
    randomHandler.postDelayed(randomRunnable, emptyTime);
    }

    @Override
    public void onResume() {
    super.onResume();
    // selectRandomly();
    }
    }


    At start I put




    selectRandomly()




    at




    onResume()




    method and I was getting an exception:



    01-27 18:28:44.969 19041-19041/com.apponative.bjja E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.apponative.bjja, PID: 19041
    java.lang.NullPointerException: Attempt to read from field 'android.view.View android.support.v7.widget.RecyclerView$ViewHolder.itemView' on a null object reference at com.apponative.bjja.fragments.Fragment_AttackGrid$2.run(Fragment_AttackGrid.java:77)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:155)
    at android.app.ActivityThread.main(ActivityThread.java:5696)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)


    According to fragment lifecycle at Fragment LifeCycle onResume() and onStart() methods are called after view has been created. I tried putting my method there too, But no success.










    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I am trying to select recyclerview item randomly with delay.I need to start random selection method after fragment load without any user interaction,But getting the following error. Afterward I put it on ImageView click to check but again I am getting same exception.Will anybody here tell me where I am making a mistake,or what else could be better way to achieve this.Below is my code



          package com.apponative.bjja.fragments;

      import android.os.Bundle;
      import android.os.Handler;
      import android.support.annotation.Nullable;
      import android.support.v4.app.Fragment;
      import android.support.v7.widget.GridLayoutManager;
      import android.support.v7.widget.RecyclerView;
      import android.view.LayoutInflater;
      import android.view.View;
      import android.view.ViewGroup;

      import com.apponative.bjja.R;
      import com.apponative.bjja.adapters.AttackGridAdapter;

      import java.util.Random;

      public class Fragment_AttackGrid extends Fragment {

      View v;
      RecyclerView grid_attack;
      AttackGridAdapter attackGridAdapter;
      Bundle b;
      int itemCount;
      Handler randomHandler;
      Runnable randomRunnable;
      Random rand;
      int randomNum = 0;
      long emptyTime;

      @Nullable
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

      v = inflater.inflate(R.layout.fragment_attack_grid, container, false);

      setUpViews();

      return v;
      }

      void setUpViews() {

      b = getArguments();
      itemCount = b.getInt(getString(R.string.item_count));
      rand = new Random();
      randomHandler = new Handler();

      grid_attack = (RecyclerView) v.findViewById(R.id.attack_grid);
      RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(), 4);

      grid_attack.setLayoutManager(layoutManager);
      attackGridAdapter = new AttackGridAdapter(getActivity(), itemCount);
      grid_attack.setAdapter(attackGridAdapter);

      v.findViewById(R.id.belt_black).setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
      selectRandomly();
      }
      });
      }

      void selectRandomly() {

      for (int i = 0; i < itemCount; i++) {
      emptyTime = emptyTime+1000;
      randomRunnable = new Runnable() {
      @Override
      public void run() {
      grid_attack.findViewHolderForAdapterPosition(randomNum).itemView.setSelected(false);
      randomNum = rand.nextInt((itemCount - 0) + 1) + 0;
      grid_attack.findViewHolderForAdapterPosition(randomNum).itemView.setSelected(true);
      }
      };
      randomHandler.postDelayed(randomRunnable, emptyTime);

      }
      emptyTime = emptyTime+2000;
      randomRunnable = new Runnable() {
      @Override
      public void run() {
      grid_attack.findViewHolderForAdapterPosition(randomNum).itemView.performClick();
      }
      };
      randomHandler.postDelayed(randomRunnable, emptyTime);
      }

      @Override
      public void onResume() {
      super.onResume();
      // selectRandomly();
      }
      }


      At start I put




      selectRandomly()




      at




      onResume()




      method and I was getting an exception:



      01-27 18:28:44.969 19041-19041/com.apponative.bjja E/AndroidRuntime: FATAL EXCEPTION: main
      Process: com.apponative.bjja, PID: 19041
      java.lang.NullPointerException: Attempt to read from field 'android.view.View android.support.v7.widget.RecyclerView$ViewHolder.itemView' on a null object reference at com.apponative.bjja.fragments.Fragment_AttackGrid$2.run(Fragment_AttackGrid.java:77)
      at android.os.Handler.handleCallback(Handler.java:739)
      at android.os.Handler.dispatchMessage(Handler.java:95)
      at android.os.Looper.loop(Looper.java:155)
      at android.app.ActivityThread.main(ActivityThread.java:5696)
      at java.lang.reflect.Method.invoke(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:372)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)


      According to fragment lifecycle at Fragment LifeCycle onResume() and onStart() methods are called after view has been created. I tried putting my method there too, But no success.










      share|improve this question















      I am trying to select recyclerview item randomly with delay.I need to start random selection method after fragment load without any user interaction,But getting the following error. Afterward I put it on ImageView click to check but again I am getting same exception.Will anybody here tell me where I am making a mistake,or what else could be better way to achieve this.Below is my code



          package com.apponative.bjja.fragments;

      import android.os.Bundle;
      import android.os.Handler;
      import android.support.annotation.Nullable;
      import android.support.v4.app.Fragment;
      import android.support.v7.widget.GridLayoutManager;
      import android.support.v7.widget.RecyclerView;
      import android.view.LayoutInflater;
      import android.view.View;
      import android.view.ViewGroup;

      import com.apponative.bjja.R;
      import com.apponative.bjja.adapters.AttackGridAdapter;

      import java.util.Random;

      public class Fragment_AttackGrid extends Fragment {

      View v;
      RecyclerView grid_attack;
      AttackGridAdapter attackGridAdapter;
      Bundle b;
      int itemCount;
      Handler randomHandler;
      Runnable randomRunnable;
      Random rand;
      int randomNum = 0;
      long emptyTime;

      @Nullable
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

      v = inflater.inflate(R.layout.fragment_attack_grid, container, false);

      setUpViews();

      return v;
      }

      void setUpViews() {

      b = getArguments();
      itemCount = b.getInt(getString(R.string.item_count));
      rand = new Random();
      randomHandler = new Handler();

      grid_attack = (RecyclerView) v.findViewById(R.id.attack_grid);
      RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(), 4);

      grid_attack.setLayoutManager(layoutManager);
      attackGridAdapter = new AttackGridAdapter(getActivity(), itemCount);
      grid_attack.setAdapter(attackGridAdapter);

      v.findViewById(R.id.belt_black).setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
      selectRandomly();
      }
      });
      }

      void selectRandomly() {

      for (int i = 0; i < itemCount; i++) {
      emptyTime = emptyTime+1000;
      randomRunnable = new Runnable() {
      @Override
      public void run() {
      grid_attack.findViewHolderForAdapterPosition(randomNum).itemView.setSelected(false);
      randomNum = rand.nextInt((itemCount - 0) + 1) + 0;
      grid_attack.findViewHolderForAdapterPosition(randomNum).itemView.setSelected(true);
      }
      };
      randomHandler.postDelayed(randomRunnable, emptyTime);

      }
      emptyTime = emptyTime+2000;
      randomRunnable = new Runnable() {
      @Override
      public void run() {
      grid_attack.findViewHolderForAdapterPosition(randomNum).itemView.performClick();
      }
      };
      randomHandler.postDelayed(randomRunnable, emptyTime);
      }

      @Override
      public void onResume() {
      super.onResume();
      // selectRandomly();
      }
      }


      At start I put




      selectRandomly()




      at




      onResume()




      method and I was getting an exception:



      01-27 18:28:44.969 19041-19041/com.apponative.bjja E/AndroidRuntime: FATAL EXCEPTION: main
      Process: com.apponative.bjja, PID: 19041
      java.lang.NullPointerException: Attempt to read from field 'android.view.View android.support.v7.widget.RecyclerView$ViewHolder.itemView' on a null object reference at com.apponative.bjja.fragments.Fragment_AttackGrid$2.run(Fragment_AttackGrid.java:77)
      at android.os.Handler.handleCallback(Handler.java:739)
      at android.os.Handler.dispatchMessage(Handler.java:95)
      at android.os.Looper.loop(Looper.java:155)
      at android.app.ActivityThread.main(ActivityThread.java:5696)
      at java.lang.reflect.Method.invoke(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:372)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)


      According to fragment lifecycle at Fragment LifeCycle onResume() and onStart() methods are called after view has been created. I tried putting my method there too, But no success.







      android android-recyclerview fragment handler runnable






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 27 '17 at 14:13

























      asked Jan 27 '17 at 13:47









      Saira Nawaz

      1661416




      1661416
























          2 Answers
          2






          active

          oldest

          votes

















          up vote
          2
          down vote













          It is possible that view still not loaded, which is why it is returning null exception.



          This function might be useful to call when fragment is loaded and visible to the user:



          // create boolean for checking if view is seen
          private boolean isViewShown = false;

          @Override
          public void setUserVisibleHint(boolean isVisibleToUser) {
          super.setUserVisibleHint(isVisibleToUser);
          if (getView() != null) {
          isViewShown = true;
          // call your function
          } else {
          isViewShown = false;
          }
          }





          share|improve this answer





















          • I am calling my fragement using FragmentTransaction , as far I have read about setUserVisibleHint(boolean isVisibleToUser) method , it is affective in case of viewpager.
            – Saira Nawaz
            Jan 27 '17 at 14:06




















          up vote
          1
          down vote













          This may happen if your onCreateViewHolder method returns null






          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














             

            draft saved


            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f41895466%2fattempt-to-read-from-field-android-view-view-android-support-v7-widget-recycler%23new-answer', 'question_page');
            }
            );

            Post as a guest
































            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            2
            down vote













            It is possible that view still not loaded, which is why it is returning null exception.



            This function might be useful to call when fragment is loaded and visible to the user:



            // create boolean for checking if view is seen
            private boolean isViewShown = false;

            @Override
            public void setUserVisibleHint(boolean isVisibleToUser) {
            super.setUserVisibleHint(isVisibleToUser);
            if (getView() != null) {
            isViewShown = true;
            // call your function
            } else {
            isViewShown = false;
            }
            }





            share|improve this answer





















            • I am calling my fragement using FragmentTransaction , as far I have read about setUserVisibleHint(boolean isVisibleToUser) method , it is affective in case of viewpager.
              – Saira Nawaz
              Jan 27 '17 at 14:06

















            up vote
            2
            down vote













            It is possible that view still not loaded, which is why it is returning null exception.



            This function might be useful to call when fragment is loaded and visible to the user:



            // create boolean for checking if view is seen
            private boolean isViewShown = false;

            @Override
            public void setUserVisibleHint(boolean isVisibleToUser) {
            super.setUserVisibleHint(isVisibleToUser);
            if (getView() != null) {
            isViewShown = true;
            // call your function
            } else {
            isViewShown = false;
            }
            }





            share|improve this answer





















            • I am calling my fragement using FragmentTransaction , as far I have read about setUserVisibleHint(boolean isVisibleToUser) method , it is affective in case of viewpager.
              – Saira Nawaz
              Jan 27 '17 at 14:06















            up vote
            2
            down vote










            up vote
            2
            down vote









            It is possible that view still not loaded, which is why it is returning null exception.



            This function might be useful to call when fragment is loaded and visible to the user:



            // create boolean for checking if view is seen
            private boolean isViewShown = false;

            @Override
            public void setUserVisibleHint(boolean isVisibleToUser) {
            super.setUserVisibleHint(isVisibleToUser);
            if (getView() != null) {
            isViewShown = true;
            // call your function
            } else {
            isViewShown = false;
            }
            }





            share|improve this answer












            It is possible that view still not loaded, which is why it is returning null exception.



            This function might be useful to call when fragment is loaded and visible to the user:



            // create boolean for checking if view is seen
            private boolean isViewShown = false;

            @Override
            public void setUserVisibleHint(boolean isVisibleToUser) {
            super.setUserVisibleHint(isVisibleToUser);
            if (getView() != null) {
            isViewShown = true;
            // call your function
            } else {
            isViewShown = false;
            }
            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jan 27 '17 at 13:56









            user2657378

            3111




            3111












            • I am calling my fragement using FragmentTransaction , as far I have read about setUserVisibleHint(boolean isVisibleToUser) method , it is affective in case of viewpager.
              – Saira Nawaz
              Jan 27 '17 at 14:06




















            • I am calling my fragement using FragmentTransaction , as far I have read about setUserVisibleHint(boolean isVisibleToUser) method , it is affective in case of viewpager.
              – Saira Nawaz
              Jan 27 '17 at 14:06


















            I am calling my fragement using FragmentTransaction , as far I have read about setUserVisibleHint(boolean isVisibleToUser) method , it is affective in case of viewpager.
            – Saira Nawaz
            Jan 27 '17 at 14:06






            I am calling my fragement using FragmentTransaction , as far I have read about setUserVisibleHint(boolean isVisibleToUser) method , it is affective in case of viewpager.
            – Saira Nawaz
            Jan 27 '17 at 14:06














            up vote
            1
            down vote













            This may happen if your onCreateViewHolder method returns null






            share|improve this answer

























              up vote
              1
              down vote













              This may happen if your onCreateViewHolder method returns null






              share|improve this answer























                up vote
                1
                down vote










                up vote
                1
                down vote









                This may happen if your onCreateViewHolder method returns null






                share|improve this answer












                This may happen if your onCreateViewHolder method returns null







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 10 at 13:56









                Sergey Nersesyan

                196111




                196111






























                     

                    draft saved


                    draft discarded



















































                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f41895466%2fattempt-to-read-from-field-android-view-view-android-support-v7-widget-recycler%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest




















































































                    Popular posts from this blog

                    Full-time equivalent

                    さくらももこ

                    13 indicted, 8 arrested in Calif. drug cartel investigation