public class Main2Activity extends AppCompatActivity { private EditText editText1, editText2, editText3, editText4; private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText1 = (EditText) findViewById(R.id.editText); editText2 = (EditText) findViewById(R.id.editText2); editText3 = (EditText) findViewById(R.id.editText3); editText4 = (EditText) findViewById(R.id.editText4); button = (Button) findViewById(R.id.button3); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String un, pw, cpw, ph; un = editText1.getText().toString(); pw = editText2.getText().toString(); cpw = editText3.getText().toString(); ph = editText4.getText().toString(); DbHelper dbHelpero = new DbHelper(Main2Activity.this); SQLiteDatabase db = dbHelpero.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(Entry.C_UNAME, un); values.put(Entry.C_PASS, pw); values.put(Entry.C_CPASS, cpw); values.put(Entry.C_PNO, ph); long newRowId = db.insert(Entry.TABLE_NAME, null, values); if (newRowId == -1) { Toast.makeText(getApplicationContext(), "Error while adding", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "Yo Registration is complete", Toast.LENGTH_SHORT).show(); } } }); } }
这是Contract.java
public class Contract { private Contract() { } public static final class Entry implements BaseColumns { public final static String TABLE_NAME = "details"; public final static String _ID = BaseColumns._ID; public final static String C_UNAME = "uname"; public final static String C_PASS = "pw"; public final static String C_CPASS = "cpw"; public final static String C_PNO = "pno"; } }
还有DbHelper.java
public class DbHelper extends SQLiteOpenHelper { public static final String LOG_TAG = DbHelper.class.getSimpleName(); public final static String DATABASE_NAME = "contacts.db"; private static final int DATABASE_VERSION = 1; public DbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String CREATE_TABLE = "CREATE TABLE " + Entry.TABLE_NAME + " (" + Entry._ID + " TEXT PRIMARY KEY AUTOINCREMENT, " + Entry.C_UNAME + " TEXT, " + Entry.C_PASS + " TEXT, " + Entry.C_CPASS + " TEXT, " + Entry.C_PNO + " TEXT" + ")"; db.execSQL(CREATE_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
没有语法错误,但应用仍然崩溃。
将您的CREATE_TABLE查询替换为:
String CREATE_TABLE = "CREATE TABLE " + Entry.TABLE_NAME + " (" + Entry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + Entry.C_UNAME + " TEXT, " + Entry.C_PASS + " TEXT, " + Entry.C_CPASS + " TEXT, " + Entry.C_PNO + " TEXT" + ")";
您无法让TEXT类型拥有AUTOINCREMENT属性,因为您当前在_ID字段中拥有属性。您需要将其更改为,INTEGER以便可以用作PRIMARY KEY,然后将其使用AUTOINCREMENT
TEXT
AUTOINCREMENT
_ID
INTEGER
PRIMARY KEY