ListView Duplicating Data - java

Have an android application that on one of the pages has a ListView. The ListView has an array with 5 objects in it that is passed into the list adapter to be displayed. On the list view it shows 5 items but the bottom one is shown as a duplicate. However when you click this item it will show the right data that isn't duplicated on another page. Below see the code and screenshots.
MyJobsFragment.java
private void bidOnList() throws ParseException
{
final ArrayList<String> jobsListArray = new ArrayList<>();
// Iterate through entire bids table
for (DataSnapshot ds : getBidListChildren())
{
// Iterate through the actual bids information
Iterable<DataSnapshot> bidsSnapShot = ds.getChildren();
for (DataSnapshot ds1 : bidsSnapShot)
{
// if the User Id equals the current user added to a list
if (getBidInformation(ds1).getUserID().equals(auth.getCurrentUser().getUid()))
{
boolean active = ds1.child("active").getValue(boolean.class);
if (active)
{
jobsListArray.add(ds.getKey());
}
}
}
}
// Go through the jobs table
for (DataSnapshot ds3 : getJobListChildren())
{
/*
If the job is in the jobsListArray previously and the status is Pending
Add to the jobsList
*/
if (jobsListArray.contains(ds3.getKey()) && getJobInformation(ds3).getJobStatus().equals("Pending"))
{
Date sdf = new SimpleDateFormat("dd/MM/yyyy").parse(genericMethods.getJobInformation(ds3).getCollectionDate());
if (new Date().before(sdf))
{
jobListKey.add(ds3.getKey());
jobList.add(getJobInformation(ds3));
}
}
}
// Display information in ListView
mAdapterBidOn = new MyCustomAdapterForTabViews(getActivity(), isAdded(), host, getLayoutInflater(), getFragmentManager());
mAdapterBidOn.addKeyArray(jobListKey);
mAdapterBidOn.addArray(jobList);
jobListViewBidOn.setAdapter(mAdapterBidOn);
// Press on the object and go view all the Job Information and Bids
jobListViewBidOn.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
BidOnJobsFragment bidOnJobsFragment = new BidOnJobsFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("Job", mAdapterBidOn.mData.get(position));
bundle.putSerializable("JobId", mAdapterBidOn.mDataKeys.get(position));
bidOnJobsFragment.setArguments(bundle);
getFragmentManager().beginTransaction().replace(R.id.content, bidOnJobsFragment).addToBackStack("tag").commit();
}
});
}
The above method adds all the relevant data into an array list and adds it into the adapter.
Custom Adapter
public class MyCustomAdapterForTabViews extends BaseAdapter
{
public ArrayList<JobInformation> mData = new ArrayList<>();
public ArrayList<JobInformation> mDataOrig = new ArrayList<>();
public ArrayList<String> mDataKeys = new ArrayList<>();
private TabHost host;
public LayoutInflater mInflater;
private FragmentActivity fragmentActivity;
private LayoutInflater layoutInflater;
private FragmentManager fragmentManager;
public MyCustomAdapterForTabViews(FragmentActivity fragmentActivity, boolean isAdded, TabHost host, LayoutInflater layoutInflater, FragmentManager fragmentManager)
{
if (isAdded)
{
this.fragmentActivity = fragmentActivity;
this.fragmentManager = fragmentManager;
this.layoutInflater = layoutInflater;
mInflater = (LayoutInflater) fragmentActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
this.host = host;
}
public void addItem(final JobInformation item)
{
mData.add(item);
mDataOrig.add(item);
}
public void addArray(final ArrayList<JobInformation> j)
{
mData.clear();
mDataOrig.clear();
mData = j;
mDataOrig = j;
}
public void addKeyArray(final ArrayList<String> k)
{
mDataKeys.clear();
mDataKeys = k;
}
#Override
public int getCount()
{
return mData.size();
}
#Override
public Object getItem(int position)
{
return mData.get(position);
}
#Override
public long getItemId(int position)
{
return 0;
}
#Override
public boolean hasStableIds()
{
return false;
}
#Override
public void registerDataSetObserver(DataSetObserver observer)
{
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer)
{
}
#Override
public boolean areAllItemsEnabled()
{
return false;
}
#Override
public boolean isEmpty()
{
return false;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
// Bid on holder
MyCustomAdapterForTabViews.GroupViewHolderBidOn holderBidOn;
// Accepted holder
final MyCustomAdapterForTabViews.GroupViewHolderAccepted holderAccepted;
// Completed holder
MyCustomAdapterForTabViews.GroupViewHolderCompleted holderCompleted;
if (convertView == null)
{
// Bid on
if (host.getCurrentTab() == 0)
{
convertView = mInflater.inflate(R.layout.job_info_bid_on, null);
holderBidOn = new MyCustomAdapterForTabViews.GroupViewHolderBidOn();
holderBidOn.textViewJobName = convertView.findViewById(R.id.textName);
holderBidOn.imageViewCross = convertView.findViewById(R.id.imageViewCross);
holderBidOn.imageViewEditPen = convertView.findViewById(R.id.imageViewEditPen);
holderBidOn.textViewJobDescription = convertView.findViewById(R.id.textDesc);
holderBidOn.textViewAddressFrom = convertView.findViewById(R.id.textAddressFrom);
holderBidOn.textViewAddressTo = convertView.findViewById(R.id.textAddressTo);
holderBidOn.textViewJobName.setText(mData.get(position).getAdvertName());
holderBidOn.textViewJobDescription.setText(mData.get(position).getAdvertDescription());
holderBidOn.textViewAddressFrom.setText(mData.get(position).getColL1() + ", " + mData.get(position).getColTown() + ", " + mData.get(position).getColPostcode());
holderBidOn.textViewAddressTo.setText(mData.get(position).getDelL1() + ", " + mData.get(position).getDelPostcode() + ", " + mData.get(position).getDelPostcode());
holderBidOn.imageViewCross.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
final DatabaseConnections databaseConnections = new DatabaseConnections();
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(fragmentActivity);
View mView = layoutInflater.inflate(R.layout.popup_creator, null);
alertDialog.setTitle("Delete Job");
alertDialog.setView(mView);
final AlertDialog dialog = alertDialog.create();
dialog.show();
TextView customText = mView.findViewById(R.id.textViewCustomText);
customText.setText("Are You Sure You Want To Delete " + mData.get(position).getAdvertName() + "?");
Button yesButton = mView.findViewById(R.id.yesButton);
Button noButton = mView.findViewById(R.id.noButton);
yesButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
// My Adverts
if (mData.get(position).getPosterID().equals(databaseConnections.getCurrentUser()))
{
databaseConnections.getDatabaseReference().child("Jobs").child(mDataKeys.get(position)).addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
databaseConnections.getDatabaseReference().child("Jobs").child(mDataKeys.get(position))
.child("jobStatus").setValue("Inactive");
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
});
databaseConnections.getDatabaseReference().child("Bids").child(mDataKeys.get(position)).addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
databaseConnections.getDatabaseReference().child("Bids").child(mDataKeys.get(position)).child(mData.get(position)
.getCourierID()).child("active").setValue(false);
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
});
}
// My Jobs
else
{
databaseConnections.getDatabaseReference().child("Bids").child(mDataKeys.get(position)).addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
databaseConnections.getDatabaseReference().child("Bids").child(mDataKeys.get(position)).child(databaseConnections.getCurrentUser()).child("active").setValue(false);
mData.remove(position);
mDataKeys.remove(position);
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
});
}
notifyDataSetChanged();
dialog.dismiss();
}
});
noButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
dialog.dismiss();
}
});
}
});
DatabaseConnections databaseConnections = new DatabaseConnections();
// My Adverts
if (mData.get(position).getPosterID().equals(databaseConnections.getCurrentUser()))
{
holderBidOn.imageViewEditPen.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
GenericMethods genericMethods = new GenericMethods();
PostAnAdvertFragment postAnAdvertFragment = new PostAnAdvertFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("JobInfo", mData.get(position));
bundle.putSerializable("JobIdKey", mDataKeys.get(position));
postAnAdvertFragment.setArguments(bundle);
genericMethods.beginTransactionToFragment(fragmentManager, postAnAdvertFragment);
}
});
}
// My Jobs
else
{
holderBidOn.imageViewEditPen.setVisibility(View.GONE);
}
convertView.setTag(holderBidOn);
}
// Accepted
else if (host.getCurrentTab() == 1)
{
convertView = mInflater.inflate(R.layout.job_info_accepted, null);
holderAccepted = new MyCustomAdapterForTabViews.GroupViewHolderAccepted();
holderAccepted.textViewJobName = convertView.findViewById(R.id.textName);
holderAccepted.textViewDescription = convertView.findViewById(R.id.textDesc);
holderAccepted.textViewAddressFrom = convertView.findViewById(R.id.textAddressFrom);
holderAccepted.textViewAddressTo = convertView.findViewById(R.id.textAddressTo);
holderAccepted.textViewBid = convertView.findViewById(R.id.textBid);
holderAccepted.textViewJobName.setText(mData.get(position).getAdvertName());
holderAccepted.textViewDescription.setText(mData.get(position).getAdvertDescription());
holderAccepted.textViewAddressFrom.setText(mData.get(position).getColL1() + ", " + mData.get(position).getColTown() + ", " + mData.get(position).getColPostcode());
holderAccepted.textViewAddressTo.setText(mData.get(position).getDelL1() + ", " + mData.get(position).getDelPostcode() + ", " + mData.get(position).getDelPostcode());
DatabaseConnections databaseConnections = new DatabaseConnections();
databaseConnections.getDatabaseReference().child("Bids").child(mDataKeys.get(position)).child(mData.get(position).getCourierID()).addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
String acceptedBid = dataSnapshot.child("userBid").getValue(String.class);
holderAccepted.textViewBid.setText("£" + acceptedBid);
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
});
convertView.setTag(holderAccepted);
}
// Completed
else if (host.getCurrentTab() == 2)
{
convertView = mInflater.inflate(R.layout.job_info_list_completed, null);
holderCompleted = new MyCustomAdapterForTabViews.GroupViewHolderCompleted();
holderCompleted.textViewJobName = convertView.findViewById(R.id.textName);
holderCompleted.imageViewCross = convertView.findViewById(R.id.imageViewCross);
holderCompleted.textViewJobName.setText(mData.get(position).getAdvertName());
holderCompleted.imageViewCross.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
final DatabaseConnections databaseConnections = new DatabaseConnections();
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(fragmentActivity);
View mView = layoutInflater.inflate(R.layout.popup_creator, null);
alertDialog.setTitle("Delete Job");
alertDialog.setView(mView);
final AlertDialog dialog = alertDialog.create();
dialog.show();
TextView customText = mView.findViewById(R.id.textViewCustomText);
customText.setText("Are You Sure You Want To Delete " + mData.get(position).getAdvertName() + "?");
Button yesButton = mView.findViewById(R.id.yesButton);
Button noButton = mView.findViewById(R.id.noButton);
yesButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
// My Adverts
if (mData.get(position).getPosterID().equals(databaseConnections.getCurrentUser()))
{
databaseConnections.getDatabaseReference().child("Jobs").child(mDataKeys.get(position)).addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
databaseConnections.getDatabaseReference().child("Jobs").child(mDataKeys.get(position))
.child("jobStatus").setValue("Inactive");
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
});
}
// My Jobs
else
{
databaseConnections.getDatabaseReference().child("Bids").child(mDataKeys.get(position)).addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
databaseConnections.getDatabaseReference().child("Bids").child(mDataKeys.get(position)).child(databaseConnections.getCurrentUser()).child("active").setValue(false);
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
});
}
notifyDataSetChanged();
dialog.dismiss();
}
});
noButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
dialog.dismiss();
}
});
}
});
convertView.setTag(holderCompleted);
}
} else
{
if (host.getCurrentTab() == 0)
{
holderBidOn = (MyCustomAdapterForTabViews.GroupViewHolderBidOn) convertView.getTag();
} else if (host.getCurrentTab() == 1)
{
holderAccepted = (MyCustomAdapterForTabViews.GroupViewHolderAccepted) convertView.getTag();
} else if (host.getCurrentTab() == 2)
{
holderCompleted = (MyCustomAdapterForTabViews.GroupViewHolderCompleted) convertView.getTag();
}
}
return convertView;
}
public class GroupViewHolderBidOn
{
public TextView textViewJobName;
public TextView textViewJobDescription;
public TextView textViewAddressFrom;
public TextView textViewAddressTo;
public ImageView imageViewCross;
public ImageView imageViewEditPen;
}
public class GroupViewHolderAccepted
{
public TextView textViewJobName;
public TextView textViewDescription;
public TextView textViewAddressFrom;
public TextView textViewAddressTo;
public TextView textViewBid;
}
public class GroupViewHolderCompleted
{
public TextView textViewJobName;
public ImageView imageViewCross;
}
public void filter(String charText)
{
ArrayList<JobInformation> jobs = new ArrayList<>();
ArrayList<JobInformation> jA = new ArrayList<>();
charText = charText.toLowerCase(Locale.getDefault());
if (charText.length() == 0)
{
mData = mDataOrig;
} else
{
for (JobInformation j : mDataOrig)
{
if (j.getWholeString().toLowerCase(Locale.getDefault()).contains(charText))
{
jobs.add(j);
jA.add(j);
} else
{
jA.add(j);
}
}
mData.clear();
mData = jobs;
mDataOrig = jA;
}
notifyDataSetChanged();
}
}
My Bids 1
My Bids 2
When you click the bottom Panasonic TV
More code can be provided if needed.
EDIT
Code runs as intended until it hits the 4th element in the array, once that point is hit, it goes off into base java classes that I'm guessing are for the adapter. It is as if its ignoring the last two and recycling the views.

