Android数据库应用程序在模拟器上运行正常,但在设备上出错

时间:2013-12-04 05:37:25

标签: 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文件复制到设备时以及安装后我运行时该应用程序并尝试登录它显示无效的用户信息。

3 个答案:

答案 0 :(得分:1)

切换到DDMS透视图并检查此位置是否存在db /data/data/YOUR_APP/databases/YOUR_DATABASAE.db

答案 1 :(得分:0)

我将您的代码更改为:

  public void insertValues(int uid,String uname,int pass,String first,String     last,String type,int date){
    SQLiteDatabase db= this.getWritableDatabase();
    ContentValues cv=new ContentValues();
    cv.put(KEY_USERID, uid);
    cv.put(KEY_USERNAME,uname);
    cv.put(KEY_USERPSWD,pass);
    cv.put(KEY_FIRSTNAME, first);
    cv.put(KEY_LASTNAME, last);
    cv.put(KEY_USERTYPE,type);
    cv.put(KEY_CREATED_AT, date);
    db.insert(TABLE_USERS, null, cv);
}

在HomeloginActivity中我手动插入记录:

dbh.insertValues(101,"mohit",123,"mohit", "mohit","1", 12);

并输入用户名:mohit密码:123

它对我来说很好,并且能够登录。

在上面的代码

中看起来像您的UsersCredential有些问题

答案 2 :(得分:0)

我找到了问题的解决方案。上面的代码是正确的,工作正常。
问题:当我在设备上安装时,我的数据库表中没有数据 当我们部署任何包含数据库和数据的Android应用程序时,那时只在设备上创建数据库,最初将没有数据,所以我们需要从服务器执行一些Insert操作或Synchronization将数据导入设备DB

在我的应用程序中,我是来自服务器的Sync数据,因此在同步之后,它在设备上也能正常工作。
希望这对Newbies有用。