无法暂停活动android SQLiteConstraintEcxeption列可能不为NULL(代码19)

时间:2014-04-01 14:59:55

标签: android android-sqlite sql-insert

我的应用程序崩溃了,即使在我梳理了我的代码之后,我也会递归地收到此错误。我说我的表的主键列可能不是null。我不知道为什么因为它是PK并自动递增。

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class AccountsDetailsActivity extends ActionBarActivity {
private EditText meterNumber;
private EditText plotNumber;
private EditText Name;
private EditText phone;
private EditText address;
private EditText account;

private Uri userUri;
private ArrayList<String>meters_list = new ArrayList<String>();

private ArrayList<String>plots_list = new ArrayList<String>();


@Override
protected void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    setContentView(R.layout.insert_user);

    // get action bar
    android.app.ActionBar actionBar = getActionBar();

    // Enabling Up / Back navigation
    actionBar.setDisplayHomeAsUpEnabled(true);

    String[] projection = new String[] { MeterTableDetails.METER_ID,MeterTableDetails.METER_NUMBER,MeterTableDetails.PLOT_NUMBER};


    Cursor cursor = getContentResolver().query(UserAccountsContentProvider.CONTENT_URI_METER, projection, null, null,
            null);

    if (cursor != null) {

        cursor.moveToFirst();
        String meter = cursor.getString(cursor
                .getColumnIndexOrThrow(MeterTableDetails.METER_NUMBER));
        String plot = cursor.getString(cursor
                .getColumnIndexOrThrow(MeterTableDetails.PLOT_NUMBER));

        plots_list.add(plot);
        meters_list.add(meter);
        cursor.close();
    }
    final   ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, meters_list);

    final   ArrayAdapter<String> plotAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, plots_list);

    meterNumber = (EditText) findViewById(R.id.insert_meter_number_user);

    meterNumber.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                hideKeyboard(v);
            }
        }
    });
    meterNumber.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {


            new AlertDialog.Builder(AccountsDetailsActivity.this)
            .setTitle("Select Meter")
            .setAdapter(dataAdapter, new DialogInterface.OnClickListener() {

              public void onClick(DialogInterface dialog, int which) {
                  meterNumber.setText(meters_list.toString());
                dialog.dismiss();
              }
            }).create().show();

        }
    });
    plotNumber = (EditText) findViewById(R.id.insert_plot_user);
    plotNumber.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                hideKeyboard(v);
            }
        }
    });

    plotNumber.setOnClickListener(new OnClickListener(){

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

            new AlertDialog.Builder(AccountsDetailsActivity.this)
            .setTitle("Select Plot Number")
            .setAdapter(plotAdapter, new DialogInterface.OnClickListener() {

              public void onClick(DialogInterface dialog, int which) {
                  plotNumber.setText(plots_list.toString());
                dialog.dismiss();
              }
            }).create().show();

        }

    });
    Name = (EditText) findViewById(R.id.insert_name_edit);
    Name.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                hideKeyboard(v);
            }
        }
    });

    address = (EditText) findViewById(R.id.insert_address);
    address.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                hideKeyboard(v);
            }
        }
    });

    account = (EditText) findViewById(R.id.insert_accountNumber);
    account.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                hideKeyboard(v);
            }
        }
    });

    phone = (EditText) findViewById(R.id.insert_phone);
    phone.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                hideKeyboard(v);
            }
        }
    });
    Button confirmButton = (Button) findViewById(R.id.btn_insert_user);

    Bundle extras = getIntent().getExtras();

    // check from the saved Instance
    userUri = (bundle == null) ? null
            : (Uri) bundle
                    .getParcelable(UserAccountsContentProvider.CONTENT_ITEM_ACCOUNT_TYPE);

    // or if passed from other activities
    if (extras != null) {

        userUri = extras
                .getParcelable(UserAccountsContentProvider.CONTENT_ITEM_ACCOUNT_TYPE);

        fillData(userUri);



    }

    confirmButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (TextUtils.isEmpty(Name.getText().toString())) {

                makeToast();

            } else if (TextUtils.isEmpty(meterNumber.getText().toString())) {

                makeToast();
            } else if (TextUtils.isEmpty(plotNumber.getText().toString())) {
                makeToast();

            } else if (TextUtils.isEmpty(address.getText().toString())) {
                makeToast();

            }
            else if (TextUtils.isEmpty(account.getText().toString())) {
                makeToast();

            }else if (TextUtils.isEmpty(phone.getText().toString())) {
                makeToast();

            }else {

                setResult(RESULT_OK);
                finish();
            }

        }

        private void makeToast() {

            Toast.makeText(AccountsDetailsActivity.this,
                    "Please enter all fields", Toast.LENGTH_LONG).show();

        }

    });
    }


