无法启动Activity ComponentInfo {} java.lang.nullPointerException

时间:2014-02-04 08:56:33

标签: java android

我还在学习java,所以如果这个问题太明显,我很抱歉。我正在尝试启动我的应用程序,它会抛出此错误。问题似乎出现在OnCreate()方法中,但我无法弄清楚是什么导致了它。

import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends Activity {
    public final static String NAME = "nick.miros.famous.problems.MESSAGE";
    public final static String EMAIL = "nick.miros.famous.problems.MESSAGE1";
    public final static String STUFFSEX = "nick.miros.famous.problems.MESSAGE2";
    public final static String BIRTHDAY = "nick.miros.famous.problems.MESSAGE3";

    private boolean agreed;
    private String sex;
    public static String bornDate;
    public EditText emailEdit;
    public EditText nameEdit;
    public EditText passwordEdit;
    // public EditText passwordRepeatEdit;
    public RadioGroup radioSex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        nameEdit = (EditText) findViewById(R.id.name);
        emailEdit = (EditText) findViewById(R.id.email);
        passwordEdit = (EditText) findViewById(R.id.password);
        // passwordRepeatEdit = (EditText) findViewById(R.id.passwordRepeat);

        emailEdit.addTextChangedListener(new GenericTextWatcher(emailEdit));
        nameEdit.addTextChangedListener(new GenericTextWatcher(nameEdit));
        passwordEdit
                .addTextChangedListener(new GenericTextWatcher(passwordEdit));
        // passwordRepeatEdit.addTextChangedListener(new
        // GenericTextWatcher(passwordRepeatEdit));

        Button Go = (Button) findViewById(R.id.sendButton);
        Go.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                sendAndCheck();
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    private String getSex(int id) {

        switch (id) {

        case R.id.radioMale:
            sex = "Male";
            break;
        case R.id.radioFemale:
            sex = "Female";
            break;
        }
        return sex;
    }

    public void showThanks() {
        Toast.makeText(this.getApplicationContext(), R.string.thank_you,
                Toast.LENGTH_LONG).show();
    }

    public void onCheckBoxClicked(View view) {
        // Is the view now checked?
        agreed = ((CheckBox) findViewById(R.id.agreementBox)).isChecked();
    }

    public final static boolean isValidEmail(CharSequence target) {
        if (target == null) {
            return false;
        } else {
            return android.util.Patterns.EMAIL_ADDRESS.matcher(target)
                    .matches();
        }
    }

    public static class DatePickerFragment extends DialogFragment implements
            DatePickerDialog.OnDateSetListener {

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the current date as the default date in the picker
            final Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH);
            int day = c.get(Calendar.DAY_OF_MONTH);

            // Create a new instance of DatePickerDialog and return it
            return new DatePickerDialog(getActivity(), this, year, month, day);
        }

        public void onDateSet(DatePicker view, int year, int month, int day) {
            // Do something with the date chosen by the user
            bornDate = Integer.toString(year) + "/" + Integer.toString(month)
                    + "/" + Integer.toString(day);
        }
    }

    public void showDatePickerDialog(View v) {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getFragmentManager(), "datePicker");
    }

    /** Called when the user clicks the Send button */
    public void sendAndCheck() {

        CharSequence emailToCheck = ((EditText) findViewById(R.id.email))
                .getText().toString();

        if (agreed) {
            // Do something in response to button

            if (isValidEmail(emailToCheck)) {
                Intent intent = new Intent(this, DisplayMessageActivity.class);
                String sent_name = ((EditText) findViewById(R.id.name))
                        .getText().toString();
                String sent_email = ((EditText) findViewById(R.id.email))
                        .getText().toString();
                int id = ((RadioGroup) findViewById(R.id.radioSex))
                        .getCheckedRadioButtonId();
                String sent_sex = getSex(id);
                String sent_birthday = bornDate;
                intent.putExtra(NAME, sent_name);
                intent.putExtra(EMAIL, sent_email);
                intent.putExtra(STUFFSEX, sent_sex);
                intent.putExtra(BIRTHDAY, sent_birthday);
                startActivity(intent);
                showThanks();

            } else {
                ((EditText) findViewById(R.id.email)).setError("wrong email!");
            }

        } else {
            AlertDialog.Builder Alert = new AlertDialog.Builder(this);

            Alert.setMessage("Please agree with the terms and conditions first");
            Alert.setTitle("Notice");
            Alert.setPositiveButton("OK", null);
            Alert.setCancelable(true);
            Alert.create().show();
        }
    }

}

这是GenericTextWatcher:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;

public class GenericTextWatcher implements TextWatcher{

    private View view;
    private PasswordValidator passwordValidator = new PasswordValidator();
    String password = ((EditText) view).getText().toString();
    GenericTextWatcher(View view) {
        this.view = view;
    }

    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

