java - Android sqlite数据库更新查询时没有这样的列

标签 java android android-sqlite multiple-columns logcat

我将一些字段插入到sqlite中,并且在更新同一字段时插入工作正常,值正在检索到edittext但没有使用upadte按钮进行更新,请给我完美的解决方案及其显示错误,例如没有列。他们插入和删除没有问题,但更新没有问题,请给我解决方案。

提前谢谢

public class DatabaseEvent extends SQLiteOpenHelper {


   public DatabaseEvent(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);
    }

    //insertData
    public void inserteacher(String name,String eventname,String eventorganization,String eventdays,String eventstart, byte[] image){
        SQLiteDatabase database=getWritableDatabase();
        String sql="INSERT INTO PRINCIPALS VALUES (NULL,?, ?, ?, ?, ?, ?)";

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

        statement.bindString(1,name);
        statement.bindString(2,eventname);
        statement.bindString(3,eventorganization);
        statement.bindString(4,eventdays);
        statement.bindString(5,eventstart);
        statement.bindBlob(6,image);

        statement.executeInsert();

    }

    public Cursor getData(String sql){
        SQLiteDatabase database=getReadableDatabase();
        return database.rawQuery(sql,null);
    }

    //updatedata

    public void updateData(String name,String eventname,String eventorganization,String eventdays,String eventstart, byte[] image, int id){
        SQLiteDatabase database=getWritableDatabase();
        //query to upadte
        String sql = "UPDATE PRINCIPALS SET name=?, eventname=?, eventorganization=?, eventdays=?, eventstart=?, image=? WHERE id=? ";

        SQLiteStatement statement=database.compileStatement(sql);

        statement.bindString(1,name);
        statement.bindString(2,eventname);
        statement.bindString(3,eventorganization);
        statement.bindString(4,eventdays);
        statement.bindString(5,eventstart);
        statement.bindBlob(6,image);
        statement.bindDouble(7,(double)id);

        statement.execute();
        database.close();

    }

    //deletedata

    public void deleteData(int id){
        SQLiteDatabase database=getWritableDatabase();
        //query to delete record using id
        String sql= "DELETE FROM PRINCIPALS WHERE id=?";

        SQLiteStatement statement=database.compileStatement(sql);
        statement.clearBindings();
        statement.bindDouble(1,(double) id);

        statement.execute();
        database.close();
    }



    @Override
    public void onCreate(SQLiteDatabase database) {


    }

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

    }


}

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {

                //alert dialog to display options of update and delete
                CharSequence[] items = {"Update", "Delete"};

                AlertDialog.Builder dialog = new AlertDialog.Builder(PrincipalEventListActivity.this);

                dialog.setTitle("Choose an action");
                dialog.setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (i == 0) {
                            //upadte
                            Cursor c = PrincipalEventActivity.databaseEvent.getData("SELECT id FROM PRINCIPALS ");
                            ArrayList<Integer> arrID = new ArrayList<>();
                            while (c.moveToNext()) {
                                arrID.add(c.getInt(0));
                            }
                            //show update diaglog
                            showDialogUpdate(PrincipalEventListActivity.this, arrID.get(position));
                        }
                        if (i == 1) {
                            //delete
                            Cursor c = PrincipalEventActivity.databaseEvent.getData("SELECT id FROM PRINCIPALS ");
                            ArrayList<Integer> arrID = new ArrayList<Integer>();
                            while (c.moveToNext()) {
                                arrID.add(c.getInt(0));
                            }
                            //show update diaglog
                            showDialogDelete(arrID.get(position));
                        }
                    }
                });
                dialog.show();
                //return true;
            }
        });

    }

    private void showDialogDelete(final int idrecord) {

        AlertDialog.Builder dialogDelete = new AlertDialog.Builder(PrincipalEventListActivity.this);
        dialogDelete.setTitle("Warning..!!!");
        dialogDelete.setMessage("Are You Sure..??");
        dialogDelete.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    PrincipalEventActivity.databaseEvent.deleteData(idrecord);
                    Toast.makeText(PrincipalEventListActivity.this, "Deleted Successfully", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    Log.e("error", e.getMessage());
                }
                updateRecordlist();
            }
        });
        dialogDelete.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialogDelete.show();
    }


    private void showDialogUpdate(Activity activity, final int position) {

        final Dialog dialog = new Dialog(activity);
        dialog.setContentView(R.layout.upadte_principal_dialog);
        dialog.setTitle("Update");

        imageViewicon = dialog.findViewById(R.id.imageviewrecord);
        final EditText edtselect = dialog.findViewById(R.id.editselect);
        final EditText edtname = dialog.findViewById(R.id.editname);
        final EditText edtorg = dialog.findViewById(R.id.editorg);
        final EditText edtdays = dialog.findViewById(R.id.editdays);
        final EditText editstart = dialog.findViewById(R.id.editstart);
        Button btnupdate = dialog.findViewById(R.id.btnprincipalupdate);

        //get all data from sqlite

        Cursor cursor = PrincipalEventActivity.databaseEvent.getData("SELECT * FROM PRINCIPALS WHERE id=" + position);
        mList.clear();
        while (cursor.moveToNext()) {
            int id = cursor.getInt(0);
            String select = cursor.getString(1);
            edtselect.setText(select);
            String name = cursor.getString(2);
            edtname.setText(name);
            String org = cursor.getString(3);
            edtorg.setText(org);
            String days = cursor.getString(4);
            edtdays.setText(days);
            String start = cursor.getString(5);
            editstart.setText(start);
            byte[] image = cursor.getBlob(6);
            imageViewicon.setImageBitmap(BitmapFactory.decodeByteArray(image, 0, image.length));

            //adding list

            mList.add(new Teacher_Event(id, select, name, org, days, start, image));

        }

        //set width of dialog
        final int width = (int) (activity.getResources().getDisplayMetrics().widthPixels * 0.95);
        //set height of dialog
        int height = (int) (activity.getResources().getDisplayMetrics().heightPixels * 0.7);
        dialog.getWindow().setLayout(width, height);
        dialog.show();

        //in update dialog click image to update image
        imageViewicon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //check external permission
                ActivityCompat.requestPermissions(PrincipalEventListActivity.this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 888);

            }
        });

        btnupdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    PrincipalEventActivity.databaseEvent.updateData(
                            edtselect.getText().toString().trim(),
                            edtname.getText().toString().trim(),
                            edtorg.getText().toString().trim(),
                            edtdays.getText().toString().trim(),
                            editstart.getText().toString().trim(),
                            PrincipalEventActivity.imageViewToByte(imageViewicon), position);
                    dialog.dismiss();
                    Toast.makeText(getApplicationContext(), "Update Successfully", Toast.LENGTH_SHORT).show();
                } catch (Exception error) {
                    Log.e("Update error", error.getMessage());
                }
                updateRecordlist();
            }
        });
    }


    private void updateRecordlist() {

        //get all data from sqlite
        Cursor cursor=PrincipalEventActivity.databaseEvent.getData("SELECT * FROM PRINCIPALS");
        mList.clear();
        while (cursor.moveToNext()){
            int id = cursor.getInt(0);
            String select=cursor.getString(1);
            String name = cursor.getString(2);
            String org =cursor.getString(3);
            String days = cursor.getString(4);
            String start=cursor.getString(5);
            byte[] image=cursor.getBlob(6);

            mList.add(new Teacher_Event(id, select, name, org, days, start, image));

        }
        Adapter.notifyDataSetChanged();
    }

    private  static 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==888){
            if(grantResults.length>0 && grantResults[0]== PackageManager.PERMISSION_GRANTED){
                //gallery intent
                Intent galleryintent=new Intent(Intent.ACTION_GET_CONTENT);
                galleryintent.setType("image/*");
                startActivityForResult(galleryintent,888);

            }else {
                Toast.makeText(this, "Dont have persmission", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

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

        if(requestCode==888 && resultCode==RESULT_OK){
            Uri imageuri =data.getData();
            try {
                Bitmap bitmap= MediaStore.Images.Media.getBitmap(getContentResolver(),imageuri);
                imageViewicon.setImageBitmap(bitmap);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}

my logcat

E/SQLiteLog: (1) 
E/Update error: no such column: name (Sqlite code 1 SQLITE_ERROR): , while compiling: UPDATE PRINCIPALS SET name=?, eventname=?, eventorganization=?, eventdays=?, eventstart=?, image=? WHERE id=?, (OS error - 11:Try again)
I/Choreographer: Skipped 42 frames!  The application may be doing too much work on its main thread.
E/: [ZeroHung]zrhung_get_config: Get config failed for wp[0x0008]
I/OpenGLRenderer: Davey! duration=764ms; Flags=0, IntendedVsync=284156144329502, Vsync=284156844329474, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=284156845468044, AnimationStart=284156845521169, PerformTraversalsStart=284156845522732, DrawStart=284156892294086, SyncQueued=284156894770648, SyncStart=284156894993044, IssueDrawCommandsStart=284156895272732, SwapBuffers=284156906992003, FrameCompleted=284156909328982, DequeueBufferDuration=340000, QueueBufferDuration=535000, 
W/libEGL: EGLNativeWindowType 0x7a9516f010 disconnect failed
W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed.
W/InputMethodManager: startInputReason = 1
D/ZrHung.AppEyeUiProbe: stop checker.
D/ViewRootImpl[PrincipalEventListActivity]: surface should not be released
D/ZrHung.AppEyeUiProbe: Current Activity:false
    not watching, wait.
W/libEGL: EGLNativeWindowType 0x7a951b3010 disconnect failed

最佳答案

更新期间,您的名称与表实际名称不匹配。请尝试以下操作:

String sql = "UPDATE PRINCIPAL SET selectname=?, eventname=?, eventorg=?, eventdays=?, eventstart=?, image=? WHERE id=? ";

createupdate sql 之间的列有两个不匹配

name should be selectname

eventorganization should be eventorg

此外,您的表名称 PRINCIPALSPRINCIPAL 不匹配。

关于java - Android sqlite数据库更新查询时没有这样的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59561742/

相关文章:

android - Sqlite 更新 DATETIME 字段不工作

Android SQLite LIKE 转义通配符

java - Jetty/Shiro 初始化错误 2013-06-01 03 :37:23. 574 :WARN:oejj. ObjectMBean:main:

java - 修改另一个类中的 ArrayList 对象值

java - 在 Google App Engine 上运行数据存储区查询

xml - Android XML 布局 - 一个屏幕上有 4 个 ImageView

Android 后退按钮和 fragment - 动画不起作用

android - 不完整的android appcompatfragmentsupport:缺少资源divider_horizo​​ntal_bright_opaque.9.png

android - SQLite 奇怪的行为

java - 如何从下拉 ListView javafx 8中获取文本框中的点击项目?