从预先存在的Android数据库中获取记录时,应用程序挂起

维布尔·卡什亚普(Vibhor Kashyap)

我有一个像这样的DatabaseHelper类:

public class DataBaseHelper extends SQLiteOpenHelper
{

// The Android's default system path of your application database.
private static String DB_PATH = android.os.Environment.getExternalStorageDirectory() + "/FitnessData/";

private static String DB_NAME = "OFSDb.db";

private SQLiteDatabase myDataBase;

private final Context myContext;

/**
 * Constructor Takes and keeps a reference of the passed context in order to
 * access to the application assets and resources.
 * 
 * @param context
 */
public DataBaseHelper(Context context)
{

    super(context, DB_NAME, null, 1);
    this.myContext = context;
}

/**
 * Creates a empty database on the system and rewrites it with your own
 * database.
 * */
public void createDataBase() throws IOException
{

    boolean dbExist = checkDataBase();

    if (dbExist)
    {
        // do nothing - database already exist
    }
    else
    {

        // By calling this method and empty database will be created into
        // the default system path
        // of your application so we are gonna be able to overwrite that
        // database with our database.
        this.getReadableDatabase();

        try
        {

            copyDataBase();

        }
        catch (IOException e)
        {

            throw new Error("Error copying database");

        }
    }

}

/**
 * Check if the database already exist to avoid re-copying the file each
 * time you open the application.
 * 
 * @return true if it exists, false if it doesn't
 */
private boolean checkDataBase()
{

    SQLiteDatabase checkDB = null;

    try
    {
        String myPath = DB_PATH + DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    }
    catch (SQLiteException e)
    {

        // database does't exist yet.

    }

    if (checkDB != null)
    {

        checkDB.close();

    }

    return checkDB != null ? true : false;
}

/**
 * Copies your database from your local assets-folder to the just created
 * empty database in the system folder, from where it can be accessed and
 * handled. This is done by transfering bytestream.
 * */



private void copyDataBase() throws IOException
{

    // Open your local db as the input stream
    InputStream myInput = myContext.getAssets().open(DB_NAME);

    // Path to the just created empty db
    String outFileName = DB_PATH + DB_NAME;

    // Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    // transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0)
    {
        myOutput.write(buffer, 0, length);
    }

    // Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

}

public void openDataBase() throws SQLException
{

    // Open the database
    String myPath = DB_PATH + DB_NAME;
    myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

}

@Override
public synchronized void close()
{

    if (myDataBase != null)
        myDataBase.close();

    super.close();

}

@Override
public void onCreate(SQLiteDatabase db)
{

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{

}

// Add your public helper methods to access and get content from the
// database.
// You could return cursors by doing "return myDataBase.query(....)" so it'd
// be easy
// to you to create adapters for your views.

public VehicleData getInfo(String regno)
{
    VehicleData vData = new VehicleData();
    String selectQuery = "SELECT  * FROM" + DB_NAME + " WHERE FIT_REF_NO = " + regno;
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst())
    {
        do
        {

            vData.regno = cursor.getString(1);
            vData.ownername = cursor.getString(2);
            vData.makername = cursor.getString(3);
            vData.makermodel = cursor.getString(4);
        }
        while (cursor.moveToNext());

    }

    return vData;

}

}

VehicleData类类似于:

public class VehicleData
{
public String regno;
public String ownername;
public String makername;
public String makermodel;
public String picsnum;
public String status;

}

我尝试使用Database Helper中的方法的类如下所示:

