出错为java.lang.NullPointerException

时间:2014-04-19 06:17:44

标签: java android visual-studio

Android和Java新手。以下是一个例子。使用以下日志时出错:

04-19 02:05:25.920: E/AndroidRuntime(791):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-19 02:05:25.920: E/AndroidRuntime(791):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-19 02:05:25.920: E/AndroidRuntime(791):  at dalvik.system.NativeStart.main(Native Method)
04-19 02:05:25.920: E/AndroidRuntime(791): Caused by: java.lang.NullPointerException
04-19 02:05:25.920: E/AndroidRuntime(791):  at com.example.crazytipcalc.CrazyTipCalc.onCreate(CrazyTipCalc.java:57)
04-19 02:05:25.920: E/AndroidRuntime(791):  at android.app.Activity.performCreate(Activity.java:5231)
04-19 02:05:25.920: E/AndroidRuntime(791):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-19 02:05:25.920: E/AndroidRuntime(791):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-19 02:05:25.920: E/AndroidRuntime(791):  ... 11 more

CrazyTipCalc.java

package com.example.crazytipcalc;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.os.Build;

public class CrazyTipCalc extends ActionBarActivity {

    private static final String TOTAL_BILL = "TOTAL_BILL";
    private static final String CURRENT_TIP = "CURRENT_TIP";
    private static final String BILL_WITHOUT_TIP = "BILL_WITHOUT_TIP";

    private double billBeforeTip;
    private double tipAmount;
    private double finalBill;

    EditText billBeforeTipET;
    EditText tipAmountET;
    EditText finalBillET;

    SeekBar tipSeekBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_crazy_tip_calc);

        if (savedInstanceState == null) {
            // getSupportFragmentManager().beginTransaction()
            //      .add(R.id.container, new PlaceholderFragment()).commit();
            billBeforeTip = 0.00;
            tipAmount = 0.00;
            finalBill = 0.00;
        } else {
            billBeforeTip = savedInstanceState.getDouble(BILL_WITHOUT_TIP);
            tipAmount = savedInstanceState.getDouble(CURRENT_TIP);
            finalBill = savedInstanceState.getDouble(TOTAL_BILL);
        }

        billBeforeTipET = (EditText) findViewById(R.id.billEditText);
        tipAmountET = (EditText) findViewById(R.id.tipEditText);
        finalBillET = (EditText) findViewById(R.id.finalBillEditText);

        tipSeekBar = (SeekBar)  findViewById(R.id.changeTipSeekBar);
        tipSeekBar.setOnSeekBarChangeListener(tipSeekBarListener);

        billBeforeTipET.addTextChangedListener(billBeforeTipListner);
    }

    private TextWatcher billBeforeTipListner = new TextWatcher() {

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {
            try {
                billBeforeTip = Double.parseDouble(arg0.toString());
            } catch (NumberFormatException e) {
                billBeforeTip = 0.00;
            }
            updateTipAndFinalBill();
        }

    };

    private void updateTipAndFinalBill(){
        double tipAmount = Double.parseDouble(tipAmountET.getText().toString());
        double finalBill = billBeforeTip + (billBeforeTip * tipAmount);
        finalBillET.setText(String.format("%.02f", finalBill));
    }

    protected void onSavedInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);

        outState.putDouble(TOTAL_BILL, finalBill);
        outState.putDouble(CURRENT_TIP, tipAmount);
        outState.putDouble(BILL_WITHOUT_TIP, billBeforeTip);

    }

    private OnSeekBarChangeListener tipSeekBarListener = new OnSeekBarChangeListener(){

        @Override
        public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
            // TODO Auto-generated method stub
            tipAmount = (tipSeekBar.getProgress()) * .01;
            tipAmountET.setText(String.format("%.02f", tipAmount));
            updateTipAndFinalBill();
        }

        @Override
        public void onStartTrackingTouch(SeekBar arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStopTrackingTouch(SeekBar arg0) {
            // TODO Auto-generated method stub

        }

    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.crazy_tip_calc, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_crazy_tip_calc,
                    container, false);
            return rootView;
        }
    }

}

fragment_crazy_tip_calc.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.crazytipcalc.CrazyTipCalc$PlaceholderFragment" >

    <TextView
        android:id="@+id/billTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="18dp"
        android:layout_marginTop="23dp"
        android:text="@string/bill_text_view" />

    <EditText
        android:id="@+id/billEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/billTextView"
        android:layout_alignBottom="@+id/billTextView"
        android:layout_marginLeft="23dp"
        android:layout_toRightOf="@+id/billTextView"
        android:ems="5"
        android:inputType="numberDecimal"
        android:text="@string/bill_edit_text" />

    <TextView
        android:id="@+id/tipTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/billEditText"
        android:layout_alignBottom="@+id/billEditText"
        android:layout_marginLeft="15dp"
        android:layout_toRightOf="@+id/billEditText"
        android:text="@string/tip_text_view" />

    <EditText
        android:id="@+id/tipEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/tipTextView"
        android:layout_alignBottom="@+id/tipTextView"
        android:layout_toRightOf="@+id/tipTextView"
        android:ems="4"
        android:inputType="numberDecimal" >

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/finalBillTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/tipTextView"
        android:layout_below="@+id/tipEditText"
        android:layout_marginTop="26dp"
        android:text="@string/final_text_view" />

    <EditText
        android:id="@+id/finalBillEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/finalBillTextView"
        android:layout_below="@+id/finalBillTextView"
        android:layout_marginTop="16dp"
        android:ems="5"
        android:inputType="numberDecimal" />

    <TextView
        android:id="@+id/changeTipTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/finalBillEditText"
        android:layout_alignLeft="@+id/billTextView"
        android:text="@string/change_tip_text_view" />

    <SeekBar
        android:id="@+id/changeTipSeekBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/finalBillEditText"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/billEditText"
        android:progress="15" />

</RelativeLayout>

的AndroidManifest.xml

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="19" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.crazytipcalc.CrazyTipCalc"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

2 个答案:

答案 0 :(得分:0)

你有

setContentView(R.layout.activity_crazy_tip_calc);

但您的观点位于fragment_crazy_tip_calc.xml。因此初始化失败导致NullPointerException

您需要更改为

setContentView(R.layout.fragment_crazy_tip_calc)
// you also have the fragment code. so instead of this i recommend the below

将视图初始化移动到Fragment的onCreateView并移动相关代码

   EditText billBeforeTipET;
   EditText tipAmountET;
   EditText finalBillET; 
   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_crazy_tip_calc,
                container, false);
           billBeforeTipET = (EditText) rootView.findViewById(R.id.billEditText);
           tipAmountET = (EditText) rootView.findViewById(R.id.tipEditText);
           finalBillET = (EditText) rootView.findViewById(R.id.finalBillEditText);
           tipSeekBar = (SeekBar) rootView.findViewById(R.id.changeTipSeekBar);
        return rootView;
    }

您还需要取消注释以下内容

   // getSupportFragmentManager().beginTransaction()
   //      .add(R.id.container, new PlaceholderFragment()).commit();

findViewById查找当前视图层次结构中提到的视图。视图属于片段布局而不属于活动。因此,您需要使用infalted视图对象来初始化视图。

答案 1 :(得分:0)

你正在初始化错误的xml文件:改变它如下:

setContentView(R.layout.fragment_crazy_tip_calc);