我正在尝试使用SQLlite数据库,我在其中创建了两个表,其中一个称为包含每个用户凭据的用户。我创建了一个名为“getAllUsersRows()
”的方法来获取表中的所有行,当我输入初始用户“TRUST”时,意图不会启动:
package com.example.welcome.madrasti;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* A login screen that offers login via email/password.
*/
public class LoginActivity extends AppCompatActivity {
private EditText uPassword;
private EditText uName;
Intent intent;
DBAdapter db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
openDB();
uPassword = (EditText) findViewById(R.id.password);
uName = (EditText) findViewById(R.id.name);
Button register = (Button) findViewById(R.id.sign_up);
Button signInButton = (Button) findViewById(R.id.sign_in);
intent = getIntent();
signInButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
attemptLogin();
}
});
register.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
attemptRegister();
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}// end onDestroy method
//**///////////////////////////////////////////////////////////////////////////////////////////////////////////////////**//
private void openDB() {
db = new DBAdapter(this);
db.open();
} // end openDB method
//**///////////////////////////////////////////////////////////////////////////////////////////////////////////////////**//
private void closeDB() {
db.close();
} // end closeDB method
//**///////////////////////////////////////////////////////////////////////////////////////////////////////////////////**//
//**///////////////////////////////////////////////////////////////////////////////////////////////////////////////////**//
private void attemptRegister() {
Intent intent = new Intent(getApplicationContext(), AddUser.class);
startActivity(intent);
}
//**///////////////////////////////////////////////////////////////////////////////////////////////////////////////////**//
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
private void attemptLogin() {
db.open();
Cursor cursor = db.getAllUsersRows();
cursor.moveToFirst();
while (cursor.moveToNext()) {
if (cursor.getString(DBAdapter.COL_NAME_TABLE_1).equals(uName.getText().toString()) && cursor.getString(DBAdapter.COL_PASSWD_TABLE_1).equals(uPassword.getText().toString())) {
if (cursor.getInt(DBAdapter.COL_ADMIN_TABLE_1) == 1) {
intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
} else {
intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
} else {
Toast.makeText(this, "إسم المستخدم أو كلمة السر خاطئة" + "\n" + "حاول مرة أخرى أو أنشئ حساب!", Toast.LENGTH_LONG).show();
}
}
cursor.close();
}
}
以下是整个数据库类:
package com.example.welcome.madrasti;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
private static final String TAG = "DBAdapter";
//columns names users
public static final String KEY_ROWID = "id";
public static final String KEY_NAME = "name";
public static final String KEY_PASSWD = "passwd";
public static final String KEY_ADMIN = "isAdmin";
public static final String KEY_U_PHONE = "phone";
// School Table Columns names
public static final String KEY_SCHOOLID = "schoolID";
public static final String KEY_SCHOOLNAME = "schoolName";
public static final String KEY_PHONE_NUM = "schoolPhone";
public static final String KEY_MATERIALS = "schoolExtraM";
public static final String KEY_FOUNDATION_DATE = "schoolFD";
public static final String KEY_CLASSES = "schoolClasses";
public static final String KEY_BUY_BOOKS = "schoolGetBooks";
public static final String KEY_HEALTH = "schoolHealthSituation";
public static final String KEY_LABORATORIES = "schoolLabs";
public static final String KEY_LOCATION = "schoolLocation";
public static final String KEY_FEES = "schoolFees";
public static final String KEY_LATITUDE = "schoolLatitude";
public static final String KEY_LONGITUDE = "schoolLongitude";
public static final String KEY_SChOOL_TYPE = "schoolType";
//columns numbers - users
public static final int COL_ROWID_TABLE_1 = 0;
public static final int COL_NAME_TABLE_1 = 1;
public static final int COL_PASSWD_TABLE_1 = 2;
public static final int COL_ADMIN_TABLE_1 = 3;
public static final int COL_PHONE_NUM_TABLE_1 = 4;
//columns numbers - schools
public static final int COL_SCHOOLID_TABLE_2 = 0;
public static final int COL_SCHOOLNAME_TABLE_2 = 1;
public static final int COL_PHONE_NUM_TABLE_2 = 2;
public static final int COL_MATERIALS_TABLE_2 = 3;
public static final int COL_FOUNDATION_DATE_TABLE_2 = 4;
public static final int COL_CLASSES_TABLE_2 = 5;
public static final int COL_BUY_BOOKS_TABLE_2 = 6;
public static final int COL_HEALTH_TABLE_2 = 7;
public static final int COL_LABORATORIES_TABLE_2 = 8;
public static final int COL_LOCATION_TABLE_2 = 9;
public static final int COL_FEES_TABLE_2 = 10;
public static final int COL_LATITUDE_TABLE_2 = 11;
public static final int COL_LONGITUDE_TABLE_2 = 12;
public static final int COL_SChOOL_TYPE_TABLE_2 = 13;
// array for the columns names
public static final String[] ALL_KEYS_TABLE_1 = new String[] {KEY_ROWID, KEY_NAME, KEY_PASSWD, KEY_ADMIN,KEY_U_PHONE};
public static final String[] ALL_KEYS_TABLE_2 = new String[] {KEY_SCHOOLID, KEY_SCHOOLNAME, KEY_PHONE_NUM, KEY_MATERIALS,KEY_FOUNDATION_DATE,KEY_CLASSES,KEY_BUY_BOOKS,KEY_HEALTH,KEY_LABORATORIES,KEY_LOCATION,KEY_FEES,KEY_LATITUDE,KEY_LONGITUDE,KEY_SChOOL_TYPE};
// the database name and the table name
public static final String DATABASE_NAME = "MyDb";
public static final String DATABASE_TABLE_1 = "users";
public static final String DATABASE_TABLE_2 = "schools";
// version
public static final int DATABASE_VERSION = 4;
// create table query
private static final String DATABASE_CREATE_SQL_1 =
"create table " + DATABASE_TABLE_1
+ "("
+ KEY_ROWID + " integer primary key autoincrement,"
+ KEY_NAME+ " text not null,"
+ KEY_PASSWD + " text not null,"
+KEY_ADMIN + " integer not null,"
+ KEY_U_PHONE + " text not null" + ")";
private static final String DATABASE_CREATE_SQL_2 =
"create table " + DATABASE_TABLE_2
+ "("
+ KEY_SCHOOLID + " integer primary key autoincrement,"
+ KEY_SCHOOLNAME + " text not null,"
+ KEY_PHONE_NUM + " text not null,"
+ KEY_MATERIALS + " text not null,"
+ KEY_FOUNDATION_DATE + " integer not null,"
+ KEY_CLASSES + " text not null,"
+ KEY_BUY_BOOKS + " text not null,"
+ KEY_HEALTH + " text not null,"
+ KEY_LABORATORIES + " text not null,"
+ KEY_FEES + " text not null,"
+ KEY_LOCATION + " text not null,"
+ KEY_LONGITUDE + " double not null,"
+ KEY_SChOOL_TYPE + " text not null,"
+ KEY_LATITUDE + " double not null" + ")";
private final Context context;
// initiates instances from class DatabaseHelper and SQLiteDatabase
private DatabaseHelper myDBHelper;
private SQLiteDatabase db; // database
// constructor
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
public void close() {
myDBHelper.close();
}
public long insertSchool(String name, String phone,String materials, int fDate,String classes,String books,String health,String labs,String fees,String location,double longitude,String type,double latitude) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_PHONE_NUM,phone);
initialValues.put(KEY_MATERIALS, materials);
initialValues.put(KEY_FOUNDATION_DATE, fDate);
initialValues.put(KEY_CLASSES, classes);
initialValues.put(KEY_BUY_BOOKS, books);
initialValues.put(KEY_HEALTH,health);
initialValues.put(KEY_LABORATORIES, labs);
initialValues.put(KEY_FEES, fees);
initialValues.put(KEY_LOCATION, location);
initialValues.put(KEY_LONGITUDE, longitude);
initialValues.put(KEY_SChOOL_TYPE, type);
initialValues.put(KEY_LATITUDE, latitude);
return db.insert(DATABASE_TABLE_2, null, initialValues);
}
public long insertUser(String name, String passwd,int isAdmin, String phone) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_PASSWD, passwd);
initialValues.put(KEY_ADMIN, isAdmin);
initialValues.put(KEY_U_PHONE, phone);
return db.insert(DATABASE_TABLE_1, null, initialValues);
}
public boolean deleteShool(String schoolName) {
String where = KEY_SCHOOLNAME + "='" + schoolName + "'";
return db.delete(DATABASE_TABLE_2, where, null) != 0;
}
public boolean deleteSchoolById(long rowId) {
String where = KEY_SCHOOLID + "=" + rowId;
return db.delete(DATABASE_TABLE_2, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_SCHOOLID);
if (c.moveToFirst()) {
do {
deleteSchoolById(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE_2, ALL_KEYS_TABLE_2,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public Cursor getAllUsersRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE_1, ALL_KEYS_TABLE_1,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public Cursor getRow(long rowId) {
String where = KEY_SCHOOLID+ "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE_2, ALL_KEYS_TABLE_2,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public Cursor getRowByName(String name) {
String where = KEY_SCHOOLNAME + "='" + name+"'";
Cursor c = db.query(true, DATABASE_TABLE_2, ALL_KEYS_TABLE_2,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL_1);
_db.execSQL(DATABASE_CREATE_SQL_2);
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, "TRUST");
initialValues.put(KEY_PASSWD, "792863");
initialValues.put(KEY_ADMIN, 1);
initialValues.put(KEY_U_PHONE, "0799504863");
_db.insert(DATABASE_TABLE_1, null, initialValues);
}
@Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data!");
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_1);
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_2);
onCreate(_db);
}
}
}
亲爱的告诉我问题在哪里以及如何解决。
logcat的:
04-08 11:49:15.583 3163-3163/? E/libprocessgroup: failed to make and chown /acct/uid_10059: Read-only file system
04-08 11:49:15.583 3163-3163/? W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
04-08 11:49:15.584 3163-3163/? I/art: Late-enabling -Xcheck:jni
04-08 11:49:15.829 3163-3163/com.example.welcome.madrasti I/InstantRun: starting instant run server: is main process
04-08 11:49:15.893 3163-3163/com.example.welcome.madrasti W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
04-08 11:49:16.005 3163-3184/com.example.welcome.madrasti D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
04-08 11:49:16.729 3163-3163/com.example.welcome.madrasti D/Atlas: Validating map...
04-08 11:49:17.985 3163-3184/com.example.welcome.madrasti D/libEGL: loaded /system/lib/egl/libEGL_emulation.so
04-08 11:49:17.986 3163-3184/com.example.welcome.madrasti D/libEGL: loaded /system/lib/egl/libGLESv1_CM_emulation.so
04-08 11:49:17.996 3163-3184/com.example.welcome.madrasti D/libEGL: loaded /system/lib/egl/libGLESv2_emulation.so
04-08 11:49:18.071 3163-3184/com.example.welcome.madrasti I/OpenGLRenderer: Initialized EGL, version 1.4
04-08 11:49:18.493 3163-3184/com.example.welcome.madrasti D/OpenGLRenderer: Enabling debug mode 0
04-08 11:49:18.515 3163-3184/com.example.welcome.madrasti W/EGL_emulation: eglSurfaceAttrib not implemented
04-08 11:49:18.515 3163-3184/com.example.welcome.madrasti W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xeec35720, error=EGL_SUCCESS
04-08 11:49:18.550 3163-3163/com.example.welcome.madrasti I/Choreographer: Skipped 33 frames! The application may be doing too much work on its main thread.
04-08 11:49:21.172 3163-3163/com.example.welcome.madrasti I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
04-08 11:49:21.176 3163-3163/com.example.welcome.madrasti I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
04-08 11:49:23.259 3163-3184/com.example.welcome.madrasti W/EGL_emulation: eglSurfaceAttrib not implemented
04-08 11:49:23.259 3163-3184/com.example.welcome.madrasti W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xe2c122c0, error=EGL_SUCCESS
04-08 11:49:23.377 3163-3163/com.example.welcome.madrasti W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
04-08 11:49:23.384 3163-3163/com.example.welcome.madrasti I/Choreographer: Skipped 129 frames! The application may be doing too much work on its main thread.
04-08 11:49:24.297 3163-3163/com.example.welcome.madrasti I/Choreographer: Skipped 54 frames! The application may be doing too much work on its main thread.
04-08 11:50:00.123 3163-3184/com.example.welcome.madrasti W/EGL_emulation: eglSurfaceAttrib not implemented
04-08 11:50:00.123 3163-3184/com.example.welcome.madrasti W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xe2c18ee0, error=EGL_SUCCESS
答案 0 :(得分:0)
我认为您遇到的问题是因为您在列名电话和列类型之间省略了空格: -
+ KEY_U_PHONE + "text not null" + ")";
因此,不是列名是手机,而是 phonetext 。
要解决此问题: -
// create table query
private static final String DATABASE_CREATE_SQL_1 =
"create table " + DATABASE_TABLE_1
+ "("
+ KEY_ROWID + " integer primary key autoincrement,"
+ KEY_NAME+ " text not null,"
+ KEY_PASSWD + " text not null,"
+KEY_ADMIN + " integer not null,"
+ KEY_U_PHONE + " text not null" + ")"; //<<<< SPACE ADDED before text not null
然后您需要执行以下操作之一: -
然后重新运行App。
错误,即没有电话列,在堆栈跟踪中显而易见,如下所示: -
04-08 12:02:18.919 1373-1373/? E/SQLiteLog: (1) table users has no column named phone
04-08 12:02:18.919 1373-1373/? E/SQLiteDatabase: Error inserting passwd=792863 phone=0799504863 isAdmin=1 name=TRUST
android.database.sqlite.SQLiteException: table users has no column named phone (code 1): , while compiling: INSERT INTO users(passwd,phone,isAdmin,name) VALUES (?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
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:1467)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
at soanswers.soanswers.DBAdapter$DatabaseHelper.onCreate(DBAdapter.java:254)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
at soanswers.soanswers.DBAdapter.open(DBAdapter.java:123)
at soanswers.soanswers.MainActivity.SO49717212(MainActivity.java:70)
at soanswers.soanswers.MainActivity.onCreate(MainActivity.java:20)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
04-08 12:02:18.927 1373-1373/? E/SQLiteLog: (1) no such column: phone
04-08 12:02:18.927 1373-1373/? D/AndroidRuntime: Shutting down VM
04-08 12:02:18.927 1373-1373/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa6261288)
04-08 12:02:18.927 1373-1373/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{soanswers.soanswers/soanswers.soanswers.MainActivity}: android.database.sqlite.SQLiteException: no such column: phone (code 1): , while compiling: SELECT DISTINCT id, name, passwd, isAdmin, phone FROM users
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteException: no such column: phone (code 1): , while compiling: SELECT DISTINCT id, name, passwd, isAdmin, phone FROM users
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032)
at soanswers.soanswers.DBAdapter.getAllUsersRows(DBAdapter.java:203)
at soanswers.soanswers.MainActivity.SO49717212(MainActivity.java:72)
at soanswers.soanswers.MainActivity.onCreate(MainActivity.java:20)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)