#Override
public long getItemId(int position)
{
return 0;
}
i think problem is in your above adapter method. change this to below :
#Override
public long getItemId(int position)
{
return position;
}

Related

How to flow Data from One RecyclerView to Another RecyclerView when an item in first RecyclerView is clicked?

Hi, I faced an issue here.. I was creating a chatbot in which user can type a text to send it and also can select a text out of the recommended texts
so I created two RecycleViews
My goal is - when the user selects one of the recommended text, then that text should appear in the Chatting RecycleView
here is my main Activity Class
public class Charts extends AppCompatActivity {
private static final String USER_KEY = "user";
private static final String BOT_KEY = "bot";
RecyclerView chart_recycle,auto_texts;
EditText message_text;
ImageView send_btn,mic_button;
ImageView setting_button;
ChartsAdapter chartsAdapter;
RecyclerView.LayoutManager linearLayout;
ArrayList<ChartModeClass> modeClassesArrayList = new ArrayList<>();
AutoAdapter autoAdapter;
RecyclerView.LayoutManager horizontal;
List<Texts> list = new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chatting_hole);
message_text = findViewById(R.id.message_text);
send_btn = findViewById(R.id.send_btn);
mic_button = findViewById(R.id.mic_btn);
setting_button = findViewById(R.id.setting_button);
chart_recycle = findViewById(R.id.chart_recycle);
chart_recycle.setHasFixedSize(true);
auto_texts = findViewById(R.id.auto_texts);
auto_texts.setHasFixedSize(true);
linearLayout = new LinearLayoutManager(getApplicationContext(), RecyclerView.VERTICAL, false);
chart_recycle.setLayoutManager(linearLayout);
//Auto text
horizontal = new LinearLayoutManager(getApplicationContext(),RecyclerView.HORIZONTAL, false);
auto_texts.setLayoutManager(horizontal);
chartsAdapter = new ChartsAdapter(modeClassesArrayList, Charts.this);
chart_recycle.setAdapter(chartsAdapter);
//Auto texts
autoAdapter = new AutoAdapter(getApplicationContext(),list);
auto_texts.setAdapter(autoAdapter);
addInputs();
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(Charts.this);
mic_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bottomSheetDialog.setContentView(R.layout.record);
bottomSheetDialog.show();
}
});
message_text.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().trim().length()==0){
mic_button.setVisibility(View.VISIBLE);
send_btn.setVisibility(View.GONE);
}else {
send_btn.setVisibility(View.VISIBLE);
mic_button.setVisibility(View.GONE);
}
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().trim().isEmpty()){
// Toast.makeText(getApplicationContext(),"Enter text",Toast.LENGTH_LONG).show();
mic_button.setVisibility(View.VISIBLE);
send_btn.setVisibility(View.GONE);
}else {
send_btn.setVisibility(View.VISIBLE);
mic_button.setVisibility(View.GONE);
}
}
#Override
public void afterTextChanged(Editable editable) {
if (editable.toString().length()==0){
mic_button.setVisibility(View.VISIBLE);
send_btn.setVisibility(View.GONE);
}
}
});
send_btn.setOnClickListener(view -> {
if (message_text.getText().toString().isEmpty()) {
Toast.makeText(Charts.this, "Please enter text..", Toast.LENGTH_SHORT).show();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
returnResponse(message_text.getText().toString());
}
message_text.setText("");
});
}
#SuppressLint("NotifyDataSetChanged")
private void returnResponse(String message) {
modeClassesArrayList.add(new ChartModeClass(message, USER_KEY));
chartsAdapter.notifyDataSetChanged();
chart_recycle.scrollToPosition(modeClassesArrayList.size()-1);
String url = "http://xxxxxxxxxxxxxxxx"+message;
String BASE_URL = "https://xxxxxxxxx";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitApi retrofitApi = retrofit.create(RetrofitApi.class);
Call<MessageModeClass> call = retrofitApi.getMessage(url);
call.enqueue(new Callback<MessageModeClass>() {
#Override
public void onResponse(#NonNull Call<MessageModeClass> call, #NonNull Response<MessageModeClass> response) {
if (response.isSuccessful()) {
MessageModeClass messageModeClass = response.body();
if (messageModeClass != null) {
modeClassesArrayList.add(new ChartModeClass(messageModeClass.getCnt(), BOT_KEY));
}
chartsAdapter.notifyDataSetChanged();
chart_recycle.scrollToPosition(modeClassesArrayList.size() - 1);
} else {
Toast.makeText(Charts.this, "response is null", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(#NonNull Call<MessageModeClass> call, #NonNull Throwable t) {
modeClassesArrayList.add(new ChartModeClass("No response check your network connection!", BOT_KEY));
chartsAdapter.notifyDataSetChanged();
chart_recycle.scrollToPosition(modeClassesArrayList.size() - 1);
}
});
}
#SuppressLint("NotifyDataSetChanged")
#Override
protected void onStart() {
super.onStart();
String lang = getIntent().getExtras().getString("lang");
if (lang.equals("english")){
modeClassesArrayList.add(new ChartModeClass("Hey welcome back am fema bot", BOT_KEY));
chartsAdapter.notifyDataSetChanged();
chart_recycle.scrollToPosition(modeClassesArrayList.size() - 1);
}else if (lang.equals("swahili")){
modeClassesArrayList.add(new ChartModeClass("Habari karibu miminni bot niliyetengenezw", BOT_KEY));
chartsAdapter.notifyDataSetChanged();
chart_recycle.scrollToPosition(modeClassesArrayList.size() - 1);
}else {
modeClassesArrayList.add(new ChartModeClass("Hey welcome back am fema bot", BOT_KEY));
chartsAdapter.notifyDataSetChanged();
chart_recycle.scrollToPosition(modeClassesArrayList.size() - 1);
}
}
private void addInputs() {
Texts text1 = new Texts("gender?");
Texts text2 = new Texts("gender equality");
Texts text3 = new Texts("what is good about females");
Texts text4 = new Texts("un goals");
Texts text5 = new Texts("about men");
list.addAll(Arrays.asList(new Texts[]{text1,text2,text3,text4,text5}));
}
}
here is my Adapter class class codes
public class AutoAdapter extends RecyclerView.Adapter<AutoAdapter.ViewHolderClass> {
Context context;
List<Texts> list;
public AutoAdapter(Context context, List<Texts> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public ViewHolderClass onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.text_list,parent,false);
ViewHolderClass viewHolderClass = new ViewHolderClass(view);
return viewHolderClass;
}
#Override
public void onBindViewHolder(#NonNull ViewHolderClass holder, #SuppressLint("RecyclerView") int position) {
holder.input_text.setText(list.get(position).getText());
holder.input_text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// my stack
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolderClass extends RecyclerView.ViewHolder {
TextView input_text;
public ViewHolderClass(#NonNull View itemView) {
super(itemView);
input_text = itemView.findViewById(R.id.input_text);
}
}
}
You can add a list of your recommendations in another RecyclerView
Then in the ViewHolder of each item of the RecyclerView add Callback to listen on click events when a user clicks one of the item like the following
public class ViewHolderClass extends RecyclerView.ViewHolder {
private TextView input_text;
private final Callback callback; // custom callback
public ViewHolderClass(#NonNull View itemView, Callback callback) {
super(itemView);
this.callback = callback;
input_text = itemView.findViewById(R.id.input_text);
// now add onClickListener of the itemView to fire custom callback
itemView.setOnClickListener(view -> {
this.callback.onItemClick(getAdapterPosition());
});
}
// this is my custom callback for return click event
public interface Callback {
void onItemClick(int position);
}
}
Now inside your adapter add the callback from viewholder
public class AutoAdapter extends RecyclerView.Adapter<AutoAdapter.ViewHolderClass> {
private Context context;
private List<Texts> list;
private AutoAdapterCallback callback;
public AutoAdapter(Context context, List<Texts> list) {
this.context = context;
this.list = list;
}
public setCallback(AutoAdapterCallback callback) {
this.callback = callback;
}
#NonNull
#Override
public ViewHolderClass onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.text_list,parent,false);
ViewHolderClass viewHolderClass = new ViewHolderClass(view, new ViewHolderClass.Callback() {
#Override
public void onItemClick(int position) {
// forward callback to adapter callback
if (callback != null) {
// get actual item from its position
final Texts texts = getItemByPosition(position);
// send to adapter callback
callback.onItemClick(texts);
}
});
return viewHolderClass;
}
#Override
public void onBindViewHolder(#NonNull ViewHolderClass holder, #SuppressLint("RecyclerView") int position) {
holder.input_text.setText(list.get(position).getText());
// I haven't used this inteady I added callback on viewholder side
// holder.input_text.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// // my stack
// }
// });
}
#Override
public int getItemCount() {
return list.size();
}
// return Texts object by given position
public Texts getItemByPosition(int position) {
return this.list.get(position);
}
// add adapter callback to be called by viewholder
public interface AdapterCallback {
void onItemClick(Texts texts);
}
}
After that, now on your Activity you can easily listen on any item when a user clicks and get its corresponding Texts object from list as following:
//code ...
// here
//Auto texts
autoAdapter = new AutoAdapter(getApplicationContext(),list);
//set callback to listen for click events
autoAdapter.setCallback(new AutoAdapter.AutoAdapterCallback() {
#Override
public void onItemClick(Texts texts) {
// you can get your clicked item here
// now you can put texts object to another RecyclerView :)
}
});
auto_texts.setAdapter(autoAdapter);
//code ...

I wanted to see all users post using a recycler view

I wanted all users post to be shown on the home fragment, it is showing all users post but it show each post 7 times. I am not sure where the error is but I would like some help with this part so that I could finish this project, I'm a newbie in java coding could anyone help me out please. Thank you in advance
Here is my post adapter
public class PostsAdapter extends RecyclerView.Adapter<PostsAdapter.myViewHolderClass> {
public static final String HOME_POSTS_TYPE = "FROM_VIEW_PROFILE";
public static final String IMAGE_LIKED = "IMAGE_LIKED";
public static final String IMAGE_NOT_LIKED = "IMAGE_NOT_LIKED";
public static final String FROM_HOME_FRAGMENT = "FROM_HOME_FRAGMENT";
private static final String TAG = "POST_ADAPTER";
Context context;
ArrayList<UsersPosts> usersPosts;
LinearLayoutManager layoutManager;
ArrayList<Comment> commentList = new ArrayList<>();
public PostsAdapter(Context context, ArrayList<UsersPosts> usersPosts, LinearLayoutManager layoutManager) {
this.context = context;
this.usersPosts = usersPosts;
this.layoutManager = layoutManager;
}
#NonNull
#Override
public myViewHolderClass onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.posts_recycler_view_layout, parent, false);
return new myViewHolderClass(view);
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull myViewHolderClass holder, int position) {
if (usersPosts.get(position).getImageUri().toLowerCase().contains(Constants.VIDEO_FILE_FIREBASE)) {
holder.postImageView.setVisibility(View.GONE);
holder.imgPlaceHolder.setVisibility(View.GONE);
holder.mainVideoLayout.setVisibility(View.VISIBLE);
playVideo(holder, usersPosts.get(position).getImageUri());
} else {
holder.playIcon.setVisibility(View.GONE);
holder.mainVideoLayout.setVisibility(View.GONE);
holder.imgPlaceHolder.setVisibility(View.VISIBLE);
holder.postImageView.setVisibility(View.VISIBLE);
GlideImageLoader.loadImageWithPlaceHolder(context, usersPosts.get(position).getImageUri()
, holder.postImageView, holder.imgPlaceHolder);
//If Posts Turn off Comments is enabled.
if (usersPosts.get(position).isTurnOffComments()) {
holder.allCommentsLayout.setVisibility(View.GONE);
holder.commentIcon.setVisibility(View.GONE);
} else {
holder.allCommentsLayout.setVisibility(View.VISIBLE);
holder.commentIcon.setVisibility(View.VISIBLE);
}
}
//Likes
HashMap<String, Object> hashMap = usersPosts.get(position).getLikes();
if (hashMap == null) {
holder.likeIcon.setTag(IMAGE_NOT_LIKED);
holder.likesCount.setText("0 Likes");
}
//Date
holder.timeCreated.setText(DateUtils.getRelativeTimeSpanString(
Long.parseLong(usersPosts.get(position).getDateCreated()),
System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS));
bindUsersData(holder.profilePic, holder.usernameAndCaption, holder.userName, usersPosts.get(position).getCaption(),
usersPosts.get(position).getUserId(), position);
HelperMethods ob1 = new HelperMethods(context, usersPosts.get(position).getPostId(), holder.likeIcon);
ob1.likeListener(holder.likesCount);
getComments(usersPosts.get(position).getPostId(), holder.allCommentsLayout, holder.viewAllCommentsTxt);
}
private void playVideo(myViewHolderClass holderClass, String imageUri) {
holderClass.playIcon.setVisibility(View.GONE);
holderClass.videoView.setVisibility(View.VISIBLE);
holderClass.videoLoadingLayout.setVisibility(View.VISIBLE);
String videoUriLastPathSegment = Uri.parse(imageUri).getLastPathSegment();
if (CachingVideos.isVideoExistsInCache(context, videoUriLastPathSegment)) {
assert videoUriLastPathSegment != null;
holderClass.videoView.setVideoPath(CachingVideos.getVideoFile(context, videoUriLastPathSegment).getPath());
} else
CachingVideos.putVideoIntoCache(context, holderClass.videoView, imageUri);
holderClass.mainVideoLayout.setOnClickListener(v -> {
if (holderClass.videoView.isPlaying()) {
holderClass.playIcon.setVisibility(View.VISIBLE);
holderClass.videoView.pause();
} else {
holderClass.videoView.start();
holderClass.playIcon.setVisibility(View.GONE);
}
});
holderClass.videoView.setOnCompletionListener(mp -> holderClass.videoView.start());
holderClass.videoView.setOnPreparedListener(mp -> {
holderClass.videoLoadingLayout.setVisibility(View.GONE);
});
}
public void getComments(String postID, final LinearLayout viewAllComment, final TextView commentTxt) {
FirebaseDatabase.getInstance().getReference(context.getString(R.string.DB_COMMENTS))
.child(postID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
commentList.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Comment comment = dataSnapshot.getValue(Comment.class);
commentList.add(comment);
}
if (commentList.size() == 0)
viewAllComment.setVisibility(View.GONE);
else {
viewAllComment.setVisibility(View.VISIBLE);
commentTxt.setText(context.getString(R.string.com___, commentList.size()));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public int getItemCount() {
return usersPosts.size();
}
private void bindUsersData(final ImageView profilePic, final TextView nameAndCaption, final TextView userName,
final String caption, String userID, final int position) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference(context.getString(R.string.DB_USERS)).child(userID);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User userDetails = snapshot.getValue(User.class);
usersPosts.get(position).setUser(userDetails);
assert userDetails != null;
if (userDetails.getProfilePic() != null) {
if (!userDetails.getProfilePic().equals(""))
Glide.with(context.getApplicationContext()).load(userDetails.getProfilePic()).into(profilePic);
}
userName.setText(userDetails.getUsername());
nameAndCaption.setText(HelperMethods.usernameAndCaption(userDetails.getUsername(), caption));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
public class myViewHolderClass extends RecyclerView.ViewHolder implements View.OnClickListener {
CardView playIcon;
VideoView videoView;
FrameLayout videoLoadingLayout;
ConstraintLayout mainVideoLayout;
ImageView profilePic, postImageView, likeIcon,
optionMenu, commentIcon, shareIcon;
TextView userName, usernameAndCaption, likesCount,
viewAllCommentsTxt, timeCreated;
LinearLayout allCommentsLayout, imgPlaceHolder;
public myViewHolderClass(#NonNull View itemView) {
super(itemView);
userName = itemView.findViewById(R.id.textView46);
likeIcon = itemView.findViewById(R.id.imageView13);
profilePic = itemView.findViewById(R.id.profile_pic_2);
postImageView = itemView.findViewById(R.id.imageView8);
commentIcon = itemView.findViewById(R.id.imageView14);
optionMenu = itemView.findViewById(R.id.imageView5);
timeCreated = itemView.findViewById(R.id.textView59);
likesCount = itemView.findViewById(R.id.textView8);
videoView = itemView.findViewById(R.id.videoView2);
playIcon = itemView.findViewById(R.id.cardView31);
shareIcon = itemView.findViewById(R.id.imageView15);
mainVideoLayout = itemView.findViewById(R.id.frameLayout);
videoLoadingLayout = itemView.findViewById(R.id.placeholder);
viewAllCommentsTxt = itemView.findViewById(R.id.textView11);
imgPlaceHolder = itemView.findViewById(R.id.linearLayout44);
usernameAndCaption = itemView.findViewById(R.id.textView47);
allCommentsLayout = itemView.findViewById(R.id.linearLayout26);
likeIcon.setOnClickListener(this);
optionMenu.setOnClickListener(this);
userName.setOnClickListener(this);
commentIcon.setOnClickListener(this);
allCommentsLayout.setOnClickListener(this);
shareIcon.setOnClickListener(this);
}
#Override
public void onClick(View view) {
HelperMethods ob1 = new HelperMethods(context, usersPosts.get(getAdapterPosition()).getPostId(), likeIcon);
User userObject = usersPosts.get(getAdapterPosition()).getUser();
if (view.getId() == R.id.imageView13) {
if (likeIcon.getTag().equals(IMAGE_NOT_LIKED))
ob1.likePostAndSaveIntoDatabase();
else
ob1.unLikePost();
} else if (view.getId() == R.id.imageView5) {
ViewPostBottomSheet bottomSheet = new ViewPostBottomSheet(HOME_POSTS_TYPE);
bottomSheet.setTargetFragment(((FragmentActivity) (context)).getSupportFragmentManager()
.findFragmentByTag(MAIN_ACTIVITY_FRAGMENT), 100);
bottomSheet.show(((FragmentActivity) context).getSupportFragmentManager(), "ViewProfileBottomSheet");
} else if (view.getId() == R.id.textView46) {
ViewProfileFragment viewProfileFragment = new ViewProfileFragment();
Bundle bundle = new Bundle();
bundle.putParcelable(FROM_HOME_FRAGMENT, userObject);
viewProfileFragment.setArguments(bundle);
((FragmentActivity) context).getSupportFragmentManager().beginTransaction()
.replace(R.id.fragmentHolder, viewProfileFragment).addToBackStack(MAIN_ACTIVITY_FRAGMENT).commit();
}
//Comments Activity
else if (view.getId() == R.id.imageView14 || view.getId() == R.id.linearLayout26)
startCommentActivity(userObject, getAdapterPosition());
else if (view.getId() == R.id.imageView15)
openShareFragment(getAdapterPosition());
}
}
private void startCommentActivity(User userObject, int adapterPosition) {
UsersPosts userPost = usersPosts.get(adapterPosition);
Intent intent = new Intent(context, CommentsActivity.class);
intent.putExtra(Constants.USER_OBJECT, userObject);
intent.putExtra(Constants.USER_POST_OBJECT, userPost);
context.startActivity(intent);
}
private void openShareFragment(int adapterPosition) {
ShareBottomSheet bottomSheet = new ShareBottomSheet(context, usersPosts.get(adapterPosition));
bottomSheet.show(((FragmentActivity) (context)).getSupportFragmentManager(), "SHARE_BOTTOM_SHEET");
}
#Override
public void onViewAttachedToWindow(#NonNull final myViewHolderClass holder) {
super.onViewAttachedToWindow(holder);
if (holder.mainVideoLayout.getVisibility() == View.VISIBLE) {
holder.videoLoadingLayout.setVisibility(View.VISIBLE);
} else
holder.playIcon.setVisibility(View.GONE);
}
#Override
public void onViewDetachedFromWindow(#NonNull myViewHolderClass holder) {
super.onViewDetachedFromWindow(holder);
if (holder.videoView.isPlaying()) {
holder.videoView.pause();
holder.playIcon.setVisibility(View.GONE);
}
}
}
here is my home fragment where I want all the posts to be displyed
public class HomeFragment extends Fragment {
public static final String TAG = "HOME_FRAGMENT";
View view;
Toolbar toolbar;
ProgressBar progressBar;
PostsAdapter postsAdapter;
RecyclerView recyclerView;
LinearLayout noPostLayout;
FirebaseUser firebaseUser;
FirebaseDatabase firebaseDatabase;
LinearLayoutManager linearLayoutManager;
TextView all;
List<String> userFollowingList = new ArrayList<>();
ArrayList<UsersPosts> postsArrayList = new ArrayList<>();
float visiblePercent = 40;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
if (view == null) {
view = inflater.inflate(R.layout.fragment_home, container, false);
recyclerView = view.findViewById(R.id.recycler_view);
toolbar = view.findViewById(R.id.toolbar5);
noPostLayout = view.findViewById(R.id.linearLayout13);
progressBar = view.findViewById(R.id.progressBar4);
all = view.findViewById(R.id.all);
firebaseDatabase = FirebaseDatabase.getInstance();
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
//Setting Up RecyclerView
linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
postsAdapter = new PostsAdapter(getContext(), postsArrayList, linearLayoutManager);
recyclerView.setAdapter(postsAdapter);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(#NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
playVideo(newState);
}
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
}
});
toolbar.setOnMenuItemClickListener(item -> {
if (item.getItemId() == R.id.search_icon) {
startActivity(new Intent(getActivity(), SearchActivity.class));
Objects.requireNonNull(getActivity()).overridePendingTransition(0, 0);
} else {
Intent intent = new Intent(getActivity(), MainChatActivity.class);
startActivity(intent);
}
return true;
});
checkFollowings();
}
return view;
}
public void checkFollowings() {
final DatabaseReference followingList = firebaseDatabase.getReference(getString(R.string.DB_FOLLOW)).child(firebaseUser.getUid())
.child(getString(R.string.USER_FOLLOWING));
followingList.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
userFollowingList.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
userFollowingList.add(dataSnapshot.getKey());
}
//this will get the post of the users that the main user is following
readPosts();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
});
}
private void readPosts() {
DatabaseReference mRef = firebaseDatabase.getReference(getString(R.string.DB_POST));
mRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
postsArrayList.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
UsersPosts usersPosts = dataSnapshot.getValue(UsersPosts.class);
assert usersPosts != null;
for (String id : userFollowingList) {
postsArrayList.add(usersPosts);
/* if (usersPosts.getUserId().equals(id)) {
postsArrayList.add(usersPosts);
}*/
}
}
if (postsArrayList.size() == 0) {
recyclerView.setVisibility(View.GONE);
noPostLayout.setVisibility(View.VISIBLE);
} else {
noPostLayout.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
postsAdapter.notifyDataSetChanged();
}
progressBar.setVisibility(View.GONE);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
});
}
#Override
public void onDestroyView() {
Log.d(TAG, "onDestroyView: ");
if (view.getParent() != null) {
((ViewGroup) view.getParent()).removeView(view);
}
super.onDestroyView();
}
}
Posting this as an answer for better code formatting. I believe you should simply add the posts like this in HomeFragment.readPosts():
...
public void onDataChange(#NonNull DataSnapshot snapshot) {
postsArrayList.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
UsersPosts usersPosts = dataSnapshot.getValue(UsersPosts.class);
postsArrayList.add(usersPosts);
}
...
}

