简体   繁体   中英

java.lang.NullPointerException with android fragment

I am trying to implement Fragments in my application. The problem occurs when I change tabs (I'm using drawer layout), I get a java.lang.NullPointerException error. I tested the code on the main activity and it worked smoothly. the only problem is when I apply it on fragment. here is the code:

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;

public class FragW extends Fragment {
    Spinner spinwatt ;
    Button calculate;
    EditText wattEdit;
    EditText costEdit;
    TextView resultText;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragw,container,false);
        calculate = (Button) getView().findViewById(R.id.calculate);
        wattEdit = (EditText) getView().findViewById(R.id.wattEdit);
        costEdit = (EditText) getView().findViewById(R.id.costEdit);

        calculate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                float wattVar = Float.parseFloat(wattEdit.getText().toString());
                float costvar = Float.parseFloat(costEdit.getText().toString());

                if (spinwatt.getSelectedItem().toString().equals("µW"))
                    wattVar = wattVar * (float) 0.000001;
                else if (spinwatt.getSelectedItem().toString().equals("mW"))
                    wattVar = wattVar * (float) 0.001;
                else if (spinwatt.getSelectedItem().toString().equals("kW"))
                    wattVar = wattVar * 1000;
                String resultvar = Float.toString(costvar * wattVar);
                resultText.setText(resultvar);

            }



        });
        spinwatt = (Spinner)getView().findViewById(R.id.spinwatt);
        ArrayAdapter<CharSequence> wattAdapter = ArrayAdapter.createFromResource(getActivity(),
                R.array.wattArray, android.R.layout.simple_spinner_item);
        wattAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinwatt.setAdapter(wattAdapter);

        return v;

    }

Here is the logCat

10-13 12:27:13.429    2563-2563/az.test2 D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
10-13 12:27:31.468    2563-2563/az.test2 D/AndroidRuntime﹕ Shutting down VM
10-13 12:27:31.468    2563-2563/az.test2 W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x409961f8)
10-13 12:27:31.488    2563-2563/az.test2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
        at az.test2.FragW.onCreateView(FragW.java:25)
        at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:795)
        at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:998)
        at android.app.BackStackRecord.run(BackStackRecord.java:622)
        at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1330)
        at android.app.FragmentManagerImpl$1.run(FragmentManager.java:417)
        at android.os.Handler.handleCallback(Handler.java:605)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4340)
        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:784)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
        at dalvik.system.NativeStart.main(Native Method)

Line 25 is: calculate = (Button) getView().findViewById(R.id.calculate); . however, all the lines that are like this cause this error (line 25, 26, 27, 55). I have also tried to initialize the variables with the definitions (in lines 16 to 20) I still got the same error. Please tell me what to do.

change this

    calculate = (Button) getView().findViewById(R.id.calculate);
    wattEdit = (EditText) getView().findViewById(R.id.wattEdit);
    costEdit = (EditText) getView().findViewById(R.id.costEdit);

to

    calculate = (Button) v.findViewById(R.id.calculate);
    wattEdit = (EditText) v.findViewById(R.id.wattEdit);
    costEdit = (EditText) v.findViewById(R.id.costEdit);

initialized your Views from inflated view in Fragment

In onCreateView() , getView() returns null as you haven't yet returned the view to the framework.

Call findViewById() on the View v you just inflated instead.

Your view is not yet created so getView() is null,Therefore change

calculate = (Button) getView().findViewById(R.id.calculate);
wattEdit = (EditText) getView().findViewById(R.id.wattEdit);
costEdit = (EditText) getView().findViewById(R.id.costEdit);
spinwatt = (Spinner)getView().findViewById(R.id.spinwatt);

to

calculate = (Button) v.findViewById(R.id.calculate);
wattEdit = (EditText) v.findViewById(R.id.wattEdit);
costEdit = (EditText) v.findViewById(R.id.costEdit);
spinwatt = (Spinner)v.findViewById(R.id.spinwatt);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM