Home > OS >  How can I delete last item and first item sql database in Android - Deletion Error
How can I delete last item and first item sql database in Android - Deletion Error

Time:12-15

I have a recyclerview and I show citynames in recyclerview and when I long click city names in recyclerview I want to delete that I clicked city.

Deletion works successfully except the first and last cities. when I want to delete last city and first city it is deleting from my recyclerview but it is not deleting from my sql database and it shows my toast message "something went wrong".

When I come back and view the recyclerview again, the first and last city names are not deleted. and when I want to delete it again it gives this error

"Adapter.notifyDataSetChanged()' on a null object reference"

My Adapter Class

public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder>  {

ArrayList<City> arrayList;
Context context;
SQLiteDatabase db ;
Cursor cursor;
int id;


public Adapter(ArrayList<City> arrayList ,Context context ){
    this.arrayList = arrayList;
    this.context = context;

    db = context.openOrCreateDatabase("City",MODE_PRIVATE,null);

    Intent intent = ((Activity) context).getIntent();
    id = intent.getIntExtra("citId", 0);
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    RecyclerviewRowBinding recyclerviewRowBinding = 
    RecyclerviewRowBinding.inflate(
    LayoutInflater.from(parent.getContext()),
    parent,
    false);

    return new MyViewHolder(recyclerviewRowBinding);

}

@Override
public void onBindViewHolder(@NonNull Adapter.MyViewHolder holder, int position) {

    holder.binding.MytxtCities.setText(arrayList.get(position).cityName);

       /*when i long click it does the deletion here*/

    holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setIcon(R.drawable.warningicon);
            builder.setMessage("Are you sure that you want to delete " arrayList.get(position).cityName);
            builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    arrayList.remove(position);
                    notifyItemRemoved(position);
                    notifyItemRangeChanged(position,arrayList.size());


                    cursor = db.rawQuery("select * from city where id=?",new String[]{String.valueOf(id)});
                    Result(cursor);



                }
            }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            }).show();


            return true;
        }


    });


    holder.itemView.setOnClickListener(v -> {
        Intent intent = new Intent(holder.itemView.getContext(),MainActivity.class);
        intent.putExtra("citId",arrayList.get(position).id);
        holder.itemView.getContext().startActivity(intent);
    });
}


private void Result(Cursor cursor){

    if(cursor.getCount() > 0){

        db.delete("City","id=?",new String[]{String.valueOf(id)});
        notifyDataSetChanged();
    }
    else{
        Toast.makeText(context,"something went wrong !",Toast.LENGTH_LONG).show();
    }


}


@Override
public int getItemCount() {
    return arrayList.size();
}



public class MyViewHolder extends RecyclerView.ViewHolder {
    TextView Mytxt_cities;
    private RecyclerviewRowBinding binding;

    public MyViewHolder(@NonNull RecyclerviewRowBinding binding) {
        super(binding.getRoot());
        this.binding = binding;
        Mytxt_cities = itemView.findViewById(R.id.Mytxt_cities);



    }


 }
}

My Recyclerview Class is cities class

public class cities extends AppCompatActivity {

RecyclerView recyclerView ;
ArrayList<City> cityArrayList;
Adapter cityadapter;
ImageView cities_back_icon;



public void init(){

    cities_back_icon = findViewById(R.id.Id_cities_back_icon);
    cities_back_icon_click_register();

    cityArrayList = new ArrayList<>();
    recyclerView = findViewById(R.id.recyclerview_id);



    SQLGet_Data();


}

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


}

private void cities_back_icon_click_register(){

    cities_back_icon.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(cities.this, MainActivity.class);
            startActivity(intent);
        }
    });
}

private void SQLGet_Data(){
    try {

        SQLiteDatabase sqLiteDatabase = this.openOrCreateDatabase("City",MODE_PRIVATE,null);
        Cursor cursor = sqLiteDatabase.rawQuery("SELECT*FROM city",null);
        int idIx = cursor.getColumnIndex("id");
        int nameIx = cursor.getColumnIndex("cityname");

        while(cursor.moveToNext()){
            String cityname = cursor.getString(nameIx);
            int id = cursor.getInt(idIx);
            City city = new City(cityname,id);
            cityArrayList.add(city);
        }
        cityadapter.notifyDataSetChanged();  <--- There is an error in this code
        cursor.close();
    }

    catch (Exception e ){
       e.printStackTrace();
    }

    /*---------------------- set recyclerview-----------------------------*/

    cityadapter = new Adapter(cityArrayList,this);
    recyclerView.setAdapter(cityadapter);
    recyclerView.setLayoutManager(new LinearLayoutManager(cities.this));



/*------- We drew a line between the data in the recyclerview ------*/

    DividerItemDecoration dividerItemDecoration = new 
    DividerItemDecoration(recyclerView.getContext(),
    DividerItemDecoration.VERTICAL);
    Drawable drawable = ContextCompat.getDrawable(getApplicationContext(), 
    R.drawable.custom_divider);
    dividerItemDecoration.setDrawable(drawable);
    recyclerView.addItemDecoration(dividerItemDecoration);

 }


 }

so what i want to ask is briefly how can i solve this error and how can I delete a data from the recyclerview and the database at the same time because sometimes the id of a data in the recyclerview and the id in the sql lite database can be different.

CodePudding user response:

Your issue is that cityAdapter at the point of error has not been instantiated and is therefore null. You instantiate it later with:-

cityadapter = new Adapter(cityArrayList,this);

You could move the instantiation before e.g.

private void SQLGet_Data(){
    cityadapter = new Adapter(cityArrayList,this);
    try { 
        ....
  • Related