I have a recyclerview. There are city names in the recyclerview and when I long click, I want to delete it from the recyclerview. I wrote some code in adapter class. When I click on the city names, I can delete them, but when I view the recyclerview again, the city names I deleted appear again. How can I fix this ?
My adapter class
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {
ArrayList<City> arrayList;
Context context;
public Adapter(ArrayList<City> arrayList ,Context context ){
this.arrayList = arrayList;
this.context = context;
}
#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);
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());
}
}).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);
});
}
#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();
cursor.close();
}
catch (Exception e ){
e.printStackTrace();
}
/*---------------------- set recyclerview-----------------------------*/
recyclerView.setLayoutManager(new LinearLayoutManager(cities.this));
cityadapter = new Adapter(cityArrayList,this);
recyclerView.setAdapter(cityadapter);
/*--------------------------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);
}
}
The problem is that you are only deleting the cities from your ArrayList that is inside your adapter. But those cities still remain in your SQL database. Then when you restart the Activity your ArrayList will be created with the data of your SQL database, where those deleted cities still exist.
To delete cities consistently you need to delete the cities not only in your adapter but also in your SQL database.
Related
I have a a view where a bunch of my Sqlite data is displayed. I recently added a column to my database called location_position. I have added a button to my relative layout so that when its clicked I want the data inside to be sorted in ascending format. I have tried following a few examples online but with the way my app is setup im struggling tom get it to work.
I have a routeView.java class and a routeAdapter
I would really apreciate if someone can show me how to have the content sorted when the button is clicked, or any resources with similar solutions
public class RouteView extends AppCompatActivity {
RecyclerView recyclerView;
routeAdapter routeAdapter;
ArrayList<String> location_id, location_name, location_county, location_description, location_route, location_position;
MyDatabaseHelper myDB;
Button createPDFButton, btnNorth, southBtn;
Context mContext = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_route_view);
Button southBtn = findViewById(R.id.button_south);
southBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Collections.sort(ArrayList);
}
});
// btnRemove = findViewById(R.id.btnRemove);
recyclerView = findViewById(R.id.recyclerView);
myDB = new MyDatabaseHelper(this);
createPDFButton = findViewById(R.id.createPDFButton);
location_id = new ArrayList<>();
location_name = new ArrayList<>();
location_county = new ArrayList<>();
location_description = new ArrayList<>();
location_route = new ArrayList<>();
location_position = new ArrayList<>();
Cursor cursor = myDB.readAllData();
createPDFButton.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onClick(View v) {
if (UserActivity.checkAppPermission(RouteView.this, "android.permission.WRITE_EXTERNAL_STORAGE", 1)){
generatePDF(recyclerView);
}
}
});
while (cursor.moveToNext()){
if(cursor.getString(4).equals("1")) {
location_id.add(cursor.getString(0));
location_name.add(cursor.getString(1));
location_county.add(cursor.getString(2));
location_description.add(cursor.getString(3));
location_route.add(cursor.getString(4));
location_position.add(cursor.getString(8));
}
}
routeAdapter = new routeAdapter(this, this, location_id, location_name, location_county, location_description, location_route, location_position);
recyclerView.setAdapter(routeAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
and this is the route adapter class
public class routeAdapter extends RecyclerView.Adapter<routeAdapter.MyViewHolder> {
//private final ClickListener listener;
private Context context;
MyDatabaseHelper myDB;
Activity activity;
private ArrayList location_id, location_name, location_county, location_description, location_position, location_route, location_image_url;
Button btnRemove;
String id, name, county, description;
routeAdapter(Activity activity, Context context, ArrayList location_id, ArrayList location_name, ArrayList location_county,
ArrayList location_description, ArrayList location_route, ArrayList location_position){
this.activity = activity;
this.context = context;
this.location_id = location_id;
this.location_name = location_name;
this.location_county = location_county;
this.location_description = location_description;
this.location_position = location_position;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.route_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
holder.location_id_txt.setText(String.valueOf(location_id.get(position)));
holder.location_name_txt.setText(String.valueOf(location_name.get(position)));
holder.location_county_txt.setText(String.valueOf(location_county.get(position)));
holder.location_description_txt.setText(String.valueOf(location_description.get(position)));
holder.mainLayout2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, RouteView.class);
intent.putExtra("id", String.valueOf(location_id.get(position)));
intent.putExtra("name", String.valueOf(location_name.get(position)));
intent.putExtra("county", String.valueOf(location_county.get(position)));
intent.putExtra("description",String.valueOf(location_description.get(position)));
activity.startActivityForResult(intent, 2);
}
});
}
#Override
public int getItemCount() { return location_id.size(); }
class MyViewHolder extends RecyclerView.ViewHolder {
TextView location_id_txt, location_name_txt, location_county_txt, location_description_txt, added_to_route_txt, location_image_url;
LinearLayout mainLayout2;
Button btnRemove;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
location_id_txt = itemView.findViewById(R.id.location_id_txt);
location_name_txt = itemView.findViewById(R.id.location_name_txt);
location_county_txt = itemView.findViewById(R.id.location_county_txt);
location_description_txt = itemView.findViewById(R.id.location_description_txt);
mainLayout2 = itemView.findViewById(R.id.mainLayout2);
}
}
}
This is the basic concept:
On clicking a button or whatever to sort the things in a specific order, you sort the ArrayList that contains the values reflected in the RecyclerView. Then you update/ recreate the RecyclerView to register the changes.
I save my recyclerview with SQliteopenhelper . I use Itemtouchhelper and I can change items positions with itemtouchhelper on recycler view but I cant update positions on my database How Can I ?
todoactivity.java
public class todoactivity extends AppCompatActivity {
TextView title;
ImageButton gorevo;
RecyclerView recyclerView;
List<String>Listsx = new ArrayList<>();
TodoActivityAdpter adapterx;
DatabaseHelper4 myDBxxx;
TextView textView;
CheckBox checkBox;
long id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todoactivity);
recyclerView=findViewById(R.id.recyclerviewxx);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
adapterx=new TodoActivityAdpter(Listsx);
recyclerView.setAdapter(adapterx);
title=findViewById(R.id.titlex);
textView=findViewById(R.id.text_viewx);
gorevo = findViewById(R.id.gorevo);
myDBxxx = new DatabaseHelper4(this);
Cursor datax = myDBxxx.getListContents();
if(datax.getCount() == 0){
}else{
while(datax.moveToNext()){
Listsx.add(datax.getString(1));
ListAdapter listAdapterx = new ArrayAdapter<>(this,R.layout.todoactivity_item,R.id.textitem,Listsx);
adapterx.notifyItemInserted(Listsx.size()-1);
}
}
gorevo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(todoactivity.this);
bottomSheetDialog.setContentView(R.layout.bottomsheetlayout3);
bottomSheetDialog.show();
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
EditText editText = bottomSheetDialog.findViewById(R.id.editx);
Button ekle = bottomSheetDialog.findViewById(R.id.ekle);
ekle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = editText.getText().toString();
Listsx.add(text);
AddDataxxx(text);
adapterx.notifyItemInserted(Listsx.size()-1);
bottomSheetDialog.hide();
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),0);
}
});
}
});
back=findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(todoactivity.this, pomodoroscreen.class);
startActivity(i);
overridePendingTransition(0,0);
}
});
ItemTouchHelper.SimpleCallback move = new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.START | ItemTouchHelper.END , 0) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
int fromPosition = viewHolder.getAdapterPosition();
int toPosition = target.getAdapterPosition();
Collections.swap(Listsx,fromPosition,toPosition);
recyclerView.getAdapter().notifyItemMoved(fromPosition,toPosition);
// I want update items position on my SQliteOpenhelper in there
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
}
};
ItemTouchHelper itemTouchHelperx = new ItemTouchHelper(move);
itemTouchHelperx.attachToRecyclerView(recyclerView);
}
public void AddDataxxx(String newEntry) {
boolean insertDatax = myDBxxx.addDataxxx(newEntry);
}
}
DatabaseHelper.java
public class DatabaseHelper4 extends SQLiteOpenHelper {
public static final String DATABASE_NAME4 = "mylistxxx.db";
public static final String TABLE_NAME4 = "mylist_dataxxx";
public static final String COL14 = "iDxxx";
public static final String COL24 = "ITEM1xxx";
public DatabaseHelper4(Context context) {
super(context, DATABASE_NAME4, null, 1);
}
#Override
public void onCreate(SQLiteDatabase dbxxx) {
String createTable = "CREATE TABLE " + TABLE_NAME4 + " (iDxxx INTEGER PRIMARY KEY AUTOINCREMENT, " +
" ITEM1xxx TEXT)";
dbxxx.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase dbxxx, int oldVersion, int newVersion) {
dbxxx.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME4);
onCreate(dbxxx);
}
public boolean addDataxxx(String textt) {
SQLiteDatabase dbxxx = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL24, textt);
long result = dbxxx.insert(TABLE_NAME4, null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
public Cursor getListContents() {
SQLiteDatabase dbxxx = this.getWritableDatabase();
Cursor dataxxx = dbxxx.rawQuery("SELECT * FROM " + TABLE_NAME4, null);
return dataxxx;
}
}
Adapter.java
public class TodoActivityAdpter extends RecyclerView.Adapter<TodoActivityAdpter.Holder> {
List<String>Listsx;
public TodoActivityAdpter(List<String>itemxxx){
this.Listsx = itemxxx;
}
#NonNull
#Override
public TodoActivityAdpter.Holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.todoactivity_item,parent,false);
Holder holder = new Holder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull TodoActivityAdpter.Holder holder, int position) {
holder.textView.setText(Listsx.get(position));
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.checkBox.isChecked()) {
holder.textView.setTextColor(view.getResources().getColor(R.color.grey));
} else {
holder.textView.setTextColor(view.getResources().getColor(R.color.Color_black));
}
}
});
}
#Override
public int getItemCount() {
return Listsx.size();
}
public class Holder extends RecyclerView.ViewHolder {
CheckBox checkBox;
TextView textView;
List<String>Listsx;
RecyclerView recyclerView;
Context mContext;
public Holder(View view) {
super(view);
textView=view.findViewById(R.id.text_viewx);
checkBox=view.findViewById(R.id.checkbox);
recyclerView=view.findViewById(R.id.recyclerviewxx);
}
}
}
Thats my java classes . My activity is todoactivity . My SQliteopenhelper is DatabaseHelper.java . My Adapter is adapter.java . I can change items position on my recyclerview but ı cant update items position on my database . How can I
I suggest adding a column with the position to use for ordering.
Please close the cursor and return a list of objects. You can read your cursor using cursor.getString(cursor.getColumnIndex(colName)). Overriding close in your helper and closing the writableDatabase is also good practise. I myself open the writableDatabase only once (upon create) and close it at the end (upon close).
Regards, Mike
SearchPage where I search the books from firebase
public class SearchPage extends AppCompatActivity {
EditText searchbar;
RecyclerView recyclerView;
DatabaseReference reference;
ArrayList<String> BookNameList;
ArrayList<String> AuthorNameList;
ArrayList<String> PicList;
ArrayList<String> PublisherList;
ArrayList<String> Shelfnols;
ArrayList<String> Desc;
SearchAdapter searchAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_page);
searchbar = (EditText) findViewById(R.id.searchbar);
reference = FirebaseDatabase.getInstance().getReference();
reference.keepSynced(true);
recyclerView = (RecyclerView) findViewById(R.id.rv);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
BookNameList = new ArrayList<>();
PublisherList = new ArrayList<>();
AuthorNameList = new ArrayList<>();
Shelfnols = new ArrayList<>();
PicList = new ArrayList<>();
Desc=new ArrayList<>();
searchbar.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if (!s.toString().isEmpty()) {
setAdapter(s.toString());
}
else{
BookNameList.clear();
AuthorNameList.clear();
PicList.clear();
PublisherList.clear();
Shelfnols.clear();
Desc.clear();
}
}
private void setAdapter(final String searchedString) {
reference.child("books").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
BookNameList.clear();
AuthorNameList.clear();
PicList.clear();
PublisherList.clear();
Shelfnols.clear();
Desc.clear();
int counter=0;
for(DataSnapshot snapshot:dataSnapshot.getChildren()){
String uid = snapshot.getKey();
Log.i(uid,"ids");
String desc = snapshot.child("Desc").getValue(String.class);
String bookname = snapshot.child("bookname").getValue(String.class);
String author = snapshot.child("author").getValue(String.class);
String image = snapshot.child("image").getValue(String.class);
String publisher = snapshot.child("Publisher").getValue(String.class);
String shelfno = snapshot.child("Shelf_no").getValue(String.class);
try {
if (bookname.toLowerCase().contains(searchedString.toLowerCase())) {
BookNameList.add(bookname);
AuthorNameList.add(author);
PublisherList.add(publisher);
Shelfnols.add(shelfno);
PicList.add(image);
Desc.add(desc);
counter++;
} else if (author.toLowerCase().contains(searchedString.toLowerCase())) {
BookNameList.add(bookname);
AuthorNameList.add(author);
PublisherList.add(publisher);
Shelfnols.add(shelfno);
PicList.add(image);
Desc.add(desc);
counter++;
}
}
catch (Exception e){
Toast.makeText(getApplicationContext(),"not found",Toast.LENGTH_LONG).show();
}
if(counter==15){
break;
}
SearchAdapter searchAdapter = new SearchAdapter(SearchPage.this, BookNameList, AuthorNameList, PicList, PublisherList, Shelfnols);
recyclerView.setAdapter(searchAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
}
this the adapter class SearchAdapter where I am getting the adapter position on click
public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.SearchViewHolder> {
final public String id="bookname";
Context context;
ArrayList<String> BookNameList;
ArrayList<String> AuthorNameList;
ArrayList<String> PicList;
ArrayList<String> PublisherList;
ArrayList<String> Shelfnols;
LinearLayout booklayout;
DatabaseReference reference;
class SearchViewHolder extends RecyclerView.ViewHolder{
ImageView bookimage;
TextView bookname, authorname,publisher,shelfno;
public SearchViewHolder(#NonNull View itemView) {
super(itemView);
bookimage = itemView.findViewById(R.id.Bookimg);
bookname = itemView.findViewById(R.id.BookName);
authorname = itemView.findViewById(R.id.AuthorName);
publisher = itemView.findViewById(R.id.Publications);
shelfno = itemView.findViewById(R.id.Shelfno);
booklayout=itemView.findViewById(R.id.LinLayout);
reference = FirebaseDatabase.getInstance().getReference();
reference.keepSynced(true);
}
}
public SearchAdapter(Context context, ArrayList<String> bookNameList, ArrayList<String> authorNameList, ArrayList<String> picList,ArrayList<String> publisherList,ArrayList<String> shelfnols) {
this.context = context;
BookNameList = bookNameList;
AuthorNameList = authorNameList;
PicList = picList;
PublisherList=publisherList;
Shelfnols=shelfnols;
}
#NonNull
#Override
public SearchAdapter.SearchViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.activity_search_layout,parent,false);
return new SearchAdapter.SearchViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SearchViewHolder holder, final int position) {
holder.bookname.setText(BookNameList.get(position));
holder.authorname.setText(AuthorNameList.get(position));
holder.publisher.setText(PublisherList.get(position));
holder.shelfno.setText(Shelfnols.get(position));
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,"clicked "+position,Toast.LENGTH_LONG).show();
Intent i = new Intent(context,Bookdetailslayout.class);
context.startActivity(i);
}
});
Glide.with(context).asBitmap().load(PicList.get(position)).placeholder(R.mipmap.ic_launcher_round).into(holder.bookimage);
}
#Override
public int getItemCount() {
return BookNameList.size();
}
this is my new activity where i want the book details to be shown
public class Bookdetailslayout extends SearchPage {
DatabaseReference reference;
TextView bookname,author,publisher,desc,location;
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bookdetailslayout);
image=(ImageView)findViewById(R.id.img) ;
bookname = (TextView)findViewById(R.id.bkname);
author = (TextView) findViewById(R.id.aname);
publisher = (TextView) findViewById(R.id.pname);
desc = (TextView) findViewById(R.id.bkdescription);
location = (TextView) findViewById(R.id.bklocation);
String Bname=getIntent().getStringExtra("bookname");
Log.i(Bname, "onCreate: ");
DatabaseReference databaseReference=FirebaseDatabase.getInstance().getReference().child("books");
}
till now I was able to set onclick to new activity and get the position of the click as item 1,2,etc...how do I use this position to get data from firebase to the new activity
create interface
public interface SetclickListener {
public void getposition(int position);
}
inside adapter create constructor
SetclickListener setclicklistener;
public SetclickListener getSetclick(Context context) {
this.context=context;
return setclicklistener;
}
public void setclicklistener(SetclickListener setclickListener){
setclicklistener=setclickListener;
}
get selected position
setclicklistener.getposition(getAdapterPosition());
then you can implement inside SearchPage activity then you can pass selected position data using Bundle you can send data to other activity
#Override
public void getposition(int position) {
Intent intent = new Intent(context,DetailsActivity.class);
intent.putExtra("name", bookNameList.get(position));
startActivity(intent);
}
}
}
i used this in my adapter class to get position
public void onClick(View v) {
Intent i = new Intent(context,Bookdetailslayout.class);
i.putExtra("bookname",BookNameList.get(position));
i.putExtra("Image",PicList.get(position));
i.putExtra("author_name",AuthorNameList.get(position));
i.putExtra("publisher_name",PublisherList.get(position));
context.startActivity(i);
}
});
then in the next activity
String imgs=getIntent().getStringExtra("Image");
String Bname=getIntent().getStringExtra("bookname");
title.setText(Bname);
String Author=getIntent().getStringExtra("author_name");
author.setText(Author);
String publisher=getIntent().getStringExtra("publisher_name");
pub.setText(publisher);
Toast.makeText(this,"image "+imgs,Toast.LENGTH_LONG).show();
Picasso.get().load(imgs).into(image);
and it works ..thanks for all the help here
I have a Recycler View in my fragment that opens activities when an item is clicked and highlights the item when it is long clicked. However, when I switch fragments or close my app and reopen it, I want the previously selected items to stay selected. I imagine this is done with Shared Preferences, but how are the selected items saved and then filled again?
Here is my custom Adapter. The TextViews are selected in onBindViewHolder :
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private ArrayList<Workout> mExampleList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public static class ExampleViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView1,mTextView2,mTextView3,mTextView4;
CardView mCardView;
public ExampleViewHolder(View itemView, final OnItemClickListener listener)
{
super(itemView);
mTextView1 = itemView.findViewById(R.id.listTextView1);
mTextView2 = itemView.findViewById(R.id.listTextView2);
mTextView3 = itemView.findViewById(R.id.listTextView3);
mTextView4 = itemView.findViewById(R.id.listTextView4);
mCardView = itemView.findViewById(R.id.cardView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
}
}
});
}
}
public ExampleAdapter(ArrayList<Workout> exampleList) {
mExampleList = exampleList;
}
#NonNull
#Override
public ExampleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_view_item,parent,false);
ExampleViewHolder evh = new ExampleViewHolder(v, mListener);
return evh;
}
#Override
public void onBindViewHolder(#NonNull final ExampleViewHolder holder, final int position) {
Workout workout = mExampleList.get(position);
holder.mTextView1.setText(workout.getText1());
holder.mTextView2.setText(workout.getText2());
holder.mTextView3.setText(workout.getText3());
holder.mTextView4.setText(workout.getText4());
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
if(holder.mTextView1.isSelected()) {
holder.mTextView1.setSelected(false);
holder.mTextView2.setSelected(false);
holder.mTextView3.setSelected(false);
holder.mTextView4.setSelected(false);
} else {
holder.mTextView1.setSelected(true);
holder.mTextView2.setSelected(true);
holder.mTextView3.setSelected(true);
holder.mTextView4.setSelected(true);
}
return true;
}
});
}
#Override
public int getItemCount() {
return mExampleList.size();
}
}
This is my fragment:
public class HomeFragment extends Fragment implements View.OnClickListener{
private RecyclerView mRecyclerView;
private ExampleAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
ArrayList<Workout> exampleList;
MainActivity mainActivity;
DataModel dataModel = new DataModel();
View rootView;
private TextView[] textViews;
private CardView[] cardViews;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home,container,false);
mainActivity = (MainActivity) getActivity();
mainActivity.setToolbarName("Workouts");
textViews = new TextView[16];
cardViews = new CardView[3];
for(int i=0; i<textViews.length; i++) {
{
String buttonID = "textView" + (i+1);
int resID = getResources().getIdentifier(buttonID, "id", getActivity().getPackageName());
textViews[i] = ((TextView) rootView.findViewById(resID));
}
}
updateWeekText();
textViews[2].setText(roundDecimals(mainActivity.getBenchMax()));
textViews[4].setText(roundDecimals(mainActivity.getSquatMax()));
textViews[6].setText(roundDecimals(mainActivity.getDeadliftMax()));
textViews[8].setText(roundDecimals(mainActivity.getPressMax()));
Button buttonNextWeek = rootView.findViewById(R.id.buttonNextWeek);
buttonNextWeek.setOnClickListener(this);
int week = MainActivity.getWeekNumber();
exampleList = new ArrayList<>();
if(week == 1 || week == 2 || week == 3 || week == 4){
exampleList.add(new Workout("Day 1", "C-S", "C-B", "Rack Pulls"));
exampleList.add(new Workout("Day 2", "2ct Paused Squat", "C-P", "Pendlay Row"));
exampleList.add(new Workout("Day 3", "C-D", "Floor Press", "Leg Press"));
} else {
exampleList.add(new Workout("Day 1", "C-S", "C-B", "2ct Paused Deadlift"));
exampleList.add(new Workout("Day 2", "Pin Squat", "C-P", "Pendlay Row"));
exampleList.add(new Workout("Day 3", "C-D", "2ct Paused Bench", "303 Tempo Squat"));
}
buildRecyclerView();
return rootView;
}
public void buildRecyclerView() {
mRecyclerView = rootView.findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getContext());
mAdapter = new ExampleAdapter(exampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new ExampleAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
if (position == 0) {
startActivity(new Intent(getActivity(),ActivityDay1.class));
}
if (position == 1) {
startActivity(new Intent(getActivity(),ActivityDay2.class));
}
}
});
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.buttonNextWeek:
createDialog();
break;
}
}
private void updateWeekText() {
textViews[9].setText("Current week: "+String.valueOf(mainActivity.getWeekNumber()));
}
private void createDialog(){
int nextWeek = mainActivity.getWeekNumber()+1;
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(getContext(), android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(getContext());
}
builder.setTitle("Start week "+nextWeek+"?")
.setMessage("Are you sure?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mainActivity.setWeekNumber(mainActivity.getWeekNumber()+1);
updateWeekText();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(R.drawable.ic_navigate_next_black_24dp)
.show();
}
public String roundDecimals(double a){
NumberFormat nf = new DecimalFormat("##.###");
return nf.format(a);
}
I'll appreciate any help.
Let me know if more code is needed.
You need to fix some errors in Adapter implementation first.
Add isCompleted boolean field into your Workout class. With current adapter implementation your "selected" state is going to get messed up merely by scrolling the recyclerView, since your don't store the value, only change ViewHolder state.
Move body of your LongLickListener into new method of ViewHolder:
void setSelected(boolean selected){
mTextView1.setSelected(selected);
mTextView2.setSelected(selected);
mTextView3.setSelected(selected);
mTextView4.setSelected(selected);
}
Now you can change your LongClickListener into:
#Override
public boolean onLongClick(View view) {
workout.isCompleted = !workout.isCompleted;
holder.setSelected(workout.isCompleted);
return true;
}
This way state of workout completion is actually stored in your data list. To ensure view state is correct, add this line to your onBindViewHolder:
holder.setSelected(workout.isCompleted);
Otherwise ViewHolder that was previously bound to "completed" workout would incorrectly display when showing "not completed" one.
As for storing the selected items - this is a bit tricky since it's mostly a persistence/database design issue.
Are your Workout items just a definition of a workout?
are they recurring?
can user add/remove workout definitions?
is there a history for completed workouts? Or it's reset daily?
You need to at least define some stable ID for each workout to properly persist them, then I suggest looking into database implementation with raw SQLite, Room or Realm.
I have a recycler view, with an ArrayList from custom objects.
Each row has a delete button, when clicked the item is deleted from the recyclerview.
Now the delete button works, and deletes the correct item from the arraylist, however when the items are displayed again in the list, only the bottom item is deleted, and the item which was really deleted from the list stays there.
Its really weird, and I cannot figure out why?
I manage the deleted item from the activity, here is the code of the activity:
public class ManageExerciseActivity extends AppCompatActivity {
private static final String TAG = "999.OffLimitsActivity";
private RecyclerView exerciseRecyclerView;
private ExerciseManageAdapter exerciseAdapter;
public ArrayList<Exercise> exerciseList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_exercise);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ManageExerciseActivity.this, AddExerciseActivity.class);
startActivity(intent);
}
});
fab.setImageBitmap(textAsBitmap("ADD", 40, Color.WHITE));
exerciseList = new ArrayList<>();
getSupportActionBar().setTitle("Manage my exercises");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
exerciseRecyclerView = (RecyclerView) findViewById(R.id.exercise_manage_recycler_view);
exerciseAdapter = new ExerciseManageAdapter(exerciseList);
exerciseAdapter.setOnItemClickListener(new ExerciseManageAdapter.ClickListener() {
#Override
public void onItemClick(final int position, final View v) {
Log.d(TAG, "onItemClick pos = " + position);
// custom dialog
AlertDialog.Builder builder = new AlertDialog.Builder(ManageExerciseActivity.this);
builder.setMessage("Do you wish to delete this exercise?")
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String itemRemoved = exerciseList.get(position).getNameOfExercise();
exerciseList.remove(position);
exerciseAdapter.notifyDataSetChanged();
Snackbar.make(v, itemRemoved + " deleted", Snackbar.LENGTH_LONG)
.setAction("Undo", null).show();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
builder.create();
builder.show();
}
});
exerciseRecyclerView.setAdapter(exerciseAdapter);
exerciseRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
and here is the adapter:
public class ExerciseManageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static ClickListener clickListener;
public ImageView exerciseItemIcon;
public TextView exerciseNameTextView;
public TextView exerciseDurationTextView;
public TextView exerciseTimesRemainingTextView;
public ImageView deleteImageView;
ArrayList<Exercise> exerciseArrayList = new ArrayList<>();
public ExerciseManageAdapter(ArrayList<Exercise> exerciseArrayList) {
this.exerciseArrayList = exerciseArrayList;
}
public interface ClickListener {
void onItemClick(int position, View v);
}
class ExerciseViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public ExerciseViewHolder(View view) {
super(view);
// view.setOnClickListener(this);
exerciseNameTextView = (TextView)view.findViewById(R.id.exercise_manage_name_textView);
exerciseDurationTextView = (TextView)view.findViewById(R.id.exercise_manage_duration_textview);
exerciseTimesRemainingTextView = (TextView)view.findViewById(R.id.exercise_manage_times_remaining);
exerciseItemIcon = (ImageView)view.findViewById(R.id.exercise_manage_item_icon);
deleteImageView = (ImageView)view.findViewById(R.id.delete_exercise_button);
deleteImageView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
clickListener.onItemClick(getAdapterPosition(), v);
}
}
public void setOnItemClickListener(ClickListener clickListener) {
ExerciseManageAdapter.clickListener = clickListener;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getItemCount() {
return exerciseArrayList.size();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.exercise_manage_item_row, parent, false);
return new ExerciseViewHolder(itemView);
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
ExerciseViewHolder exerciseViewHolder = (ExerciseViewHolder) holder;
exerciseNameTextView.setText(exerciseArrayList.get(position).getNameOfExercise());
exerciseDurationTextView.setText(exerciseArrayList.get(position).getDurationOfExercise());
exerciseTimesRemainingTextView.setText(exerciseArrayList.get(position).getTimesPerWeek() + " times a week");
exerciseItemIcon.setImageResource(exerciseArrayList.get(position).getExerciseIcon());
}
}
Thanks
try this.!
notifyItemRemoved(position);
notifyItemRangeChanged(position, mData.size());