Android Fragment onCreateView中的NullPointerException

时间:2014-05-21 08:29:28

标签: android nullpointerexception

您好我已经阅读了所有类似的问题/答案,我想我可以肯定这与选定的主题无关!

我现在使用主题灯,因此操作栏nullpointer问题应该没有问题。

这里有例外:

05-21 09:54:47.076: E/AndroidRuntime(24459): FATAL EXCEPTION: main
05-21 09:54:47.076: E/AndroidRuntime(24459): Process: de.poetjan.powerconsumption, PID: 24459
05-21 09:54:47.076: E/AndroidRuntime(24459): java.lang.NullPointerException
05-21 09:54:47.076: E/AndroidRuntime(24459):    at de.poetjan.powerconsumption.Verbrauch.onCreateView(Verbrauch.java:131)
05-21 09:54:47.076: E/AndroidRuntime(24459):    at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
05-21 09:54:47.076: E/AndroidRuntime(24459):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
05-21 09:54:47.076: E/AndroidRuntime(24459):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
05-21 09:54:47.076: E/AndroidRuntime(24459):    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
05-21 09:54:47.076: E/AndroidRuntime(24459):    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
05-21 09:54:47.076: E/AndroidRuntime(24459):    at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
05-21 09:54:47.076: E/AndroidRuntime(24459):    at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
05-21 09:54:47.076: E/AndroidRuntime(24459):    at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
05-21 09:54:47.076: E/AndroidRuntime(24459):    at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
05-21 09:54:47.076: E/AndroidRuntime(24459):    at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)

这里是我的片段Verbrauch.java;

