键手机预期整数但值是android.text.SpannableString。返回了默认值0

时间:2014-03-02 17:44:26

标签: android string textview autolink

点击“编辑”后 - 丢失了手机和网络链接。如果单击后退按钮而不保存 - 电话和Web将返回到表单。

如何解决此错误? Key phone expected String but value was a android.text.SpannableString. The default value <null> was returned

Contact.java

public class Contact extends Activity implements DatePickedListener {

    Button saveContactButton;

    EditText etNameContact;
    EditText etPhone;
    EditText etBirthday;
    EditText etPassport;
    EditText etAddressPS;
    EditText etSite;
    EditText etNote;

    ContactDBmoy cqh;
    SQLiteDatabase db;

    private Long rowId;

    private int mYear;
    private int mMonth;
    private int mDay;


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contact_edit);

        // Инициализируем наш класс-обёртку
                cqh = new ContactDBmoy(this);



        saveContactButton = (Button) findViewById(R.id.saveContactButton);


        etNameContact = (EditText) findViewById(R.id.etNameContact);
        etPhone = (EditText) findViewById(R.id.etPhone);
        etBirthday = (EditText) findViewById(R.id.etBirthday);
        etPassport = (EditText) findViewById(R.id.etPassport);
        etAddressPS = (EditText) findViewById(R.id.etAddressPS);
        etSite = (EditText) findViewById(R.id.etSite);
        etNote = (EditText) findViewById(R.id.etNote);

        // получаем текущее время
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH) + 1;
        mDay = c.get(Calendar.DAY_OF_MONTH);

        // выводим текущее время
        updateDisplay();


        // при наличии дополнений заполнение данными EditTexts
    Bundle extras = getIntent().getExtras(); // получение дополнений

    if (extras != null) {

             rowId = extras.getLong("rowId");

             etNameContact.setText(extras.getString(ContactDBmoy.COLUMN_NAME));  
             etPhone.setText(extras.getString(ContactDBmoy.COLUMN_PHONE));  
             etBirthday.setText(extras.getString(ContactDBmoy.COLUMN_BIRTHDAY));  
             etPassport.setText(extras.getString(ContactDBmoy.COLUMN_PASSPORT_SN));  
             etAddressPS.setText(extras.getString(ContactDBmoy.COLUMN_ADRESS));  
             etSite.setText(extras.getString(ContactDBmoy.COLUMN_SITE));
             etNote.setText(extras.getString(ContactDBmoy.COLUMN_NOTE));
          }




        // настройка слушателя событий для кнопки Save Contact
        saveContactButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                if (TextUtils.isEmpty(etNameContact.getText().toString())) {
                    Toast.makeText(Contact.this, "Данные не введены",
                            Toast.LENGTH_LONG).show();
                } else {
                    saveState();
                    setResult(RESULT_OK);
                    finish();
                }
            }
        });
    }

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

public void onDatePicked(Calendar date) {
    // выводим выбранную дату в текстовой метке 461
    mYear = date.get(Calendar.YEAR);
    mMonth = date.get(Calendar.MONTH) + 1;
    mDay = date.get(Calendar.DAY_OF_MONTH);

    updateDisplay();
}

// обновляем дату для вывода в TextView
public void updateDisplay() {
    etBirthday.setText(new StringBuilder().append(mDay).append(".")
            .append(mMonth).append(".").append(mYear));

}


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        saveState();
        outState.putSerializable(ContactDBmoy._ID, rowId);
    }

    @Override
    protected void onPause() {
        super.onPause();
        // saveState();
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    private void saveState() {

        String name_contact = etNameContact.getText().toString();
        String phone = etPhone.getText().toString();
        String birthday = etBirthday.getText().toString();
        String passport_sn = etPassport.getText().toString();
        String adress = etAddressPS.getText().toString();
        String site = etSite.getText().toString();
        String note = etNote.getText().toString();

        if (name_contact.length() == 0 && phone.length() == 0) {
            return;
        }

        if (rowId == null) {
            long id = cqh.createNewContact(name_contact, phone, birthday, passport_sn, adress, site, note);
            if (id > 0) {
                rowId = id;
            }
        } else {
            cqh.updateContact(rowId, name_contact, phone, birthday, passport_sn, adress, site, note);
        }
    }
}

ContactDB.java

public class ContactDBmoy extends SQLiteOpenHelper implements BaseColumns {

    // константы для конструктора
    private static final String DATABASE_NAME = "contact_db.db";
    private static final int DATABASE_VERSION = 1;
    public static final String TABLE_NAME = "contact_table";

