How to implement like button hitting count in RecyclerView. I have already created a like button and counter TextView with this code but when I hit the like button the application crashes. This is my code, what's wrong? I am using toggle button for like option and a TextView for counting like hitting.
This is my viewholder
public class WritingsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView MainTitle;
public ImageView Mainimage;
public ImageView Profimage;
public TextView ProfName;
public TextView txv;
public ToggleButton liketglbtn;
public TextView MainDesc, Idvkanme;
private ItemClickListner itemClickListner;
public void setItemClickListner(ItemClickListner itemClickListner) {
this.itemClickListner = itemClickListner;
}
public WritingsViewHolder(View itemView) {
super(itemView);
MainTitle = (TextView)itemView.findViewById(R.id.RTitle);
Mainimage = (ImageView)itemView.findViewById(R.id.rImageView);
Profimage = (ImageView)itemView.findViewById(R.id.Profile_Image);
ProfName = (TextView)itemView.findViewById(R.id.Prof_Name);
MainDesc = (TextView)itemView.findViewById(R.id.rDescriptionTv);
Idvkanme = (TextView)itemView.findViewById(R.id.Idavaka_Name);
txv = (TextView)itemView.findViewById(R.id.tx);
liketglbtn = (ToggleButton) itemView.findViewById(R.id.likeToggleBtn);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
itemClickListner.onClick(v,getAdapterPosition(),false);
}
}
This is my activity
public class WritingsActivity extends AppCompatActivity {
RecyclerView recyclerView;
FirebaseRecyclerOptions<IdavakaModel> options;
FirebaseRecyclerAdapter<IdavakaModel, WritingsViewHolder> adapter;
DatabaseReference MCC;
String categoryId = "";
RecyclerView.LayoutManager layoutManager;
TextView smsCountText;
int pendingSMSCount = 10;
static Button notifCount;
static int mNotifCount = 0;
Button FBcard, YoutubeCard;
private static final String APP_ID = "ca-app-pub-8867939169855032~9998384849";
Button mSaveBtn, mShareBtn;
private long backPressedTime;
private Toast backToast;
private int mCounter = 0;
ToggleButton btn;
TextView txv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_writings);
FBcard = (Button) findViewById(R.id.button1);
FBcard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent toy = new Intent(WritingsActivity.this, IdavakaNewsUploadActivity.class);
startActivity(toy);
WritingsActivity.this.finish();
}
});
MobileAds.initialize(this,APP_ID);
AdView adView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
//Bottom Navigation Bar
final BottomNavigationView bottomNavigationView = (BottomNavigationView)findViewById(R.id.botmnavigation);
bottomNavigationView.setSelectedItemId(R.id.action_privacy);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.myhome:
startActivity(new Intent(getApplicationContext(),MainActivity.class));
overridePendingTransition(0,0);
return true;
case R.id.action_notification:
startActivity(new Intent(getApplicationContext(),ChristianNewsMainActivity.class));
overridePendingTransition(0,0);
return true;
case R.id.action_privacy:
return true;
}
return false;
}
});
MCC= FirebaseDatabase.getInstance().getReference().child("Writings");
recyclerView = (RecyclerView) findViewById(R.id.readingroom_recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
LoadData(categoryId);
}
private void LoadData(String categoryId) {
options = new FirebaseRecyclerOptions.Builder<IdavakaModel>().setQuery(MCC,IdavakaModel.class).build();
adapter = new FirebaseRecyclerAdapter<IdavakaModel, WritingsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull WritingsViewHolder writingsViewHolder, int i, #NonNull IdavakaModel idavakaModel) {
writingsViewHolder.MainTitle.setText(idavakaModel.getTitle());
writingsViewHolder.MainDesc.setText(idavakaModel.getDesc());
writingsViewHolder.ProfName.setText(idavakaModel.getProfname());
writingsViewHolder.Idvkanme.setText(idavakaModel.getIdavakaname());
Picasso.get().load(idavakaModel.getPostimage())
.into(writingsViewHolder.Mainimage);
Picasso.get().load(idavakaModel.getProfimage())
.into(writingsViewHolder.Profimage);
writingsViewHolder.setItemClickListner(new ItemClickListner() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Intent detailsIntent = new Intent(WritingsActivity.this, IdavakaDetailActivity.class);
detailsIntent.putExtra("CategoryId", adapter.getRef(position).getKey());
startActivity(detailsIntent);
}
});
writingsViewHolder.liketglbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCounter++;
txv.setText(Integer.toString(mCounter));
}
});
}
#NonNull
#Override
public WritingsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.writngs_items, parent, false);
return new WritingsViewHolder(v);
}
};
adapter.startListening();
recyclerView.setAdapter(adapter);
}
#Override
public void onBackPressed() {
if (backPressedTime + 2000 > System.currentTimeMillis()) {
backToast.cancel();
super.onBackPressed();
WritingsActivity.this.finish();
return;
} else {
backToast = Toast.makeText(getBaseContext(), "See You Soon", Toast.LENGTH_SHORT);
backToast.show();
}
backPressedTime = System.currentTimeMillis();
WritingsActivity.this.finish();
}
public void onCustomToggleClick (View view) {
Toast.makeText(this, "Liked",Toast.LENGTH_SHORT).show();
}
}
You are getting NullPointerException because the TextView you are using is in Activity named txv where you are setting counter. But the problem is you have declared TextView in Activity but have not initialized anywhere in the Activity. You MUST initialize that variable via findViewbyId method before setting values.
Furthermore, you have initialized txv TextView and accessing on Activity that is why you are getting NLP. TextView is a part of Activity layout which you have not Initialized. On the hand you have initialized txv in Adapter which is of no use.
Related
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;
}
}
I have been trying to implement search using firestoreUI but when i run my code the logcat says that:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.firebase.ui.firestore.FirestoreRecyclerAdapter.startListening()' on a null object reference
at com.example.homebarberv1.Search.onStart(Search.java:93)
below is my code:
public class Search extends AppCompatActivity implements FirebaseAuth.AuthStateListener{
private EditText searchField;
private Button searchButton;
private RecyclerView searchRecyclerview;
private FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
private FirestoreRecyclerAdapter<User, UsersViewHolder> adapter;
private String searchText;
static {
FirebaseFirestore.setLoggingEnabled(true);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_search);
searchField = findViewById(R.id.SearchField);
searchButton = findViewById(R.id.SearchButton);
searchRecyclerview = findViewById(R.id.SearchContainer);
LinearLayoutManager manager = new LinearLayoutManager(this);
manager.setReverseLayout(true);
manager.setStackFromEnd(true);
searchRecyclerview .setHasFixedSize(true);
searchRecyclerview .setLayoutManager(manager);
BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView);
bottomNavigationView.setSelectedItemId(R.id.search);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.search:
return true;
case R.id.appointment:
startActivity(new Intent(getApplicationContext(),HomePage.class));
overridePendingTransition(0,0);
return true;
case R.id.profile:
startActivity(new Intent(getApplicationContext(),Profile.class));
overridePendingTransition(0,0);
return true;
}
return false;
}
});
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
searchText = searchField.getText().toString();
firebaseUserSearch(searchText);
}
});
}
#Override
public void onStart() {
super.onStart();
if (isSignedIn()) {
adapter.startListening();
}
firebaseAuth.addAuthStateListener(this);
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
FirebaseAuth.getInstance().removeAuthStateListener(this);
}
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth auth) {
if (isSignedIn()) {
adapter.startListening();
} else {
Toast.makeText(Search.this,"user are not signed in",Toast.LENGTH_LONG);
}
}
private boolean isSignedIn() {
return FirebaseAuth.getInstance().getCurrentUser() != null;
}
#NonNull
private void firebaseUserSearch(String searchText){
CollectionReference sCollection =
FirebaseFirestore.getInstance().collection("Barbers");
Query sQuery = sCollection.startAt(searchText).endAt(searchText + "\uf8ff");
FirestoreRecyclerOptions<User> options =
new FirestoreRecyclerOptions.Builder<User>()
.setQuery(sQuery, User.class)
.setLifecycleOwner(this)
.build();
adapter = new FirestoreRecyclerAdapter<User, UsersViewHolder>(options) {
#NonNull
#Override
public UsersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.searchlist, parent, false);
return new UsersViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull UsersViewHolder holder, int position, #NonNull User model) {
holder.setName(model.getShopname());
holder.setPic(model.getPiclink());
holder.setAddress(model.getAddress() + ", " + model.getPostcode().toString() + ", " + model.getCity());
}
};
searchRecyclerview.setAdapter(adapter);
}
public class UsersViewHolder extends RecyclerView.ViewHolder {
private View mView;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setName(String name){
TextView userNameView = (TextView) mView.findViewById(R.id.shopNameS);
userNameView.setText(name);
}
public void setPic(String link){
ImageView imageView = (ImageView)mView.findViewById(R.id.imageS);
Picasso.get().load(link).into(imageView);
}
public void setAddress(String address){
TextView addressView = (TextView) mView.findViewById(R.id.shopAddressS);
addressView.setText(address);
}
}
}
the error refers to this line:
adapter.startListening();
I'm still new to Android, so I do not really understand what I'm doing wrong here, help is really appreciated
You need to ensure that adapter has been given a value, before you call adapter.startListening on it.
That means that in onStart you need to ensure the adapter exists:
#Override
public void onStart() {
super.onStart();
if (isSignedIn() && adapter != null) {
adapter.startListening();
}
firebaseAuth.addAuthStateListener(this);
}
And then also start listening on the adapter when you create it and the user is signed in. So:
adapter = new FirestoreRecyclerAdapter<User, UsersViewHolder>(options) {
...
});
if (isSignedIn()) {
adapter.startListening();
}
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();
}
});
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();
I'd like to be able to send an object from parsed JSON data displayed on a RecyclerView to a new activity on click. Below is the relevant code:
I've tried a few solutions but I don't get any results. I've been getting this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at athena.sentineljs.com.athena.RVNewsAdapter$NewsViewHolder.onClick(RVNewsAdapter.java:55)
RVNewsAdapter:
public class RVNewsAdapter extends RecyclerView.Adapter<RVNewsAdapter.NewsViewHolder> {
public static final String KEY_LINK = "link";
public static class NewsViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
private static final String TAG = "Hello";
CardView cv;
TextView date;
TextView link;
TextView title;
TextView today;
List<News> news;
public NewsViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.cv);
date = (TextView) itemView.findViewById(R.id.date);
link = (TextView) itemView.findViewById(R.id.link);
title = (TextView) itemView.findViewById(R.id.heading);
today = (TextView) itemView.findViewById(R.id.today);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Context context = view.getContext();
Intent intent;
intent = new Intent(context, Details.class);
intent.putExtra("LINK", news.toString());
context.startActivity(intent);
}
}
List<News> news;
RVNewsAdapter(List<News> news) {
this.news = news;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public RVNewsAdapter.NewsViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.itemnewsfeed, viewGroup, false);
NewsViewHolder nvh = new NewsViewHolder(v);
return nvh;
}
#Override
public void onBindViewHolder(NewsViewHolder newsViewHolder, int i) {
newsViewHolder.date.setText(news.get(i).date);
newsViewHolder.link.setText(news.get(i).link);
newsViewHolder.title.setText(news.get(i).title);
newsViewHolder.today.setText(news.get(i).today);
}
#Override
public int getItemCount() {
if (news != null) {
return news.size();
}
return 0;
}
}
Details activity:
public class Details extends AppCompatActivity {
private static final String TAG_LINK = "link";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent in = getIntent();
// Get JSON values from previous intent
String link = in.getStringExtra("link");
// Displaying all values on the screen
TextView lblLink = (TextView) findViewById(R.id.link);
lblLink.setText(link);
Log.d("Details", "Data not shown");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
You should send the news object like this
#Override
public void onClick(View view) {
Context context = view.getContext();
Intent intent = new Intent(context, Details.class);
int clickPosition = getAdapterPosition(); // get position of clicked item
News newObject = news.get(clickPosition); // get clicked new object from news(news is an ArrayList)
intent.putExtra("LINK", newObject);
context.startActivity(intent);
}
Also for pass the object via Intent correctly please see this answer