public class Reference extends Activity
{
public static String rslt = "";
public static String picsNumber = "";
public static String ipAdress;
Button bproceed;
Button bSendRef;
TextView regno;
TextView ownername;
TextView vmake;
TextView vmodel;
DataBaseHelper controller;

@Override
protected void onCreate(Bundle savedInstanceState)
{

    super.onCreate(savedInstanceState);
    setContentView(R.layout.reference);
    // set color for fields
    regno = ((TextView) findViewById(R.id.regnum));
    regno.setTextColor(Color.parseColor("#34afdd"));
    ownername = (TextView) findViewById(R.id.ownername);
    ownername.setTextColor(Color.parseColor("#34afdd"));
    vmake = ((TextView) findViewById(R.id.vmake));
    vmake.setTextColor(Color.parseColor("#34afdd"));
    vmodel = ((TextView) findViewById(R.id.vmodel));
    vmodel.setTextColor(Color.parseColor("#34afdd"));
    HideStaticTexts();
    final TextView tvNotif = (TextView) findViewById(R.id.tvNotif);
    tvNotif.setVisibility(View.INVISIBLE);
    // disable proceed button until data recieved from web service
    bproceed = (Button) findViewById(R.id.bproceed);
    bSendRef = (Button) findViewById(R.id.bSendRef);
    bproceed.setEnabled(false);
    bproceed.setClickable(false);
    /* Get data Against Ref Number using button Submit */


    DataBaseHelper myDbHelper = new DataBaseHelper(this);


    try
    {

        myDbHelper.createDataBase();

    }
    catch (IOException ioe)
    {

        throw new Error("Unable to create database");

    }

    try
    {

        myDbHelper.openDataBase();

    }
    catch (SQLException sqle)
    {

        throw sqle;

    }

    // handling send from keyboard
    final EditText edt = (EditText) findViewById(R.id.editText1);
    edt.setOnEditorActionListener(new OnEditorActionListener()
    {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
        {
            boolean handled = false;
            if (actionId == EditorInfo.IME_ACTION_SEND)
            {
                bSendRef.callOnClick();
                handled = true;
            }
            return handled;
        }
    });

    ((Button) findViewById(R.id.bSendRef)).setOnClickListener(new View.OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            // TODO Auto-generated method stub
            String searchUser = edt.getText().toString();
            VehicleData response = controller.getInfo(searchUser);

            ShowStaticTexts();

            ((TextView) findViewById(R.id.regnumval)).setText(response.regno); /*
                                                                                 * Regn
                                                                                 * No
                                                                                 */
            ((TextView) findViewById(R.id.ownerNameVal)).setText(response.ownername); /*
                                                                                     * Owner
                                                                                     * name
                                                                                     */
            ((TextView) findViewById(R.id.vehicleMakeVal)).setText(response.makername); /*
                                                                                         * Manufacturer
                                                                                         * Name
                                                                                         */
            ((TextView) findViewById(R.id.vehicleModelVal)).setText(response.makermodel); /*
                                                                                         * Maker
                                                                                         * Name
                                                                                         */
            picsNumber = response.picsnum;
            Toast.makeText(Reference.this.getApplicationContext(), picsNumber + " images will be clicked", Toast.LENGTH_LONG).show();
            tvNotif.setVisibility(View.VISIBLE);
            tvNotif.setText(picsNumber + " IMAGES WILL BE CLICKED ");
            bproceed.setEnabled(true);
            bproceed.setClickable(true);

        }

    });
    /* Start Camera Using Proceed Button */
    bproceed.setOnClickListener(new View.OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            // TODO Auto-generated method stub
            if (picsNumber.equals("4"))
            {
                Intent intent = new Intent(Reference.this, Camera.class);
                // ---use putExtra() to add new key/value pairs---
                intent.putExtra("refnum", ((EditText) findViewById(R.id.editText1)).getText().toString());
                intent.putExtra("regno", ((TextView) findViewById(R.id.regnumval)).getText().toString());
                intent.putExtra("picnum", picsNumber);
                startActivity(intent);
                finish();
            }
            else
            {
                Intent intent = new Intent(Reference.this, Camera2.class);
                // ---use putExtra() to add new key/value pairs---
                intent.putExtra("refnum", ((EditText) findViewById(R.id.editText1)).getText().toString());
                intent.putExtra("regno", ((TextView) findViewById(R.id.regnumval)).getText().toString());
                intent.putExtra("picnum", picsNumber);
                startActivity(intent);
                finish();

            }

        }
    });
    /* Clear form using Clear Button */
    ((Button) findViewById(R.id.bclear)).setOnLongClickListener(new OnLongClickListener()
    {
        @Override
        public boolean onLongClick(View v)
        {
            // TODO Auto-generated method stub
            Intent intent = new Intent(Reference.this, Settings.class);
            String reset = "RESET";
            intent.putExtra("reSet", reset);
            startActivity(intent);
            return true;
        }
    });

    /* Clear All Controls Using Clear Button */
    ((Button) findViewById(R.id.bclear)).setOnClickListener(new View.OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            ((EditText) findViewById(R.id.editText1)).setText("");
            clearAllControls();
            // force keyboard to show up when reset is called
            edt.requestFocus();
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(edt, InputMethodManager.SHOW_IMPLICIT);
            tvNotif.setVisibility(View.INVISIBLE);
            HideStaticTexts();

        }

    });
}

private void HideStaticTexts()
{
    // TODO Auto-generated method stub
    regno.setVisibility(View.INVISIBLE);
    ownername.setVisibility(View.INVISIBLE);
    vmake.setVisibility(View.INVISIBLE);
    vmodel.setVisibility(View.INVISIBLE);
}

