java.lang.ClassCastException: android.widget.EditText

4

Вот мой код JAVA. Когда я запускаю свое приложение, оно вылетает, и в моем журнале появляются следующие ошибки

    11-21 00:21:48.828: E/AndroidRuntime(349): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.geekosoft.contactsonline/com.geekosoft.contactsonline.AddContact}: java.lang.ClassCastException: android.widget.EditText
    11-21 00:21:48.828: E/AndroidRuntime(349):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
    11-21 00:21:48.828: E/AndroidRuntime(349):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
    11-21 00:21:48.828: E/AndroidRuntime(349):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
    11-21 00:21:48.828: E/AndroidRuntime(349):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
    11-21 00:21:48.828: E/AndroidRuntime(349):  at android.os.Handler.dispatchMessage(Handler.java:99)
    11-21 00:21:48.828: E/AndroidRuntime(349):  at android.os.Looper.loop(Looper.java:123)
    11-21 00:21:48.828: E/AndroidRuntime(349):  at android.app.ActivityThread.main(ActivityThread.java:3683)
    11-21 00:21:48.828: E/AndroidRuntime(349):  at java.lang.reflect.Method.invokeNative(Native Method)
    11-21 00:21:48.828: E/AndroidRuntime(349):  at java.lang.reflect.Method.invoke(Method.java:507)
    11-21 00:21:48.828: E/AndroidRuntime(349):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
    11-21 00:21:48.828: E/AndroidRuntime(349):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
    11-21 00:21:48.828: E/AndroidRuntime(349):  at dalvik.system.NativeStart.main(Native Method)
    11-21 00:21:48.828: E/AndroidRuntime(349): Caused by: java.lang.ClassCastException: android.widget.EditText
    11-21 00:21:48.828: E/AndroidRuntime(349):  at com.geekosoft.contactsonline.AddContact.initilizeEditContactInfo(AddContact.java:123)
    11-21 00:21:48.828: E/AndroidRuntime(349):  at com.geekosoft.contactsonline.AddContact.initilize(AddContact.java:68)
    11-21 00:21:48.828: E/AndroidRuntime(349):  at com.geekosoft.contactsonline.AddContact.onCreate(AddContact.java:42)
    11-21 00:21:48.828: E/AndroidRuntime(349):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
    11-21 00:21:48.828: E/AndroidRuntime(349):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)

