简体   繁体   English

Android数据库应用程序在模拟器上运行良好,但在设备上显示错误

[英]Android database application runs fine on emulator but gives an error on the device

I've created a simple database Android app. 我创建了一个简单的数据库Android应用程序。 When I debug or run my application on the Emulator it works fine (ie it reads and writes the database) but when I run it on the device it is unable to read and write the db. 当我在模拟器上调试或运行我的应用程序时,它可以正常工作(即,它可以读写数据库),但是当我在设备上运行它时,则无法读取和写入数据库。 I think I've to update my DatabaseHelper class. 我想我必须更新我的DatabaseHelper类。 can anyone help me out... DatabaseHelper.java 谁能帮帮我... 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);
    }
}

I'm calling following statement in my HomeLoginActivity.java to create the database. 我在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);
    }
}

When I run my app on the Emulator and try to login using userDetails present in the database, its works fine and gets logged in, but when I copy the .apk file to the device and after installation when I run the app and try to login it shows Invalid UserInformation. 当我在模拟器上运行我的应用程序并尝试使用数据库中存在的userDetails登录时,它可以正常工作并获得登录,但是当我将.apk文件复制到设备上并在安装后运行该应用程序并尝试登录时它显示无效的UserInformation。

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

i changed your code to this: 我将您的代码更改为此:

  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);
}

In HomeloginActivity i manually inserted record: 在HomeloginActivity中,我手动插入了记录:

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

and entered username:mohit password:123 并输入用户名:mohit密码:123

it worked fine for me and was able to login. 它对我来说效果很好,并且能够登录。

looks like some problem with your UsersCredential in above code 上面的代码中的UsersCredential似乎有问题

I've found the solution for my question. 我已经找到了解决我问题的方法。 The code above is correct and works fine.. 上面的代码是正确的,并且可以正常工作。
The problem: There was no data in my database tables when I installed on the device. 问题:安装在设备上时,数据库表中没有数据。
When we deploy any Android application with database and data in it, that time only database is created on the device there will be no data initially, So we need to do some Insert Operation or Synchronization from the Server to get the data into the device DB . 当我们部署任何具有数据库和数据的Android应用程序时,那时仅在设备上创建数据库,最初将没有数据,因此我们需要从服务器执行一些Insert操作或Synchronization操作以将数据获取到设备DB

In my app I'm Sync data from the server, so After the Sync it was working fine on device as well. 在我的应用中,我正在Sync服务器中的数据,因此在同步之后,它在设备上也可以正常工作。
Hope this will be helpful for Newbies . 希望这对Newbies有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android应用程序可以在模拟器上正常运行,但不能在真实设备上运行 - Android Application works fine on emulator but not on a real device 我的Android应用程序在模拟器上运行,但无法在我的Android设备上运行 - My Android application runs on emulator but not working on my android device 应用程序在模拟器上运行正常,但在真实设备上崩溃 - App runs fine on emulator, but crashes on real device 应用程序在设备上运行,但在模拟器上崩溃? - Application runs on Device but crashes on Emulator? Android应用程序在模拟器上运行,在手机上崩溃 - Android Application Runs on Emulator, Crashes on Phone 模拟器运行正常,但应用程序显示白屏,错误如下 - emulator runs fine but app shows white screen, error is below Android设备上不在模拟器上的IndexOutOfBoundsException错误 - IndexOutOfBoundsException error on Android device not on emulator Android应用程序可以在模拟器中完美运行,但由于外部数据库而无法在设备上运行 - Android app runs perfectly in emulator but not on device due to external DB Android哈希代码不匹配:实际设备上出现onFacebookError,应用在模拟器上运行 - Android Hash code Mismatch : onFacebookError on actual device, app runs on emulator Android应用程序可在模拟器中运行,但无法在设备上运行 - Android application works in emulator but failed in device
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM