I have created a listview where I want to put all the fetched data according to the result of the previous activity values. Like, I have a Spinner and an Edittext then a search button.
The result will be according to the spinner value and edit text value both. But it is not coming. Please help.
Below my Test class with its layout file (here the spinner and edit text present)
and The SearchResults activity, and Useradapter (model class)
Test.java
public class Test extends AppCompatActivity {
Spinner sp;
EditText e1;
Button logout, searchuser;
FirebaseAuth firebaseAuth;
FirebaseUser firebaseUser;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_home);
logout = (Button)findViewById(R.id.logout);
searchuser = (Button)findViewById(R.id.searchbutt1);
sp = (Spinner)findViewById(R.id.selectblood) ;
e1 = (EditText)findViewById(R.id.searchpin);
firebaseAuth = FirebaseAuth.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
final String[] bloodgroups = new String[]{"A+","A-", "B+", "B-","O+", "O-", "AB+", "AB-"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, bloodgroups);
sp.setAdapter(adapter);
searchuser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String bloods = sp.getSelectedItem().toString();
String pin1 = e1.getText().toString();
Intent intent = new Intent(Test.this, Searchresults.class);
intent.putExtra("bloods", bloods);
intent.putExtra("pin1", pin1);
startActivity(intent);
}
});
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alert = new AlertDialog.Builder(Test.this);
alert.setMessage("Are you Sure?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
FirebaseAuth.getInstance().signOut();
Intent i = new Intent(getApplicationContext(), SignupPage.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog dialogg = alert.create();
dialogg.show();
}
});
}
}
Layout file (Fragmenthome.xml)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/button">
<ImageView
android:id="#+id/imageView3"
android:layout_width="match_parent"
android:layout_height="400dp"
android:src="#drawable/bloodimage"
app:layout_constraintBottom_toTopOf="#+id/cardView2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.32999998" />
<androidx.cardview.widget.CardView
android:id="#+id/cardView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
app:cardCornerRadius="15dp"
app:cardElevation="4dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.7">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="20dp">
<Spinner
android:id="#+id/selectblood"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/searchpin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Pincode"
android:inputType="number"/>
</com.google.android.material.textfield.TextInputLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
<Button
android:id="#+id/searchbutt1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="40dp"
android:layout_marginEnd="40dp"
android:background="#drawable/buttonpressed"
android:text="Search"
android:textColor="#ffffff"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/cardView2"
app:layout_constraintVertical_bias="0.32" />
<Button
android:id="#+id/logout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="40dp"
android:layout_marginEnd="40dp"
android:background="#drawable/buttonpressed"
android:text="Logout"
android:textColor="#ffffff"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/searchbutt1" />
Searchresults Activity
public class Searchresults extends AppCompatActivity {
String pinfin;
String bloodfin;
ArrayList<String> donorList;
ListView listView;
ArrayAdapter<String> arrayAdapter;
public static ArrayList<UserAdapter> donorInfo;
DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_searchresults);
Bundle extras = getIntent().getExtras();
bloodfin = extras.getString("bloods");
pinfin = extras.getString("pin1");
donorList = new ArrayList<>();
donorInfo = new ArrayList<>();
listView = (ListView) findViewById(R.id.list_donor);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item,
donorList);
listView.setAdapter(arrayAdapter);
myRef = FirebaseDatabase.getInstance().getReference("Users");
myRef.child(bloodfin).child(pinfin).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
UserAdapter donor = dataSnapshot.getValue(UserAdapter.class);
donorInfo.add(donor);
assert donor != null;
String donorInfo = donor.namefin + " \n" + donor.gender + " \n" + donor.phonefin + " \n" + donor.addfin + " \n" + donor.bloodfin ;
donorList.add(donorInfo);
arrayAdapter.notifyDataSetChanged();
}
#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) {
Toast.makeText(Searchresults.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
UserAdapter Class
public class UserAdapter {
public String email, namefin, addfin, statefin, phonefin, pinfin, bloodfin, gender;
public UserAdapter(String email, String namefin, String addfin, String statefin, String pinfin, String phonefin, String bloodfin, String gender) {
this.email = email;
this.namefin = namefin;
this.addfin = addfin;
this.statefin = statefin;
this.phonefin = phonefin;
this.pinfin = pinfin;
this.bloodfin = bloodfin;
this.gender = gender;
}
public String getEmail() {
return email;
}
public String getNamefin() {
return namefin;
}
public String getAddfin() {
return addfin;
}
public String getStatefin() {
return statefin;
}
public String getPhonefin() {
return phonefin;
}
public String getPinfin() {
return pinfin;
}
public String getBloodfin() {
return bloodfin;
}
public String getGender() {
return gender;
}
public void setEmail(String email) {
this.email = email;
}
public void setNamefin(String namefin) {
this.namefin = namefin;
}
public void setAddfin(String addfin) {
this.addfin = addfin;
}
public void setStatefin(String statefin) {
this.statefin = statefin;
}
public void setPhonefin(String phonefin) {
this.phonefin = phonefin;
}
public void setPinfin(String pinfin) {
this.pinfin = pinfin;
}
public void setBloodfin(String bloodfin) {
this.bloodfin = bloodfin;
}
public void setGender(String gender) {
this.gender = gender;
}
}
myRef = FirebaseDatabase.getInstance().getReference("Users");
myRef.child(bloodfin).child(pinfin).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
UserAdapter donor = dataSnapshot.getValue(UserAdapter.class);
donorInfo.add(donor);
assert donor != null;
String donorInfo = donor.namefin + " \n" + donor.gender + " \n" + donor.phonefin + " \n" + donor.addfin + " \n" + donor.bloodfin ;
donorList.add(donorInfo);
arrayAdapter = new ArrayAdapter(donorList, getContext());
recyclerview.setAdapter(arrayAdapter);
}
Related
I am new to this, I am trying to load images from Firestore into a Grid layout recyclerview, the Toast in Firestore onSuccess method shows "Success" message, but the images aren't showing, I am not sure where I did wrong. I used the Image Url saved in Firestore from Firebase Storage.
Could someone please help? Thank you in advance.
Firestore structure:
The PhotoActivity:
public class PhotoActivity extends AppCompatActivity {
private static final int PICK_IMAGE_REQUEST = 1;
private LinearLayout confirmLayout;
private ImageView pickedImageView;
private EditText titleEditText, photoDescriptionEditText;
private ProgressBar progressBar;
private String title, photoDescription;
private Date datePhoto;
private Uri pickedImageUrl;
private FirebaseFirestore db;
private FirebaseAuth mAuth;
private String userId;
private CollectionReference collectionReference;
private StorageReference storageReference;
private FloatingActionButton fab;
private RecyclerView recyclerView;
private List<Photo> photoList;
private PhotoAdapter photoAdapter;
private ProgressBar circularProgressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
confirmLayout = (LinearLayout) findViewById(R.id.confirmPhotoUploadLayout);
pickedImageView = (ImageView) findViewById(R.id.pickedImage);
titleEditText = (EditText) findViewById(R.id.photoTitle);
photoDescriptionEditText = (EditText) findViewById(R.id.photoDescription);
progressBar = (ProgressBar) findViewById(R.id.progressbarPhoto);
recyclerView = (RecyclerView) findViewById(R.id.recyclerViewPhoto);
circularProgressbar = (ProgressBar) findViewById(R.id.progress_circularPhoto);
db = FirebaseFirestore.getInstance();
mAuth = FirebaseAuth.getInstance();
userId = mAuth.getCurrentUser().getUid();
storageReference = FirebaseStorage.getInstance().getReference(userId);
collectionReference = FirebaseFirestore.getInstance().collection("main").document(userId).collection("photo");
fab = (FloatingActionButton) findViewById(R.id.fabPhoto);
circularProgressbar.setVisibility(View.VISIBLE);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
photoList = new ArrayList<>();
photoAdapter = new PhotoAdapter(this, photoList);
recyclerView.setAdapter(photoAdapter);
showPhotoGrid();
}
private void showPhotoGrid() {
collectionReference
.orderBy("datePhoto", Query.Direction.DESCENDING)
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
assert queryDocumentSnapshots != null;
if (!queryDocumentSnapshots.isEmpty()){
//if contains photos
circularProgressbar.setVisibility(View.GONE);
Toast.makeText(PhotoActivity.this, "Success", Toast.LENGTH_SHORT).show();
List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
for (DocumentSnapshot documentSnapshot : list){
Photo photo = documentSnapshot.toObject(Photo.class);
assert photo != null;
photo.setID(documentSnapshot.getId());
photoList.add(photo);
}
photoAdapter.notifyDataSetChanged();
} else {
//show no photos
circularProgressbar.setVisibility(View.GONE);
Toast.makeText(PhotoActivity.this, "No photos added yet", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
circularProgressbar.setVisibility(View.GONE);
Toast.makeText(PhotoActivity.this, "Error in showing images: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
public void addPhoto(View view) {
showImageChooser();
}
private void showImageChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
pickedImageUrl = data.getData();
Picasso.with(this).load(pickedImageUrl).into(pickedImageView);
confirmLayout.setVisibility(View.VISIBLE);
fab.setVisibility(View.GONE);
photoAdapter.notifyDataSetChanged();
}
}
public void hideConfirmLayout(View view) {
pickedImageView.setImageDrawable(null);
confirmLayout.setVisibility(View.GONE);
fab.setVisibility(View.VISIBLE);
}
public void uploadPhoto(View view) {
title = titleEditText.getText().toString().trim();
photoDescription = photoDescriptionEditText.getText().toString().trim();
if (title.isEmpty()) {
titleEditText.setError("Please give a title");
} else if (photoDescription.isEmpty()) {
photoDescription = "No description for this photo";
}
if (pickedImageUrl != null) {
if (title.isEmpty()) {
titleEditText.setError("Required");
} else {
StorageReference imageReference = storageReference.child(title + "." + getFileExtension(pickedImageUrl));
imageReference.putFile(pickedImageUrl).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setProgress(0);
}
}, 1000);
String thatImageUrl = taskSnapshot.getStorage().getDownloadUrl().toString();
Photo photo = new Photo(userId, title, photoDescription, thatImageUrl, datePhoto);
collectionReference.add(photo).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(PhotoActivity.this, "Saved to gallery", Toast.LENGTH_SHORT).show();
confirmLayout.setVisibility(View.GONE);
pickedImageView.setImageDrawable(null);
titleEditText.setText(null);
photoDescriptionEditText.setText(null);
fab.setVisibility(View.VISIBLE);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(PhotoActivity.this, "Firestore error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(PhotoActivity.this, "Storage error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
progressBar.setVisibility(View.VISIBLE);
double progress = 100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount();
progressBar.setProgress((int) progress);
}
});
}
} else {
Toast.makeText(this, "No photo is selected", Toast.LENGTH_LONG).show();
}
}
private String getFileExtension(Uri uri) {
//get photo type: jpeg, png
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
}
}
The Photo object class
public class Photo implements Serializable {
private String ID;
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
private String photoTitle;
private String photoDescription;
private String photoUrl;
#ServerTimestamp
private Date datePhoto;
public Date getDatePhoto() {
return datePhoto;
}
public void setDatePhoto(Date datePhoto) {
this.datePhoto = datePhoto;
}
public Photo() {
}
public Photo(String ID, String photoTitle, String photoDescription, String photoUrl, Date datePhoto) {
this.ID = ID;
this.photoTitle = photoTitle;
this.photoDescription = photoDescription;
this.photoUrl = photoUrl;
this.datePhoto = datePhoto;
}
public String getPhotoTitle() {
return photoTitle;
}
public void setPhotoTitle(String photoTitle) {
this.photoTitle = photoTitle;
}
public String getPhotoDescription() {
return photoDescription;
}
public void setPhotoDescription(String photoDescription) {
this.photoDescription = photoDescription;
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
}
the PhotoAdapter:
public class PhotoAdapter extends RecyclerView.Adapter<PhotoAdapter.PhotoViewHolder> {
private Context context;
private List<Photo> photoList;
public PhotoAdapter(Context context, List<Photo> photoList) {
this.context = context;
this.photoList = photoList;
}
#NonNull
#Override
public PhotoViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new PhotoViewHolder(LayoutInflater.from(context).inflate(R.layout.single_photo_layout, parent, false));
}
#Override
public void onBindViewHolder(#NonNull PhotoViewHolder holder, int position) {
Photo photo = photoList.get(position);
if (photo.getPhotoUrl() != null && !photo.getPhotoUrl().isEmpty()){
Picasso.with(context).load(photo.getPhotoUrl()).into(holder.showImage);
}
}
#Override
public int getItemCount() {
return photoList.size();
}
public class PhotoViewHolder extends RecyclerView.ViewHolder {
ImageView showImage;
public PhotoViewHolder(View inflate) {
super(inflate);
showImage = inflate.findViewById(R.id.singlePhotoImageView);
}
}
}
xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/gradient0"
tools:context=".PhotoActivity">
<TextView
android:id="#+id/titlePhoto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="#font/quicksand_bold"
android:gravity="center"
android:padding="#dimen/_20sdp"
android:text="PHOTO GALLERY"
android:textColor="#color/white"
android:textSize="#dimen/_14sdp"
android:layout_alignParentTop="true"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerViewPhoto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/titlePhoto"/>
<LinearLayout
android:id="#+id/confirmPhotoUploadLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="#drawable/white_rounded"
android:gravity="center"
android:orientation="vertical"
android:paddingTop="#dimen/_20sdp"
android:paddingBottom="#dimen/_10sdp"
android:visibility="gone">
<EditText
android:id="#+id/photoTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/_16sdp"
android:layout_marginTop="#dimen/_16sdp"
android:background="#null"
android:hint="Photo title" />
<EditText
android:id="#+id/photoDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/_16sdp"
android:layout_marginEnd="#dimen/_16sdp"
android:layout_marginBottom="#dimen/_16sdp"
android:background="#null"
android:hint="Write something about this photo..." />
<ProgressBar
android:id="#+id/progressbarPhoto"
style="#style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="invisible"
tools:visibility="visible" />
<ImageView
android:id="#+id/pickedImage"
android:layout_width="match_parent"
android:layout_height="#dimen/_300sdp"
android:layout_marginBottom="#dimen/_14sdp"
android:scaleType="centerCrop" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/_10sdp"
android:gravity="center">
<Button
android:layout_width="120dp"
android:layout_height="wrap_content"
android:background="#drawable/red_rounded_bg"
android:onClick="hideConfirmLayout"
android:text="cancel"
android:textColor="#color/white" />
<Button
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/_10sdp"
android:background="#drawable/rounded_button"
android:onClick="uploadPhoto"
android:text="save to gallery"
android:textColor="#color/white" />
</LinearLayout>
</LinearLayout>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fabPhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_margin="#dimen/_20sdp"
android:clickable="true"
android:focusable="true"
android:onClick="addPhoto"
android:src="#drawable/ic_add" />
<ProgressBar
android:id="#+id/progress_circularPhoto"
android:layout_width="#dimen/_100sdp"
android:layout_height="#dimen/_100sdp"
android:layout_centerInParent="true"
android:visibility="gone"
tools:visibility="visible"/>
</RelativeLayout>
single photo Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/singlePhotoImageView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
I found a solution based on this post--> How to use getdownloadurl in recent versions?
taskSnapshot.getStorage().getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//get the uri and carry out action here
//uri = correct filepath
}
now the images are showing in the recyclerview, yay ! Thanks for the help!
It seems like your urls are wrong.
taskSnapshot.getDownloadUrl returns Task, not the Uri or Url string. You need to add OnSuccessListener callback to get download Uri
Try to save urls by this way:
taskSnapshot.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Uri downloadUrl = uri;
String url = downloadUrl.toString()
// save this url to Firestore
}
Check this in Official documentation
my code
**I have a UserAdapter, and a Search Fragment and the user_item and user class. The problem is, the three Click Listeners to open the "Search Fragment " the app crashe!! and close.
i hope so i give u good explanation for the problem
and thanks for the help in advance
**
public class SearchFragment extends Fragment {
private RecyclerView recyclerView;
private UserAdapter userAdapter;
private List<User> userList;
EditText search_bar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_search, container, false);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
search_bar = view.findViewById(R.id.search_bar);
userList = new ArrayList<>();
userAdapter = new UserAdapter(getContext(), userList, true);
recyclerView.setAdapter(userAdapter);
readUsers();
search_bar.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) {
searchUsers(charSequence.toString().toLowerCase());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
return view;
}
private void searchUsers(String s){
Query query = FirebaseDatabase.getInstance().getReference("Users").orderByChild("username")
.startAt(s)
.endAt(s+"\uf8ff");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
userList.add(user);
}
userAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void readUsers() {
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (search_bar.getText().toString().equals("")) {
userList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
userList.add(user);
}
userAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
** my code class Use**
public class User {
private String id;
private String username;
private String fullname;
private String imageurl;
private String bio;
public User(String id, String username, String fullname, String imageurl, String bio) {
this.id = id;
this.username = username;
this.fullname = fullname;
this.imageurl = imageurl;
this.bio = bio;
}
public User() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getImageurl() {
return imageurl;
}
public void setImageurl(String imageurl) {
this.imageurl = imageurl;
}
public String getBio() {
return bio;
}
public void setBio(String bio) {
this.bio = bio;
}
}
my code UserAdapter
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ImageViewHolder> {
private Context mContext;
private List<User> mUsers;
private boolean isFragment;
private FirebaseUser firebaseUser;
public UserAdapter(Context context, List<User> users, boolean isFragment){
mContext = context;
mUsers = users;
this.isFragment = isFragment;
}
#NonNull
#Override
public UserAdapter.ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.user_item, parent, false);
return new UserAdapter.ImageViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final UserAdapter.ImageViewHolder holder, final int position) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
final User user = mUsers.get(position);
holder.btn_follow.setVisibility(View.VISIBLE);
isFollowing(user.getId(), holder.btn_follow);
holder.username.setText(user.getUsername());
holder.fullname.setText(user.getFullname());
Glide.with(mContext).load(user.getImageurl()).into(holder.image_profile);
if (user.getId().equals(firebaseUser.getUid())){
holder.btn_follow.setVisibility(View.GONE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isFragment) {
SharedPreferences.Editor editor = mContext.getSharedPreferences("PREFS", MODE_PRIVATE).edit();
editor.putString("profileid", user.getId());
editor.apply();
((FragmentActivity) mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
} else {
Intent intent = new Intent(mContext, Main2Activity.class);
intent.putExtra("publisherid", user.getId());
mContext.startActivity(intent);
}
}
});
holder.btn_follow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.btn_follow.getText().toString().equals("follow")) {
FirebaseDatabase.getInstance().getReference().child("Follow").child(firebaseUser.getUid())
.child("following").child(user.getId()).setValue(true);
FirebaseDatabase.getInstance().getReference().child("Follow").child(user.getId())
.child("followers").child(firebaseUser.getUid()).setValue(true);
addNotification(user.getId());
} else {
FirebaseDatabase.getInstance().getReference().child("Follow").child(firebaseUser.getUid())
.child("following").child(user.getId()).removeValue();
FirebaseDatabase.getInstance().getReference().child("Follow").child(user.getId())
.child("followers").child(firebaseUser.getUid()).removeValue();
}
}
});
}
private void addNotification(String userid){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Notifications").child(userid);
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("userid", firebaseUser.getUid());
hashMap.put("text", "started following you");
hashMap.put("postid", "");
hashMap.put("ispost", false);
reference.push().setValue(hashMap);
}
#Override
public int getItemCount() {
return mUsers.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder {
public TextView username;
public TextView fullname;
public CircleImageView image_profile;
public Button btn_follow;
public ImageViewHolder(View itemView) {
super(itemView);
username = itemView.findViewById(R.id.username);
fullname = itemView.findViewById(R.id.fullname);
image_profile = itemView.findViewById(R.id.image_profile);
btn_follow = itemView.findViewById(R.id.btn_follow);
}
}
private void isFollowing(final String userid, final Button button){
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference()
.child("Follow").child(firebaseUser.getUid()).child("following");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(userid).exists()){
button.setText("following");
} else{
button.setText("follow");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
** user_item**
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp"
android:orientation="vertical">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/image_profile"
android:src="#mipmap/ic_launcher"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/image_profile"
android:layout_marginStart="5dp"
android:orientation="vertical"
android:layout_centerVertical="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/username"
android:text="username"
android:maxLines="1"
android:textStyle="bold"
android:textColor="#color/colorPrimaryDark"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fullname"
android:text="full_name"
android:maxLines="1"/>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="30dp"
android:background="#drawable/button_background"
android:id="#+id/btn_follow"
android:textColor="#color/colorPrimary"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:visibility="gone"/>
</RelativeLayout>
stack trace
E/AndroidRuntime: FATAL EXCEPTION: main
Process: commenting, PID: 24881
java.lang.ClassCastException: androidx.appcompat.widget.AppCompatButton cannot be cast to androidx.recyclerview.widget.RecyclerView
at commenting.Fragment.SearchFragment.onCreateView(SearchFragment.java:47)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
at androidx.fragment.app.FragmentManagerImpl$2.run(FragmentManagerImpl.java:150)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
I/Process: Sending signal. PID: 24881 SIG: 9
Fragment.SearchFragment
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Fragment.SearchFragment">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/bar"
android:background="?android:attr/windowBackground">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
android:id="#+id/toolbar">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_search_light"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/search_bar"
android:background="#android:color/transparent"
android:hint="search_bar"
android:layout_marginStart="10dp"
android:inputType="text"/>
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/bar"
android:id="#+id/recycler_view"/>
</RelativeLayout>
It looks like your search fragment layout doesn't have the RecyclerView component and the button on that layout has the recycler_view id which you try to use to inflate your RecyclerView. That's why you're getting this exception.
Add a RecyclerView to your layout and set its id to recycler_view so that you can grab the RV in your code.
I am trying to get a TextView value item within the RecyclerView. My RecyclerView layout file has two TextViews, one is Product Name and the other for the Quantity as you can see here
=== This is my cart_items_layout_item ===
<TextView
android:id="#+id/cart_list_product_name"
android:layout_width="160dp"
android:layout_height="wrap_content"
android:text="Product Name"
android:textColor="#color/colorPrimary"
android:textSize="16sp"
android:layout_marginLeft="5dp"
android:textStyle="bold"/>
<TextView
android:id="#+id/cart_list_product_quantity"
android:layout_width="160dp"
android:layout_height="wrap_content"
android:text="Product Quantity"
android:textColor="#color/colorPrimary"
android:textSize="16sp"
android:layout_marginRight="5dp"
android:layout_alignParentRight="true"
android:gravity="end"
android:textStyle="bold"/>
This is my activity_cart xml
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</RelativeLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/cart_list"
android:layout_width="match_parent"
android:layout_height="542dp"
android:layout_above="#+id/next"
android:layout_below="#id/header_color"
android:layout_marginBottom="113dp">
</androidx.recyclerview.widget.RecyclerView>
<Button
android:id="#+id/next"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#drawable/button"
android:text="CONFIRM ORDER/S"
android:textColor="#color/colorPrimaryDark"
android:layout_margin="10dp" />
<Button
android:id="#+id/sendSMSButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="0dp"
android:layout_marginRight="0dp"
android:layout_marginBottom="69dp"
android:background="#drawable/button"
android:text="Send"
android:textColor="#color/colorPrimaryDark" />
<TextView
android:id="#+id/smsphoneNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/cart_list"
android:text="0918"/>
This is my RecyclerView Adapter Class
#Override
protected void onStart() {
super.onStart();
final DatabaseReference cartListRef =
FirebaseDatabase.getInstance().getReference().child("Cart List");
FirebaseRecyclerOptions<Cart> options =
new FirebaseRecyclerOptions.Builder<Cart>()
.setQuery(cartListRef.child("User View")
.child(Prevalent.CurrentOnlineUsers.getPhone())
.child("Products"), Cart.class)
.build();
FirebaseRecyclerAdapter<Cart, CartViewHolder> adapter =
new FirebaseRecyclerAdapter<Cart, CartViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull CartViewHolder
holder, int i, #NonNull final Cart model) {
holder.txtProductName.setText(model.getProductName());
holder.txtProductQuantity.setText("Quantity = " +
model.getQuantity());
holder.itemView.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View view)
{
CharSequence options[] = new CharSequence[]
{
"Edit",
"Removed"
};
AlertDialog.Builder builder = new
AlertDialog.Builder(CartActivity.this);
builder.setTitle("Cart Options");
builder.setItems(options, new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface
dialogInterface, int i)
{
if (i == 0)
{
Intent intent = new
Intent(CartActivity.this, ProductDetailsActivity.class);
intent.putExtra("pid",model.getPid());
startActivity(intent);
}
if(i == 1)
{
cartListRef.child("User View")
.child(Prevalent.CurrentOnlineUsers.getPhone())
.child("Products")
.child(model.getPid())
.removeValue()
.addOnCompleteListener(new
OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull
Task<Void> task)
{
if (task.isSuccessful())
{
Toast.makeText(CartActivity.this, "Item removed successfully",
Toast.LENGTH_SHORT).show();
// Intent intent = new
Intent(CartActivity.this, Home.class);
//
startActivity(intent);
}
}
});
}
if(i == 1)
{
cartListRef.child("Admin View")
.child(Prevalent.CurrentOnlineUsers.getPhone())
.child("Products")
.child(model.getPid())
.removeValue()
.addOnCompleteListener(new
OnCompleteListener<Void>() {
#Override
public void
onComplete(#NonNull Task<Void> task)
{
if (task.isSuccessful())
{
Toast.makeText(CartActivity.this, "Item removed successfully",
Toast.LENGTH_SHORT).show();
// Intent intent =
new Intent(CartActivity.this, Home.class);
//
startActivity(intent);
}
}
});
}
}
});
builder.show();
}
});
}
#NonNull
#Override
public CartViewHolder onCreateViewHolder(#NonNull ViewGroup
parent, int viewType) {
View view =
LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_items_layout,
parent, false);
CartViewHolder holder = new CartViewHolder(view);
return holder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
=== this is my Cart class/Model ===
public class Cart
{
private String
date,discount,pid,productDesc,productName,productSupplier,quantity,time;
public Cart()
{
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDiscount() {
return discount;
}
public void setDiscount(String discount) {
this.discount = discount;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getProductDesc() {
return productDesc;
}
public void setProductDesc(String productDesc) {
this.productDesc = productDesc;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductSupplier() {
return productSupplier;
}
public void setProductSupplier(String productSupplier) {
this.productSupplier = productSupplier;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public Cart(String date, String discount, String pid, String productDesc,
String productName, String productSupplier, String quantity, String time)
{
this.date = date;
this.discount = discount;
this.pid = pid;
this.productDesc = productDesc;
this.productName = productName;
this.productSupplier = productSupplier;
this.quantity = quantity;
this.time = time;
}
=== CartViewHolder ===
public class CartViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener
{
public TextView txtProductName, txtProductQuantity;
private ItemClickListener itemClickListener;
public CartViewHolder(#NonNull View itemView) {
super(itemView);
txtProductName = itemView.findViewById(R.id.cart_list_product_name);
txtProductQuantity =
itemView.findViewById(R.id.cart_list_product_quantity);
}
#Override
public void onClick(View view)
{
itemClickListener.onClick(view, getAdapterPosition(), false);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
}
As you can see in this Image, i use the cart class/model to pass the data to them, then i created another class called CartViewHolder i use this class to set the data into Recycler View. i want to get this values and put it in the message particularly in the SMS. i dont know how to pass it i tried several codes for it.
private void sendSmsBySIntent ()
{
//Want to set specific Phone Number here
Uri uri = Uri.parse("SET DEFAULT VALUE FOR THIS");
Intent smsSIntent = new Intent(Intent.ACTION_SENDTO, uri);
//Want to Intent the Items in Here the Product Name and the Quantity
smsSIntent.putExtra("PUT THE ITEMS HERE");
try{
startActivity(smsSIntent);
} catch (Exception ex) {
Toast.makeText(CartActivity.this, "Your sms has failed...",
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}
you can use your List<Cart> cart model list item to send product and quantity to
sms.
private void sendSmsBySIntent (Cart model)
{
//Want to set specific Phone Number here
Uri uri = Uri.parse("SET DEFAULT VALUE FOR THIS");
Intent smsSIntent = new Intent(Intent.ACTION_SENDTO, uri);
smsSIntent.putExtra("pName",model.getProductName());
smsSIntent.putExtra("pQty",model.getQuantity());
try{
startActivity(smsSIntent);
} catch (Exception ex) {
Toast.makeText(CartActivity.this, "Your sms has failed...",
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}
You need the list you sent to the adapter. Send it as a parameter to the sendSmsBySIntent() function and make a for loop where you build a String.
ie.:
private void sendSmsBySIntent (List<Cart> yourList){
StringBuilder extra = new StringBuilder();
for (int i = 0; i < yourList.size(); i++) {
//Build the string the way you want
extra.append(yourList.get(i).getName()).append(" ").append(yourList.get(i).getQuantity);
}
//Want to set specific Phone Number here
Uri uri = Uri.parse("SET DEFAULT VALUE FOR THIS");
Intent smsSIntent = new Intent(Intent.ACTION_SENDTO, uri);
//Want to Intent the Items in Here the Product Name and the Quantity
smsSIntent.putExtra(extra.toString());
try{
startActivity(smsSIntent);
} catch (Exception ex) {
Toast.makeText(CartActivity.this, "Your sms has failed...",
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}
Edit:
I changed the function inside () , check it.
Now, when you call the function you have to pass the list you are working with. Like so: sendSmsBySIntent(placeHereYourCartList)
I can't retrieve data from the firebase and view it at recyclerView
this my database at firebaseenter image description here
There are no problem appear but in my run is not display the items this is my run enter image description here
and this my code I tried every thing I don't know what the problem help me please
public class account_preview extends AppCompatActivity {
private ArrayList<outflow>outflows;
private RecyclerView recyclerView;
RecyclerAdapter adapter;
DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account_preview);
FirebaseDatabase database = FirebaseDatabase.getInstance();
myRef =
database.getReference("user_account/(username)/bank_accounts/1");
adapter = new RecyclerAdapter(outflows, account_preview.this);
recyclerView = (RecyclerView) findViewById(R.id.RecyclerView);
recyclerView.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
recyclerView.setLayoutManager(llm);
llm.setOrientation(LinearLayoutManager.VERTICAL);
onStart();
new GetDataFromFirebase().
executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
// Read from the database
recyclerView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
myRef.child("outflow").child("1").addValueEventListener(new
ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
outflows=new ArrayList<outflow>();
for (DataSnapshot dataSnapshot1:
dataSnapshot.getChildren()){
outflow values =
dataSnapshot1.getValue(outflow.class);
outflows.add(values);}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
System.out.println("Failed to read value." +
error.toException());
}
});
}
private class GetDataFromFirebase extends
AsyncTask<Void,Void,Boolean>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Void... voids) {
return false;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
}
}
public class RecyclerAdapter extends
RecyclerView.Adapter<RecyclerAdapter.ViewHolder>{
private Context context;
private ArrayList<outflow> values;
public RecyclerAdapter(ArrayList<outflow> values, account_preview
context) {
this.values = values;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
return new ViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_outflows, parent, false));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.name.setText( values.get(position).getCategory());
holder.c.setText((int) values.get(position).getAmount());
}
#Override
public int getItemCount() {
int arr = 0;
try{
if(values.size()==0){
arr = 0;
}
else{
arr=values.size();
}
}catch (Exception e){
}
return arr;
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView name,c;
ViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.totaloutflow);
c=(TextView)itemView.findViewById(R.id.total);
}
}
}
public class outflow {
private double amount;
private String date;
private String time;
private String attachment;
private String category;
private String location;
private String vendor;
private int rate;
public outflow(double amount, String date, String time, String attachment, String category, String location, String vendor) {
this.amount = amount;
this.date = date;
this.time = time;
this.attachment = attachment;
this.category = category;
this.location = location;
this.vendor = vendor;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getAttachment() {
return attachment;
}
public void setAttachment(String attachment) {
this.attachment = attachment;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getVendor() {
return vendor;
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
public int getRate() {
return rate;
}
public void setRate(int rate) {
this.rate = rate;
}
}
activity_account_preview.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/RecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</android.support.constraint.ConstraintLayout>
list_outflows.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".account_preview">
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#27233A"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/navigation" />
<TextView
android:id="#+id/textView"
android:layout_width="84dp"
android:layout_height="44dp"
android:layout_marginEnd="36dp"
android:layout_marginStart="8dp"
android:padding="5dp"
android:text="(التاريخ)"
android:textColor="#000000"
android:textSize="20dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="64dp"
tools:ignore="MissingConstraints" />
<Button
android:id="#+id/button"
android:layout_width="251dp"
android:layout_height="61dp"
android:layout_marginBottom="24dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:background="#9FB4C7"
android:text="حذف الحساب"
android:textColor="#ffffff"
android:textSize="30dp"
app:layout_constraintBottom_toTopOf="#+id/navigation"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.437"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/floatingActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:background="#D6C9C9"
android:clickable="true"
app:backgroundTint="#D6C9C9"
app:layout_constraintBottom_toTopOf="#+id/navigation"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.976"
app:layout_constraintStart_toStartOf="parent"
app:srcCompat="#android:drawable/ic_input_add" />
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_width="392dp"
android:layout_height="64dp"
android:layout_margin="2.5dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="184dp"
app:cardBackgroundColor="#color/lightgrey"
app:cardCornerRadius="4dp"
app:layout_constraintBottom_toTopOf="#+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView"
app:layout_constraintVertical_bias="1.0"
tools:ignore="MissingConstraints">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_weight="0.30"
android:orientation="vertical">
<TextView
android:id="#+id/totaloutflow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:text="الفواتير"
android:textColor="#color/colorPrimaryDark"
android:textSize="25sp" />
<TextView
android:id="#+id/total"
android:layout_width="388dp"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:layout_marginStart="4dp"
android:text="ريال سعودي"
android:textSize="15sp"
android:textStyle="bold" />
</LinearLayout>
</android.support.v7.widget.CardView>
</android.support.constraint.ConstraintLayout>
Firebase has its own Adapter for RecyclerView so better use that.
public FirebaseRecyclerAdapter<taskdata, ShowDataViewHolder> getmFirebaseAdapter() {
return mFirebaseAdapter;
}
public void setmFirebaseAdapter(FirebaseRecyclerAdapter<taskdata, ShowDataViewHolder> mFirebaseAdapter) {
this.mFirebaseAdapter = mFirebaseAdapter;
}
//View Holder For Recycler View
public static class ShowDataViewHolder extends RecyclerView.ViewHolder {
private final TextView image_title ;
public ShowDataViewHolder(final View itemView)
{
super(itemView);
image_title = itemView.findViewById(R.id.taskname);
}
private void Image_Title(String title)
{
image_title.setText(title);
}
}
#Override
public void onStart() {
super.onStart();
FirebaseAuth mauth = FirebaseAuth.getInstance();
String userod = mauth.getCurrentUser().getUid();
myref = FirebaseDatabase.getInstance().getReference("Yourself").child(userod).child("task");
setmFirebaseAdapter(new FirebaseRecyclerAdapter<taskdata, ShowDataViewHolder>(
taskdata.class, R.layout.taskitem, ShowDataViewHolder.class, myref.orderByValue()) {
public void populateViewHolder(final ShowDataViewHolder viewHolder, taskdata model, final int position) {
viewHolder.Image_Title(model.getTaskname());
}
});
recyclerView.setAdapter(getmFirebaseAdapter());
myref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.getValue() == null){
Toast.makeText(getContext(),"No Bookmarks added yet!",Toast.LENGTH_SHORT).show();
}else {
mFirebaseAdapter.notifyItemChanged(0);
mFirebaseAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mFirebaseAdapter.notifyItemInserted(taskdata2.size()-1);
}
If you need more help on the code please go to my github - https://github.com/afreakyelf/Yourself/blob/master/app/src/main/java/com/example/rajat/yourself/taskadapterhome.java
To solve this, please just add the following lines of code inside the costructor:
public RecyclerAdapter(List<outflow> list, account_preview context) {
this.list = list
this.context = context
}
I wants to create an app where online conversation will happen. I do it by using of Firebase. I connect the Firebase and can able to add data in database table in multiple device.
Problem is inserted data is only visible from the device who have inserted it in database table. Rest of the other device cannot view it automatically. It will visible while that device insert a new data in database table. I am sending my code in following. Please have look.
Activity_main
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.swatin.firebaselistviewsaveretriveshow.MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="openAddArea"
android:id="#+id/topbutton"
android:onClick="openBellowtopbutton"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/bellowtopbutton"
android:orientation="horizontal"
android:layout_below="#+id/topbutton"
android:visibility="visible"
>
<EditText
android:layout_width="0dp"
android:layout_weight="5"
android:layout_height="wrap_content"
android:id="#+id/nameEditText"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="add"
android:id="#+id/saveBtn"/>
</LinearLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/bellowtopbutton"
android:id="#+id/list"
/>
</RelativeLayout>
MainActivity
public class MainActivity extends AppCompatActivity {
ListView lv;
ArrayAdapter<String> adapter;
DatabaseReference db;
FirebaseHelper helper;
EditText nameEditTxt;
Button saveBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv= (ListView) findViewById(R.id.list);
db= FirebaseDatabase.getInstance().getReference();
helper=new FirebaseHelper(db,this);
nameEditTxt = (EditText) findViewById(R.id.nameEditText) ;
saveBtn = (Button) findViewById(R.id.saveBtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//GET DATA
String name=nameEditTxt.getText().toString();
//SET DATA
Spacecraft s=new Spacecraft();
s.setName(name);
//VALIDATE
if(name.length()>0 && name != null)
{
if(helper.save(s))
{
nameEditTxt.setText("");
adapter=new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,helper.retrieve());
lv.setAdapter(adapter);
}
}else
{
Toast.makeText(MainActivity.this, "Name cannot be empty", Toast.LENGTH_SHORT).show();
}
}
});
adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,helper.retrieve());
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, helper.retrieve().get(position), Toast.LENGTH_SHORT).show();
}
});
}
public void openBellowtopbutton(View view)
{
LinearLayout bellowtopbutton = (LinearLayout) findViewById(R.id.bellowtopbutton);
if(bellowtopbutton.getVisibility() == View.VISIBLE)
{
bellowtopbutton.setVisibility(View.GONE);
}
else
{
bellowtopbutton.setVisibility(View.VISIBLE);
}
}
}
Spacecraft
public class Spacecraft {
String name;
public Spacecraft() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
FirebaseHelper
public class FirebaseHelper {
DatabaseReference db;
Boolean saved=null;
ArrayList<String> spacecrafts=new ArrayList<>();
Context context;
public FirebaseHelper(DatabaseReference db,Context context) {
this.db = db;
this.context = context;
}
//WRITE
public Boolean save(Spacecraft spacecraft)
{
if(spacecraft==null)
{
saved=false;
}
else
{
try
{
db.child("Spacecraft").push().setValue(spacecraft);
saved=true;
}catch (DatabaseException e)
{
e.printStackTrace();
saved=false;
}
}
return saved;
}
//READ
public ArrayList<String> retrieve()
{
db.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
Toast.makeText(context, "callMe", Toast.LENGTH_SHORT).show();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return spacecrafts;
}
private void fetchData(DataSnapshot dataSnapshot)
{
spacecrafts.clear();
for (DataSnapshot ds : dataSnapshot.getChildren())
{ String name=ds.getValue(Spacecraft.class).getName();
spacecrafts.add(name);
}
}
}