How To Add Multiple Cards Of The Same CardView To A RecyclerView? - java

Here is a video of what I trying to do and explanation of the issue that I am having. Go to the following link below.
https://file.re/2021/09/12/2021-09-1210-43-21/
Here is the XML, Java, and Manifest Code Video. Go to the following link below.
https://file.re/2021/09/12/2021-09-1211-32-13/
Answer worked, but now I have two new problems. Here is the video link below.
https://file.re/2021/09/12/2021-09-1212-08-04/
I am creating an app that lists CardView layouts to a RecyclerView.
My app will add the CardView layout to the RecyclerView list, but it only lists one. I want it to add multiples of the same CardView when the user clicks on the button to add the card (basically cloning the CardView layout one under the other).
Here is what I have in my Button Click...
ftocConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ArrayList<RecyclerItem> addFahToCelCard = new ArrayList<>();
addFahToCelCard.add(new RecyclerItem());
recyclerView = findViewById(R.id.recycler_item_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerItemAdapter = new RecyclerItemAdapter(addFahToCelCard);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerItemAdapter);
}
}
});
I've tried putting the ArrayList<RecyclerItem> addFahToCelCard = new ArrayList<>(); under the MainActivity extends AppCompatActivity class just before the onCreate like this...
public class MainActivity extends AppCompatActivity {
final private ArrayList<RecyclerItem> addFahToCelCard = new ArrayList<>();
That didn't work.
If I don't keep ArrayList<RecyclerItem> addFahToCelCard = new ArrayList<>(); in the button click listener, and I add a new CardView it will add a new one behind the original one each time the button is clicked, and if I delete the card it keep popping back up until I delete them all off. How do I fix this the way I want it to behave? I hope this all makes sense.
I appreciate the help!
Here is everything in the java class..
public class MainActivity extends AppCompatActivity {
ArrayList<RecyclerItem> addFahToCelCard;
private Animation fromBottom;
private Animation toBottom;
private Boolean clicked = false;
private RecyclerView recyclerView;
private RecyclerItemAdapter recyclerItemAdapter;
private RecyclerView.LayoutManager layoutManager;
public FloatingActionButton mainConverterMenuFloatBtn;
public TextView chooseConverterLabel, ftocConverterLabelBtn, ftokConverterLabelBtn, ctofConverterLabelBtn, ctokConverterLabelBtn, ktofConverterLabelBtn, ktocConverterLabelBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fromBottom = AnimationUtils.loadAnimation(MainActivity.this, R.anim.from_bottom_animation);
toBottom = AnimationUtils.loadAnimation(MainActivity.this, R.anim.to_bottom_animation);
mainConverterMenuFloatBtn = findViewById(R.id.add_temp_converter_float_btn);
chooseConverterLabel = findViewById(R.id.choose_converter_label);
ftocConverterLabelBtn = findViewById(R.id.add_f_to_c_converter_label_btn);
ftokConverterLabelBtn = findViewById(R.id.add_f_to_k_converter_label_btn);
ctofConverterLabelBtn = findViewById(R.id.add_c_to_f_converter_label_btn);
ctokConverterLabelBtn = findViewById(R.id.add_c_to_k_converter_label_btn);
ktofConverterLabelBtn = findViewById(R.id.add_k_to_f_converter_label_btn);
ktocConverterLabelBtn = findViewById(R.id.add_k_to_c_converter_label_btn);
addFahToCelCard = new ArrayList<>();
recyclerView = findViewById(R.id.recycler_item_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerItemAdapter = new RecyclerItemAdapter(addFahToCelCard);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerItemAdapter);
mainConverterMenuFloatBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mainConverterMenu();
}
});
ftocConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
addFahToCelCard.add(new RecyclerItem());
recyclerItemAdapter.notifyDataSetChanged();
closeActionButton();
}
}
});
ftokConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
closeActionButton();
}
}
});
ctofConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
closeActionButton();
}
}
});
ctokConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
closeActionButton();
}
}
});
ktofConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
closeActionButton();
}
}
});
ktocConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
closeActionButton();
}
}
});
}
private void addFahToCelCard() {
}
private void mainConverterMenu() {
setVisibility(clicked);
setClickable(clicked);
setAnimation(clicked);
clicked = !clicked;
}
private void setVisibility(Boolean clicked) {
if (!clicked) {
chooseConverterLabel.setVisibility(View.VISIBLE);
ftocConverterLabelBtn.setVisibility(View.VISIBLE);
ftokConverterLabelBtn.setVisibility(View.VISIBLE);
ctofConverterLabelBtn.setVisibility(View.VISIBLE);
ctokConverterLabelBtn.setVisibility(View.VISIBLE);
ktofConverterLabelBtn.setVisibility(View.VISIBLE);
ktocConverterLabelBtn.setVisibility(View.VISIBLE);
} else {
chooseConverterLabel.setVisibility(View.GONE);
ftocConverterLabelBtn.setVisibility(View.GONE);
ftokConverterLabelBtn.setVisibility(View.GONE);
ctofConverterLabelBtn.setVisibility(View.GONE);
ctokConverterLabelBtn.setVisibility(View.GONE);
ktofConverterLabelBtn.setVisibility(View.GONE);
ktocConverterLabelBtn.setVisibility(View.GONE);
}
}
private void setClickable(Boolean clicked) {
if (!clicked) {
chooseConverterLabel.setClickable(true);
ftocConverterLabelBtn.setClickable(true);
ftokConverterLabelBtn.setClickable(true);
ctofConverterLabelBtn.setClickable(true);
ctokConverterLabelBtn.setClickable(true);
ktofConverterLabelBtn.setClickable(true);
ktocConverterLabelBtn.setClickable(true);
} else {
chooseConverterLabel.setClickable(false);
ftocConverterLabelBtn.setClickable(false);
ftokConverterLabelBtn.setClickable(false);
ctofConverterLabelBtn.setClickable(false);
ctokConverterLabelBtn.setClickable(false);
ktofConverterLabelBtn.setClickable(false);
ktocConverterLabelBtn.setClickable(false);
}
}
private void setAnimation(Boolean clicked) {
if (!clicked) {
chooseConverterLabel.startAnimation(fromBottom);
ftocConverterLabelBtn.startAnimation(fromBottom);
ftokConverterLabelBtn.startAnimation(fromBottom);
ctofConverterLabelBtn.startAnimation(fromBottom);
ctokConverterLabelBtn.startAnimation(fromBottom);
ktofConverterLabelBtn.startAnimation(fromBottom);
ktocConverterLabelBtn.startAnimation(fromBottom);
} else {
chooseConverterLabel.startAnimation(toBottom);
ftocConverterLabelBtn.startAnimation(toBottom);
ftokConverterLabelBtn.startAnimation(toBottom);
ctofConverterLabelBtn.startAnimation(toBottom);
ctokConverterLabelBtn.startAnimation(toBottom);
ktofConverterLabelBtn.startAnimation(toBottom);
ktocConverterLabelBtn.startAnimation(toBottom);
}
}
private void closeActionButton() {
setVisibility(clicked);
setClickable(clicked);
setAnimation(clicked);
clicked = !clicked;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.app_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.show_hide_float_convert_btn) {
if (mainConverterMenuFloatBtn.isShown()) {
mainConverterMenuFloatBtn.setVisibility(View.GONE);
item.setIcon(R.drawable.ic_baseline_visibility_off_32);
} else if (!mainConverterMenuFloatBtn.isShown()) {
mainConverterMenuFloatBtn.setVisibility(View.VISIBLE);
item.setIcon(R.drawable.ic_baseline_visibility_32);
}
} else if (id == R.id.app_help) {
} else if (id == R.id.tip_developer) {
} else if (id == R.id.premium_features) {
} else if (id == R.id.about_app) {
} else if (id == R.id.exit_app) {
}
return super.onOptionsItemSelected(item);
}
public static class RecyclerItemAdapter extends RecyclerView.Adapter<RecyclerItemAdapter.RecyclerViewHolder> {
public ArrayList<RecyclerItem> recyclerItemList;
public AdapterView.OnItemClickListener recyclerItemListener;
public interface OnItemClickListener {
void onItemClick (int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
recyclerItemListener = (AdapterView.OnItemClickListener) listener;
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder {
EditText inputFahValueET;
TextView fahtoCelResult;
ImageView tempIconAndConvertBtn;
ImageView deleteCardBtn;
String shortResult, longResult;
public RecyclerViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
inputFahValueET = itemView.findViewById(R.id.input_fahrenheit_value_to_convert);
fahtoCelResult = itemView.findViewById(R.id.output_result_ftc);
tempIconAndConvertBtn = itemView.findViewById(R.id.temp_icon_convert_btn);
deleteCardBtn = itemView.findViewById(R.id.remove_card);
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 RecyclerItemAdapter(ArrayList<RecyclerItem> rList) {
recyclerItemList = rList;
}
#NonNull
#Override
public RecyclerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fahrenheit_to_celsius_converter_layout, parent, false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(v, (OnItemClickListener) recyclerItemListener);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewHolder holder, int position) {
RecyclerItem currentItem = recyclerItemList.get(position);
final String[] result = new String[1];
holder.tempIconAndConvertBtn.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View view) {
String getIputFahValue = holder.inputFahValueET.getText().toString();
NumberFormat nf = new DecimalFormat("0.000");
if(!getIputFahValue.isEmpty()) {
double d = Double.parseDouble(getIputFahValue);
double dd = d - 32;
double ddd = dd * 5;
double dddd = ddd / 9;
result[0] = Double.toString(dddd);
holder.fahtoCelResult.setText(nf.format(dddd) + "°C");
holder.fahtoCelResult.setVisibility(View.VISIBLE);
holder.shortResult = nf.format(dddd) + "°C";
holder.longResult = getIputFahValue + "°F is " + nf.format(dddd) + "°C";
if (result[0].contains(".0")) {
result[0] = result[0].replace(".0", "");
holder.fahtoCelResult.setText(result[0] + "°C");
holder.fahtoCelResult.setVisibility(View.VISIBLE);
holder.shortResult = result[0] + "°C";
holder.longResult = getIputFahValue + "°F is " + result[0] + "°C";
}else if (result[0].contains(".000")) {
result[0] = result[0].replace(".000", "");
holder.fahtoCelResult.setText(result[0] + "°C");
holder.fahtoCelResult.setVisibility(View.VISIBLE);
holder.shortResult = result[0] + "°C";
holder.longResult = getIputFahValue + "°F is " + result[0] + "°C";
}
}else {
Toast.makeText(view.getContext(), "Fahrenheit Value Field Cannot Be Blank!", Toast.LENGTH_LONG).show();
}
}
});
holder.fahtoCelResult.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
AlertDialog.Builder adb = new AlertDialog.Builder(view.getContext());
adb.setIcon(R.drawable.ic_baseline_file_copy_32);
adb.setTitle("Copy Result");
adb.setMessage("You can copy the result to your clipboard if you would like. Choose if you want the short or long result copied to your clipboard.\n\nExample of Short and Long Result:\nShort Result: 32°C\nLong Result: 0°F is 32°C");
adb.setPositiveButton("Short", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ClipboardManager cbm = (ClipboardManager) view.getContext().getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Copy", holder.shortResult);
cbm.setPrimaryClip(clip);
Toast.makeText(view.getContext(), "Result Copied!", Toast.LENGTH_SHORT).show();
}
});
adb.setNegativeButton("Long", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ClipboardManager cbm = (ClipboardManager) view.getContext().getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Copy", holder.longResult);
cbm.setPrimaryClip(clip);
Toast.makeText(view.getContext(), "Result Copied!", Toast.LENGTH_SHORT).show();
}
});
adb.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {}});
adb.create();
adb.show();
return false;
}
});
holder.deleteCardBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
recyclerItemList.remove(position);
notifyItemRemoved(position);
}
});
}
#Override
public int getItemCount() {
return recyclerItemList.size();
}
}
public class RecyclerItem {
public RecyclerItem() {
}
}
}
The recyclerView should be listing the CardViews and also allowing duplicates.