package de.poetjan.powerconsumption;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.AlertDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.net.ParseException;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class Verbrauch extends Fragment  {

    private double ba;
    private double ea;
    private double zwischen;
    //  private AdView adView;
    int mYear1;
    int mMonth1;
    int mDay1; 
    int mYear2;
    int mMonth2;
    int mDay2; 
    Button pickdate;
    Button pickdate2;
    Button berechnen;
    ToggleButton month;
    ToggleButton quarteryear;
    ToggleButton halfyear;
    ToggleButton year;
    EditText dateDisplay1;
    EditText dateDisplay2;
    EditText kwhDisplay1;
    EditText kwhDisplay2;
    TextView textView5;
    TextView textView6;
    TextView textView50;
    EditText editText5;
    long diff;
    int differ;
    String fromDate;
    String toDate;
    String neuformatjahr1;
    String neuformatmonat1;
    String neuformattag1;
    String neuformatjahr2;
    String neuformatmonat2;
    String neuformattag2;
    String gesamt2o;
    String gesamt1o;
    private boolean mBool = false;
    private boolean firststart = false;
    final SimpleDateFormat df = new SimpleDateFormat("ddMMyyyy");
    final DecimalFormat formatter = new DecimalFormat("#.##");

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

        View rootView = inflater.inflate(R.layout.verbrauch, container, false);

        getActivity();
        //initialize ViewElements
        boolean firstboot = getActivity().getSharedPreferences("BOOT_PREF", FragmentActivity.MODE_PRIVATE).getBoolean("firstboot", true);
        dateDisplay1 = (EditText) rootView.findViewById(R.id.dateDisplay1);
        dateDisplay2 = (EditText) rootView.findViewById(R.id.dateDisplay2);
        kwhDisplay1 = (EditText) rootView.findViewById(R.id.kwhDisplay1);
        kwhDisplay2 = (EditText) rootView.findViewById(R.id.kwhDisplay2);
        editText5 = (EditText) rootView.findViewById(R.id.editText5);
        textView5 = (TextView) rootView.findViewById(R.id.textView5);
        textView6 = (TextView) rootView.findViewById(R.id.textView6);
        textView50 = (TextView) rootView.findViewById(R.id.textView50);
        pickdate = (Button) rootView.findViewById(R.id.pickDate);
        pickdate2 = (Button) rootView.findViewById(R.id.pickDate2);
        berechnen = (Button) rootView.findViewById(R.id.button10);
        month = (ToggleButton) rootView.findViewById(R.id.button1);
        quarteryear = (ToggleButton) rootView.findViewById(R.id.button2);
        halfyear = (ToggleButton) rootView.findViewById(R.id.button3);
        year = (ToggleButton) rootView.findViewById(R.id.button4);

        //           Bei erstem Start Anleitung zeigen
        if (firstboot){
            // 1) Launch the authentication activity

            getActivity();
            // 2) Then save the state
            getActivity().getSharedPreferences("BOOT_PREF", FragmentActivity.MODE_PRIVATE)
            .edit()
            .putBoolean("firstboot", false)
            .commit();

            AlertDialog.Builder alertbox = new AlertDialog.Builder(getActivity());
            alertbox.setMessage(R.string.firststart);
            alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() {

                // click listener on the alert box
                public void onClick(DialogInterface arg0, int arg1) {
                    // the button was clicked

                }
            });

            // show it
            alertbox.show();
        }

        // Button SET 1
        pickdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                showDatePicker1();
            }}
                );


        // Button Abschlag berechnen
        berechnen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {   
                    if(textView5.getText().toString().isEmpty() || editText5.getText().toString().isEmpty())   {

                        Toast.makeText(getActivity(), R.string.beideeingebenab, Toast.LENGTH_SHORT).show();

                    }

                    else {

                        if (firststart == true)    {
                            Double verbrauchsmenge =   Double.valueOf(textView5.getText().toString().replace(',', '.')); 
                            Double preisprok =  Double.parseDouble(editText5.getText().toString().replace(',', '.'));

                            Double ERG = verbrauchsmenge * preisprok;

                            textView50.setText(formatter.format(ERG));
                        }
                        else {
                            Toast.makeText(getActivity(), R.string.calfirst, Toast.LENGTH_SHORT).show();
                        }
                    }      
                }
                catch (NumberFormatException e) {}
            }}
                );

        // Button SET 2
        pickdate2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(dateDisplay1.getText().toString().matches("")) {

                    Toast.makeText(getActivity(), R.string.zuersteingeben, Toast.LENGTH_SHORT).show();
                }

                else {
                    showDatePicker2();
                }
            }}
                );

        // Button Month
        month.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Double a = Double.parseDouble(kwhDisplay1.getText().toString());
                    Double b = Double.parseDouble(kwhDisplay2.getText().toString());


                    if (a < b) {
                        getdaysbetween();
                        berechnemonat();
                        mBool = true;
                        month.setChecked(mBool);
                        mBool = false;
                        quarteryear.setChecked(mBool);
                        halfyear.setChecked(mBool);
                        year.setChecked(mBool);
                    }
                    else {
                        Toast.makeText(getActivity(), R.string.musskleinersein, Toast.LENGTH_SHORT).show();
                        mBool = true;
                        month.setChecked(mBool);
                        mBool = false;
                        quarteryear.setChecked(mBool);
                        halfyear.setChecked(mBool);
                        year.setChecked(mBool);
                    }
                }

                catch (NumberFormatException e) {
                    Toast.makeText(getActivity(), R.string.beideeingeben, Toast.LENGTH_SHORT).show();
                    mBool = true;
                    month.setChecked(mBool);
                    mBool = false;
                    quarteryear.setChecked(mBool);
                    halfyear.setChecked(mBool);
                    year.setChecked(mBool);
                }
            }}
                );

        //Button Vierteljahr
        quarteryear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {
                    Double a = Double.parseDouble(kwhDisplay1.getText().toString());
                    Double b = Double.parseDouble(kwhDisplay2.getText().toString());

                    if (a < b) {
                        getdaysbetween();
                        berechnequarter();
                        mBool = true;
                        quarteryear.setChecked(mBool);
                        mBool = false;
                        month.setChecked(mBool);
                        halfyear.setChecked(mBool);
                        year.setChecked(mBool); 

                    }
                    else {
                        Toast.makeText(getActivity(), R.string.musskleinersein, Toast.LENGTH_SHORT).show();
                        mBool = true;
                        quarteryear.setChecked(mBool);
                        mBool = false;
                        month.setChecked(mBool);
                        halfyear.setChecked(mBool);
                        year.setChecked(mBool);
                    }

                }
                catch (NumberFormatException e) {
                    Toast.makeText(getActivity(), R.string.beideeingeben, Toast.LENGTH_SHORT).show();
                    mBool = true;
                    quarteryear.setChecked(mBool);
                    mBool = false;
                    month.setChecked(mBool);
                    halfyear.setChecked(mBool);
                    year.setChecked(mBool);
                }
            }}
                );

        //Button Halbjahr
        halfyear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Double a = Double.parseDouble(kwhDisplay1.getText().toString());
                    Double b = Double.parseDouble(kwhDisplay2.getText().toString());

                    if (a < b) {
                        getdaysbetween();
                        berechnehalf();
                        mBool = true;
                        halfyear.setChecked(mBool);
                        mBool = false;
                        quarteryear.setChecked(mBool);
                        month.setChecked(mBool);
                        year.setChecked(mBool);

                    }
                    else {
                        Toast.makeText(getActivity(), R.string.musskleinersein, Toast.LENGTH_SHORT).show();
                        mBool = true;
                        halfyear.setChecked(mBool);
                        mBool = false;
                        quarteryear.setChecked(mBool);
                        month.setChecked(mBool);
                        year.setChecked(mBool);
                    }
                }
                catch (NumberFormatException e) {
                    Toast.makeText(getActivity(), R.string.beideeingeben, Toast.LENGTH_SHORT).show();
                    mBool = true;
                    halfyear.setChecked(mBool);
                    mBool = false;
                    quarteryear.setChecked(mBool);
                    month.setChecked(mBool);
                    year.setChecked(mBool);
                }
            }}
                );

        //Button Jahr
        year.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Double a = Double.parseDouble(kwhDisplay1.getText().toString());
                    Double b = Double.parseDouble(kwhDisplay2.getText().toString());

                    if (a < b) {
                        getdaysbetween();
                        berechneyear();
                        mBool = true;
                        year.setChecked(mBool);
                        mBool = false;
                        quarteryear.setChecked(mBool);
                        halfyear.setChecked(mBool);
                        month.setChecked(mBool);

                    }
                    else {
                        Toast.makeText(getActivity(), R.string.musskleinersein, Toast.LENGTH_SHORT).show();
                        mBool = true;
                        year.setChecked(mBool);
                        mBool = false;
                        quarteryear.setChecked(mBool);
                        halfyear.setChecked(mBool);
                        month.setChecked(mBool);
                    }
                }
                catch (NumberFormatException e) {
                    Toast.makeText(getActivity(), R.string.beideeingeben, Toast.LENGTH_SHORT).show();
                    mBool = true;
                    year.setChecked(mBool);
                    mBool = false;
                    quarteryear.setChecked(mBool);
                    halfyear.setChecked(mBool);
                    month.setChecked(mBool);
                }
            }}
                );

        return rootView;
    }

    // Methode zur Berechnung der kWh-Differenz im Zeitraum für Monat
    private void berechnemonat(){

        if (kwhDisplay1.getText().toString().isEmpty() || kwhDisplay2.getText().toString().isEmpty()) {

            Toast.makeText(getActivity(), R.string.beideeingeben, Toast.LENGTH_SHORT).show();

        }
        else if (dateDisplay1.getText().toString().isEmpty() || dateDisplay2.getText().toString().isEmpty()){
            Toast.makeText(getActivity(), R.string.hintdateset, Toast.LENGTH_SHORT).show();
        } 

        else {
            ba = Double.valueOf(kwhDisplay1.getText().toString());
            ea = Double.valueOf(kwhDisplay2.getText().toString());

            zwischen = ((ea-ba)/differ)*30.41666666666667;
            textView5.setText(String.valueOf(formatter.format(zwischen)));
        }
    }
    //Methode zur Berechnung der kWh-Differenz im Zeitraum für vierteljahr
    private void berechnequarter(){
        if (kwhDisplay1.getText().toString().isEmpty() || kwhDisplay2.getText().toString().isEmpty()) {

            Toast.makeText(getActivity(), R.string.beideeingeben, Toast.LENGTH_SHORT).show();

        }
        else if (dateDisplay1.getText().toString().isEmpty() || dateDisplay2.getText().toString().isEmpty()){
            Toast.makeText(getActivity(), R.string.hintdateset, Toast.LENGTH_SHORT).show();
        } 

        else {
            ba = Double.valueOf(kwhDisplay1.getText().toString());
            ea = Double.valueOf(kwhDisplay2.getText().toString());

            zwischen = ((ea-ba)/differ)*91.25;
            textView5.setText(String.valueOf(formatter.format(zwischen)));
        }
    }
    //Methode zur Berechnung der kWh-Differenz im Zeitraum für Halbjahr
    private void berechnehalf(){

        if (kwhDisplay1.getText().toString().isEmpty() || kwhDisplay2.getText().toString().isEmpty()) {

            Toast.makeText(getActivity(), R.string.beideeingeben, Toast.LENGTH_SHORT).show();

        }
        else if (dateDisplay1.getText().toString().isEmpty() || dateDisplay2.getText().toString().isEmpty()){
            Toast.makeText(getActivity(), R.string.hintdateset, Toast.LENGTH_SHORT).show();
        } 

        else {
            ba = Double.valueOf(kwhDisplay1.getText().toString());
            ea = Double.valueOf(kwhDisplay2.getText().toString());

            zwischen = ((ea-ba)/differ)*182.5;
            textView5.setText(String.valueOf(formatter.format(zwischen)));
        }
    }
    //Methode zur Berechnung der kWh-Differenz im Zeitraum für Jahr
    private void berechneyear(){
        if (kwhDisplay1.getText().toString().isEmpty() || kwhDisplay2.getText().toString().isEmpty()) {

            Toast.makeText(getActivity(), R.string.beideeingeben, Toast.LENGTH_SHORT).show();

        }
        else if (dateDisplay1.getText().toString().isEmpty() || dateDisplay2.getText().toString().isEmpty()){
            Toast.makeText(getActivity(), R.string.hintdateset, Toast.LENGTH_SHORT).show();
        } 

        else {
            ba = Double.valueOf(kwhDisplay1.getText().toString());
            ea = Double.valueOf(kwhDisplay2.getText().toString());

            zwischen = ((ea-ba)/differ)*365;
            textView5.setText(String.valueOf(formatter.format(zwischen)));
        }
    }
    // Methode zur Berechnung der Anzahl der Tage im Zeitraum
    private void getdaysbetween(){

        if(dateDisplay1.getText().toString().isEmpty() || dateDisplay2.getText().toString().isEmpty()) {
            Toast.makeText(getActivity(), R.string.beideeingeben, Toast.LENGTH_SHORT).show();    

        }

        else {

            try {

                fromDate = gesamt1o;
                toDate = gesamt2o;
                firststart = true;
                try {

                    //Convert to Date
                    Date startDate = df.parse(gesamt1o);
                    Calendar c1 = Calendar.getInstance();
                    //Change to Calendar Date
                    c1.setTime(startDate);

                    //Convert to Date
                    Date endDate = df.parse(gesamt2o);
                    Calendar c2 = Calendar.getInstance();
                    //Change to Calendar Date
                    c2.setTime(endDate);



                    //get Time in milli seconds
                    long ms1 = c1.getTimeInMillis();
                    long ms2 = c2.getTimeInMillis(); 
                    //get difference in milli seconds
                    diff = ms2 - ms1;


                } catch (ParseException e) {
                    e.printStackTrace();
                } catch (java.text.ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                //Find number of days by dividing the mili seconds
                int diffInDays = (int) (diff / (24 * 60 * 60 * 1000));
                differ = diffInDays;
            }
            catch (NumberFormatException e) {
                Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.err), Toast.LENGTH_SHORT).show();
            }
        }
    }
    // Zeige DatePickerFragment1
    private void showDatePicker1() {
        DatePickerFragment date = new DatePickerFragment();
        /**
         * Set Up Current Date Into dialog
         */
        Calendar calender = Calendar.getInstance();
        Bundle args = new Bundle();
        args.putInt("year", calender.get(Calendar.YEAR));
        args.putInt("month", calender.get(Calendar.MONTH));
        args.putInt("day", calender.get(Calendar.DAY_OF_MONTH));
        date.setArguments(args);
        /**
//         * Set Call back to capture selected date
//         */
        date.setCallBack(ondate);
        date.show(getChildFragmentManager(), "Date Picker");
    }

    OnDateSetListener ondate = new OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            mYear1 = year;      
            mMonth1 = monthOfYear;
            mDay1 = dayOfMonth;

            neuformatjahr1 = String.valueOf(mYear1);


            if (mMonth1+1 < 10){
                neuformatmonat1 = "0"+ String.valueOf(mMonth1+1); 
            }

            else {neuformatmonat1 = String.valueOf(mMonth1+1);}

            if (mDay1 < 10){
                neuformattag1 = "0"+ String.valueOf(mDay1); 
            }

            else {neuformattag1 =String.valueOf(mDay1);}

            gesamt1o = neuformattag1+neuformatmonat1+neuformatjahr1;
            String gesamt1 = neuformattag1+"."+neuformatmonat1+"."+neuformatjahr1;
            dateDisplay1.setText(gesamt1);

        }



    };
    //Zeige DatePickerFragment2
    private void showDatePicker2() {
        DatePickerFragment date = new DatePickerFragment();
        /**
         * Set Up Current Date Into dialog
         */
        Calendar calender = Calendar.getInstance();
        Bundle args = new Bundle();
        args.putInt("year", calender.get(Calendar.YEAR));
        args.putInt("month", calender.get(Calendar.MONTH));
        args.putInt("day", calender.get(Calendar.DAY_OF_MONTH));
        date.setArguments(args);
        /**
         * Set Call back to capture selected date
         */
        date.setCallBack(ondate2);
        date.show(getChildFragmentManager(), "Date Picker");
    }

    OnDateSetListener ondate2 = new OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            mYear2 = year;
            mMonth2 = monthOfYear;
            mDay2 = dayOfMonth;

            neuformatjahr2 = String.valueOf(mYear2);


            if (mMonth2+1 < 10){
                neuformatmonat2 = "0"+ String.valueOf(mMonth2+1); 
            }

            else {neuformatmonat2 = String.valueOf(mMonth2+1);}

            if (mDay2 < 10){
                neuformattag2 = "0"+ String.valueOf(mDay2); 
            }

            else{neuformattag2 =String.valueOf(mDay2);}

            gesamt2o = neuformattag2+neuformatmonat2+neuformatjahr2;
            String gesamt2 = neuformattag2+"."+neuformatmonat2+"."+neuformatjahr2;

            dateDisplay2.setText(gesamt2);


        }



    };


}

3 个答案:

答案 0 :(得分:2)

我认为你的按钮 berechnen 为空。当您设置onClickListener时,在此之前放置一个空检查。并且您无法从XML文件中获取此参考。

答案 1 :(得分:0)

您可能需要添加onCreate()方法,尝试添加:

protected void onCreate (Bundle savedInstanceState)
{
    super.onCreate (savedInstanceState);
    setContentView (R.layout.name_of_your_fragment_xml);

        //add fragment 

        .....

}

答案 2 :(得分:0)

您正在尝试访问片段的onCreateView中的活动,该活动主要导致NPE,尝试将getActivity()内容移动到

onActivityCreated(Bundle savedInstanceState)

阅读有关片段生命周期和活动生命周期的更多信息