и вот мой код Java

    package com.geekosoft.contactsonline;

    import java.util.ArrayList;
    import java.util.Iterator;
    import android.app.Activity;
    import android.content.ContentResolver;
    import android.content.Context;
    import android.database.Cursor;
    import android.os.Build;
    import android.os.Bundle;
    import android.provider.ContactsContract;
    import android.provider.ContactsContract.CommonDataKinds.Phone;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Spinner;
    import android.widget.TableLayout;

    public class AddContact extends Activity implements OnClickListener {

        public static final String TAG = AddContact.class.getSimpleName();

        ArrayList contactPhoneTypes, contactEmailTypes, contactIMTypes, contactAddressTypes;
        String contactid;
        int phoneNumbersIdStarter, emailIdStarter, imIdStarter, addressIdStarter;

        LayoutInflater layoutInflater;

        EditText name, number;
        Spinner phoneType, emailType, addressType;
        Button addPhoneField, addEmailField, addIMField, addAddressField;
        TableLayout phoneFiledsCont, emailFiledsCont, imFiledsCont, addressFiledsCont;

        @Override
        protected void onCreate (Bundle contactsOnline) {
            super.onCreate(contactsOnline);
            setContentView(R.layout.add_contact);
            initilize();
        }

        public void initilize () {
            initilizeSpinnerTypes();
            phoneNumbersIdStarter = 1000;
            emailIdStarter = 2000;
            imIdStarter = 3000;
            addressIdStarter = 4000;

            layoutInflater =  (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            name = (EditText) findViewById(R.id.etContactName);
            addPhoneField = (Button) findViewById(R.id.bAddPhoneField);
            addEmailField = (Button) findViewById(R.id.bAddEmailField);
            addIMField = (Button) findViewById(R.id.bAddIMField);
            addAddressField = (Button) findViewById(R.id.bAddaddressField);
            phoneFiledsCont = (TableLayout) findViewById(R.id.tlPhoneFiledCont);
            emailFiledsCont = (TableLayout) findViewById(R.id.tlEmailFiledsCont);
            imFiledsCont = (TableLayout) findViewById(R.id.tlIMFiledsCont);
            addressFiledsCont = (TableLayout) findViewById(R.id.tlAddressFiledsCont);

            addPhoneField.setOnClickListener(this);
            addEmailField.setOnClickListener(this);
            addIMField.setOnClickListener(this);
            addAddressField.setOnClickListener(this);
            initilizeEditContactInfo();
        }

        public void initilizeSpinnerTypes() {
            contactPhoneTypes = new ArrayList();
            contactPhoneTypes.add(ContactsContract.CommonDataKinds.Phone.TYPE_HOME);
            contactPhoneTypes.add(ContactsContract.CommonDataKinds.Phone.TYPE_WORK);
            contactPhoneTypes.add(ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
            contactPhoneTypes.add(ContactsContract.CommonDataKinds.Phone.TYPE_OTHER);
    //      contactPhoneTypes.add(ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM);

            contactEmailTypes = new ArrayList();
            contactEmailTypes.add(ContactsContract.CommonDataKinds.Email.TYPE_HOME);
            contactEmailTypes.add(ContactsContract.CommonDataKinds.Email.TYPE_WORK);
            contactEmailTypes.add(ContactsContract.CommonDataKinds.Email.TYPE_MOBILE);
            contactEmailTypes.add(ContactsContract.CommonDataKinds.Email.TYPE_OTHER);

            contactIMTypes = new ArrayList();
            contactIMTypes.add(ContactsContract.CommonDataKinds.Im.TYPE_HOME);
            contactIMTypes.add(ContactsContract.CommonDataKinds.Im.TYPE_WORK);
            contactIMTypes.add(ContactsContract.CommonDataKinds.Im.TYPE_OTHER);

            contactAddressTypes = new ArrayList();
            contactAddressTypes.add(ContactsContract.CommonDataKinds.SipAddress.TYPE_HOME);
            contactAddressTypes.add(ContactsContract.CommonDataKinds.SipAddress.TYPE_WORK);
            contactAddressTypes.add(ContactsContract.CommonDataKinds.SipAddress.TYPE_OTHER);
        }

        public void initilizeEditContactInfo () {
            contactid = getIntent().getStringExtra("contactId");
            Log.d(TAG, "id = "+contactid);
            Log.d(TAG, "query = "+ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
            ContentResolver cr = getContentResolver();
            Cursor contact = cr.query(ContactsContract.Contacts.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone._ID+" = ?",new String[]{contactid}, "DISPLAY_NAME ASC");
    //      Cursor contacts = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);

            if (contact.getCount() > 0) {
                contact.moveToFirst();
                String name = contact.getString(contact.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                Log.d(TAG, "name = "+name);
                this.name.setText(name);
                int loopCounter = 0;
                if (Integer.parseInt(contact.getString(contact.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                    Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID+" = ?",new String[]{contactid}, null);
                    while (phones.moveToNext()) {
                        loopCounter++;
                        int phoneType = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
                        String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        Log.d(TAG, "phone = "+phoneNumber);
                        addTextField("phone");
                        EditText phoneNumberField = (EditText) findViewById(8084+phoneNumbersIdStarter);
                        phoneNumberField.setText(phoneNumber);
                        Log.d("Spinner Getting", "Spinner Id = " + (8083+phoneNumbersIdStarter));
                        Spinner phoneNumberSpinner = (Spinner) findViewById(8083+phoneNumbersIdStarter);
                        Log.d("After Spinner", "phone counter = " + phoneNumbersIdStarter);
                        switch (phoneType) {
                            case Phone.TYPE_MOBILE:
    //                          phoneNumberSpinner.setSelection(2, false);
                                break;
                            case Phone.TYPE_HOME:
    //                          phoneNumberSpinner.setSelection(0, false);
                                String phoneTypesCodes = "home = "+Phone.TYPE_HOME+"mobile = "+Phone.TYPE_MOBILE+"work = "+Phone.TYPE_WORK
                                        +"other = "+Phone.TYPE_OTHER;
                                Log.d(name + "(home number)", phoneNumber + phoneTypesCodes);
                                break;
                            case Phone.TYPE_WORK:
    //                          phoneNumberSpinner.setSelection(1, false);
                                break;
                            case Phone.TYPE_OTHER:
    //                          phoneNumberSpinner.setSelection(3, false);
                                break;
                        }
                    } 
                    phones.close();
                }
            }
            contact.close();
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.bAddPhoneField:
                addTextField("phone");
                break;
            case R.id.bAddEmailField:
                addTextField("email");
                break;
            case R.id.bAddIMField:
                addTextField("im");
                break;
            case R.id.bAddaddressField:
                addTextField("address");
                break;
            }
        }

        public void addTextField(String fieldType) {
            // for text field code is 84
            // for spinner code is 83
            if (fieldType.equals("phone")) {
                // for phone number code is 80
                phoneNumbersIdStarter++;
                View view = layoutInflater.inflate(R.layout.add_phone_row, null);
                EditText phoneNumberField = (EditText) view.findViewById(R.id.etContactPhone);
                Spinner phoneTypeSpinner = (Spinner) view.findViewById(R.id.sContactPhoneType);
                Log.d(TAG, "spinner id = " + phoneTypeSpinner.getId());
                phoneNumberField.setId(8084+phoneNumbersIdStarter);
                phoneTypeSpinner.setId(8083+phoneNumbersIdStarter);
                Log.d("Spinner Created", "Spinner Id = " + phoneTypeSpinner.getId());
                setSpinnerValues(phoneTypeSpinner, "phone");
                phoneFiledsCont.addView(view);
            } else if (fieldType.equals("email")) {
                // for email code is 69
                emailIdStarter++;
                View view = layoutInflater.inflate(R.layout.add_email_row, null);
                EditText emailAddressField = (EditText) view.findViewById(R.id.etContactEmail);
                Spinner emailTypeSpinner = (Spinner) view.findViewById(R.id.sContactEmailType);
                emailAddressField.setId(6984+emailIdStarter);
                emailTypeSpinner.setId(6983+emailIdStarter);
                Log.d(TAG, "inside true");
                setSpinnerValues(emailTypeSpinner, "email");
                Log.d(TAG, "inside true 2");
                emailFiledsCont.addView(view);
            } else if (fieldType.equals("im")) {
                // for address code is 65
                imIdStarter++;
                View view = layoutInflater.inflate(R.layout.add_im_row, null);
                EditText imField = (EditText) view.findViewById(R.id.etContactIM);
                Spinner imTypeSpinner = (Spinner) view.findViewById(R.id.sContactIMType);
                imField.setId(6584+imIdStarter);
                imTypeSpinner.setId(6583+imIdStarter);
                setSpinnerValues(imTypeSpinner, "im");
                imFiledsCont.addView(view);
            } else if (fieldType.equals("address")) {
                // for im code is 73
                addressIdStarter++;
                View view = layoutInflater.inflate(R.layout.add_address_row, null);
                EditText addressField = (EditText) view.findViewById(R.id.etContactAddress);
                Spinner addressTypeSpinner = (Spinner) view.findViewById(R.id.sContactAddressType);
                addressField.setId(7384+addressIdStarter);
                addressTypeSpinner.setId(7383+addressIdStarter);
                setSpinnerValues(addressTypeSpinner, "address");
                addressFiledsCont.addView(view);
            }
        }

        public void setSpinnerValues (Spinner spinner, String spinnerType) {
            ArrayAdapter spinnerAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
            spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

            Iterator iter = null;
            if (spinnerType.equals("phone")) {
                iter = contactPhoneTypes.iterator();
            } else if (spinnerType.equals("email")) {
                iter = contactEmailTypes.iterator();
            } else if (spinnerType.equals("im")) {
                iter = contactIMTypes.iterator();
            } else if (spinnerType.equals("address")) {
                iter = contactAddressTypes.iterator();
            }

            while (iter.hasNext()) {
                if (spinnerType.equals("phone")) {
                    spinnerAdapter.add(ContactsContract.CommonDataKinds.Phone.getTypeLabel(this.getResources(), iter.next(), getString(R.string.undefinedTypeLabel)).toString());
                } else if (spinnerType.equals("email")) {
                    spinnerAdapter.add(ContactsContract.CommonDataKinds.Email.getTypeLabel(this.getResources(), iter.next(), getString(R.string.undefinedTypeLabel)).toString());
                } else if (spinnerType.equals("im")) {
                    spinnerAdapter.add(ContactsContract.CommonDataKinds.Im.getTypeLabel(this.getResources(), iter.next(), getString(R.string.undefinedTypeLabel)).toString());
                } else if (spinnerType.equals("address")) {
                    spinnerAdapter.add(ContactsContract.CommonDataKinds.Im.getTypeLabel(this.getResources(), iter.next(), getString(R.string.undefinedTypeLabel)).toString());
                }
            }

            spinner.setAdapter(spinnerAdapter);
            spinner.setPrompt(getString(R.string.selectLabel));
        }

    }

вот мой add_contact.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent">

    <LinearLayout android:orientation="vertical"
        android:layout_width="fill_parent" android:layout_height="wrap_content">

        <TableLayout 
            android:layout_width="fill_parent" android:layout_height="wrap_content">

            <TableRow>

                <TextView android:text="Target Account"
                    android:layout_width="wrap_content" android:layout_height="wrap_content" />

            </TableRow>
            <TableRow>

                <Spinner android:id="@+id/accountSpinner"
                    android:layout_height="wrap_content" android:layout_width="fill_parent"
                    android:layout_weight="1" />

            </TableRow>
            <TableRow>

                <TextView android:text="Contact Name"
                    android:layout_width="wrap_content" android:layout_height="wrap_content" />

            </TableRow>
            <TableRow>

                <EditText android:id="@+id/etContactName"
                    android:layout_height="wrap_content" android:layout_width="wrap_content"
                    android:layout_weight="1"/>

            </TableRow>
            <TableRow>

                <TextView android:text="Contact Phone"
                    android:layout_width="wrap_content" android:layout_height="wrap_content"/>

            </TableRow>
            <TableRow>

                <Button android:id="@+id/bAddPhoneField"
                    android:layout_width="wrap_content" android:layout_height="wrap_content"
                    android:text="Add Field"/>

            </TableRow>

        </TableLayout>
        <TableLayout android:id="@+id/tlPhoneFiledCont" 
            android:layout_width="fill_parent" android:layout_height="wrap_content">

        </TableLayout>
        <TableLayout 
            android:layout_width="fill_parent" android:layout_height="wrap_content">

            <TableRow>

                <TextView android:text="Contact Email"
                    android:layout_width="wrap_content" android:layout_height="wrap_content"/>

            </TableRow>

        </TableLayout>
        <Button android:id="@+id/bAddEmailField"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:text="Add Field"/>
        <TableLayout android:id="@+id/tlEmailFiledsCont" 
            android:layout_width="fill_parent" android:layout_height="wrap_content">

        </TableLayout>

        <TextView android:text="Contact IM"
            android:layout_width="wrap_content" android:layout_height="wrap_content"/>
        <Button android:id="@+id/bAddIMField"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:text="Add Field"/>
        <TableLayout android:id="@+id/tlIMFiledsCont" 
            android:layout_width="fill_parent" android:layout_height="wrap_content">

        </TableLayout>

        <TextView android:text="Contact Address"
            android:layout_width="wrap_content" android:layout_height="wrap_content"/>
        <Button android:id="@+id/bAddaddressField"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:text="Add Field"/>
        <TableLayout android:id="@+id/tlAddressFiledsCont" 
            android:layout_width="fill_parent" android:layout_height="wrap_content">

        </TableLayout>

        <TableLayout 
            android:layout_width="fill_parent" android:layout_height="wrap_content">

            <TableRow>

                <Button android:text="@string/save"
                    android:layout_height="wrap_content" android:layout_width="fill_parent"
                    android:id="@+id/contactSaveButton" android:layout_weight="1"/>

            </TableRow>

        </TableLayout>

    </LinearLayout>

</ScrollView>

а вот мой add_phone_row.xml

<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent" >

    <EditText android:id="@+id/etContactPhone"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_weight="1" android:inputType="phone" />

    <Spinner android:id="@+id/sContactPhoneType"
        android:layout_width="wrap_content" android:layout_height="wrap_content" />

</TableRow>

Я создаю Spinnerи EditTextдинамично в функции ниже

    if (fieldType.equals("phone")) {
            // for phone number code is 80
            phoneNumbersIdStarter++;
            View view = layoutInflater.inflate(R.layout.add_phone_row, null);
            EditText phoneNumberField = (EditText) view.findViewById(R.id.etContactPhone);
            Spinner phoneTypeSpinner = (Spinner) view.findViewById(R.id.sContactPhoneType);
            Log.d(TAG, "spinner id = " + phoneTypeSpinner.getId());
            phoneNumberField.setId(8084+phoneNumbersIdStarter);
            phoneTypeSpinner.setId(8083+phoneNumbersIdStarter);
            Log.d("Spinner Created", "Spinner Id = " + phoneTypeSpinner.getId());
            setSpinnerValues(phoneTypeSpinner, "phone");
            phoneFiledsCont.addView(view);
        }

и получить их значения, как показано ниже

    EditText phoneNumberField = (EditText) findViewById(8084+phoneNumbersIdStarter);
    Spinner phoneNumberSpinner = (Spinner) findViewById(8083+phoneNumbersIdStarter);

и каждый раз, когда я добавляю эти поля, я также добавляю 1 в phoneNumbersIdStarter

если я прокомментирую следующую строку в своем коде, она отлично работает

    Spinner phoneNumberSpinner = (Spinner) findViewById(8083+phoneNumbersIdStarter);

7
  • 1
    В принципе, вы пытаетесь бросить EditTextк Spinner. Возможно, вы ошиблись взглядом сfindViewById 20 ноя '14 в 22: 542014-11-20 19:54
  • Нет , я не отливка EditTextк Spinner. если вы проверите мой код, у меня есть функция, addTextFieldи я создаю EditTextи Spinnerкаждый раз, когда вызываю эту функцию. Но я получаю эту ошибку, когда пытаюсь получить доступ к ней Spinnerв другой функции.
    Ali
    21 нояб.
  • @PiyushGupta Я тоже добавил xml файл
    Ali
    21 ноя '14 в 7:52
  • Зачем внедряете OnClickListener? 22 ноя '14 в 16:53
  • @jyoon, потому что я создаю EditTextи Spinnerнажимаю кнопку
    Ali
    22 ноя '14 в 16:55
0

Есть ли у вас какая-то конкретная причина не получать доступ к виджетам с помощью R.id.?

Я не считаю хорошей идеей использовать «8083 + phoneNumbersIdStarter», потому что идентификатор int, который создается в классе R, будет меняться при каждой компиляции, поэтому, вероятно, int 8083 + phoneNumbersIdStarter относится к виджету, который не является EditText.

Итак, изменитесь на что-то вроде этого:

Spinner phoneNumberSpinner = (Spinner) findViewById(R.id.your_spinner_id);
1
  • Да, у меня есть. Я создаю Spinnerи EditTextв своем классе java, если вы проверяете функцию, названную так, как addTextFieldвы ее узнаете.
    Ali
    21 ноя '14 в 6:50
0

Сам нашел ошибку. Ошибка возникла из-за конфликта идентификаторов. Потому что я добавлял 1в phoneNumbersIdStarterпо щелчку Add Phone Button. Итак, мой EditText IDнаблюдатель был 8084+phoneNumbersIdStarterи Spinner IDстартер, 8083+phoneNumbersIdStarterпоэтому при создании полей во второй раз возник Spinnnerконфликт EditText.

Устранена ошибка, изменив Spinner IDстартер с 8083+phoneNumbersIdStarterна, 9083+phoneNumbersIdStarterкак показано ниже, теперь он отлично работает.

EditText phoneNumberField = (EditText) findViewById(8084+phoneNumbersIdStarter);
Spinner phoneNumberSpinner = (Spinner) findViewById(9083+phoneNumbersIdStarter);