Well, I think you are just using the RecyclerView the wrong way.
In your code snippet, you are initializing the RecyclerView as well as the adapter and all other components every time the user clicks the button.
First of all you will have to create the insert method in the RecyclerItemAdapter class.
RecyclerItemAdapter.java
class RecyclerItemAdapter extends RecyclerView.Adapter<YourViewHolder> {
private ArrayList<RecyclerItem> items;
RecyclerItemAdapter(ArrayList<RecyclerItem> recyclerItems) {
this.items = recyclerItems;
}
//...
public void addItem(RecyclerItem item) {
items.add(item);
notifyDataSetChanged();
}
}
Then, you have ton initialize the RecyclerView only once. The best place to do that is in the onCreate method.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ArrayList<RecyclerItem> addFahToCelCard;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addFahToCelCard = new ArrayList<>();
setupRecyclerView();
setupClickListener();
}
private void setupRecyclerView() {
recyclerView = findViewById(R.id.recycler_item_view);
recyclerItemAdapter = new RecyclerItemAdapter(addFahToCelCard);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
recyclerView.setAdapter(recyclerItemAdapter);
}
}
Now add your onClickListener which will only add the card to the list.
private void setupClickListener() {
ftocConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
recyclerItemAdapter.addItem(new RecyclerItem());
}
});
}

What is your xml layout for this cardview ? It looks like this cardview is in another layout that has match parent as width and height.
If thats the case items are too big to show.
Okay so try making first reletive layout height = 100dp to match the card view in fahrenheit_to_celsius_converter_layout.xml

well I didn't understand the problem very well but from what I understood here's what you should do :
first you shouldn't be creating a new recycler view on every button click, instead you should put the code that initializes the recycler view in onCreate method that exist in the activity class and just keep a reference to the arraylist that holds the data and the adapter as global variables.
whenever the user clicks the button you should add a new item to the arraylist of data and use adapter.notifyDataItemSetChanged to tell the recycle view to check if there's any change happened to the recycle view and take action if necessary
here's a part of code that explains what I'm saying and I hope you that even if that doesn't answer your question, you catch a glimpse of how to deal with recyclerview :
first as I said you should keep a reference to the arraylist that holds the data and the adapter as global variables so put those outside any method in the activity
RecyclerItemAdapter recyclerItemAdapter ;
ArrayList <RecyclerItem>addFahToCelCard ;
and then put this code instead of the button code
addFahToCelCard = new ArrayList<>();
recyclerView = findViewById(R.id.recycler_item_view);
layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerItemAdapter = new RecyclerItemAdapter(addFahToCelCard);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerItemAdapter);
ftocConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addFahToCelCard.add(new RecyclerItem());
recyclerItemAdapter.notifyDataSetChanged();
}
}
});
that way whenever you want to edit the recyclerView data anytime you can add/remove items from the global arraylist and notify the adapter just like the code inside the button OnClickListener
update to the last video posted about the exception
this problem raises when you delete some items, try to use holder.getAbsoluteAdapterPosition(), instead of getAdapterPosition or the old final position value.
whenever you use a value inside a listener I guess it takes the value that exists right now and hold it as final, so if you have 5 items and deleted the first 3, the last two will still have their position stored as 4 and 5 instead of 1 and 2, thats why you should call the holder.getAbsoluteAdapterPosition() to get the current position instead of the final stored one, that way he stores the holder as final instead of storing a const int value.

Related

How to show dynamic items in one row of RecyclerView? When the row clicked shows all items again

I know how to add items to RecyclerView and show them, but let's say I add some dynamic items to the RecyclerView like this image
Here After click save button, it creates three rows in the RecyclerView like below image, which I don't want it creates three rows.
Instead I want to create one row, and when I clicked in that row then shows the three items like this image.
AddChecklist class
public class AddChecklist extends AppCompatActivity {
Button btnAddItem;
public LinearLayout linearLayout;
DbHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_checklist);
dbHelper = new DbHelper(this);
btnAddItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addView();
}
});
}
public void addView(){
View checklistView = getLayoutInflater().inflate(R.layout.checklist_view, null, false);
EditText etChecklistItem = checklistView.findViewById(R.id.et_checklist_item);
CheckBox checkBox = checklistView.findViewById(R.id.check_box);
linearLayout.addView(checklistView);
ImageView imgDelete = checklistView.findViewById(R.id.img_delete);
imgDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
removeView(checklistView);
}
});
}
public void removeView(View view){
linearLayout.removeView(view);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
DbHelper dbHelper = new DbHelper(getApplicationContext());
switch (item.getItemId()) {
case R.id.btn_save:
ChecklistHelper checklistHelper = new ChecklistHelper();
for (int i = 0; i < linearLayout.getChildCount(); i++) {
View v = linearLayout.getChildAt(i);
EditText etChecklistItem = v.findViewById(R.id.et_checklist_item);
CheckBox checkBox = v.findViewById(R.id.check_box);
if (checkBox.isChecked()) {
checklistHelper.setStatus("1");
}
else
checklistHelper.setStatus("0");
dbHelper.insertChecklist(checklistHelper.getStatus(), etChecklistItem.getText().toString(), DateTime.date(), DateTime.time(), System.currentTimeMillis());
}
finish();
break;
}
return true;
}
}
Adapter class
public class ChecklistItems extends AppCompatActivity {
Toolbar toolbar;
RecyclerView recyclerView;
String content;
String status;
boolean isEditChecklist = false;
private ChecklistAdapter checklistAdapter;
DbHelper dbHelper;
List<ChecklistHelper> checks;
int id;
ChecklistHelper checklistHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checklist_items);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
checklistHelper = new ChecklistHelper();
dbHelper = new DbHelper(this);
checks = dbHelper.getChecklists();
checklistAdapter = new ChecklistAdapter(checks);
recyclerView.setAdapter(checklistAdapter);
}
public class ChecklistAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private boolean isEnableDelete = false;
List<ChecklistHelper> checkList;
public ChecklistAdapter(List<ChecklistHelper> checkList) {
this.checkList = checkList;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.checklist_layout_child, parent, false);
return new ChecklistChildViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
ChecklistChildViewHolder checklistChildViewHolder = (ChecklistChildViewHolder) holder;
checklistChildViewHolder.updateVisibility(isEnableDelete);
checklistChildViewHolder.checkBox.setText(checkList.get(position).getContent());
checklistChildViewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
String txt = checklistChildViewHolder.checkBox.getText().toString();
if (b)
checklistChildViewHolder.checkBox.setText(lineThrough(txt));
else
checklistChildViewHolder.checkBox.setText(txt);
}
});
checklistChildViewHolder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dbHelper.deleteChecklist(id);
finish();
}
});
}
#Override
public int getItemCount() {
return checkList.size();
}
public void updateItems(boolean isEnableDelete){
this.isEnableDelete = isEnableDelete;
notifyDataSetChanged();
}
public class ChecklistChildViewHolder extends RecyclerView.ViewHolder {
CheckBox checkBox;
ImageView delete, edit;
ChecklistChildViewHolder(#NonNull View itemView) {
super(itemView);
checkBox = itemView.findViewById(R.id.checkbox_child);
delete = itemView.findViewById(R.id.delete_child);
edit = itemView.findViewById(R.id.edit_child);
delete.setVisibility(View.INVISIBLE);
edit.setVisibility(View.INVISIBLE);
}
public void updateVisibility(boolean isEnableDelete){
if (isEnableDelete) {
delete.setVisibility(View.VISIBLE);
edit.setVisibility(View.VISIBLE);
}
else {
delete.setVisibility(View.INVISIBLE);
edit.setVisibility(View.INVISIBLE);
}
}
}
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
DbHelper dbHelper = new DbHelper(this);
// long id = getIntent().getIntExtra("id", 0);
switch (item.getItemId()) {
case R.id.edit:
isEditChecklist = true;
checklistAdapter.updateItems(true);
invalidateOptionsMenu();
break;
case R.id.save:
Toast.makeText(getApplicationContext(), "saved ", Toast.LENGTH_SHORT).show();
checklistAdapter.updateItems(false);
isEditChecklist = false;
finish();
break;
case R.id.delete:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Delete Checklist");
builder.setMessage("Are you sure?");
builder.setPositiveButton("Continue ", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dbHelper.deleteChecklist(id);
// checklistAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "checklist deleted", Toast.LENGTH_SHORT).show();
finish();
}
});
builder.setNegativeButton("Cancel ", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
}).create().show();
break;
}
return true;
}
}

When I click on next song my seekbar sometimes gets updated and sometimes not. I am not getting what's the error in my code probably with the seekbar

