簡體   English   中英

Android Studio:應用未保存到數據庫或從數據庫中讀取

[英]Android Studio: app not saving to/reading from database

所以我的應用是QR碼掃描儀。 當前,它將讀取QR碼並將其顯示給用戶。 我想要將其保存到數據庫中,然后繼續從中讀取。 目前,它不執行最后兩個操作,而我正在努力找出導致問題的原因-保存到數據庫還是從數據庫中讀取。

我的數據庫代碼是這樣的:

public class Database {
    private static final String DATABASE_NAME = "QRCodeScanner";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_NAME = "codes";

    private OpenHelper mDbHelper;
    private SQLiteDatabase mDb;
    private final Context dbContext;

    private static final String DATABASE_CREATE =
            "CREATE TABLE " + TABLE_NAME + " (" +
                    "codeid INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    "code TEXT NOT NULL);";

    public Database(Context ctx) {
        this.dbContext = ctx;
    }

    public Database open() throws SQLException {
        mDbHelper = new OpenHelper(dbContext);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }

    public boolean createUser(String code) {
        ContentValues initialValues = new ContentValues();
        initialValues.put("codes", code);

        return mDb.insert(TABLE_NAME, null, initialValues) > 0;
    }


    public ArrayList<String[]> fetchUser(String code) throws SQLException {

        ArrayList<String[]> myArray = new ArrayList<String[]>();

        int pointer = 0;

        Cursor mCursor = mDb.query(TABLE_NAME, new String[] {"codeid", "code",
                        }, "code LIKE '%" + code + "%'", null,
                null, null, null);

        int codeNameColumn = mCursor.getColumnIndex("code");


        if (mCursor != null){
            if (mCursor.moveToFirst()){
                do {
                    myArray.add(new String[3]);
                    myArray.get(pointer)[0] = mCursor.getString(codeNameColumn);
                    pointer++;
                } while (mCursor.moveToNext());
            } else {
                myArray.add(new String[3]);
                myArray.get(pointer)[0] = "NO RESULTS";
                myArray.get(pointer)[1] = "";
            }
        }

        return myArray;

    }

    public ArrayList<String[]> selectAll() {

        ArrayList<String[]> results = new ArrayList<String[]>();


        int counter = 0;

        Cursor cursor = this.mDb.query(TABLE_NAME, new String[] { "codeid", "codes" }, null, null, null, null, "codeid");

        if (cursor.moveToFirst()) {
            do {
                results.add(new String[3]);
                results.get(counter)[0] = cursor.getString(0);
                counter++;
            } while (cursor.moveToNext());
        }
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }

        return results;
    }


    private static class OpenHelper extends SQLiteOpenHelper {

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

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
            onCreate(db);
        }
    }
}

我的主要Java代碼是這個。

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private Button Scan;
private ArrayList<String[]> viewall;
private TextView QR_output;
private IntentIntegrator ScanCode;
private ListView lv;
private ArrayList Search = new ArrayList();
ArrayList<String[]> searchResult;

Database dbh;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // this caused an error on earlier APKs which made the app switch from 17 to 27
    setContentView(R.layout.activity_main);

    // Defines the Scan button
    Scan = findViewById(R.id.Scan);
    // defines the output for text
    QR_output = findViewById(R.id.QR_Output);

    // looks for the user clicking "Scan"
    Scan.setOnClickListener(this);

    ScanCode = new IntentIntegrator(this);
    // Means the scan button will actually do something
    Scan.setOnClickListener(this);

    lv = findViewById(R.id.list);

    dbh = new Database(this);
    dbh.open();

}

public void displayAll(View v){

    Search.clear();
    viewall = dbh.selectAll();
    String surname = "", forename = "";

    for (int count = 0 ; count < viewall.size() ; count++) {
        code = viewall.get(count)[1];
        Search.add(surname + ", " + forename);
    }
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
            this,
            android.R.layout.simple_list_item_1,
            Search);

    lv.setAdapter(arrayAdapter);
}




// will scan the qr code and reveal its secrets
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
    if (result != null) {
        // if an empty QR code gets scanned it returns a message to the user
        if (result.getContents() == null) {
            Toast.makeText(this, "This QR code is empty.", Toast.LENGTH_LONG).show();
        } else try {
            // converts the data so it can be displayed
            JSONObject obj = new JSONObject(result.getContents());
            // this line is busted and does nothing
            QR_output.setText(obj.getString("result"));
        } catch (JSONException e) {
            e.printStackTrace();
                String codes = result.getContents();
                boolean success = false;

                success = dbh.createUser(codes);
            // outputs the data to a toast
            Toast.makeText(this, result.getContents(), Toast.LENGTH_LONG).show();
        }
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

@Override
public void onClick(View view) {
    // causes the magic to happen (It initiates the scan)
    ScanCode.initiateScan();
}

}

您的問題很可能與initialValues.put("codes", code); 因為根據您的表定義,沒有列稱為code ,而列名似乎是code

因此,使用initialValues.put("code", code); 可能會很好地解決問題。

附加的

強烈建議您在代碼中為所有命名項(表,列,視圖觸發器等)定義並隨后使用常量,因此該值將始終相同。

例如

private static final String DATABASE_NAME = "QRCodeScanner";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "codes";
public static final String COLUMN_CODEID = "codeid"; //<<<<<<<<< example note making public allows the variable to be used elsewhere
public static final String COLUMN_CODE = "code";   //<<<<<<<<<< another example

private OpenHelper mDbHelper;
private SQLiteDatabase mDb;
private final Context dbContext;

private static final String DATABASE_CREATE =
        "CREATE TABLE " + TABLE_NAME + " (" +
                COLUMN_CODEID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + //<<<<<<<<<<
                COLUMN_CODE + " TEXT NOT NULL);"; //<<<<<<<<<<

........ other code omitted for brevity

public boolean createUser(String code) {
    ContentValues initialValues = new ContentValues();
    initialValues.put(COLUMN_CODE, code); //<<<<<<<<<< CONSTANT USED

    return mDb.insert(TABLE_NAME, null, initialValues) > 0;
}

通過從Cursor提取數據而不是使用Cursor getColumnIndex方法提供偏移量時,不使用硬編碼的列偏移量,也可能會遇到較少的問題。

例如代替:-

results.get(counter)[0] = cursor.getString(0);

最好使用:-

results.get(counter)[0] = cursor.getString(cursor.getColumnIndex(COLUMN_CODEID));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM