在SQLite中有数据输入错误

问题描述 投票:0回答:1

我一直试图让这个数据库运行4天并出现同样的错误。我已经耗尽了所有资源。谁知道这里发生了什么?此代码在我的主要活动上。

public static SQLiteHelper sqLiteHelper;

final int REQUEST_CODE_GALLERY = 999;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    init();

    sqLiteHelper = new SQLiteHelper(this, "FoodDB.sqlite", null, 1);

    sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS FOOD (Id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, image BLOG)");

    btnChoose.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ActivityCompat.requestPermissions(
                    MainActivity.this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    REQUEST_CODE_GALLERY
            );
        }
    });

    btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            try {
                sqLiteHelper.insertData(
                        edtName.getText().toString().trim(),
                        edtPrice.getText().toString().trim(),
                        imageViewToByte(imageView)

                );
                Toast.makeText(getApplicationContext(), "Entry Added", Toast.LENGTH_LONG).show();
                edtName.setText("");
                edtPrice.setText("");
                imageView.setImageResource(R.mipmap.ic_launcher);
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    });
    btnList.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this, FoodList.class);
            startActivity(intent);
        }
    });
}

private byte[] imageViewToByte(ImageView image) {
    Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] byteArray = stream.toByteArray();
    return byteArray;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if(requestCode == REQUEST_CODE_GALLERY) {
        if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(intent, REQUEST_CODE_GALLERY);
        }
        else {
            Toast.makeText(getApplicationContext(), "Permission Denied", Toast.LENGTH_LONG).show();
        }
        return;
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if(requestCode == REQUEST_CODE_GALLERY && resultCode == RESULT_OK && data != null) {
        Uri uri = data.getData();
        try {
            InputStream inputStream = getContentResolver().openInputStream(uri);

            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            imageView.setImageBitmap(bitmap);
        }
        catch (FileNotFoundException e){
            e.printStackTrace();
        }

    }

    super.onActivityResult(requestCode, resultCode, data);

}

private void init() {
     edtName = (EditText) findViewById(R.id.edtName);
     edtPrice = (EditText) findViewById(R.id.edtPrice);
     btnChoose = (Button) findViewById(R.id.btnChoose);
     btnAdd = (Button) findViewById(R.id.btnAdd);
     btnList = (Button) findViewById(R.id.btnList);
     imageView = (ImageView) findViewById(R.id.imageView);

}

}

这是我的SQLite Helper。我对SQLite很新,所以我为无知而道歉。

public class SQLiteHelper extends SQLiteOpenHelper {

public SQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, name, factory, version);


}
public void queryData(String sql) {
    SQLiteDatabase database = getWritableDatabase();
    database.execSQL(sql);
}

public void insertData(String name, String price, byte[] image) {
    SQLiteDatabase database = getWritableDatabase();
    String sql = "INSERT INTO FOOD VALUES (NULL, ?, ?, ?)";

    SQLiteStatement statement = database.compileStatement(sql);
    statement.clearBindings();

    statement.bindString(1, name);
    statement.bindString(2, price);
    statement.bindBlob(3, image);

    statement.executeInsert();
}
public Cursor getData(String sql) {
    SQLiteDatabase database = getReadableDatabase();
    return database.rawQuery(sql, null);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {

}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

}
}

这是我的logcat读数。

12-18 17:17:12.468 3678-3678/stash.media.devsolutionsbeyond.sqlite W/System.err: 