**Main Activity.java**
This is main activity where I instantiate all methods/objects. Here I use Dexter library to grab files from user's external storage, then I made one method called find songs which helps in finding the path of files and list them accordingly. Then I made another method called display songs which will help in getting the whole size of songs and then display the whole list with their names accordingly. Then with the help of custom adapter I passed my list of songs which is in array named item.
public class MainActivity extends AppCompatActivity {
ListView listView;
String [] items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listViewSong);
runtimePermission();
}
public void runtimePermission(){
Dexter.withContext(this)
.withPermissions(Manifest.permission.READ_EXTERNAL_STORAGE,Manifest
.permissi
on.RECORD_AUDIO)
.withListener(new MultiplePermissionsListener() {
#RequiresApi(api = Build.VERSION_CODES.R)
#Override
public void
onPermissionsChecked(MultiplePermissionsReport
multiplePermissionsReport)
{
displaySongs();
}
#Override
public void
onPermissionRationaleShouldBeShown(List<PermissionRequest> list,
PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
}
public ArrayList<File> findSong(File file){
ArrayList arrayList = new ArrayList();
Log.d(TAG, "findSong:"+ file.getPath());
File [] files = file.listFiles();
if (files!=null) {
Log.d(TAG, "findSong:"+ files.length);
for (File singleFile : files) {
if (singleFile.isDirectory() && !singleFile.isHidden()) {
arrayList.addAll(findSong(singleFile));
} else {
if (singleFile.getName().endsWith(".mp3") &&
!singleFile.getName().startsWith(".")) {
arrayList.add(singleFile);
}
}
}
}
return arrayList;
}
public void displaySongs(){
ArrayList<File> mySongs =
findSong(Environment.getExternalStorageDirectory());
String [] items = new String [mySongs.size()];
if(mySongs == null)return; // this is very important function
otherwise app will crash
for (int i=0; i<mySongs.size(); i++){
items[i] = mySongs.get(i).getName().replace(".mp3",
"");
}
Log.d(TAG, "displaySongs:"+ items.length);
(this,
android.R.layout.simple_list_item_1,items);
CustomAdapter customAdapter = new CustomAdapter(this,
Arrays.asList(items));
Log.d(TAG, "displaySongs:"+ customAdapter.getCount());
listView.setAdapter(customAdapter);
listView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
String currentSong = (String)
listView.getItemAtPosition(position);
startActivity(new Intent(getApplicationContext(),
PlayerActivity.class)
.putExtra("currentSong", currentSong)
.putExtra("position",position)
.putExtra("songs",mySongs));
}
});
}
class CustomAdapter extends ArrayAdapter {
public android.util.Log Log;
List<String> names;
LayoutInflater inflater;
Context context;
public CustomAdapter(Context context, List<String> names) {
super(context,R.layout.list_item ,names);
this.names=names;
this.context=context;
}
#Override
public View getView(int position, View convertView, ViewGroup
parent) {
inflater=LayoutInflater.from(getContext()); //inflater is
responsible for taking your xml files that defines your layout
// and converting them into view objects.
View
customview=inflater.inflate(R.layout.list_item,parent,false);
String data=names.get(position);
//String data1=names.get(position+1);
TextView tv=
(TextView)customview.findViewById(R.id.textsongname);
tv.setText(data);
tv.setSelected(true);
//TextView tv1=(TextView)customview.findViewById(R.id.TeamB);
//tv1.setText(data1);
return customview;
}
}
}
**PlayerActivity.java**
I tried to make a Thread named update seek bar which will update my seek bar to current position after that I applied set on click bar change listener so that whenever user update position of sidebar it should get updated. But error here is that when I run my app using this code on emulator its working completely fine but when installed in my phone 2 errors are coming. One after completion of song its not jumping automatically to the next song and second when user update sidebar and press next, sidebar is not coming to position 0, and this whole error is showing on my phone not in emulator.
public class PlayerActivity extends AppCompatActivity {
Button play,next,fastforward, previous, fastrewind;
TextView txtsn, txtsstart, txtsstop;
SeekBar seekBar;
BarVisualizer visualizer;
Thread updateSeekBar;
String sName;
public static final String EXTRA_NAME = "song_name";
static MediaPlayer mediaPlayer;
int position;
ArrayList mySongs;
ImageView imageView;
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId()== android.R.id.home){
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onDestroy() {
if (visualizer != null){
visualizer.release();
}
super.onDestroy();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
getSupportActionBar().setTitle("Now Playing");
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
play = findViewById(R.id.play);
next = findViewById(R.id.next);
previous = findViewById(R.id.previous);
fastforward = findViewById(R.id.fastforward);
fastrewind = findViewById(R.id.fastrewind);
txtsn = findViewById(R.id.txtsn);
txtsstart = findViewById(R.id.txtsstart);
txtsstop = findViewById(R.id.txtsstop);
seekBar = findViewById(R.id.seekbar);
visualizer = findViewById(R.id.blast);
imageView = findViewById(R.id.iamgeView);
if (mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
}
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
mySongs = (ArrayList) bundle.getParcelableArrayList("songs");
sName = intent.getStringExtra("currentSong");
position = bundle.getInt("position",0);
txtsn.setText(sName);
txtsn.setSelected(true);
Uri uri = Uri.parse(mySongs.get(position).toString()); // uri is
usually use tell a content provider what we want to access by
reference
mediaPlayer = MediaPlayer.create(this,uri);
mediaPlayer.start();
seekBar.setMax(mediaPlayer.getDuration());
updateSeekBar = new Thread(){
#Override
public void run() {
int currentPosition = 0;
while (currentPosition<mediaPlayer.getDuration()){
try {
currentPosition = mediaPlayer.getCurrentPosition();
seekBar.setProgress(currentPosition);
sleep(500);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
};
updateSeekBar.start();
seekBar.setOnSeekBarChangeListener(new
SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mediaPlayer.seekTo(seekBar.getProgress());
}
});
String endTime = createTime(mediaPlayer.getDuration());
txtsstop.setText(endTime);
final Handler handler = new Handler();
final int delay = 1000;
handler.postDelayed(new Runnable() {
#Override
public void run() {
String currentTime =
createTime(mediaPlayer.getCurrentPosition());
txtsstart.setText(currentTime);
handler.postDelayed(this,delay);
}
},delay);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()){
play.setBackgroundResource(R.drawable.ic_play);
mediaPlayer.pause();
}
else {
play.setBackgroundResource(R.drawable.ic_pause);
mediaPlayer.start();
}
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.release();
if(position!=mySongs.size()-1){
position = position + 1;
}
else{
position = 0;
}
Uri uri = Uri.parse(mySongs.get(position).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(),
uri);
sName = mySongs.get(position).toString();
txtsn.setText(sName);
mediaPlayer.start();
play.setBackgroundResource(R.drawable.ic_pause);
seekBar.setMax(mediaPlayer.getDuration());
startAnimation(imageView);
int audiosessionId = mediaPlayer.getAudioSessionId();
if(audiosessionId!= -1){
visualizer.setAudioSessionId(audiosessionId);
}
}
});
mediaPlayer.setOnCompletionListener(new
MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
next.performClick();
}
});
int audiosessionId = mediaPlayer.getAudioSessionId();
if(audiosessionId!= -1){
visualizer.setAudioSessionId(audiosessionId);
}
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.release();
if(position!=0){
position = position - 1;
}
else{
position = mySongs.size() - 1;
}
Uri uri = Uri.parse(mySongs.get(position).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(),
uri);
sName = mySongs.get(position).toString();
txtsn.setText(sName);
mediaPlayer.start();
play.setBackgroundResource(R.drawable.ic_pause);
seekBar.setMax(mediaPlayer.getDuration());
startAnimation(imageView);
int audiosessionId = mediaPlayer.getAudioSessionId();
if(audiosessionId!= -1){
visualizer.setAudioSessionId(audiosessionId);
}
}
});
fastforward.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()){
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition()+1000);
}
}
});
fastrewind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()){
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition()-1000);
}
}
});
}
private boolean isPermissionGranted(){
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R){
return Environment.isExternalStorageManager();
}
else {
int readExternalStoragePermission =
ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE);
return readExternalStoragePermission ==
PackageManager.PERMISSION_GRANTED;
}
}
public void startAnimation(View view){
ObjectAnimator animator =
ObjectAnimator.ofFloat(imageView,"rotation",0f,360f);
animator.setDuration(1000);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(animator);
animatorSet.start();
}
public String createTime(int duration) {
String time = "";
int min = duration/1000/60;
int sec = duration/1000%60;
time+=min+":";
if (sec<10) {
time+="0";
}
time+=sec;
return time;
}
}