private void ShowStaticTexts()
{
    // TODO Auto-generated method stub
    regno.setVisibility(View.VISIBLE);
    ownername.setVisibility(View.VISIBLE);
    vmake.setVisibility(View.VISIBLE);
    vmodel.setVisibility(View.VISIBLE);
}

public void clearAllControls()
{
    ((TextView) findViewById(R.id.regnumval)).setText("");
    ((TextView) findViewById(R.id.ownerNameVal)).setText("");
    ((TextView) findViewById(R.id.vehicleMakeVal)).setText("");
    ((TextView) findViewById(R.id.vehicleModelVal)).setText("");

}

public static void hideSoftKeyboard(Activity activity, View view)
{
    InputMethodManager imm = (InputMethodManager)        activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);
}

}

当我在editText中输入字符串并按下按钮时,应用程序挂起。甚至无法读取LogCat。请帮我?

Phantômaxx

"SELECT * FROM" + DB_NAME + " WHERE FIT_REF_NO = " + regno;……崩溃!

1-在FROM
2之后您错过了一个空格-DB_NAME应该是YOUR_TABLE_NAME

尝试:

"SELECT  * FROM " + YOUR_TABLE_NAME + " WHERE FIT_REF_NO = " + regno;

另请注意,列基于0我希望您没有检索到另一个索引为0的列

if (cursor.moveToFirst())
{
    do
    {
        //vData.XYX = cursor.getString(0);
        vData.regno = cursor.getString(1);
        vData.ownername = cursor.getString(2);
        vData.makername = cursor.getString(3);
        vData.makermodel = cursor.getString(4);
    }
    while (cursor.moveToNext());

但是,按索引检索列值不是一件好事,尤其是如果您使用星号(*)代替指定字段名(永远不能保证总是将列提取到列集中的某个位置)。
您可以选择或者两者兼而有之:

1-指定所有列名称insetad为*,以确保按此顺序获取它们。
2-使用cursor.getString(cursor.getColumnIndex(“ columnName”));

此外,如果regnostring,则应将其值用单引号引起来,例如:

"SELECT  * FROM " + YOUR_TABLE_NAME + " WHERE FIT_REF_NO = '" + regno + "'";

但是,如果您绑定参数那就更好,例如:

"SELECT  * FROM " + YOUR_TABLE_NAME + " WHERE FIT_REF_NO = ?";
//...
Cursor cursor = db.rawQuery(selectQuery, new String[]{regno});

希望我能帮上忙。

[编辑]

指定数据库路径绝不是一个好主意。
Android在其默认路径下自动处理数据库:

/data/data/your.app.name/databases/your.db

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Android应用程序。从数据库中获取数据

更新应用程序,覆盖android中预先填充的新数据库

预先创建的 SQLite 数据库集成到 android 应用程序中

向预先存在的Qt应用程序添加表单

Django - 访问 mySQL 数据库中预先存在的数据

如何在Visual Studio for Mac中打开预先存在的.NET Core应用程序?

从Android应用程序获取SQLite数据库

从android应用程序获取数据并将其存储在使用php的sql数据库中

如何从数据库中获取数据而不刷新Android应用程序?

Android应用程序未保存在mysql数据库中

在Android的SQLite数据库中插入数据时,应用程序崩溃

仅当我的应用程序未托管在预先存在的路径上时,资产才能正确映射

从 Android 应用程序中的数据库获取表名列表

更新我的Android应用程序中的数据库

将上传的数据获取到 android studio 上的 firebase 实时数据库时,应用程序崩溃

Android应用程序从服务器检索数据,保存在数据库中并显示给用户

哪些方法可用于管理不同版本的预先存在的数据库?

使用Flask,python和postgresql,如何连接到预先存在的数据库?

如何在预先存在的SQL数据库之上使用Elastic Search?

Sqlalchemy; 将主键设置为预先存在的数据库表(不使用sqlite)

IdentityServer 4和预先存在的SQL Server数据库

从iOS捆绑包访问预先存在的数据库(只读)

从数据收集应用程序记录数据库中的设备ID

Windows Store应用程序中无法删除Sqlite数据库中的记录

我应该从我的应用程序将哪些数据保存在Sqlite数据库中?

具有预先填充的sqlite数据库的iOS船运应用程序

LINQ 更新查询不会更新 Xamarin 表单应用程序中的数据库记录

使用在不同节点上运行的应用程序处理数据库中的记录

在RSpec + Factory Girl中在哪里创建应用程序范围的数据库记录?