private void fillData(Uri uri) {

    String[] projection = new String[] { AccountsTableDetails.KEY_CUSTOMER_ID,
            AccountsTableDetails.KEY_LAST_NAME,
            AccountsTableDetails.KEY_METER_NUMBER,
            AccountsTableDetails.KEY_PLOT_NUMBER,
            AccountsTableDetails.KEY_ADDRESS,
            AccountsTableDetails.KEY_PHONE_NUMBER,
            AccountsTableDetails.KEY_ACCOUNT_NUMBER};

    Cursor cursor = getContentResolver().query(uri, projection, null, null,
            null);

    if (cursor != null) {
        cursor.moveToFirst();

        Name.setText(cursor.getString(cursor
                .getColumnIndexOrThrow(AccountsTableDetails.KEY_LAST_NAME)));
        meterNumber.setText(cursor.getString(cursor
                .getColumnIndexOrThrow(AccountsTableDetails.KEY_METER_NUMBER)));
        plotNumber.setText(cursor.getString(cursor
                .getColumnIndexOrThrow(AccountsTableDetails.KEY_PLOT_NUMBER)));
        address.setText(cursor.getString(cursor
                .getColumnIndexOrThrow(AccountsTableDetails.KEY_ADDRESS)));

        phone.setText(cursor.getString(cursor
                .getColumnIndexOrThrow(AccountsTableDetails.KEY_PHONE_NUMBER)));


        account.setText(cursor.getString(cursor
                .getColumnIndexOrThrow(AccountsTableDetails.KEY_ACCOUNT_NUMBER)));

        // always close the cursor
        cursor.close();
    }

}

private void hideKeyboard(View v) {
    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);

}

protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    saveState();
    outState.putParcelable(
            UserAccountsContentProvider.CONTENT_ITEM_ACCOUNT_TYPE,
            userUri);
}

private void saveState() {
    String name = Name.getText().toString();
    String meter = meterNumber.getText().toString();
    String plot = plotNumber.getText().toString();
    String Address = address.getText().toString();
    String Account = account.getText().toString();
    String Phone = phone.getText().toString();

    // only save if either name or account number
    // is available

    if (name.length() == 0 && Account.length() == 0) {
        return;
    }

    ContentValues values = new ContentValues();
    values.put(AccountsTableDetails.KEY_LAST_NAME, name);
    values.put(AccountsTableDetails.KEY_METER_NUMBER, meter);
    values.put(AccountsTableDetails.KEY_PLOT_NUMBER, plot);
    values.put(AccountsTableDetails.KEY_ADDRESS, Address);
    values.put(AccountsTableDetails.KEY_ACCOUNT_NUMBER, Account);
    values.put(AccountsTableDetails.KEY_PHONE_NUMBER, Phone);

    if (userUri == null) {
        // New item
        userUri = getContentResolver().insert(
                UserAccountsContentProvider.CONTENT_URI_ACCOUNTS,
                values);
    } else {
        // Update meter
        getContentResolver().update(userUri, values, null, null);
    }

}

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


}

这是Logcat:

04-01 17:48:30.413: E/AndroidRuntime(2317): java.lang.RuntimeException: Unable to pause activity  {com.isys.waterbillingsystem/com.isys.waterbillingsystem.AccountsDetailsActivity}:     android.database.sqlite.SQLiteConstraintException: customers.customerMeterId may not be NULL (code 19)
04-01 17:48:30.413: E/AndroidRuntime(2317): Caused by:  android.database.sqlite.SQLiteConstraintException: customers.customerMeterId may not be NULL (code 19)
04-01 17:48:30.413: E/AndroidRuntime(2317):     at  android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
 04-01 17:48:30.413: E/AndroidRuntime(2317):    at  android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
04-01 17:48:30.413: E/AndroidRuntime(2317):     at  android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
04-01 17:48:30.413: E/AndroidRuntime(2317):     at  android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)

问题是什么?

1 个答案:

答案 0 :(得分:0)

解决方案是一个非常小的错误。在我的customers表中,我将customerMeterId列设置为整数不为空

如下所示:

// Database creation SQL statement for customers table
    private static final String CREATE_TABLE_CUSTOMERS = "create table " 
            + TABLE_CUSTOMERS
            + "(" 
            + KEY_CUSTOMER_ID + " integer primary key autoincrement, " 
            + KEY_FIRST_NAME + " text, " 
            + KEY_LAST_NAME + " text, "
            + KEY_ADDRESS + " varchar, "
            + KEY_EMAIL + " varchar, "
            + KEY_PHONE_NUMBER + " integer, "
            + KEY_ACCOUNT_NUMBER + " integer, "
            + KEY_CUSTOMER_METER_ID + " integer not null, "
            + KEY_METER_NUMBER + " integer not null, "
            + KEY_PLOT_NUMBER + " varchar not null "

            + ");"; 

这个列最初是一个外键,从另一个名为meters的表插入。所以这个表中的meter_id将被插入到这个列中。这就是为什么它是整数而不是null。但是我已经改变了结构,忘记了编辑该部分。不知道它,每次我试图插入我的表,我得到错误 customerMeterId可能不是空

要纠正我刚刚从描述中删除 not null 并将其保留为整数。意味着它现在可以接受空值。