无法从onClick Android调用另一个方法 - 抛出illegalStateException

时间:2018-02-21 02:23:53

标签: java android

我对Android很新,我正在创建一个简单的联系人应用。我有一个“联系”类,其中包含名字,姓氏等,在我的活动中,我试图从编辑文本框中读取输入并创建新联系人。

问题是当我在辅助活动页面中调用createContact()时,会在执行方法之前立即抛出illegalStateException。我一直在寻找修复过去的一天,并且不知道这是错的。这两个函数都是项目中第二个活动页面的一部分,它们都在同一个Java类中......就像我可以在onclick方法中访问我想要的任何内容一样,但是只要我尝试一个函数或类外的类调用方法,我得到一个例外。

感谢您的帮助。

以下是我onclick的代码:

public void onSaveClicked(View v) {

        // Create a new contact from form data
        Contact contact = createContact();


        try {
        FileOutputStream fileout=openFileOutput("contactList.txt", MODE_PRIVATE);
        OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
        outputWriter.write(contact.getFirstName());
        outputWriter.close();

        //display file saved message
        Toast.makeText(getBaseContext(), contact.getFirstName() + contact.getLastName() + " saved successfully!",
                Toast.LENGTH_SHORT).show();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

createContact方法:

    private Contact createContact()  {
    Contact contact = new Contact(
            firstNameEditText.getText().toString(),
            middleInitialEditText.getText().toString().charAt(0), //Convert string to char
            lastNameEditText.getText().toString(),
            phoneNumberEditText.getText().toString(),
            convertDate(birthdateButton.getText()),     // Convert CharSequence to Date Obj
            convertDate(firstMetButton.getText())       // Convert CharSequence to Date Obj
    );
    return contact;
}

堆栈追踪:

02-21 02:36:58.399 11526-11526/com.fafaffy.contacts E/AndroidRuntime: FATAL EXCEPTION: main
                                                                  Process: com.fafaffy.contacts, PID: 11526
                                                                  java.lang.IllegalStateException: Could not execute method for android:onClick
                                                                      at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
                                                                      at android.view.View.performClick(View.java:5637)
                                                                      at android.view.View$PerformClick.run(View.java:22429)
                                                                      at android.os.Handler.handleCallback(Handler.java:751)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                      at android.os.Looper.loop(Looper.java:154)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                   Caused by: java.lang.reflect.InvocationTargetException
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                                                                      at android.view.View.performClick(View.java:5637) 
                                                                      at android.view.View$PerformClick.run(View.java:22429) 
                                                                      at android.os.Handler.handleCallback(Handler.java:751) 
                                                                      at android.os.Handler.dispatchMessage(Handler.java:95) 
                                                                      at android.os.Looper.loop(Looper.java:154) 
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6119) 
                                                                      at java.lang.reflect.Method.invoke(Native Method) 
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
                                                                   Caused by: java.lang.IllegalArgumentException: Cannot format given Object as a Date
                                                                      at java.text.DateFormat.format(DateFormat.java:302)
                                                                      at java.text.Format.format(Format.java:157)
                                                                      at com.fafaffy.contacts.DetailContact.convertDate(DetailContact.java:117)
                                                                      at com.fafaffy.contacts.DetailContact.createContact(DetailContact.java:107)
                                                                      at com.fafaffy.contacts.DetailContact.onSaveClicked(DetailContact.java:72)
                                                                      at java.lang.reflect.Method.invoke(Native Method) 
                                                                      at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
                                                                      at android.view.View.performClick(View.java:5637) 
                                                                      at android.view.View$PerformClick.run(View.java:22429) 
                                                                      at android.os.Handler.handleCallback(Handler.java:751) 
                                                                      at android.os.Handler.dispatchMessage(Handler.java:95) 
                                                                      at android.os.Looper.loop(Looper.java:154) 
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6119) 
                                                                      at java.lang.reflect.Method.invoke(Native Method) 
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 

完整的活动代码:

public class DetailContact extends AppCompatActivity {

// Create vars for all form fields
private EditText firstNameEditText;
private EditText lastNameEditText;
private EditText middleInitialEditText;
private EditText phoneNumberEditText;
private Button birthdateButton;
private Button firstMetButton;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getSupportActionBar().hide();
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_detail_contact);


    // Assign vars to form fields
    firstNameEditText       = (EditText)findViewById(R.id.firstNameTextBox);
    lastNameEditText        = (EditText)findViewById(R.id.lastNameTextBox);
    middleInitialEditText   = (EditText)findViewById(R.id.middleInitialTextBox);
    phoneNumberEditText     = (EditText)findViewById(R.id.phoneNumberTextBox);
    birthdateButton         = (Button)findViewById(R.id.birthdate);
    firstMetButton          = (Button)findViewById(R.id.firstContactDateButton);


}
public void showDatePickerDialog(View v) {
    DatePickerFragment newFragment = new DatePickerFragment();
    newFragment.setButton((Button)v);
    newFragment.show(getFragmentManager(), "date picker");
    //((Button)v).setText(newFragment.getSelectedDate().toString());
}






// Working Save Function  --------------------------------------------------------------------------------------------------------
    public void onSaveClicked(View v) {

        // Create a new contact from form data
        Contact contact = createContact();

        try {
        FileOutputStream fileout=openFileOutput("contactList.txt", MODE_PRIVATE);
        OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
        outputWriter.write(contact.getFirstName());
        outputWriter.close();

        //display file saved message
        Toast.makeText(getBaseContext(), contact.getFirstName() + contact.getLastName() + " saved successfully!",
                Toast.LENGTH_SHORT).show();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

// Method creates a contact from form input
// Middle initial is converted from string to char
// Birthdate & firstMet date are both converted from CharSequence to Date objects
public  Contact createContact()  {
    Contact contact = new Contact(
            firstNameEditText.getText().toString(),
            middleInitialEditText.getText().toString().charAt(0), //Convert string to char
            lastNameEditText.getText().toString(),
            phoneNumberEditText.getText().toString(),
            convertDate(birthdateButton.getText()),     // Convert CharSequence to Date Obj
            convertDate(firstMetButton.getText())       // Convert CharSequence to Date Obj
    );

    return contact;
}


// Helper method from createContact method -- birtdate & firstmet date need to be converted
// from CharSequence to Date objects to match Contact model
private Date convertDate(CharSequence input) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String dateString = sdf.format(input);
    Date date = null;
    try {
        date = sdf.parse(dateString);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return date;
}

}

1 个答案:

答案 0 :(得分:2)

问题是您提供给convertDate方法的日期。这在堆栈跟踪中清楚地说明了。最好修改convertDate方法,如下所示,在try catch块中也包含sdf.format方法。并且更改了catch接近所有异常而不是特定的解析异常。

private Date convertDate(CharSequence input) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

     date = null;
    try {
         String dateString = sdf.format(input);
        date = sdf.parse(dateString);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return date;
}