-1

I have this custom spinner(which has an icon and a number) and I am trying to get the value of the selected item on the spinner. I am using fragments and I seem to be getting some problems of how fragments work and all. I got a NullPointerException when I tried to call setOnItemSelectedListener on the spinner. Based on the logcat errors, the cause of the NPE seems to be originating from the AdapterView.

AlertsFragment.java

public class AlertsFragment extends Fragment{


    private Switch switch1;
    int [] numbers={10,20,30,40,50,60,70, 80, 90, 100, 110, 120};
    int flags[] = {R.drawable.low, R.drawable.low, R.drawable.low, R.drawable.low,
            R.drawable.medium, R.drawable.medium, R.drawable.medium, R.drawable.medium,
            R.drawable.high, R.drawable.high, R.drawable.high, R.drawable.high};


    private AlertsFragment.OnFragmentInteractionListener listener;

    public static AlertsFragment newInstance() {
        return new AlertsFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

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

        View view=inflater.inflate(R.layout.fragment_alerts, container, false);

        switch1= (Switch)view.findViewById(R.id.LEDSwitch);
        switch1.setChecked(false);
        switch1.setTextOn("On");
        switch1.setTextOff("Off");

        Spinner spin = (Spinner)view.findViewById(R.id.LDRspinner);

        CustomAdapter customAdapter=new CustomAdapter(getActivity(),flags,numbers);
        spin.setAdapter(customAdapter);
        spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {

                int value =Integer.valueOf(parent.getItemAtPosition(position).toString());

                String alertMsg= "Alert Raised";
                String alertMsg2= "No Alert Raised";

                if(value< 50){
                    Toast.makeText(
                            getActivity(),alertMsg, Toast.LENGTH_LONG).show();
                }

                else if(value>50){
                    Toast.makeText(
                            getActivity(),alertMsg2, Toast.LENGTH_LONG).show();
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        return view;
    }

    @Override
    public void onAttach(android.content.Context context) {

        super.onAttach(context);

        if (context instanceof AlertsFragment.OnFragmentInteractionListener) {
            listener = (AlertsFragment.OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        listener = null;
    }

    public interface OnFragmentInteractionListener {
    }
}

CustomAdapter.java

public class CustomAdapter extends BaseAdapter {

    Context context;
    int level[];
    int[] numbers;
    LayoutInflater inflter;

    public CustomAdapter(Context applicationContext, int[] level, int[] numbers) {
        this.context = applicationContext;
        this.level = level;
        this.numbers = numbers;
        inflter = (LayoutInflater.from(applicationContext));
    }

    @Override
    public int getCount() {
        return level.length;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view = inflter.inflate(R.layout.custom_spinner_items, null);
        ImageView icon = (ImageView) view.findViewById(R.id.imageView);
        TextView names = (TextView) view.findViewById(R.id.textView);
        icon.setImageResource(level[i]);
        names.setText(String.valueOf(numbers[i]));

        return view;
    }

}

Logcat:

03-17 23:58:47.202 24238-24238/com.example.teerna.smartagriculturev5 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                       java.lang.NullPointerException
                                                                                           at com.example.teerna.smartagriculturev5.AlertsFragment$1.onItemSelected(AlertsFragment.java:60)
                                                                                           at android.widget.AdapterView.fireOnSelected(AdapterView.java:899)
                                                                                           at android.widget.AdapterView.access$200(AdapterView.java:50)
                                                                                           at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:863)
                                                                                           at android.os.Handler.handleCallback(Handler.java:725)
                                                                                           at android.os.Handler.dispatchMessage(Handler.java:92)
                                                                                           at android.os.Looper.loop(Looper.java:137)
                                                                                           at android.app.ActivityThread.main(ActivityThread.java:5283)
                                                                                           at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                           at java.lang.reflect.Method.invoke(Method.java:511)
                                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
                                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
                                                                                           at dalvik.system.NativeStart.main(Native Method)

The logcat's error in the AlertsFragment.java at line 60 points to this:

int value =Integer.valueOf(parent.getItemAtPosition(position).toString());

I have checked out other questions related to this and I tried many ways to solve this by changing Context to Activity in CustomAdapter.java or by initializing a variable Context to null and using it in onAttach method in AlertsFragment.java but they didn't work. I might have done it wrong, I would appreciate some help in it though.

Tia
  • 1,220
  • 5
  • 22
  • 47
  • try to initialize your variable value to 0 at first and then assign it – Xay Mar 17 '18 at 20:22
  • 1
    Possible duplicate of [Null pointer Exception - findViewById()](https://stackoverflow.com/questions/19078461/null-pointer-exception-findviewbyid) – Joe C Mar 17 '18 at 20:22
  • @AkshayRohilla you mean, initialize the variable `context` in the CustomAdapter.java to null? – Tia Mar 17 '18 at 20:28
  • yeah..just try to initialize the variable and after assign it – Xay Mar 17 '18 at 20:43
  • @AkshayRohilla Getting the same error at the same line – Tia Mar 17 '18 at 20:53
  • can you tell why you have used Integer Class instead of simple primitive data type i.e. int – Xay Mar 17 '18 at 21:03
  • Initializing context to null or value to 0 didn't change anything. I used the Integer class because I had to get an integer value of the string and that's the only way I found of doing it. – Tia Mar 17 '18 at 21:09
  • 1
    you can use Integer.parseInt() for getting an integer value from string value – ygngy Mar 17 '18 at 22:13

1 Answers1

1

your CustomAdapter always returns null for all positions:

@Override
public Object getItem(int i) {
    return null;
}

change it to:

@Override
public Object getItem(int i) {
   return level[i];
}

maybe it results to null pointer exception

ygngy
  • 3,630
  • 2
  • 18
  • 29