java - Android 数据库应用程序在模拟器上运行良好,但在设备上出现错误

标签 java android

我创建了一个简单的数据库 Android 应用程序。当我在模拟器上调试或运行我的应用程序时,它工作正常(即它读取和写入数据库),但是当我在设备上运行它时,它无法读取和写入数据库。我想我必须更新我的 DatabaseHelper 类。谁能帮我吗... DatabaseHelper.java

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.sush.myapp.data.model.UsersCredentials;

public class DatabaseHelper extends SQLiteOpenHelper {
    // Logcat tag
    //private static final String LOG = "DatabaseHelper";

    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "DemoDB.db";

    // Table Names
    private static final String TABLE_USERS = "Users";
    private static final String TABLE_SCORES = "Scores";
    private static final String TABLE_SYNCSTATUS = "SyncStatus";

    // Common column names
    private static final String KEY_ID = "id";
    private static final String KEY_CREATED_AT = "created_at";

    // USERS Table - column names
    private static final String KEY_USERID = "userID";
    private static final String KEY_USERNAME = "userName";
    private static final String KEY_USERPSWD = "userPswd";
    private static final String KEY_FIRSTNAME = "firstName";
    private static final String KEY_LASTNAME = "lastName";
    private static final String KEY_USERTYPE = "userType";

    // SCORES Table - column names
    private static final String KEY_USER_ID = "userID";
    private static final String KEY_GAME_ID = "gameID";
    private static final String KEY_SCORES = "scores";

    // SYNCSTATUS Table - column names
    private static final String KEY_STATRDATE = "startDate";
    private static final String KEY_ENDDATE = "endDate";
    private static final String KEY_STATUS = "status";

    // Table Create Statements
    // USERS table create statement
    private static final String CREATE_TABLE_USERS = "CREATE TABLE IF NOT EXISTS "
            + TABLE_USERS + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_USERID
            + " TEXT," + KEY_USERNAME + " INTEGER," + KEY_USERPSWD + " TEXT," 
            + KEY_FIRSTNAME + " TEXT," + KEY_LASTNAME + " TEXT," + KEY_USERTYPE + " INTEGER,"
            + KEY_CREATED_AT + " DATETIME" + ")";

    // Tag table create statement
    private static final String CREATE_TABLE_SCORES = "CREATE TABLE IF NOT EXISTS "
            + TABLE_SCORES + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_USER_ID 
            + " INTEGER," + KEY_GAME_ID + " INTEGER," + KEY_SCORES + " INTEGER," 
            + KEY_CREATED_AT + " DATETIME" + ")";

    // todo_tag table create statement
    private static final String CREATE_TABLE_SYNCSTATUS = "CREATE TABLE IF NOT EXISTS "
            + TABLE_SYNCSTATUS + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + KEY_STATRDATE + " DATETIME," + KEY_ENDDATE + " DATETIME," + KEY_STATUS + " INTEGER,"
            + KEY_CREATED_AT + " DATETIME" + ")";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // creating required tables
        db.execSQL(CREATE_TABLE_USERS);
        db.execSQL(CREATE_TABLE_SCORES);
        db.execSQL(CREATE_TABLE_SYNCSTATUS);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // on upgrade drop older tables
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_SCORES);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_SYNCSTATUS);
        // create new tables
        onCreate(db);
    }

    //Validate user for login, Return true if correct username and password else return false.
    public Cursor validateUserLogin(String uname, String pswd)
    {
        SQLiteDatabase db=this.getWritableDatabase();
        String[] whereArgs = new String[]{uname, pswd};
        String query = "SELECT "+KEY_USERID+", "+KEY_USERTYPE+" FROM "+TABLE_USERS+" WHERE "+KEY_USERNAME+" = ? AND "+KEY_USERPSWD+" = ?";
        Cursor cur= db.rawQuery(query, whereArgs);
        //Boolean b = cur.moveToFirst();
        if (cur.moveToFirst() == true)
            //return cur.getInt(cur.getColumnIndex(KEY_USERID));
            return cur;
        else
            return null;
    }

    //To get user full name by passing userID.
    public String getUserFullName(int uID)
    {
        SQLiteDatabase db=this.getWritableDatabase();
        String[] whereArgs = new String[]{Integer.toString(uID)};
        String query = "SELECT "+KEY_FIRSTNAME+" || ' ' || "+KEY_LASTNAME+" AS FullName FROM "+TABLE_USERS+" WHERE "+KEY_USERID+" = ?";
        Cursor cur= db.rawQuery(query, whereArgs);
        int index;
        if (cur.moveToFirst() == true)
        {
            index= cur.getColumnIndex("FullName");
            return cur.getString(index);
        }
        else
            return "";
    }

    //********************** CRUD for Users Table **********************//
    public void insertValues(UsersCredentials uc){
        SQLiteDatabase db= this.getWritableDatabase();
        ContentValues cv=new ContentValues();
        cv.put(KEY_USERID, uc.getUserID());
        cv.put(KEY_USERNAME, uc.getUserName());
        cv.put(KEY_USERPSWD, uc.getUserPassword());
        cv.put(KEY_FIRSTNAME, uc.getUserFirstName());
        cv.put(KEY_LASTNAME, uc.getUserLastName());
        cv.put(KEY_USERTYPE, uc.getUserType());
        cv.put(KEY_CREATED_AT, getDateTime());
        db.insert(TABLE_USERS, null, cv);
    }

    public void deleteRecords() {
        SQLiteDatabase db= this.getWritableDatabase();
        db.execSQL("delete from Users");
    }

    private String getDateTime() {
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "dd-MM-yyyy HH:mm:ss", Locale.getDefault());
        Date date = new Date();
        return dateFormat.format(date);
    }
}