Data from Firebase is not displayed in the RecyclerView that is in the fragment

There is a problem with the data displayed in the recyclerview when I run my program
it looks like this:
.
For the data that is displayed I use firebase like this the
data structure:
When I want to display data in recyclerview in a fragment, but the data doesn't appear. I use Firebase as database
NotaAdapter.java
public class NotaAdapter extends RecyclerView.Adapter<NotaAdapter.MyViewHolder> {
Context context;
ArrayList<ListNota> listnota;
public NotaAdapter (Context c,ArrayList<ListNota> p) {
this.context = c;
this.listnota = p;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
return new MyViewHolder(LayoutInflater.from(context)
.inflate(R.layout.item_nota, parent, false));
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.no_nota.setText(listnota.get(i).getId_nota());
myViewHolder.total_harga.setText(String.valueOf(listnota.get(i).getTotal_seluruh()));
final String getnoNOta = listnota.get(i).getId_nota();
myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent gotoDetailNota = new Intent(context, DetailNotaAct.class);
gotoDetailNota.putExtra("no_nota", getnoNOta);
context.startActivity(gotoDetailNota);
}
});
}
#Override
public int getItemCount() {
return listnota.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView no_nota, total_harga;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
no_nota = itemView.findViewById(R.id.xid_nota);
total_harga = itemView.findViewById(R.id.xtotal_seluruh);
}
}
}
ListNota.java
public class ListNota {
private String id_nota;
private Integer total_seluruh;
public ListNota() {
}
public ListNota(String id_nota, Integer total_seluruh) {
this.id_nota = id_nota;
this.total_seluruh = total_seluruh;
}
public String getId_nota() {
return id_nota;
}
public void setId_nota(String id_nota) {
this.id_nota = id_nota;
}
public Integer getTotal_seluruh() {
return total_seluruh;
}
public void setTotal_seluruh(Integer total_seluruh) {
this.total_seluruh = total_seluruh;
}
}
HistoryFragment.java
public class HistoryFragment extends Fragment {
TextView txt_history, txt_toko, txt_report, txt_nama_toko, txt_jenis_toko;
LinearLayout btn_buat_nota;
DatabaseReference databaseUser, databaseToko, databaseNota;
String USERNAME_KEY = "usernamekey";
String username_key = "";
String username_key_new = "";
String id_Toko = "";
ProgressDialog progress;
RecyclerView nota_place;
ArrayList<ListNota> list;
NotaAdapter notaAdapter;
private View Notaview;
public HistoryFragment(){
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Notaview = inflater.inflate(R.layout.fragment_history, container, false);
txt_nama_toko = (TextView) Notaview.findViewById(R.id.txt_nama_toko);
txt_jenis_toko = (TextView) Notaview.findViewById(R.id.txt_jenis_toko);
txt_history = (TextView) Notaview.findViewById(R.id.txt_history);
txt_toko = (TextView) Notaview.findViewById(R.id.txt_toko);
txt_report = (TextView) Notaview.findViewById(R.id.txt_report);
btn_buat_nota = (LinearLayout) Notaview.findViewById(R.id.btn_buat_nota);
progress = new ProgressDialog(getActivity());
progress.setTitle("Loading");
progress.setMessage("Memuat Data");
progress.setCancelable(false);
progress.show();
getUsernameLocal();
databaseUser = FirebaseDatabase.getInstance().getReference().child("Users").child(username_key_new);
databaseUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
id_Toko = dataSnapshot.child("id_toko").getValue().toString();
databaseToko = FirebaseDatabase.getInstance().getReference().child("Toko").child(id_Toko);
databaseToko.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
txt_nama_toko.setText(dataSnapshot.child("nama_toko").getValue().toString());
//cek apakah child jenis toko ada
if (dataSnapshot.hasChild("jenis_toko")){
txt_jenis_toko.setText(dataSnapshot.child(" jenis_toko").getValue().toString());
}else{
txt_jenis_toko.setText("Jenis toko belum disetting");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
btn_buat_nota.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String id_nota = generateRandomString(16);
Intent gotoBuatNota = new Intent(getActivity(), BuatNotaAct.class);
gotoBuatNota.putExtra("id_nota", id_nota);
startActivity(gotoBuatNota);
}
});
nota_place = (RecyclerView) Notaview.findViewById(R.id.nota_place);
notaAdapter = new NotaAdapter(getContext(), list);
nota_place.setAdapter(notaAdapter);
nota_place.setLayoutManager(new LinearLayoutManager(getActivity()));
return Notaview;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
list = new ArrayList<ListNota>();
loaddata();
}
private void loaddata(){
databaseNota = FirebaseDatabase.getInstance().getReference().child("Nota").child(id_Toko);
databaseNota.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren()){
ListNota p = dataSnapshot1.getValue(ListNota.class);
list.add(p);
}
progress.dismiss();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public String generateRandomString(int length){
char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
StringBuilder stringBuilder = new StringBuilder();
Random random = new Random();
for(int i = 0; i < length; i++){
char c = chars[random.nextInt(chars.length)];
stringBuilder.append(c);
}
return stringBuilder.toString();
}
public void getUsernameLocal(){
SharedPreferences sharedPreferences = getActivity().getSharedPreferences(USERNAME_KEY, MODE_PRIVATE);
username_key_new = sharedPreferences.getString(username_key,"");
}
}
you are reading it from the wrong node, you are passing reference that you want to read data from the node Named "users".
Your Database reference should look like this
databaseUser = FirebaseDatabase.getInstance().getReference("Nota").child("Toko_Kita20082020371").child(username_key_new);
Also make sure your list should have all the variables that a node has.
For example a node has
name,id,price,description;
then same varibles should be declared in your list to successfully ready dta from the firebase.