Recycler Adapter item bug

I'm trying to make a comment page like instagram but I'm getting a ridiculous error;
Every comment row has one recyclerview and user click the "show replies" button I make Recyclerview visible but After 10-11 items, recyclerview of that item is also visible.
I know my English is terrible by mistake but i need help.
holder.replyCount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(main,"sdf",Toast.LENGTH_LONG).show();
new Comment().getCommentResponse(getCommentModels.get(position).getId(), new IMainResponse() {
#Override
public <T> void Succsess(Response<T> _response) {
getCommentModel = (List<getCommentModel>) _response.body();
AdapterComment adapterComment = new AdapterComment(main, getCommentModel);
holder.recyclerView.setVisibility(View.VISIBLE);
holder.recyclerView.setAdapter(adapterComment);
holder.recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(main);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
holder.recyclerView.setLayoutManager(linearLayoutManager);
}
#Override
public void Error(ErrorModel _eresponse) {
}
});
}
});
Create a boolean in your model class to keep track of visibility
if (getCommentModels.get(position).isVisible()) {
holder.recyclerView.setVisibility(View.VISIBLE);
} else {
holder.recyclerView.setVisibility(View.GONE);
}
holder.replyCount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getCommentModels.get(position).setVisible(!getCommentModels.get(position).isVisible());
notifyItemChanged(position);
new Comment().getCommentResponse(getCommentModels.get(position).getId(), new IMainResponse() {
#Override
public <T> void Succsess(Response<T> _response) {
getCommentModel = (List<getCommentModel>) _response.body();
AdapterComment adapterComment = new AdapterComment(main, getCommentModel);
holder.recyclerView.setAdapter(adapterComment);
holder.recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(main);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
holder.recyclerView.setLayoutManager(linearLayoutManager);
}
#Override
public void Error(ErrorModel _eresponse) {
}
});
}
});

Setting the dataset for Recyclerview after filter

