Problems with Sqlitehelper

Asked

Viewed 57 times

0

Hello, I have a registration project and I’m having trouble reading Sqlitehelper, the app only runs without it, when I try to use gives error, the app turns off, if anyone can help me find where is the error thank you. follow the code, if anyone can help me... Thank you.

public class MainActivity extends AppCompatActivity {

public static SQLiteHelper mSQLiteHelper;

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

    mSQLiteHelper = new SQLiteHelper( this, "RECORDDB.sqlite",null,1 );
    mSQLiteHelper.queryData("CREATE TABLE IF NOT EXISTS RECORD(_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age VARCHAR, phone VARCHAR, image BLOB ");

List class

public class RecordListActivity extends AppCompatActivity {
ListView mListView;
ArrayList<Model> mList;
RecordListAdapter mAdapter = null;
ImageView imageViewIcon;

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

    mListView = findViewById( R.id.listView );
    mList = new ArrayList<>(  );
    mAdapter = new RecordListAdapter( this, R.layout.row, mList );
    mListView.setAdapter( mAdapter );

    Cursor cursor = MainActivity.mSQLiteHelper.getData( "SELECT * FROM RECORD" );
    mList.clear();
    while (cursor.moveToNext()){
        int id       = cursor.getInt   ( 0 );
        String name  = cursor.getString( 1 );
        String age   = cursor.getString( 2 );
        String phone = cursor.getString( 3 );
        byte[] image = cursor.getBlob  ( 4 );
        mList.add( new Model( id, name, age, phone, image ) );

    }
    mAdapter.notifyDataSetChanged();
    if(mList.size()==0){
        Toast.makeText( this,"No record found...",Toast.LENGTH_SHORT ).show();
    }
    mListView.setOnItemLongClickListener( new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view,  final int position, long id) {

        final CharSequence[] items = {"Update","Delete"};

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

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

     btnUpdate.setOnClickListener( new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                MainActivity.mSQLiteHelper.updateData(
                        edtName .getText().toString().trim(),
                        edtAge  .getText().toString().trim(),
                        edtPhone.getText().toString().trim(),
                        MainActivity.imageViewToByte( imageViewIcon ),
                        position
                );
                //dialog.dismiss();
                Toast.makeText( getApplicationContext(), "Update Successful", Toast.LENGTH_SHORT ).show();
            }
            catch (Exception error) {
                Log.e( "Update error", error.getMessage() );
            }
            updateRecordList();
        }
    });
}

 private void updateRecordList() {
    Cursor cursor = MainActivity.mSQLiteHelper.getData( "SELECT * FROM RECORD" );
    mList.clear();
    while ( cursor.moveToNext() ){
        int id = cursor.getInt         ( 0 );
        String name  = cursor.getString( 1 );
        String age   = cursor.getString( 2 );
        String phone = cursor.getString( 3 );
        byte[] image = cursor.getBlob  ( 4 );

        mList.add( new Model(id, name, age, phone, image  ) );
        mAdapter.notifyDataSetChanged();
    }
}

Sqlitehelper class

public class SQLiteHelper extends SQLiteOpenHelper {

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 age, String phone, byte[] image ){
    SQLiteDatabase database = getWritableDatabase();
    String sql = "INSERT INTO RECORD VALUES(NULL, ?, ?, ?, ?)";
    SQLiteStatement statement = database.compileStatement( sql );
    statement.clearBindings();

    statement.bindString( 1,name );
    statement.bindString( 2,age );
    statement.bindString( 3,phone );
    statement.bindBlob  ( 4,image  );

    statement.executeInsert();
}

public void updateData(String name, String age, String phone, byte[] image, int id){
    SQLiteDatabase database = getWritableDatabase();
    String sql = "UPDATE RECORD SET name=?, age=?, phone=?, image=? WHERE id=?";
    SQLiteStatement statement = database.compileStatement( sql );

    statement.bindString( 1, name  );
    statement.bindString( 2, age   );
    statement.bindString( 3, phone );
    statement.bindBlob  ( 4, image );
    statement.bindDouble( 5, (double)id );

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

public void deleteData (int id){
    SQLiteDatabase database = getWritableDatabase();
    String sql = "DELETE FROM RECORD WHERE id=?";
    SQLiteStatement statement = database.compileStatement( sql );
    statement.clearBindings();
    statement.bindDouble( 1, (double)id );
    statement.execute();
    database.close();
}

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

07-04 14:31:13.361 2081-2081/com.daniel.listview_cadastro E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.daniel.listview_cadastro/com.daniel.listview_cadastro.Produtos}: android.database.sqlite.SQLiteException: Can't downgrade database from version 2 to 1
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2114)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2139)
    at android.app.ActivityThread.access$700(ActivityThread.java:143)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1241)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4960)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
    at dalvik.system.NativeStart.main(Native Method)
 Caused by: android.database.sqlite.SQLiteException: Can't downgrade database from version 2 to 1
    at android.database.sqlite.SQLiteOpenHelper.onDowngrade(SQLiteOpenHelper.java:361)
    at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:255)
    at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
    at com.daniel.listview_cadastro.SQLiteHelper.queryData(SQLiteHelper.java:19)
    at com.daniel.listview_cadastro.Produtos.onCreate(Produtos.java:50)
    at android.app.Activity.performCreate(Activity.java:5203)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2078)

I think the error is in these lines below but I don’t know how to fix

    at com.daniel.listview_cadastro.SQLiteHelper.queryData(SQLiteHelper.java:19)
    at com.daniel.listview_cadastro.Produtos.onCreate(Produtos.java:50)
  • It is probably an SQL error that is causing this. If you open Android Studio Logcat you will be able to see Stacktrace. Edit your post and paste this message to help identify the error.

  • I found the error in this line mSQLiteHelper = new Sqlitehelper( this, "RECORDDB.sqlite",null,1 ); I put as version 1 and in Gradie this version 2, I just passed to version 2 and it worked.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.