Sort one of the array in multiple arrays inside list item

i have a custom listview that has 3 textview for Name, Unique id and Number of Absent and 1 image button for Delete in every list item. I tried to sort the number of absent, it sorts but the order breaks. I saw in internet the comparator and i think that's the solution to my problem but i don't know how to use it. Hoping that someone here can help me.
This is how i add values in my 3 ArrayList (mUid for unique id, MFullname for name, mStatus for Number of absent)
pagod = FirebaseDatabase.getInstance().getReference().child("users").child("teacher").child(user.getUid().toString().trim()).child("class").child(aba).child(message).child("Listofstudents");
pagod.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
String userid = child.child("userid").getValue().toString().trim();
String name = child.child("name").getValue().toString().trim();
mUid.add(userid);
mFullname.add(name);
//studentlist.invalidateViews();
//adapter.notifyDataSetChanged();
if (dataSnapshot.child(userid).child("attendance").exists()) {
pagodnapagod = FirebaseDatabase.getInstance().getReference();
Query query = pagodnapagod.child("users").child("teacher").child(user.getUid().toString().trim()).child("class").child(aba).child(message).child("Listofstudents").child(userid).child("attendance").child("finals").orderByChild("status").equalTo("absent");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String numberOfStudent ="Number of Absent: "+dataSnapshot.getChildrenCount();
//Toast.makeText(MyClassesActivity.this, numberOfStudent, Toast.LENGTH_SHORT).show();
mStatus.add(numberOfStudent);
//Collections.sort(mStatus, Collections.reverseOrder());
adapters.notifyDataSetChanged();
progressDialog.dismiss();
} else {
String numberOfStudent = "Number of Absent: 0";
mStatus.add(numberOfStudent);
//Collections.sort(mStatus, Collections.reverseOrder());
adapters.notifyDataSetChanged();
progressDialog.dismiss();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
String numberOfStudent = "Number of Absent: 0";
mStatus.add(numberOfStudent);
//Collections.sort(mStatus, Collections.reverseOrder());
adapters.notifyDataSetChanged();
progressDialog.dismiss();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
This is my custom adapter.
class Adapters extends BaseAdapter implements Filterable {
private Context context;
private int resource;
private int ids;
private ArrayList arrayList;
private List<String> originalData=null;
private List<String>filteredData=null;
private List<String> userId;
private List<String> status;
private FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
private Adapters.ItemFilter mFilter = new Adapters.ItemFilter();
private LayoutInflater inflater;
public Adapters(Context context, int resource, int id, ArrayList arrayList, ArrayList userId, ArrayList status){
this.context = context;
this.resource = resource;
this.ids = id;
this.arrayList = arrayList;
this.filteredData = arrayList ;
this.originalData = arrayList ;
this.userId = userId;
this.status = status;
inflater = LayoutInflater.from(context);
}
public int getCount() {
return filteredData.size();
}
public Object getItem(int position) {
return filteredData.get(position);
}
public long getItemId(int position) {
return position;
}
// Hold views of the ListView to improve its scrolling performance
private class ViewHolder {
public TextView type;
public TextView uid;
public TextView count;
public ImageButton removeButton;
}
public View getView(final int position, final View convertView, ViewGroup parent) {
View rowView = convertView;
// Inflate the list_item.xml file if convertView is null
if(rowView==null){
rowView = inflater.inflate(R.layout.listitem6, null);
rowView= inflater.inflate(resource, parent, false);
Adapters.ViewHolder viewHolder = new Adapters.ViewHolder();
viewHolder.type= (TextView) rowView.findViewById(R.id.txt);
viewHolder.uid= (TextView) rowView.findViewById(R.id.id);
viewHolder.count= (TextView) rowView.findViewById(R.id.count);
viewHolder.removeButton= (ImageButton) rowView.findViewById(btn_del);
rowView.setTag(viewHolder);
}
final String x = (String) arrayList.get(position);
final String y = arrayList.get(position).toString().trim();
// Set text to each TextView of ListView item
Adapters.ViewHolder holder = (Adapters.ViewHolder) rowView.getTag();
holder.type.setText(x);
holder.uid.setText(x);
holder.count.setText(x);
holder.removeButton.setBackgroundResource(R.drawable.deletes);
holder.removeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
View parentRow = (View) view.getParent();
ListView listView = (ListView) parentRow.getParent();
final int position = listView.getPositionForView(parentRow);
TextView userId=(TextView) parentRow.findViewById(R.id.id);
TextView userName=(TextView) parentRow.findViewById(R.id.txt);
final String name = userName.getText().toString().trim();
final String uid = userId.getText().toString().trim();
//Toast.makeText(StudentListActivity.this, name +"\n" + uid, Toast.LENGTH_SHORT).show();
final AlertDialog.Builder builder2=new AlertDialog.Builder(context);
final View dialogView = inflater.inflate(R.layout.customdialog, null);
builder2.setView(dialogView);
final EditText input = (EditText) dialogView.findViewById(R.id.edit1);
final TextInputLayout inputs = (TextInputLayout) dialogView.findViewById(R.id.text_field);
TextWatcher watcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
inputs.setErrorEnabled(false);
inputs.setError(null);
}
};
input.addTextChangedListener(watcher);
builder2.setTitle("Delete Class");
builder2.setMessage("Do you want to delete "+y+" from this class?");
builder2.setPositiveButton("ok", null);
builder2.setNegativeButton("cancel", null);
builder2.setIcon(R.drawable.deletes);
builder2.setCancelable(false);
final AlertDialog mAlertDialog = builder2.create();
mAlertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(final DialogInterface dialog) {
Button a = mAlertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// TODO Do something
if (input.getText().toString().equalsIgnoreCase("delete")) {
arrayList.remove(position);
notifyDataSetChanged();
Toast.makeText(view.getContext(), y + " has been deleted in this class", Toast.LENGTH_SHORT).show();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("users").child("teacher").child(user.getUid().toString().trim()).child("class").child(aba).child(message).child("Listofstudents").child(uid);
mDatabase.setValue(null);
ref0 = FirebaseDatabase.getInstance().getReference();
ref0.child("usersclass").orderByChild("userid_classid").equalTo(uid+"-"+message).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
String hello = child.getKey();
ref0.child("usersclass").child(hello).setValue(null);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
dialog.dismiss();
notifyDataSetChanged();
restartThis();
} else {
inputs.setError("Enter word DELETE");
}
}
});
Button b = mAlertDialog.getButton(AlertDialog.BUTTON_NEGATIVE);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// TODO Do something
dialog.dismiss();
}
});
}
});
mAlertDialog.show();
}
});
holder.type.setText(filteredData.get(position));
holder.uid.setText(userId.get(position));
holder.count.setText(status.get(position));
return rowView;
}
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<String> list = originalData;
int count = list.size();
final ArrayList<String> nlist = new ArrayList<String>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
filterableString = list.get(i);
if (filterableString.toLowerCase().contains(filterString)) {
nlist.add(filterableString);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
}