    public static final String COLUMN_NAME = "name_contact";
    public static final String COLUMN_PHONE = "phone";
    public static final String COLUMN_BIRTHDAY = "birthday";
    public static final String COLUMN_PASSPORT_SN = "passport_sn";
    public static final String COLUMN_ADRESS = "adress";
    public static final String COLUMN_SITE = "site";
    public static final String COLUMN_NOTE = "note";

    ContactDBmoy cqh;
    SQLiteDatabase sdb;

    private static final String SQL_CREATE_CONTACTS = "CREATE TABLE "
            + TABLE_NAME + " (" + BaseColumns._ID
            + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_NAME + " text not null, " + COLUMN_PHONE
            + " text not null, " + COLUMN_BIRTHDAY + " integer, "
            + COLUMN_PASSPORT_SN + " text not null, " + COLUMN_ADRESS + " text not null, "
            + COLUMN_SITE + " text not null, " + COLUMN_NOTE + " text not null" + ");";


    private static final String SQL_DELETE_CONTACTS = "DROP TABLE IF EXISTS "
            + TABLE_NAME;


    public ContactDBmoy(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        // TODO Auto-generated constructor stub
    }

    public ContactDBmoy(Context context, String name, CursorFactory factory,
            int version, DatabaseErrorHandler errorHandler) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION, errorHandler);
        // TODO Auto-generated constructor stub
    }



    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL(SQL_CREATE_CONTACTS);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        Log.w(ContactDBmoy.class.getName(), "Обновление базы данных с версии " + oldVersion
                + " до версии " + newVersion
                + ", которое удалит все старые данные");
        // Удаляем предыдущую таблицу при апгрейде
        db.execSQL(SQL_DELETE_CONTACTS);

        // Создаём новый экземпляр таблицы
        onCreate(db);
    }



    /**
     * Создаёт новый элемент списка. Если создан успешно - возвращается
     * номер строки rowId, иначе -1
     */


    public long createNewContact(String name_contact, String phone, String birthday, String passport_sn, String adress, String site, String note) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues initialValues = createContentValues( name_contact, phone, birthday, passport_sn, adress, site, note);


    long row = db.insert(TABLE_NAME, null, initialValues);
    db.close();

    return row;

}

    /**
     * Обновляет список
     */

    public boolean updateContact(long rowId, String name_contact, String phone, String birthday, String passport_sn, String adress, String site, String note) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues updateValues = createContentValues(name_contact, phone, birthday, passport_sn, adress, site, note);

        return db.update(TABLE_NAME, updateValues, _ID + "=" + rowId,
                null) > 0;
    }


    public void deleteContact(long rowId) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_NAME, _ID + "=" + rowId, null);
        db.close();
    }


    public Cursor getAllContact() {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.query(TABLE_NAME, new String[] { BaseColumns._ID, COLUMN_NAME, COLUMN_PHONE, COLUMN_BIRTHDAY, COLUMN_PASSPORT_SN, COLUMN_ADRESS, COLUMN_SITE, COLUMN_NOTE
     }, null,
                null, COLUMN_NAME, null, null);
    }



    public Cursor getOneContact(long rowId) throws SQLException {
        SQLiteDatabase db = this.getReadableDatabase();
    }
        return db.query(true, TABLE_NAME,
                new String[] { COLUMN_NAME, COLUMN_PHONE, COLUMN_BIRTHDAY, COLUMN_PASSPORT_SN, COLUMN_ADRESS, COLUMN_SITE, COLUMN_NOTE }, _ID + "=" + rowId, null,
                null, null, null, null);
    }



    private ContentValues createContentValues(String name_contact, String phone, String birthday, String passport_sn, String adress, String site, String note) {
        ContentValues cv = new ContentValues();

        cv.put(COLUMN_NAME, name_contact);
        cv.put(COLUMN_PHONE, phone);
        cv.put(COLUMN_BIRTHDAY, birthday);
        cv.put(COLUMN_PASSPORT_SN, passport_sn);
        cv.put(COLUMN_ADRESS, adress);
        cv.put(COLUMN_SITE, site);
        cv.put(COLUMN_NOTE, note);
        return cv;
    }

}

我在XML文件中添加后发生了此错误:

android:autoLink="phone"
android:linksClickable="true"

1 个答案:

答案 0 :(得分:0)

通过替换行来解决问题:

etPhone.setText(extras.getString(Contac tDBmoy.COLUMN_PHONE)); etSite.setText(extras.getString(ContactDBmoy.COLUMN_SITE));

on:

etPhone.setText(extras.get(ContactDBmoy.COLUMN_PHONE).toString()); etSite.setText(extras.get(ContactDBmoy.COLUMN_SITE).toString());