我在 HomeLoginActivity.java 中调用以下语句来创建数据库。

@SuppressWarnings("deprecation")
public class HomeLoginActivity extends ActivityGroup {

    Button btnSinup;
    EditText user_ID;
    EditText user_pswd;
    SQLiteDatabase db;
    DatabaseHelper dbh;
    Cursor cur;
    String name;
    Intent intent;
    int uID, uType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home_login);
        //statement to Create/Open DB
        db = new DatabaseHelper(this).getWritableDatabase();

        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        dbh = new DatabaseHelper(getApplicationContext());
        user_ID = (EditText)findViewById(R.id.userID);
        user_pswd = (EditText)findViewById(R.id.userPswd);
        btnSinup =(Button)findViewById(R.id.btnLogin);
        btnSinup.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v) {
                if (user_ID.getText().toString().equals(""))
                {
                    Toast.makeText(v.getContext(), "Enter the user ID", Toast.LENGTH_SHORT).show();
                }
                else if (user_pswd.getText().toString().equals(""))
                {
                    Toast.makeText(v.getContext(), "Enter the password", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    try{
                        cur = dbh.validateUserLogin(user_ID.getText().toString(), user_pswd.getText().toString());
                        if(cur != null)
                        {
                            startManagingCursor(cur);
                            if(cur.moveToFirst())
                            {
                                uID = cur.getInt(0);
                                //Toast.makeText(v.getContext(), "uID = "+uID, Toast.LENGTH_SHORT).show();
                                uType = cur.getInt(1);
                                //Toast.makeText(v.getContext(), "uType = "+uType, Toast.LENGTH_SHORT).show();
                                cur.close();
                                name = dbh.getUserFullName(uID);
                                if(uType == 3) //Goto Admin Home
                                {
                                    //Toast.makeText(v.getContext(), "Name = "+name, Toast.LENGTH_SHORT).show();
                                    Intent adminHome = new Intent(v.getContext(), HomeAdminActivity.class);
                                    adminHome.putExtra("ID", uID);
                                    adminHome.putExtra("userFullName", name);
                                    replaceContentView("home_admin", adminHome);
                                }
                                else //Goto Users Home
                                {
                                    //Toast.makeText(v.getContext(), "Name = "+name, Toast.LENGTH_SHORT).show();
                                    Intent userHome = new Intent(v.getContext(), HomeUserActivity.class);
                                    userHome.putExtra("ID", uID);
                                    userHome.putExtra("userFullName", name);
                                    replaceContentView("home_user", userHome);
                                }
                            }
                            else
                            {
                                Toast.makeText(v.getContext(), "User not found", Toast.LENGTH_SHORT).show();
                                cur.close();
                            }
                        }
                        else
                        {
                            Toast.makeText(v.getContext(), "Invalid username or password", Toast.LENGTH_SHORT).show();
                            cur.close();
                        }
                    }catch(Exception e){
                        //cur.close();
                        //Toast.makeText(v.getContext(), "Error = "+e, Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    public void replaceContentView(String homeID, Intent homeIntent) {
        View view = getLocalActivityManager().startActivity(homeID,homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)) .getDecorView();
        this.setContentView(view);
    }
}

当我在模拟器上运行我的应用程序并尝试使用数据库中存在的 userDetails 登录时,它工作正常并登录,但是当我将 .apk 文件复制到设备后当我运行应用程序并尝试登录时安装显示无效的用户信息。

最佳答案

切换到 DDMS 视角并检查该位置是否存在数据库 /data/data/YOUR_APP/databases/YOUR_DATABASEE.db

关于java - Android 数据库应用程序在模拟器上运行良好,但在设备上出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20367753/

相关文章:

java - maven-install-plugin 如何与 pom 配置一起使用一次安装一些 jar

android - MPAndroidChart:如何隐藏图表背景?

Java:序列化 String[] 数组以存储在 MySQL 数据库中?

java - 如何在不使用打印机驱动程序的情况下将打印机连接到java应用程序

java - Spring 安全 "Remember Me"复选框

android webview - 设置引用(对于版本 < 2.2 aka Froyo)

android - Appcelerator titanium - 带进度条的闪屏

android - 在 recyclerView 的行内处理按钮单击

android - 为什么在测量自定义 View /布局时 MaterialAlertDialog 这么慢?

java - 用Java打印数据