我有一个DBHelper类,我已经保存了用户的信息。我还想从服务器保存用户的令牌,但是在logcat中显示错误。请查看我的代码并指出我的错误。
我的DBHelper课程:
public class DBHelper {
private static final String DATABASE_NAME = "tingUser.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "profileInfo";
private static final String IMAGES_TABLE = "userImage";
private static final String COL_ID = "databaseId";
public static final String COL_USER_ID = "userId";
public static final String COL_FULL_NAME = "fullName";
public static final String COL_GENDER = "gender";
public static final String COL_DOB = "DOB";
public static final String COL_MOBILE_NUM = "mobileNum";
public static final String COL_OCCUPATION = "occupation";
public static final String COL_ORGANIZATION = "organization";
public static final String COL_TOKEN = "JWT Token";
private static final String COL_PROFILE_PHOTO = "profilePhoto";
private Context mCtx;
private DatabaseManager databaseManager;
private SQLiteDatabase db;
public DBHelper(Context context){
this.mCtx = context;
databaseManager = new DatabaseManager(mCtx);
}
public DBHelper open() throws SQLException{
db = databaseManager.getWritableDatabase();
return this;
}
public void close(){
databaseManager.close();
}
public boolean saveInputField(TingTingUser user){
SQLiteDatabase userDb = databaseManager.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_FULL_NAME, user.getDisplayName());
values.put(COL_USER_ID, user.getUserId());
values.put(COL_GENDER, user.getGender());
values.put(COL_DOB, user.getDob());
values.put(COL_MOBILE_NUM, user.getMobileNumber());
values.put(COL_ORGANIZATION, user.getOrganization());
values.put(COL_OCCUPATION, user.getOccupation());
values.put(COL_TOKEN, user.getJWT_token());
Log.d("database",values.toString());
//values.put(COL_TOKEN, (user.getJWT_token() != null) ? user.getJWT_token() : null);
long result = userDb.insert(TABLE_NAME, null, values); // error occurs here
userDb.close();
if (result == -1){
return false;
} else {
return true;
}
}
public TingTingUser getCurrentUser(int id){
SQLiteDatabase currDB = databaseManager.getWritableDatabase();
Cursor cursor = currDB.query(true, TABLE_NAME, new String[]{COL_ID, COL_USER_ID, COL_FULL_NAME, COL_GENDER, COL_DOB, COL_MOBILE_NUM, COL_OCCUPATION, COL_ORGANIZATION}, COL_ID + "=?", new String[]{String.valueOf(id)}, null, null, null, null);
if (cursor != null && cursor.moveToFirst()){
TingTingUser user = new TingTingUser(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6), cursor.getString(7) );
return user;
}
return null;
}
public void saveCameraImage(byte[] imageBytes){
SQLiteDatabase camDb = databaseManager.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_PROFILE_PHOTO, imageBytes);
camDb.insert(IMAGES_TABLE, null, contentValues);
}
public void saveGalleryImage(byte[] imageBytes){
ContentValues contentValues = new ContentValues();
contentValues.put(COL_PROFILE_PHOTO, imageBytes);
db.insert(IMAGES_TABLE, null, contentValues);
}
public byte[] getImage(){
Cursor cursor = db.query(true, IMAGES_TABLE, new String[]{COL_PROFILE_PHOTO,}, null, null, null, null, COL_ID + " DESC", "1");
if (cursor.moveToFirst()){
byte[] blob = cursor.getBlob(cursor.getColumnIndex(COL_PROFILE_PHOTO));
cursor.close();
return blob;
}
cursor.close();
Toast.makeText(mCtx, "No Image Found", Toast.LENGTH_SHORT).show();
return null;
}
public class DatabaseManager extends SQLiteOpenHelper {
public DatabaseManager(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String db_create = " Create Table " + TABLE_NAME + " ("
+ COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COL_USER_ID + " TEXT, "
+ COL_FULL_NAME + " TEXT, "
+ COL_GENDER + " TEXT, "
+ COL_DOB + " TEXT, "
+ COL_MOBILE_NUM + " TEXT, "
+ COL_OCCUPATION + " TEXT, "
+ COL_ORGANIZATION + " TEXT "
+ COL_TOKEN + " TEXT VARCHAR 1024) ";
sqLiteDatabase.execSQL(db_create);
String img_create = "Create table " + IMAGES_TABLE + " ("
+ COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COL_PROFILE_PHOTO + " BLOB NOT NULL )";
sqLiteDatabase.execSQL(img_create);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(sqLiteDatabase);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + IMAGES_TABLE);
onCreate(sqLiteDatabase);
}
}
}
在我的活动中,除令牌外,其他字段都在保存。我已经调用了helper方法来保存令牌,如下所示:
JsonObjectRequest otpObjectRequest = new JsonObjectRequest(Request.Method.POST, Constants.TING_VERIFY_OTP_ENDPOINT, verifyOTPObject, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("OTPDialogFragment", "OTP Verification Response is: \t" + response.toString());
Log.d("OTPDialogFragment", "OTP Verified Successfully");
try {
JSONObject verifyObject = new JSONObject(response.toString());
JSONObject userObject = verifyObject.getJSONObject("user");
userId = userObject.getString("_id");
Log.d(TAG, "Retrieved user id is:\t" + userId);
userToken = verifyObject.getString("token"); // getting user token from server correctly
Log.d("jwt token", userToken);
TingTingUser user = new TingTingUser();
user.setDisplayName(fullName);
user.setMobileNumber(num);
user.setGender(genderVal);
user.setDob(dob);
user.setOccupation("default");
user.setOrganization("default");
user.setUserId(userId);
user.setJWT_token(userToken); // saving in model class
if (!TextUtils.isEmpty(fullName) && !TextUtils.isEmpty(genderVal) && !TextUtils.isEmpty(dob) && !TextUtils.isEmpty(userId) && !userToken.isEmpty()){
if (dbHelper.saveInputField(user) == true){ // saving model object in db and error occurs here
Toast.makeText(getContext(), "Saved User", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Save Failed", Toast.LENGTH_SHORT).show();
}
logcat错误:
Error inserting JWT Token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1YTA5YTM3NDJhODE1YjIyNzhkMzBmYWUiLCJpYXQiOjE1MTA1ODExMTh9.0SpOuVkxAKQew539dif2Gjd2DRKgiR-A0IpU9mgs_zA fullName=the link userId=5a09a3742a815b2278d30fae occupation=default gender=Male DOB=1578335820 mobileNum=1234566789 organization=default
android.database.sqlite.SQLiteException: near "Token": syntax error (code 1): , while compiling: INSERT INTO profileInfo(JWT Token,fullName,userId,occupation,gender,DOB,mobileNum,organization) VALUES (?,?,?,?,?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at com.billionusers.tingting.db.DBHelper.saveInputField(DBHelper.java:71)
at com.billionusers.tingting.activities.SignUpActivity$OTPDialogFragment$6.onResponse(SignUpActivity.java:480)
at com.billionusers.tingting.activities.SignUpActivity$OTPDialogFragment$6.onResponse(SignUpActivity.java:452)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:742)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:5529)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
它在我的create table语句中显示了语法错误,但是我觉得一切都很好。请指出我的错误。感谢。
答案 0 :(得分:1)
应该是:
INSERT INTO profileInfo(JWT_token,fullName,userId,occupation,gender,DOB,mobileNum,organization) VALUES (?,?,?,?,?,?,?,?)
变量中不能包含空格。