Error in recyclerView

Can anyone check if there are errors in it. here my code, If there is any error in the code please tell me? I don't know how to fix the code Search.java.
in my RecyclerItemClickListener.java
public interface RecyclerItemClickListener {
void onItemClick(int position);
}
My Adapter HierAdapter.java
public class HireAdapter extends RecyclerView.Adapter<HireAdapter.ViewHolder>{
private ArrayList<HireItem> TeacherItemList;
private Context context;
private RecyclerItemClickListener itemClickListener;
public HireAdapter(Context c, ArrayList<HireItem> teacherItemList, RecyclerItemClickListener listener) {
TeacherItemList = teacherItemList;
context = c;
itemClickListener = listener;
}
public static class ViewHolder extends RecyclerView.ViewHolder{
public final TextView nameText, subjectText,levelText ,cityText;
public ViewHolder(View itemView) {
super(itemView);
nameText = (TextView)itemView.findViewById(R.id.result_name);
subjectText = (TextView)itemView.findViewById(R.id.result_subject);
levelText = (TextView)itemView.findViewById(R.id.result_level);
cityText = (TextView)itemView.findViewById(R.id.result_city);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_teachers,parent,false);
final ViewHolder viewHolder = new ViewHolder(rowView);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemClickListener.onItemClick(viewHolder.getLayoutPosition());
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.nameText.setText(TeacherItemList.get(position).getResult_name());
holder.subjectText.setText(TeacherItemList.get(position).getResult_subject());
holder.levelText.setText(TeacherItemList.get(position).getResult_level());
holder.cityText.setText(TeacherItemList.get(position).getResult_city());
//Here it is simply write onItemClick listener here
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, ProfileTeaAdapter.class);
context.startActivity(intent);
}
});
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public int getItemCount() {
return TeacherItemList.size();
}}
Here Search.java, I wrote notes at each error. Because I did not know how to correct some codes to work with HireAdapter and RecyclerItemClickListener, can anyone solve the error?
public class Search extends Fragment implements RecyclerItemClickListener {
private Context context;
private RecyclerView recyclerView;
private DatabaseReference databaseReference;
private FirebaseAuth firebaseAuth;
private List<HireItem> hireItem = new ArrayList<>();
HireAdapter mAdapter;
ImageView bt_search;
ProgressDialog progressDialog;
Spinner spinner_sort;
String key = "req_skill1";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_search,container,false);
//Getting FireBase Instance
firebaseAuth = FirebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference("teachers");
//Getting id of Views
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.rv_places);
recyclerView.setAdapter(mAdapter);
//
bt_search = (ImageView)view.findViewById(R.id.bt_search);
spinner_sort = (Spinner)view.findViewById(R.id.spinner_sort);
setupSpinner();
List<HireItem> hireItem = new ArrayList<>();
mAdapter = new HireAdapter(getContext(),R.layout.list_item_teachers,hireItem); // error at (getContext(),R.layout.list_item_teachers,hireItem)
bt_search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mAdapter != null){
mAdapter.clear(); // error at .clear();
}
progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Searching Teachers");
progressDialog.show();
FirebaseDatabase.getInstance().getReference("teachers").orderByChild("subject").startAt(key).endAt(key + "~")
.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Teachers child = dataSnapshot.getValue(Teachers.class);
HireItem hireItem = new HireItem(child.teaname, child.city, child.subject, child.level, child.sex,child.mobile, child.qualification, child.skill1, child.experince, child.salary,child.age);
mAdapter.add(hireItem); // error at .add
progressDialog.dismiss();
if(mAdapter == null){
Toast.makeText(getContext(), "No Match Found", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
if(mAdapter == null){
Toast.makeText(getContext(), "No Match Found", Toast.LENGTH_SHORT).show();
}
else{
recyclerView.setAdapter(mAdapter); // error at recyclerView
}
}
});
return view;
}
private void setupSpinner(){
ArrayAdapter adapter = ArrayAdapter.createFromResource(getContext(),R.array.array_teacher_sort,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner_sort.setAdapter(adapter);
spinner_sort.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
key = (String)adapterView.getItemAtPosition(i);
if(key.equals(getString(R.string.sort_A))){
key = "Math";
}else if(key.equals(getString(R.string.sort_AA))){
key = "computer";
}
else if(key.equals(getString(R.string.sort_AB))){
key = "Biology";
}
else if(key.equals(getString(R.string.sort_AD))){
key = "Physics";
}
else if(key.equals(getString(R.string.sort_AXX))){
key = "Holy Quran";
}
else if(key.equals(getString(R.string.sort_AZ))){
key = "Chysics";
}
else if(key.equals(getString(R.string.sort_AS))){
key = "English";
}
else if(key.equals(getString(R.string.sort_AQ))){
key = "Arabic";
}
else if(key.equals(getString(R.string.sort_ADD))){
key = "Science";
}
else if(key.equals(getString(R.string.sort_AE))){
key = "History";
}
else if(key.equals(getString(R.string.sort_AW))){
key = "Geograpghy";
}
else if(key.equals(getString(R.string.sort_AR))){
key = "Art education";
}
else if(key.equals(getString(R.string.sort_AT))){
key = "Family education";
}
else if(key.equals(getString(R.string.sort_aae))){
key = "Religion";
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public void onResume() {
super.onResume();
mAdapter.clear(); // error at .clear();
}
#Override
public void onItemClick(int position) {
} }
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_teachers,parent,false);
final ViewHolder viewHolder = new ViewHolder(rowView);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemClickListener.onItemClick(viewHolder.getLayoutPosition());
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.nameText.setText(TeacherItemList.get(position).getResult_name());
holder.subjectText.setText(TeacherItemList.get(position).getResult_subject());
holder.levelText.setText(TeacherItemList.get(position).getResult_level());
holder.cityText.setText(TeacherItemList.get(position).getResult_city());
//Here it is simply write onItemClick listener here
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, ProfileTeaAdapter.class);
context.startActivity(intent);
}
});
}
Here you are setting onClickListner on the same view twice. The Listener set in the onBindViewHolder will override the Listner set in the onCreateViewHolder method.

Categories

Resources