id is always returning 0 in Android Studio SQLite. Help me point out the problem

63 Views Asked by At

I'm creating a todo list app with Android Studio.

My MainActivity.java

package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private EditText etEnterColor;
    private Button btnAddNote;
    private RecyclerView rvColors;
    private List<ColorsModel> colorsModelsList;
    private CustomColorsAdapter customColorsAdapter;
    ColorDatabaseHelper colorDatabaseHelper = new ColorDatabaseHelper(MainActivity.this);

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

        rvColors = findViewById(R.id.recyclerview_main_colors);
        etEnterColor = findViewById(R.id.editText_main_enterColors);
        btnAddNote = findViewById(R.id.button_main_add);

        loadAdapter();
        addButton();
        deleteSwipe();

    }

    public void addButton(){
        btnAddNote.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String extractColor = etEnterColor.getText().toString();

                colorDatabaseHelper.createNote(new ColorsModel(extractColor));

                loadAdapter();
                etEnterColor.setText("");
            }
        });
    }

    public void loadAdapter(){
        colorsModelsList = new ColorDatabaseHelper(MainActivity.this).readNote();
        customColorsAdapter = new CustomColorsAdapter(colorsModelsList);
        rvColors.setAdapter(customColorsAdapter);
    }

    public void deleteSwipe(){
        ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                Toast.makeText(MainActivity.this, "ID: " + colorsModelsList.get(viewHolder.getAdapterPosition()).getId(), Toast.LENGTH_SHORT).show();
                colorDatabaseHelper.deleteNote(colorsModelsList.get(viewHolder.getAdapterPosition()).getId());
                colorsModelsList.remove(viewHolder.getAdapterPosition());
                customColorsAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());
            }
        };

        ItemTouchHelper touchHelper = new ItemTouchHelper(simpleCallback);
        touchHelper.attachToRecyclerView(rvColors);
    }
}

Here is my Database

package com.example.myapplication;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

public class ColorDatabaseHelper extends SQLiteOpenHelper {
    public static final String NAME = "colors.db";
    public static final int VERSION = 1;
    public static final String TABLE_COLORS = "COLORS";
    public static final String COLUMN_ID = "ID";
    public static final String COLUMN_NAME = "NAME";

    public ColorDatabaseHelper(@Nullable Context context) {
        super(context, NAME, null, VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String query = "CREATE TABLE " + TABLE_COLORS + " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_NAME + " TEXT);";
        db.execSQL(query);
    }

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

    public void createNote(ColorsModel colorsModel){
        SQLiteDatabase sqLiteDatabase = getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COLUMN_NAME, colorsModel.getName());
        sqLiteDatabase.insert(TABLE_COLORS, null, contentValues);
        sqLiteDatabase.close();
    }

    public List<ColorsModel> readNote(){
        List<ColorsModel> colorsModelList = new ArrayList<>();
        SQLiteDatabase sqLiteDatabase = getReadableDatabase();
        String query = "SELECT * FROM " + TABLE_COLORS + ";";
        Cursor cursor = sqLiteDatabase.rawQuery(query, null);

        cursor.moveToFirst();
        while (!cursor.isAfterLast()){
            @SuppressLint("Range") int id = cursor.getInt(cursor.getColumnIndex(COLUMN_ID));
            @SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex(COLUMN_NAME));

            colorsModelList.add(new ColorsModel(name));
            cursor.moveToNext();
        }

        cursor.close();
        sqLiteDatabase.close();
        return colorsModelList;
    }

    public void deleteNote(int id){
        SQLiteDatabase sqLiteDatabase = getWritableDatabase();
        String whereclause = COLUMN_NAME + "='" + id + "';";
        sqLiteDatabase.delete(TABLE_COLORS, whereclause, null);

        sqLiteDatabase.close();

    }
}

The only problem is whenever I swipe any items in the list, the ID it gets is always 0. I am completely sure that all methods in my Database are working..

Example snippet of my database

Just a beginner here. Thanks!

I can solve the problem by making changes like getting the name instead of id

    public void deleteNote(**String name**){
        SQLiteDatabase sqLiteDatabase = getWritableDatabase();
        String whereclause = COLUMN_NAME + "='" + **name** + "';";
        sqLiteDatabase.delete(TABLE_COLORS, whereclause, null);

        sqLiteDatabase.close();

    }

then changing onSwiped to

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                Toast.makeText(MainActivity.this, "ID: " + colorsModelsList.get(viewHolder.getAdapterPosition()).getName(), Toast.LENGTH_SHORT).show();
                colorDatabaseHelper.deleteNote(colorsModelsList.get(viewHolder.getAdapterPosition())**.getName()**);
                colorsModelsList.remove(viewHolder.getAdapterPosition());
                customColorsAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());
            }

I want to use the ID instead of other variables but I can't figure it out somehow.

2

There are 2 best solutions below

1
ramboli On BEST ANSWER

It seems you didn't pass the ID to new created object in readNotes function:

colorsModelList.add(new ColorsModel(name));

The ID will always be the initial value when accessing it by getID().

3
Arya_ On

I appreciate your efforts,

I think you might have a problem continuously re-creating an instance of ColorModel List which is a bad practice for setting adapter. Because when you do that, you are losing the list object that the adapter was originally set to, instead try to insert data into the same list object

My solution to loadAdapter():

public void loadAdapter(){
        List<ColorModel> temp = new ColorDatabaseHelper(MainActivity.this).readNote();
        if(temp.size()==0){
            colorModelList = temp;            
            customColorsAdapter = new CustomColorsAdapter(colorsModelsList);
            rvColors.setAdapter(customColorsAdapter);
        }
        else{
            colorsModelsList.add(temp.get(temp.size()-1));
            customColorsAdapter.notifyDataSetChanged();
        }
        
    }

Now do note that if it's for the first time you have to do it the way you did it

Let me know if I missed anything, I'll try updating my answer