0

im inserting some field to sqlite and inserting works fine while updating the same field the values are retrieving to edittext but not updating with upadte button please give me perfect solution and its showing error like no column. they is no problem with insert and delete but not update please provide me solution.

thank you in advance

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

  • Where you create your table `PRINCIPALS`? I don't see any code – Md. Asaduzzaman Jan 02 '20 at 10:30
  • teacher table only the principle – sahana valli Jan 02 '20 at 10:38
  • I want to know did you create table `PRINCIPALS` yet with `CREATE TABLE PRINCIPALS ... `? I don't see any code like that – Md. Asaduzzaman Jan 02 '20 at 10:39
  • //creating database databaseEvent = new DatabaseEvent(this,"PRINCIPALEVENTDB.sqlite",null,1); //creating table databaseEvent.queryData("CREATE TABLE IF NOT EXISTS PRINCIPAL (id INTEGER PRIMARY KEY AUTOINCREMENT, selectname VARCHAR, eventname VARCHAR, eventorg VARCHAR, eventdays VARCHAR, eventstart VARCHAR, image BLOB)"); – sahana valli Jan 02 '20 at 10:43

2 Answers2

0

I think you modified the database scheme after the first install of the app.

You have to write an update script from the old version of the Database to the new version. (ALTER TABLE tablename ADD COLUMN ....)

Or delete and install the app again.

Naveed Abbas
  • 220
  • 3
  • 10
0

During update your column name is not match with table actual column name. Try below:

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

There are two mismatch in column between create and update sql

name should be selectname

eventorganization should be eventorg

Also your table name PRINCIPALS not match with PRINCIPAL.

Md. Asaduzzaman
  • 14,963
  • 2
  • 34
  • 46