RecyclerView, wrong positioning of data - java

im making a program that can view data and image at the same time using recyclerview
MainActivity
mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
ArrayList<Upload> mUpload = new ArrayList<>();
String y = "report";
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
childcount = postSnapshot.child(userID).getChildrenCount() - 5;
String z = y+childcount;
Upload upload = postSnapshot.child(userID).child(z).getValue(Upload.class);
Upload uploads = postSnapshot.child(userID).getValue(Upload.class);
mUploads.add(upload);
mUploads.add(uploads);
mUpload.addAll(mUploads);
Log.d(TAG, "sampleData " + mUploads);
}
mAdapter = new ImageAdapter(getActivity(), mUpload);
mRecycleView.setAdapter(mAdapter);
}
ImageAdapter
#Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getiName());
holder.textViewDate.setText(uploadCurrent.getDate());
holder.textViewAddress.setText(uploadCurrent.getAddress());
holder.textViewPhone.setText(uploadCurrent.getPhone());
holder.textViewReport.setText(uploadCurrent.getReport());
Picasso.with(mContext)
.load(uploadCurrent.getImageUrl())
.fit()
.centerCrop()
.into(holder.imageView);
holder.setIsRecyclable(false);
holder.getLayoutPosition();
}
Upload Class
public class Upload {
private String mName;
private String mImageUrl;
private String date;
private String address;
private String phone;
private String iName;
private String report;
public Upload() {
//empty constructor needed
}
public Upload(String name, String imageUrl) {
if (name.trim().equals("")) {
name = "No Name";
}
mName = name;
mImageUrl = imageUrl;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getiName() {
return iName;
}
public void setiName(String iName) {
this.iName = iName;
}
public String getReport() {
return report;
}
public void setReport(String report) {
this.report = report;
}
public String getDate() { return date; }
public void setDate(String date) { this.date = date; }
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public String getImageUrl() {
return mImageUrl;
}
public void setImageUrl(String imageUrl) {
mImageUrl = imageUrl;
}
}
xml file
enter image description here
output i get
enter image description here
as you can see i got wrong positioning of data, i also try to merge the 2 arraylist data which is upload and uploads but nothings change, can someone help me with this project. thank you so much

Related

How to create a retrofit2 array in android studio?

I took this information out of a JSON and initialized it, but I don't understand how I can get the data out of the form to pass them to the cardView afterward. Or is there an easier way?
MainActivity
public class MainActivity extends AppCompatActivity {
Context context;
Example example;
Response responses;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView rv = (RecyclerView)findViewById(R.id.cartView);
LinearLayoutManager llm = new LinearLayoutManager(context);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("Secret Url") // For some reason I cannot show the url
.addConverterFactory(GsonConverterFactory.create())
.build();
Api api = retrofit.create(Api.class);
ArrayList arrayList = new ArrayList();
Call<Example> call = api.getRespon();
call.enqueue(new Callback<Example>() {
#Override
public void onResponse(Call<Example> call, Response<Example> response) {
if(response.code() != 200){
Toast.makeText(MainActivity.this, "Connect",Toast.LENGTH_SHORT).show();
return;
}
Example examples = response.body();
for(int i=0; i<examples.getResponse().size(); i++){
String f_name = response.body().getResponse().iterator().next().getfName();
String l_name = response.body().getResponse().iterator().next().getlName();
String birthday = response.body().getResponse().iterator().next().getBirthday();
String SpecName = response.body().getResponse().iterator().next().getSpecialty()
.iterator().next().getName();
int SpecId = response.body().getResponse().iterator().next().getSpecialty()
.iterator().next().getSpecialtyId();
}
}
#Override
public void onFailure(Call<Example> call, Throwable t) {
Toast.makeText(MainActivity.this, "Fail",Toast.LENGTH_SHORT).show();
}
});
}
}
At the moment I have not finished the class because I can not specify the data that have been implemented
PersonaAdapter
public class PersonAdapter extends RecyclerView.Adapter<PersonAdapter.PersonViewHolder> {
Context context;
Example example;
MainActivity mainActivity;
public static class PersonViewHolder extends RecyclerView.ViewHolder{
CardView cv;
TextView l_name, f_name, birthday, SpecName, Age;
ImageView avatar;
public PersonViewHolder(View itemView) {
super(itemView);
cv = itemView.findViewById(R.id.cartView);
l_name = itemView.findViewById(R.id.textLName);
f_name = itemView.findViewById(R.id.textFName);
birthday = itemView.findViewById(R.id.textBirthday);
SpecName = itemView.findViewById(R.id.textSpecName);
Age = itemView.findViewById(R.id.textAge);
}
}
// иницилизация
#Override
public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_layout,viewGroup,false);
PersonViewHolder phv = new PersonViewHolder(v);
return phv;
}
#Override
public void onBindViewHolder(PersonViewHolder personViewHolder, int i) {
//***
}
#Override
public int getItemCount() {
return example.getResponse().size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
}
Handler itself
Response
public class Response {
#SerializedName("f_name")
#Expose
private String fName;
#SerializedName("l_name")
#Expose
private String lName;
#SerializedName("birthday")
#Expose
private String birthday;
#SerializedName("avatr_url")
#Expose
private String avatrUrl;
#SerializedName("specialty")
#Expose
private List<Specialty> specialty = null;
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public Response withfName(String fName) {
this.fName = fName;
return this;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public Response withlName(String lName) {
this.lName = lName;
return this;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public Response withBirthday(String birthday) {
this.birthday = birthday;
return this;
}
public String getAvatrUrl() {
return avatrUrl;
}
public void setAvatrUrl(String avatrUrl) {
this.avatrUrl = avatrUrl;
}
public Response withAvatrUrl(String avatrUrl) {
this.avatrUrl = avatrUrl;
return this;
}
public List<Specialty> getSpecialty() {
return specialty;
}
public void setSpecialty(List<Specialty> specialty) {
this.specialty = specialty;
}
public Response withSpecialty(List<Specialty> specialty) {
this.specialty = specialty;
return this;
}
}
Specialty
public class Specialty {
#SerializedName("specialty_id")
#Expose
private Integer specialtyId;
#SerializedName("name")
#Expose
private String name;
public Integer getSpecialtyId() {
return specialtyId;
}
public void setSpecialtyId(Integer specialtyId) {
this.specialtyId = specialtyId;
}
public Specialty withSpecialtyId(Integer specialtyId) {
this.specialtyId = specialtyId;
return this;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Specialty withName(String name) {
this.name = name;
return this;
}
}
I solved the problem by creating a list and putting the data into an array
List<Worker> workerList = new ArrayList<>();
for(int i = 0; i < examples.getResponse().size(); i++){
String f_name = response.body().getResponse().get(i).getfName();
String l_name = response.body().getResponse().get(i).getlName();
String birthday = response.body().getResponse().get(i).getBirthday();
String SpecName = response.body().getResponse().get(i).getSpecialty()
.iterator().next().getName();
String SpecId = response.body().getResponse().iterator().next().getSpecialty()
.iterator().next().getSpecialtyId().toString();
String AvatarUrl = response.body().getResponse().get(i).getAvatrUrl();
workerList.add(new Worker(f_name, l_name, birthday, SpecName, SpecId, AvatarUrl));
In Worker has a constructor and getter

How to filter a custom listView with text, image and checkbox?

Watching a tutorial I have a listView.
I have an EditText and want to filter the listView content by what is in the EditText.
Here is my adapter class:
class ListViewAdapter extends BaseAdapter {
private List<listAudienceFriendsExcept> FriendsExceptList;
private Context context;
ListViewAdapter(Context context, List<listAudienceFriendsExcept> FriendsExceptList) {
this.context = context;
this.FriendsExceptList = FriendsExceptList;
}
#Override
public int getCount() {
return FriendsExceptList.size();
}
#Override
public Object getItem(int pos) {
return FriendsExceptList.get(pos);
}
#Override
public long getItemId(int pos) {
return pos;
}
#SuppressLint("ViewHolder")
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
view = LayoutInflater.from(context).inflate(R.layout.model,viewGroup,false);
TextView name = view.findViewById(R.id.name);
ImageView avatar = view.findViewById(R.id.avatar);
final CheckBox checkbox = view.findViewById(R.id.checkbox);
final listAudienceFriendsExcept thisListAudienceFriendsExcept = FriendsExceptList.get(position);
// Setting data to listView items
checkbox.setTag(thisListAudienceFriendsExcept.getId());
name.setText(thisListAudienceFriendsExcept.getGetFirstName());
if (!thisListAudienceFriendsExcept.getGetAvatar().equals("default_avatar.png")) {
Glide.with(avatar)
.load(API_BASE_URL+"files/avatar_back_files/"+thisListAudienceFriendsExcept.getGetAvatar())
.circleCrop()
.fitCenter()
.into(avatar);
} else if (thisListAudienceFriendsExcept.getGetSex().equals("male")) {
Glide.with(avatar)
.load(API_BASE_URL+"tools/img/default_avatar.png")
.circleCrop()
.fitCenter()
.into(avatar);
} else {
Glide.with(avatar)
.load(API_BASE_URL+"tools/img/female_default_avatar.png")
.circleCrop()
.fitCenter()
.into(avatar);
}
return view;
}
}
Here my list:
static class listAudienceFriendsExcept {
#SerializedName("id")
private int id;
#SerializedName("first_name")
private String first_name;
#SerializedName("last_name")
private String last_name;
#SerializedName("avatar")
private String avatar;
#SerializedName("sex")
private String sex;
public listAudienceFriendsExcept(int id, String first_name, String last_name, String avatar, String sex) {
this.id = id;
this.first_name = first_name;
this.last_name = last_name;
this.avatar = avatar;
this.sex = sex;
}
int getId() {
return id;
}
String getGetFirstName() {
return first_name;
}
String getGetLastName() {
return last_name;
}
String getGetAvatar() {
return avatar;
}
String getGetSex() {
return sex;
}
}
Here my populateListView:
private void populateListView(List<listAudienceFriendsExcept> thisList) {
ListView listViewAudienceFriendsExcept = findViewById(R.id.listViewAudienceFriendsExcept);
ListViewAdapter adapter = new ListViewAdapter(this, thisList);
listViewAudienceFriendsExcept.setAdapter(adapter);
}
I tried that:
final TextInputEditText first_name_edit_text = findViewById(R.id.first_name_edit_text);
first_name_edit_text.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence cs, int s, int b, int c) {
friendListAdapter.getFilter().filter(newText); // What is **friendListAdapter** in my case ?
}
I'm using Retrofit tho get data from server when activity start:
private void callServer() {
/*Create handle for the RetrofitInstance interface*/
df myAPIService = RetrofitClientInstance.getRetrofitInstance().create(df.class);
Call<List<listAudienceFriendsExcept>> call = myAPIService.getListAudienceFriendsExcept();
call.enqueue(new Callback<List<listAudienceFriendsExcept>>() {
#SuppressWarnings("NullableProblems")
#Override
public void onResponse(Call<List<listAudienceFriendsExcept>> call, Response<List<listAudienceFriendsExcept>> response) {
populateListView(response.body());
}
#SuppressWarnings("NullableProblems")
#Override
public void onFailure(Call<List<listAudienceFriendsExcept>> call, Throwable throwable) {
Toast.makeText(MainActivity.this, throwable.getMessage()+"èèè", Toast.LENGTH_LONG).show();
}
});
}
I have googled and found that: friendListAdapter.getFilter().filter(newText); But I don't know to use in my case.
Any Solution?
My other question:
How could I pass the user ID to php server ?
Thanks.`
You can use streams to filter.
//add this imports on your class or activity
//import com.annimon.stream.Collectors;
//import com.annimon.stream.Stream;
//import com.annimon.stream.function.Predicate;
List<listAudienceFriendsExcept> original_list=new ArrayList<>();
List<listAudienceFriendsExcept> search_list=new ArrayList<>();
EditText serch_field;
void setup()
{
//original_list=whatever the source of the list is
//be sure to populate the original list before proceeding here
populateListView(original_list);
serch_field.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
search_list = Stream.of(original_list).filter(new Predicate<listAudienceFriendsExcept>() {
#Override
public boolean test(listAudienceFriendsExcept item) {
// return item.getGetFirstName().toUpperCase().contains(serch_field.getText().toString().toUpperCase())||item.getGetLastName().toUpperCase().contains(serch_field.getText().toString().toUpperCase());//if you want to filter multiple fields
return item.first_name.toUpperCase().contains(serch_field.getText().toString().toUpperCase());//to filter first name only
}
}).collect(com.annimon.stream.Collectors.<listAudienceFriendsExcept>toList());
populateListView(search_list);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
For the model
public class listAudienceFriendsExcept {
#SerializedName("id")
private int id;
#SerializedName("first_name")
public String first_name;
#SerializedName("last_name")
private String last_name;
#SerializedName("avatar")
private String avatar;
#SerializedName("sex")
private String sex;
public listAudienceFriendsExcept(int id, String first_name, String last_name, String avatar, String sex) {
this.id = id;
this.first_name = first_name;
this.last_name = last_name;
this.avatar = avatar;
this.sex = sex;
}
int getId() {
return id;
}
public String getGetFirstName() {
return first_name;
}
public String getGetLastName() {
return last_name;
}
public String getGetAvatar() {
return avatar;
}
public String getGetSex() {
return sex;
}
}
And on Gradle-dependencies add
implementation 'com.annimon:stream:1.1.2'

Add custom markers to google maps from geopints stored on firebase

Excuse my ignorance but I am very new to Android Studio and Java. I have adapted a lot the following code from another course to my needs, but it is not working.
I am trying to add custom markers to my Google maps Android app. Lhe locations of the markers are stored as geopoints on firebase. I have attempted to do so using cluster marker. The app crashes immediately when I attempt to run it with the following shortened error.
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.firestore.CollectionReference com.google.firebase.firestore.FirebaseFirestore.collection(java.lang.String)' on a null object reference
at com.codingwithmitch.googlemaps2018.ui.MapsActivity.addMapMarkers(MapsActivity.java:400)
at com.codingwithmitch.googlemaps2018.ui.MapsActivity.onMapReady(MapsActivity.java:486)
I am attempting to display every geopoint in the Stop Locations Collection
I cannot screen shot my firebase but it looks as follows:
Collection
"Stop Locations">>>>>Documents
"KzDQ2sITZ3O8GEoZgp0I",...etc >>>>>Fields
Geo:""
Name:""
avatar:""
loc_id""
If I were to guess I would say the mLocationInformations is empty, probably originating from here >> mLocationInformations.add(document.toObject(LocationInformation.class))
code from MapsActivity:
private ClusterManager<ClusterMarker> mClusterManager;
private MyClusterManagerRenderer mClusterManagerRenderer;
private ArrayList<ClusterMarker> mClusterMarkers = new ArrayList<>();
private LocationInformation mLocationInformation;
private ArrayList<LocationInformation> mLocationInformations = new ArrayList<>();
private void addMapMarkers(){
CollectionReference locationsRef = mDb
.collection("Stop Locations");
locationsRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful()){
for (QueryDocumentSnapshot document : task.getResult()) {
mLocationInformations.add(document.toObject(LocationInformation.class));
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
if(mMap != null){
if(mClusterManager == null){
mClusterManager = new ClusterManager<ClusterMarker>(this.getApplicationContext(), mMap);
}
if(mClusterManagerRenderer == null){
mClusterManagerRenderer = new MyClusterManagerRenderer(
this,
mMap,
mClusterManager
);
mClusterManager.setRenderer(mClusterManagerRenderer);
}
for(LocationInformation locationInformation: mLocationInformations){
Log.d(TAG, "addMapMarkers: location: " + locationInformation.getGeo().toString());
try{
String snippet = "";
snippet = "";
int avatar = R.drawable.cartman_cop; // set the default avatar
try{
avatar = Integer.parseInt(locationInformation.getAvatar());
}catch (NumberFormatException e){
Log.d(TAG, "addMapMarkers: no avatar ");
}
ClusterMarker newClusterMarker = new ClusterMarker(
new LatLng(locationInformation.getGeo().getLatitude(), locationInformation.getGeo().getLongitude()),
//locationInformation.getName().getUsername(),
locationInformation.getLoc_id(),
snippet,
avatar,
locationInformation.getName()
);
mClusterManager.addItem(newClusterMarker);//adding to the map
mClusterMarkers.add(newClusterMarker);//making an easy access array list
}catch (NullPointerException e){
Log.e(TAG, "addMapMarkers: NullPointerException: " + e.getMessage() );
}
}
mClusterManager.cluster();
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if(mLocationPermissionGranted){
getDeviceLocation();
}else{
Toast.makeText(this, "mLocationpermission denied at origin", Toast.LENGTH_SHORT).show();
}
addMapMarkers();
}
}
LocationInfromation.java
import com.google.firebase.firestore.GeoPoint;
public class LocationInformation {
private String Name;
private GeoPoint Geo;
private String avatar;
private String loc_id;
public LocationInformation(String Name, GeoPoint Geo, String avatar, String loc_id) {
this.Name = Name;
this.Geo = Geo;
this.avatar = avatar;
this.loc_id = loc_id;
}
public LocationInformation(){
}
public String getLoc_id() {
return loc_id;
}
public void setLoc_id(String loc_id) {
this.loc_id = loc_id;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
private Double longitude;
public String getName() {
return Name;
}
public void setName(String name) {
this.Name = Name;
}
public GeoPoint getGeo() {
return Geo;
}
public void setGeo(GeoPoint geo) {
this.Geo = Geo;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
#Override
public String toString() {
return "LocationInformation{" +
"Name=" + Name +
", Geo=" + Geo +
", avatar='" + avatar +
", loc_id='" + loc_id +
'}';
}
}
ClusterMArker.java
import com.google.android.gms.maps.model.LatLng;
import com.google.maps.android.clustering.ClusterItem;
public class ClusterMarker implements ClusterItem {
private LatLng position; // required field
private String title; // required field
private String snippet; // required field
private int iconPicture;
private String name;
public ClusterMarker(LatLng position, String title, String snippet, int iconPicture, String name) {
this.position = position;
this.title = title;
this.snippet = snippet;
this.iconPicture = iconPicture;
this.name = name;
}
public ClusterMarker() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIconPicture() {
return iconPicture;
}
public void setIconPicture(int iconPicture) {
this.iconPicture = iconPicture;
}
public void setPosition(LatLng position) {
this.position = position;
}
public void setTitle(String title) {
this.title = title;
}
public void setSnippet(String snippet) {
this.snippet = snippet;
}
public LatLng getPosition() {
return position;
}
public String getTitle() {
return title;
}
public String getSnippet() {
return snippet;
}
}
[enter image description here][1]
To solve this, please add the following line of code:
FirebaseFirestore mDb = FirebaseFirestore.getInstance();
Right before this line:
CollectionReference locationsRef = mDb.collection("Stop Locations");
So your FirebaseFirestore object is initialized correctly.

How to pass a class with an abstract class type as parameter in parcelable android studio java

I am trying to pass this class as a parcelable in android.
public class Outfit implements Parcelable {
private List<Item> itemList;
private String mName;
private String mImageUrl;
public Outfit() {}
public Outfit(String mName, String mImageUrl) {
this.mName = mName;
this.mImageUrl = mImageUrl;
}
protected Outfit(Parcel in) {
itemList = in.createTypedArrayList(Item.CREATOR);
mName = in.readString();
mImageUrl = in.readString();
}
public static final Creator<Outfit> CREATOR = new Creator<Outfit>() {
#Override
public Outfit createFromParcel(Parcel in) {
return new Outfit(in);
}
#Override
public Outfit[] newArray(int size) {
return new Outfit[size];
}
};
public String getmName() {
return mName;
}
public String getmImageUrl() {
return mImageUrl;
}
#Override
public String toString() {
return mName;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeTypedList(itemList);
parcel.writeString(mName);
parcel.writeString(mImageUrl);
}
}
the problem is that Item is abstract and itemList = in.creatTypedArrayList(Item.CREATOR) because Item does not have a CREATOR . Only its subclasses have this implementation.
Item.java
public abstract class Item implements Parcelable {
private String mName;
private String mColor;
private String mImageUrl;
private List<TagHolder> tags = new ArrayList<>();
private String mKey;
public Item(){
}
public Item(String mName, String mColor, String mImageUrl) {
this.mName = mName;
this.mColor = mColor;
this.mImageUrl = mImageUrl;
}
protected Item(Parcel in) {
mName = in.readString();
mColor = in.readString();
mImageUrl = in.readString();
tags = in.createTypedArrayList(TagHolder.CREATOR);
mKey = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mName);
dest.writeString(mColor);
dest.writeString(mImageUrl);
dest.writeTypedList(tags);
dest.writeString(mKey);
}
#Override
public int describeContents() {
return 0;
}
public void setmName(String mName) {
this.mName = mName;
}
public void setmImageUrl(String mImageUrl) {
this.mImageUrl = mImageUrl;
}
public List<TagHolder> getTags() {
return tags;
}
public String getmColor() {
return mColor;
}
public String getmImageUrl() {
return mImageUrl;
}
public void setmColor(String mColor) {
this.mColor = mColor;
}
public String getmName() {
return mName;
}
public void setTags(List<TagHolder> tags) {
this.tags = tags;
}
#Exclude // dont need this in our firebase database
public String getKey() {
return mKey;
}
#Exclude
public void setMkey(String key) {
mKey = key;
}
public abstract String getCategory();
}
I am able to parce a List as a parcelable array when I call put extra. But when I try to do so for outfit it gives error . Is there any way to pass Outfit as a parcelable?
Do you try using another method for the list?
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeList(itemList);
parcel.writeString(mName);
parcel.writeString(mImageUrl);
}
protected Outfit(Parcel in) {
in.readList(itemList, Item.class.getClassLoader());
mName = in.readString();
mImageUrl = in.readString();
}

Custom ArrayAdapter display the last Information only

I have an ArrayAdapter which lists user's data, but it lists the last user's data, it show the correct number of row, if there are 5 users it shows 5 rows but all of them are the same, the last user.
The main activity is this:
for(DataSnapshot Ds : dS.getChildren()) {
Object key = Ds.getKey();
String StringKey = String.valueOf(key);
getname(StringKey);
}
private void getname(String ID){
final String IDfinal = ID;
DatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Name = dataSnapshot.child("Users").child(IDfinal).child("name").getValue(String.class);
Email = dataSnapshot.child("Users").child(IDfinal).child("email").getValue(String.class);
Gender = dataSnapshot.child("Users").child(IDfinal).child("gender").getValue(String.class);
Birthday = dataSnapshot.child("Users").child(IDfinal).child("data_birth").getValue(String.class);
UserInformation ID = new UserInformation(Name,Email,Gender,Birthday);
userInformationsList.add(ID);
list();
Toast.makeText(SearchActivity.this,Name,Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(SearchActivity.this,"Error 404",Toast.LENGTH_SHORT).show();
}
});
}
private void list(){
customAdapter customAdapterIntent= new customAdapter(this,R.layout.userslist,userInformationsList);
mListView.setAdapter(customAdapterIntent);
}
}
UserInformation.java
public class UserInformation {
private static String Name;
private static String Gender;
private static String Email;
private static String Birthday;
public UserInformation(String Name,String Gender,String Email,String Birthday){
this.Birthday=Birthday;
this.Email=Email;
this.Gender=Gender;
this.Name=Name;
}
public static String getName(){return Name;}
public static String getEmail(){return Email;}
public static String getGender(){return Gender;}
public static String getBirthday(){return Birthday;}
}
customAdapter.java
public class customAdapter extends ArrayAdapter<UserInformation> {
public customAdapter(Context context, int layoutResource, List<UserInformation> userInformationsList) {
super(context, layoutResource, userInformationsList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
view = layoutInflater.inflate(R.layout.userslist, null);
}
UserInformation userInformation = getItem(position);
if (userInformation != null) {
TextView Name = (TextView) view.findViewById(R.id.textNameList);
//name.setText(name[position]);
TextView email = (TextView) view.findViewById(R.id.textEmailList);
//email.setText(Email[position]);
TextView gender = (TextView) view.findViewById(R.id.textGenderList);
//gender.setText(Gender[position]);
TextView birthday = (TextView) view.findViewById(R.id.textBirthdayList);
//birthday.setText(Birthday[position]);
if (Name != null) {
Name.setText(UserInformation.getName());
}
if (email != null) {
email.setText(UserInformation.getEmail());
}
if (gender != null) {
gender.setText(UserInformation.getGender());
}
if (birthday != null) {
birthday.setText(UserInformation.getBirthday());
}
}
return view;
}
}
For setting values why are you using Class (UserInformation) instead of Class name use its object userInformation.
if (Name != null) {
Name.setText(userInformation.getName());
}
if (email != null) {
email.setText(userInformation.getEmail());
}
if (gender != null) {
gender.setText(userInformation.getGender());
}
if (birthday != null) {
birthday.setText(userInformation.getBirthday());
}
One more thing , make below values non-static
public class UserInformation {
private String Name;
private String Gender;
private String Email;
private String Birthday;
public UserInformation(String Name,String Gender,String Email,String Birthday){
this.Birthday=Birthday;
this.Email=Email;
this.Gender=Gender;
this.Name=Name;
}
public String getName(){return Name;}
public String getEmail(){return Email;}
public String getGender(){return Gender;}
public String getBirthday(){return Birthday;}
}

Categories

Resources