I am filtering my data using onQueryTextChange, the list filters but it still shows the old data set(unfiltered) which results in data from the old list, even though it shows the new filtered list.
Can someone fix my code which will display the right data set after filter, and unfiltered dataset when the a user will clear the search text.
I will explain it better with screenshots.
Before filter Screenshot 1, clicking on a item will toast the text on it.
After Filter Screenshot 2, on click it is supposed to say HDFC BANK, instead it still shows the data from Position 1 from the unfiltered data set.
I was told its because I am using the BankNames List (unfiltered) text at position when clicking, because of which this is happening.
Can someone please fix my logic here, I am unable to figure this out, even though it seems simple, I am new to Android.
MainActivity.java
public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener
{
List<DataAdapter> DataAdapterClassList;
RecyclerView recyclerView;
final List<DataAdapter> filteredModelList = new ArrayList<>();
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerViewAdapter recyclerViewadapter;
ProgressBar progressBar;
JsonArrayRequest jsonArrayRequest;
ArrayList<String> BankNames;
RequestQueue requestQueue;
String HTTP_SERVER_URL = "http://hiddenforsecurity.com";
View ChildView;
int RecyclerViewClickedItemPOS;
LinearLayout lyt, icicBtn, hdfcBtn, axisBtn, sbiBtn, pnbBtn, yesBtn;
private static int firstVisibleInListview;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DataAdapterClassList = new ArrayList<>();
BankNames = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView1);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
lyt = (LinearLayout) findViewById(R.id.Layout1);
final Intent go = new Intent(MainActivity.this, StateList.class);
icicBtn = (LinearLayout) findViewById(R.id.icicBtn);
hdfcBtn = (LinearLayout) findViewById(R.id.hdfcBtn);
axisBtn = (LinearLayout) findViewById(R.id.axisBtn);
sbiBtn = (LinearLayout) findViewById(R.id.sbiBtn);
pnbBtn = (LinearLayout) findViewById(R.id.pnbBtn);
yesBtn = (LinearLayout) findViewById(R.id.yesBtn);
final Intent i = new Intent(this, StateList.class);
// JSON data web call function call from here.
JSON_WEB_CALL();
//RecyclerView Item click listener code starts from here.
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
GestureDetector gestureDetector = new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
return true;
}
});
#Override
public boolean onInterceptTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
ChildView = Recyclerview.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if (ChildView != null && gestureDetector.onTouchEvent(motionEvent)) {
//Getting RecyclerView Clicked item value.
RecyclerViewClickedItemPOS = Recyclerview.getChildAdapterPosition(ChildView);
Toast.makeText(MainActivity.this, BankNames.get(RecyclerViewClickedItemPOS), Toast.LENGTH_SHORT).show();
//Printing RecyclerView Clicked item clicked value using Toast Message.
//i.putExtra("selectedbank", BankNames.get(RecyclerViewClickedItemPOS));
//startActivity(i);
}
return false;
}
#Override
public void onTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
icicBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "ICICI BANK LIMITED");
startActivity(go);
}
});
axisBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "AXIS BANK");
startActivity(go);
}
});
hdfcBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "HDFC BANK");
startActivity(go);
}
});
sbiBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "STATE BANK OF INDIA");
startActivity(go);
}
});
pnbBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "PUNJAB NATIONAL BANK");
startActivity(go);
}
});
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "YES BANK");
startActivity(go);
}
});
}
public void JSON_WEB_CALL(){
progressBar.setVisibility(View.VISIBLE);
jsonArrayRequest = new JsonArrayRequest(HTTP_SERVER_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
DataAdapter GetDataAdapter2 = new DataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setBankName(json.getString("BANK"));
//Adding subject name here to show on click event.
BankNames.add(json.getString("BANK"));
}
catch (JSONException e)
{
e.printStackTrace();
}
DataAdapterClassList.add(GetDataAdapter2);
}
progressBar.setVisibility(View.GONE);
recyclerViewadapter = new RecyclerViewAdapter(DataAdapterClassList, this);
recyclerView.setAdapter(recyclerViewadapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
final List<DataAdapter> filteredModelList = filter(DataAdapterClassList, newText);
if (filteredModelList.size() > 0) {
recyclerViewadapter.setFilter(filteredModelList);
return true;
} else {
Toast.makeText(MainActivity.this, "Not Found", Toast.LENGTH_SHORT).show();
return false;
}
}
private List<DataAdapter> filter(List<DataAdapter> models, String query) {
query = query.toLowerCase();
final List<DataAdapter> filteredModelList = new ArrayList<>();
for (DataAdapter model : models) {
final String text = model.getBankName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
recyclerViewadapter = new RecyclerViewAdapter(filteredModelList, MainActivity.this);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
recyclerView.setAdapter(recyclerViewadapter);
recyclerViewadapter.notifyDataSetChanged();
return filteredModelList;
}
}
RecyclerviewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
public DataAdapter dataAdapter;
List<DataAdapter> dataAdapters;
public RecyclerViewAdapter(List<DataAdapter> getDataAdapter, Context context){
super();
this.dataAdapters = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
dataAdapter = dataAdapters.get(position);
viewHolder.TextViewName.setText(dataAdapter.getBankName());
}
#Override
public int getItemCount() {
return dataAdapters.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView TextViewName;
public ViewHolder(View itemView) {
super(itemView);
TextViewName = (TextView) itemView.findViewById(R.id.TextViewCard) ;
}
}
public void setFilter(List<DataAdapter> bankNames) {
dataAdapters = new ArrayList<>();
dataAdapters.addAll(bankNames);
notifyDataSetChanged();
}
}
Make global variable for filteredList and take data from that list. The error happened because you are toasting from the full list. Not filteredList
Try this
may this issue that your are Printing Toast of BankNames.get(RecyclerViewClickedItemPOS) from your Oldlist not From the filteredModelList
Remove this
//Getting RecyclerView Clicked item value.
RecyclerViewClickedItemPOS = Recyclerview.getChildAdapterPosition(ChildView);
Toast.makeText(MainActivity.this, BankNames.get(RecyclerViewClickedItemPOS), Toast.LENGTH_SHORT).show();
and set Toast in Adapter class
viewHolder.TextViewName..setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, dataAdapter.getBankName(), Toast.LENGTH_SHORT).show();
}
});

Recyclerview filter picks previous element data after Filteres