    public void afterTextChanged(Editable editable) {
        String text = editable.toString();
        switch(view.getId()){
            case R.id.name:
                if (!(text.equals("")))
                {

                }
                else
                {
                    ((EditText) view).setError("wrong name!");
                }
                break;
            case R.id.email:
                CharSequence emailToCheck = ((EditText) view).getText().toString();
                if (isValidEmail(emailToCheck))
                {

                }
                else
                {
                    ((EditText) view).setError("wrong email!");

                }

                break;
            case R.id.password:
                if (passwordValidator.isValidPassword(text))
                {

                }
                else
                {
                    ((EditText) view).setError("must have 1 uppercase letter, 1 number and be 6 characters long");
                }
                break;
           /* case R.id.passwordRepeat:
                String password = (((EditText) view) findViewById(R.id.password).getText().toString();
                if (text.equals(password))
                {

                }
                else
                {
                    ((EditText) view).setError("passwords don't match");
                }
                break;*/
        }
    }

    public final static boolean isValidEmail(CharSequence target) {
        if (target == null) {
            return false;
        } else {
            return android.util.Patterns.EMAIL_ADDRESS.matcher(target)
                            .matches();
        }
    }

    public class PasswordValidator{

      private Pattern pattern;
      private Matcher matcher;

      private static final String PASSWORD_PATTERN = 
                "((?=.*\\d)(?=.*[A-Z]).{6,20})";

      public PasswordValidator(){
          pattern = Pattern.compile(PASSWORD_PATTERN);
      }

      /**
       * Validate password with regular expression
       * @param password password for validation
       * @return true valid password, false invalid password
       */
      public boolean isValidPassword(String password){

          matcher = pattern.matcher(password);
          return matcher.matches();

      }
  }
}

这是LogCat:

02-04 03:59:14.267: D/dalvikvm(2400): GC_FOR_ALLOC freed 37K, 7% free 2640K/2820K, paused 1ms, total 34ms
02-04 03:59:14.267: I/dalvikvm-heap(2400): Grow heap (frag case) to 3.319MB for 635808-byte allocation
02-04 03:59:14.277: D/dalvikvm(2400): GC_FOR_ALLOC freed 2K, 6% free 3258K/3444K, paused 10ms, total 10ms
02-04 03:59:14.377: D/AndroidRuntime(2400): Shutting down VM
02-04 03:59:14.377: W/dalvikvm(2400): threadid=1: thread exiting with uncaught exception (group=0xb2eb7648)
02-04 03:59:14.377: E/AndroidRuntime(2400): FATAL EXCEPTION: main
02-04 03:59:14.377: E/AndroidRuntime(2400): java.lang.RuntimeException: Unable to start activity ComponentInfo{nick.miros.famous.problems/nick.miros.famous.problems.MainActivity}: java.lang.NullPointerException
02-04 03:59:14.377: E/AndroidRuntime(2400):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
02-04 03:59:14.377: E/AndroidRuntime(2400):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
02-04 03:59:14.377: E/AndroidRuntime(2400):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
02-04 03:59:14.377: E/AndroidRuntime(2400):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
02-04 03:59:14.377: E/AndroidRuntime(2400):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-04 03:59:14.377: E/AndroidRuntime(2400):     at android.os.Looper.loop(Looper.java:137)
02-04 03:59:14.377: E/AndroidRuntime(2400):     at android.app.ActivityThread.main(ActivityThread.java:5103)
02-04 03:59:14.377: E/AndroidRuntime(2400):     at java.lang.reflect.Method.invokeNative(Native Method)
02-04 03:59:14.377: E/AndroidRuntime(2400):     at java.lang.reflect.Method.invoke(Method.java:525)
02-04 03:59:14.377: E/AndroidRuntime(2400):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
02-04 03:59:14.377: E/AndroidRuntime(2400):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-04 03:59:14.377: E/AndroidRuntime(2400):     at dalvik.system.NativeStart.main(Native Method)
02-04 03:59:14.377: E/AndroidRuntime(2400): Caused by: java.lang.NullPointerException
02-04 03:59:14.377: E/AndroidRuntime(2400):     at nick.miros.famous.problems.GenericTextWatcher.<init>(GenericTextWatcher.java:15)
02-04 03:59:14.377: E/AndroidRuntime(2400):     at nick.miros.famous.problems.MainActivity.onCreate(MainActivity.java:46)
02-04 03:59:14.377: E/AndroidRuntime(2400):     at android.app.Activity.performCreate(Activity.java:5133)
02-04 03:59:14.377: E/AndroidRuntime(2400):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
02-04 03:59:14.377: E/AndroidRuntime(2400):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
02-04 03:59:14.377: E/AndroidRuntime(2400):     ... 11 more

1 个答案:

答案 0 :(得分:0)

第15行NullPointerException初始化(GenericTextWatcher)中有<init>

在那里你有一个成员变量:

String password = ((EditText) view).getText().toString();
此时

viewnull,您只需稍后在构造函数中指定它。将此代码移动到构造函数或更高版本。