#################################################################
12-18 17:17:12.468 3678-3678/stash.media.devsolutionsbeyond.sqlite W/System.err: Error Code : 1 (SQLITE_ERROR)
12-18 17:17:12.468 3678-3678/stash.media.devsolutionsbeyond.sqlite W/System.err: Caused By : SQL(query) error or missing database.
12-18 17:17:12.468 3678-3678/stash.media.devsolutionsbeyond.sqlite W/System.err:    (table FOOD has 3 columns but 4 values were supplied (code 1): , while compiling: INSERT INTO FOOD VALUES (NULL, ?, ?, ?))
12-18 17:17:12.468 3678-3678/stash.media.devsolutionsbeyond.sqlite W/System.err: #################################################################
12-18 17:17:12.469 3678-3678/stash.media.devsolutionsbeyond.sqlite W/System.err:     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
12-18 17:17:12.469 3678-3678/stash.media.devsolutionsbeyond.sqlite W/System.err:     at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1008)
12-18 17:17:12.469 3678-3678/stash.media.devsolutionsbeyond.sqlite W/System.err:     at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:573)
12-18 17:17:12.469 3678-3678/stash.media.devsolutionsbeyond.sqlite W/System.err:     at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
12-18 17:17:12.469 3678-3678/stash.media.devsolutionsbeyond.sqlite W/System.err:     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
12-18 17:17:12.469 3678-3678/stash.media.devsolutionsbeyond.sqlite W/System.err:     at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
12-18 17:17:12.469 3678-3678/stash.media.devsolutionsbeyond.sqlite W/System.err:     at android.database.sqlite.SQLiteDatabase.compileStatement(SQLiteDatabase.java:1306)
12-18 17:17:12.469 3678-3678/stash.media.devsolutionsbeyond.sqlite W/System.err:     at stash.media.devsolutionsbeyond.sqlite.SQLiteHelper.insertData(SQLiteHelper.java:29)
12-18 17:17:12.469 3678-3678/stash.media.devsolutionsbeyond.sqlite W/System.err:     at stash.media.devsolutionsbeyond.sqlite.MainActivity$2.onClick(MainActivity.java:63)
12-18 17:17:12.469 3678-3678/stash.media.devsolutionsbeyond.sqlite W/System.err:     at android.view.View.performClick(View.java:6207)
12-18 17:17:12.469 3678-3678/stash.media.devsolutionsbeyond.sqlite W/System.err:     at android.widget.TextView.performClick(TextView.java:11094)
12-18 17:17:12.469 3678-3678/stash.media.devsolutionsbeyond.sqlite W/System.err:     at android.view.View$PerformClick.run(View.java:23639)
12-18 17:17:12.469 3678-3678/stash.media.devsolutionsbeyond.sqlite W/System.err:     at android.os.Handler.handleCallback(Handler.java:751)
12-18 17:17:12.469 3678-3678/stash.media.devsolutionsbeyond.sqlite W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
12-18 17:17:12.469 3678-3678/stash.media.devsolutionsbeyond.sqlite W/System.err:     at android.os.Looper.loop(Looper.java:154)
12-18 17:17:12.469 3678-3678/stash.media.devsolutionsbeyond.sqlite W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6688)
12-18 17:17:12.469 3678-3678/stash.media.devsolutionsbeyond.sqlite W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
12-18 17:17:12.469 3678-3678/stash.media.devsolutionsbeyond.sqlite W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
12-18 17:17:12.469 3678-3678/stash.media.devsolutionsbeyond.sqlite W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
12-18 17:17:12.469 3678-3678/stash.media.devsolutionsbeyond.sqlite I/Choreographer: Skipped 513 frames!  The application may be doing too much work on its main thread.
java android android-sqlite
1个回答
0
投票

在运行App之前,可以添加价格列或将insertData方法更改为: -

public void insertData(String name, String price, byte[] image) {
    SQLiteDatabase database = getWritableDatabase();
    String sql = "INSERT INTO FOOD VALUES (null, ?, ?)";

    SQLiteStatement statement = database.compileStatement(sql);
    statement.clearBindings();

    statement.bindString(1, name);
    //statement.bindString(2, price); //<<<< needs price column
    statement.bindBlob(2, image);

    statement.executeInsert();
}

上面的代码对我有用,至少在添加一个条目时(虽然我确实使用了以下内容来避免Null Pointer Exception并且还避免获取图像): -

                sqLiteHelper.insertData(
                        edtName.getText().toString().trim(),
                        edtPrice.getText().toString().trim(),
                        new byte[]{1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9}
                        //imageViewToByte(imageView)

                );

而不是有一个图像。也许最初使用它作为它所代表的要添加的图像可以为null(即,您应该在插入之前验证输入。)

添加价格列

如果你去添加价格列路线然后删除应用程序的数据或卸载应用程序,然后更改: -

sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS FOOD (Id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, image BLOG)");

sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS FOOD (Id INTEGER PRIMARY KEY, name TEXT, price TEXT image BLOG)");

笔记!

© www.soinside.com 2019 - 2024. All rights reserved.