I am filtering my recyclerview data with onQueryTextChange method, the filter is working fine, however when I am clicking on a element after filter, it still picks up the element that was placed before the filter. Could some one point me out what I am doing wrong here.
MainActivity.java
public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener
{
List<DataAdapter> DataAdapterClassList;
RecyclerView recyclerView;
EditText etSearch;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerViewAdapter recyclerViewadapter;
ProgressBar progressBar;
JsonArrayRequest jsonArrayRequest;
ArrayList<String> BankNames;
RequestQueue requestQueue;
String HTTP_SERVER_URL = "http://hiddenforsecurity.com?method=apiTest";
View ChildView;
int RecyclerViewClickedItemPOS;
LinearLayout lyt, icicBtn, hdfcBtn, axisBtn, sbiBtn, pnbBtn, yesBtn;
private static int firstVisibleInListview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DataAdapterClassList = new ArrayList<>();
BankNames = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView1);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
lyt = (LinearLayout) findViewById(R.id.Layout1);
final Intent go = new Intent(MainActivity.this, StateList.class);
icicBtn = (LinearLayout) findViewById(R.id.icicBtn);
hdfcBtn = (LinearLayout) findViewById(R.id.hdfcBtn);
axisBtn = (LinearLayout) findViewById(R.id.axisBtn);
sbiBtn = (LinearLayout) findViewById(R.id.sbiBtn);
pnbBtn = (LinearLayout) findViewById(R.id.pnbBtn);
yesBtn = (LinearLayout) findViewById(R.id.yesBtn);
final Intent i = new Intent(this, StateList.class);
// JSON data web call function call from here.
JSON_WEB_CALL();
//RecyclerView Item click listener code starts from here.
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
GestureDetector gestureDetector = new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
return true;
}
});
#Override
public boolean onInterceptTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
ChildView = Recyclerview.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if (ChildView != null && gestureDetector.onTouchEvent(motionEvent)) {
//Getting RecyclerView Clicked item value.
RecyclerViewClickedItemPOS = Recyclerview.getChildAdapterPosition(ChildView);
Toast.makeText(MainActivity.this, BankNames.get(RecyclerViewClickedItemPOS), Toast.LENGTH_SHORT).show();
//Printing RecyclerView Clicked item clicked value using Toast Message.
//i.putExtra("selectedbank", BankNames.get(RecyclerViewClickedItemPOS));
//startActivity(i);
}
return false;
}
#Override
public void onTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
icicBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "ICICI BANK LIMITED");
startActivity(go);
}
});
axisBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "AXIS BANK");
startActivity(go);
}
});
hdfcBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "HDFC BANK");
startActivity(go);
}
});
sbiBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "STATE BANK OF INDIA");
startActivity(go);
}
});
pnbBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "PUNJAB NATIONAL BANK");
startActivity(go);
}
});
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "YES BANK");
startActivity(go);
}
});
}
public void JSON_WEB_CALL(){
progressBar.setVisibility(View.VISIBLE);
jsonArrayRequest = new JsonArrayRequest(HTTP_SERVER_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
DataAdapter GetDataAdapter2 = new DataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setBankName(json.getString("BANK"));
//Adding subject name here to show on click event.
BankNames.add(json.getString("BANK"));
}
catch (JSONException e)
{
e.printStackTrace();
}
DataAdapterClassList.add(GetDataAdapter2);
}
progressBar.setVisibility(View.GONE);
recyclerViewadapter = new RecyclerViewAdapter(DataAdapterClassList, this);
recyclerView.setAdapter(recyclerViewadapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
final List<DataAdapter> filteredModelList = filter(DataAdapterClassList, newText);
if (filteredModelList.size() > 0) {
recyclerViewadapter.setFilter(filteredModelList);
return true;
} else {
Toast.makeText(MainActivity.this, "Not Found", Toast.LENGTH_SHORT).show();
return false;
}
}
private List<DataAdapter> filter(List<DataAdapter> models, String query) {
query = query.toLowerCase();
final List<DataAdapter> filteredModelList = new ArrayList<>();
for (DataAdapter model : models) {
final String text = model.getBankName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
recyclerViewadapter = new RecyclerViewAdapter(filteredModelList, MainActivity.this);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
recyclerView.setAdapter(recyclerViewadapter);
recyclerViewadapter.notifyDataSetChanged();
return filteredModelList;
}
}
RecyclerviewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
public DataAdapter dataAdapter;
List<DataAdapter> dataAdapters;
public RecyclerViewAdapter(List<DataAdapter> getDataAdapter, Context context){
super();
this.dataAdapters = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
dataAdapter = dataAdapters.get(position);
viewHolder.TextViewName.setText(dataAdapter.getBankName());
}
#Override
public int getItemCount() {
return dataAdapters.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView TextViewName;
public ViewHolder(View itemView) {
super(itemView);
TextViewName = (TextView) itemView.findViewById(R.id.TextViewCard) ;
}
}
public void setFilter(List<DataAdapter> bankNames) {
dataAdapters = new ArrayList<>();
dataAdapters.addAll(bankNames);
notifyDataSetChanged();
}
}
Please have a look at these screenshot for better understanding of my query.
When I click on a item before filter, Toast displays correct data.
Unfiltered Screenshot
When I click on a item after filtering, Toast still displays the data from the above screenshot, where as it was supposed to show HDFC BANK.Filtered Screenshot
Its because you are changing dataset in list view but later on in Toast you reffer to BankNames which is different dataset.
In your example list has ony 1 element due to filters. While you click it, clicked index will be in fact 0, not x as you would require and later on you are picking 0 indexed bank from BankNames not from filtered result set.
To get things right, use the same dataset for list view and data fetch.
You can do that, by simply creating filteredBankNames collection that will contain currently filtered results, and pass that to your list view. In the same time, in on click event, pick bank name from filteredBankNames as well insteed of BankNames
So for example:
// make this not final local variable, but a field in activity so you can remember filtered items
final List<DataAdapter> filteredModelList = filter(DataAdapterClassList, newText);
if (filteredModelList.size() > 0) {
recyclerViewadapter.setFilter(filteredModelList);
return true;
} else {
and with Toast
Toast.makeText(MainActivity.this, filteredModelList.get(RecyclerViewClickedItemPOS), Toast.LENGTH_SHORT).show();

Categories