0

I have used seekbar like quite a few times but never faced problem. Yesterday I was dealing with Fragments which I am not too familiar with but implemented successfully. But at the end of the day when I included seekbar to the fragment and problems started. Not sure this is coz of fragments or what. Here is my code.

fragment_main.xml

<LinearLayout>
<SeekBar
    android:id="@+id/seek"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:max="100"/>
</LinearLayout>

FragmentMain.java

public class FragmentMain extends Fragment {

final static String TAG = "FragmentMain";
TextView mainTextView;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_main, container, false);

    SeekBar seekBar = (SeekBar) getActivity().findViewById(R.id.seek);
    seekBar.setProgress(40);

    return view;
}
}

This FragmenMain is the center page of my viewPager.

I dont know why my code is crashing giving NullPointerException at setProgress.

Feel free to suggest edits.

Srujan Barai
  • 2,295
  • 4
  • 29
  • 52
  • The question has been marked duplicate comparing it with a question with a very broad aspect. I obviously know what nullPointerException means. I was not able to spot it here. Comeon! @Blackbelt – Srujan Barai May 14 '16 at 02:36
  • That's the question I use for every NPE related questions. I could I agree on the fact that's slightly different in your case, but really your fragment related NPE question has been asked over and over again in the past. When you get a null reference from findViewById, it is always because you are looking for it in the wrong place – Blackbelt May 14 '16 at 06:45

2 Answers2

1

Change

SeekBar seekBar = (SeekBar) getActivity().findViewById(R.id.seek);

to

SeekBar seekBar = (SeekBar) view.findViewById(R.id.seek);
Linh
  • 57,942
  • 23
  • 262
  • 279
1

The problem is here

SeekBar seekBar = (SeekBar) getActivity().findViewById(R.id.seek);

You need to find the view with the parent view which your inflating not with context, replace it with

SeekBar seekBar = (SeekBar) view.findViewById(R.id.seek);

Hope it helps

Atiq
  • 14,435
  • 6
  • 54
  • 69