Using FirestoreRecyclerAdapter but phone's screen looks separately - firebase

I'm using FirestoreRecyclerAdapter and faced with the problem.
My challenge is that I can add documents and retrieve them the recyclerview but for some reason, thw phone's screen looks separately as attached phone's schreenshot.
how can I do?
Thank You.
This is Adapter;
public MyFriendsAdapter(#NonNull FirestoreRecyclerOptions<ProfileModelClass> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull MyFriendsViewholder holder, int position, #NonNull ProfileModelClass model)
{
holder.myNickname.setText(model.getNickname());
holder.myAge.setText(model.getAge());
holder.myGender.setText(model.getGender());
holder.myDistance.setText(model.getDistance());
holder.myUserDescription.setText(model.getUserDescription());
holder.myMarriage.setText(model.getMarriage());
holder.myAddress.setText(model.getAddress());
// String visit_user_id = getSnapshots().getSnapshot(position).getId();
// Intent chatIntent = new Intent(MainActivity.this, ChatActivity.class);
// chatIntent.putExtra("visit_user_id", visit_user_id);
// startActivity(chatIntent);
Glide.with(holder.myProfileImageView.getContext()).load(model.getProfileImage()).into(holder.myProfileImageView);
Glide.with(holder.myPictureOne.getContext()).load(model.getPictureOne()).into(holder.myPictureOne);
Glide.with(holder.myPictureTwo.getContext()).load(model.getPictureTwo()).into(holder.myPictureTwo);
}
#NonNull
#Override
public MyFriendsViewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.all_friends_list_layout,
parent, false);
return new MyFriendsViewholder(view);
}
class MyFriendsViewholder extends RecyclerView.ViewHolder
{
CircleImageView myProfileImageView;
TextView myNickname,myAge, myGender, myDistance, myUserDescription, myMarriage, myAddress,
myFriendsProfile, SendMessageButton;
ImageView myPictureOne, myPictureTwo;
public MyFriendsViewholder(#NonNull View itemView)
{
super(itemView);
myProfileImageView = itemView.findViewById(R.id.all_friends_profile_image_layout);
myNickname = itemView.findViewById(R.id.all_friends_nickname_layout);
myGender = itemView.findViewById(R.id.all_friends_gender_layout);
myAge = itemView.findViewById(R.id.all_friends_age_layout);
myDistance = itemView.findViewById(R.id.all_friends_distance_layout);
myUserDescription = itemView.findViewById(R.id.all_friends_description_layout);
myMarriage = itemView.findViewById(R.id.all_friends_marriage_layout);
myAddress = itemView.findViewById(R.id.all_friends_address_layout);
myPictureOne = itemView.findViewById(R.id.all_friends_post_image_first);
myPictureTwo = itemView.findViewById(R.id.all_friends_post_image_second);
myFriendsProfile = itemView.findViewById(R.id.all_friends_information_layout);
SendMessageButton = itemView.findViewById(R.id.all_friends_call_layout);
myFriendsProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
itemView.getContext().startActivity(new Intent(itemView.getContext(), ProfileActivity.class));
}
});
SendMessageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
itemView.getContext().startActivity(new Intent(itemView.getContext(), ChatActivity.class));
}
});
}
This is MainActivity;
private DatabaseReference UsersRef;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference firstUsersProfilesColRef = db.collection("usersProfiles");
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFirestoreList = findViewById(R.id.all_users_list);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UsersRef = FirebaseDatabase.getInstance().getReference().child("allUsers");
mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("홈");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ToolbarProfileBtn = (ImageButton) findViewById(R.id.toolbar_profile_button);
drawerLayout = (DrawerLayout) findViewById(R.id.drawable_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayout, R.string.open, R.string.close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
navigationView = (NavigationView) findViewById(R.id.navigation_view);
View navView = navigationView.inflateHeaderView(R.layout.navigation_header);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
UserMenuSelector(item);
return false;
}
});
ToolbarProfileBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
SendUserToSetupActivity();
}
});
DisplayAllUsersList();
}
private void DisplayAllUsersList()
{
Query salaryQuery = firstUsersProfilesColRef;
FirestoreRecyclerOptions<ProfileModelClass> options = new FirestoreRecyclerOptions.Builder<ProfileModelClass>()
.setQuery(salaryQuery, ProfileModelClass.class)
.build();
adapter = new MyFriendsAdapter(options);
mFirestoreList.setHasFixedSize(true);
mFirestoreList.setLayoutManager(new LinearLayoutManager(this));
mFirestoreList.setAdapter(adapter);
}
#Override
protected void onStart()
{
super.onStart();
adapter.startListening();
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null)
{
SendUserToLoginActivity();
}
else
{
CheckUserExistence();
}
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
This is phone's screenshot;
enter image description here

In your layout file all_friends_list_layout. I think you have used android:layout_height="match_parent"
so there you need to use
android:layout_height="wrap_content"
Or instead of wrap_content you can also use any value like 150dp or whatever you feel appropriate for your need.

Related

Retrieve data from Firebase in Recycler view using fragment take too much time

I am using two fragments in the main activity, In first fragment[FirstFragment] load data from firebase and show in Recycler view, In the second fragment[uploadUserCarInformation] take data from user and store at the firebase,
I am facing a problem when the application starts then first fragment load very quickly and data show but when replace the first fragment from the second fragment and when replacing back from the second fragment to the first fragment then take 4 to 5 minutes to load data from firebase in recyclerView.
Kindly tell me where I modify the code,
Main Activity
public class MainActivity extends AppCompatActivity {
FrameLayout simpleFrameLayout;
TabLayout tabLayout;
Fragment fragment1 = new FirstFragment();
Fragment fragment2 =new SecondFragment();
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the reference of FrameLayout and TabLayout
tabLayout=findViewById(R.id.simpleTabLayout);
simpleFrameLayout = (FrameLayout) findViewById(R.id.simpleFrameLayout);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment1);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
// perform setOnTabSelectedListener event on TabLayout
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
// get the current selected tab's position and replace the fragment accordingly
switch (tab.getPosition()) {
case 0:
tab.getIcon().setColorFilter(null);
fragmentReplace(fragment1,"fragment1");
break;
case 1:
fragmentReplace(fragment2,"fragment2");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
public void fragmentReplace(Fragment fragment,String fragmentName)
{
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment);
Log.d("Running Fragment",fragmentName+ " is running");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
}
FirstFragment
public class FirstFragment extends Fragment {
private RecyclerView mRecyclerView;
private ImageAdapter mAdapter;
private DatabaseReference mDatabaseRef;
private List<carInformation> mUpload;
View view;
public FirstFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//retrieveAndSendData();
Log.d("Lifecycle","onCreate called");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("Lifecycle","onCreateView called");
view=inflater.inflate(R.layout.fragment_first,container,false);
mRecyclerView=view.findViewById(R.id.recyler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.d("Lifecycle","onViewCreate called");
retrieveAndSendData();
}
public void retrieveAndSendData()
{
mUpload=new ArrayList<>();
mDatabaseRef= FirebaseDatabase.getInstance().getReference();
ValueEventListener valueEventListener=new ValueEventListener() {
#Override
//get firebase data using datasnapshot (read data)
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot : dataSnapshot.getChildren())
{
String key = postSnapshot.getKey();
DatabaseReference databaseReference=mDatabaseRef.child(key);
for (DataSnapshot child: postSnapshot.getChildren())
{
String userBookId = child.getKey();
if(userBookId.equals("city") )
{
break;
}
else
{
// Toast.makeText(getActivity(),userBookId,Toast.LENGTH_LONG).show();
databaseReference.child(userBookId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
carInformation userInformationObj=dataSnapshot.getValue(carInformation.class);
mUpload.add(userInformationObj);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
}
mAdapter = new ImageAdapter(getActivity(),mUpload);
mRecyclerView.setAdapter(mAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getActivity(),databaseError.getMessage(),Toast.LENGTH_SHORT).show();
}
};
mDatabaseRef.addValueEventListener(valueEventListener);
}
uploadUserCarInformation
public class uploadUserCarInformation extends Fragment {
View view;
FirebaseAuth firebaseAuth;
DatabaseReference databaseReference;
StorageReference storageReference;
private StorageTask mUploadTask;
ImageView imageView;
static int PICK_IMAGE=1;
Spinner spin;
// mdatabase.push().getkey() -> generate uniqe id
RadioGroup radioGroupCondition,radioGroupTransmission,radioGroupSupported;
RadioButton radioButtonCondition,radioButtonTranmission,radioButtonSupported;
String radioButtonConditionString,radioButtonSupportedString,radioButtonTransmissionString;
Button addCar,signout;
int selectedIdCondition,selectedIdTransmission,selectedIdSupported;
String ownerName,carName,phoneNuberString,countryString;
TextInputLayout name,carNamePlusModel,phoneNumber,country;
carInformation car_Information=new carInformation();
private ProgressBar progressBar;
private Uri imageUri;
String[] bankNames=new String[374];
InputStream in;
int i=0;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view=inflater.inflate(R.layout.upload_user_car_information,container,false);
firebaseAuth=FirebaseAuth.getInstance();
storageReference=FirebaseStorage.getInstance().getReference("uploads");
name=view.findViewById(R.id.textFieldCarOwner);
carNamePlusModel=view.findViewById(R.id.textFieldCarNameModel);
phoneNumber=view.findViewById(R.id.textFieldPhoneNumber2);
addCar=view.findViewById(R.id.addCar);
signout=view.findViewById(R.id.sign_out);
progressBar=view.findViewById(R.id.progress_bar);
// progressBar.getProgressDrawable().setColorFilter(
// Color.RED, android.graphics.PorterDuff.Mode.SRC_IN);
radioGroupCondition=view.findViewById(R.id.radioGroupCarCondtion);
radioGroupSupported=view.findViewById(R.id.radioGroupCarSupport);
radioGroupTransmission=view.findViewById(R.id.radioGroupCarTransmission);
// progressBar=new ProgressBar(getActivity());
spin = view.findViewById(R.id.Countryspinner2);
imageView=(ImageView) view.findViewById(R.id.selectImage);
//imageView.setImageResource(R.drawable.select_image);
try
{
InputStream fr = this.getResources().openRawResource(R.raw.cities);
BufferedReader br = new BufferedReader(new InputStreamReader(fr));
ArrayList<String> lines=new ArrayList<String>();
String currentLine=br.readLine();
while(currentLine!=null)
{
lines.add(currentLine);
currentLine=br.readLine();
}
Collections.sort(lines);
fr.close(); //closes the stream and release the resources
for(String line : lines)
{
bankNames[i]=line;
// System.out.println(line);
i++;
}
}
catch(IOException e)
{
e.printStackTrace();
}
ArrayAdapter<String> aa=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item,bankNames);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
AdapterView.OnItemSelectedListener listener = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
spin.setOnItemSelectedListener(listener);
spin.setAdapter(aa);
signout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseAuth.signOut();
Fragment fragment = new SecondFragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
});
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onFileChooser();
}
});
addCar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mUploadTask !=null && mUploadTask.isInProgress())
{
Toast.makeText(getActivity(),"Uploading Task",Toast.LENGTH_SHORT).show();
}
else
{
carImageAndDetailUploading();
}
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null)
{
imageUri = data.getData();
//A powerful image downloading and caching library and get image from library for Android
Picasso.with(getActivity()).load(imageUri).into(imageView);
}
}
private void carImageAndDetailUploading()
{
FirebaseUser user=firebaseAuth.getCurrentUser();
databaseReference= FirebaseDatabase.getInstance().getReference(user.getUid());
selectedIdCondition=radioGroupCondition.getCheckedRadioButtonId();
radioButtonCondition=view.findViewById(selectedIdCondition);
radioButtonConditionString=radioButtonCondition.getText().toString();
selectedIdSupported=radioGroupSupported.getCheckedRadioButtonId();
radioButtonSupported=view.findViewById(selectedIdSupported);
radioButtonSupportedString=radioButtonSupported.getText().toString();
selectedIdTransmission=radioGroupTransmission.getCheckedRadioButtonId();
radioButtonTranmission=view.findViewById(selectedIdTransmission);
radioButtonTransmissionString=radioButtonTranmission.getText().toString();
ownerName=name.getEditText().getText().toString().trim();
carName=carNamePlusModel.getEditText().getText().toString().trim();
phoneNuberString=phoneNumber.getEditText().getText().toString().trim();
countryString=spin.getSelectedItem().toString();
if(TextUtils.isEmpty(ownerName) || TextUtils.isEmpty(carName) || TextUtils.isEmpty(phoneNuberString) || TextUtils.isEmpty(countryString))
{
Toast.makeText(getActivity(),"Please fill the empty fields ",Toast.LENGTH_LONG).show();
return; //return stooping the function to execute further
}
else if(imageUri == null)
{
Toast.makeText(getActivity(),"No file Selected ",Toast.LENGTH_LONG).show();
return;
}
long phone=Long.parseLong(phoneNuberString);
car_Information.setCarName(carName);
car_Information.setOwnerName(ownerName);
car_Information.setUserPhoneNumber(phone);
car_Information.setCountry(countryString);
car_Information.setCarCondtion(radioButtonConditionString);
car_Information.setCarSupported(radioButtonSupportedString);
car_Information.setCarTransmission(radioButtonTransmissionString);
StorageReference fileReference=storageReference.child(System.currentTimeMillis()+ "." + getFileExtension(imageUri));
mUploadTask = fileReference.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//below code user can see 100 % progress bar for 5 sec
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setProgress(0);
}
},5000);
String uniqueKey=databaseReference.push().getKey();
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
car_Information.setImageUrl(downloadUrl.toString());
car_Information.setUnique_key(uniqueKey);
// databaseReference.child("car details"+car_Information.getUnique_key());
// databaseReference.child("car details"+car_Information.getUnique_key()).setValue(car_Information);
databaseReference.child(car_Information.getUnique_key());
databaseReference.child(car_Information.getUnique_key()).setValue(car_Information);
Toast.makeText(getActivity(),"Successfully Upload",Toast.LENGTH_SHORT).show();
clear_editText();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress=(100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
progressBar.setProgress((int) progress);
}
});
}
private void onFileChooser()
{
Intent intent =new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent,PICK_IMAGE);
//startActivityForResult(Intent.createChooser(intent,"Select Picture"),PICK_IMAGE);
}
private String getFileExtension(Uri uri)
{
//this method for get file extension
ContentResolver cR=getActivity().getContentResolver();
MimeTypeMap mime=MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void clear_editText()
{
name.getEditText().setText(" ");
carNamePlusModel.getEditText().setText(" ");
phoneNumber.getEditText().setText(" ");
}
}
enter image description here
enter image description here

Search in Fragments that hold Recyclerview

I have 3 Fragments and they all are holding a recyclerView. But I don't know how I should call adapter.getFilter().filter(newText); in onQueryTextChange. Any ideas?
MainActivity:
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDB;
private BottomNavigationView bottomNavigationView;
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
myDB = new DatabaseHelper(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//----Start Bottom Navigation Bar
bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(bottomNavMethod);
getSupportFragmentManager().beginTransaction().replace(R.id.container, new PasswortFragment()).commit();
String id = getResources().getResourceEntryName(bottomNavigationView.getId());
//----End Bottom Navigation Bar
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return true;
}
private BottomNavigationView.OnNavigationItemSelectedListener bottomNavMethod =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
switch(item.getItemId()){
case R.id.passwoerter:
fragment = new PasswortFragment();
break;
case R.id.bankdaten:
fragment = new BankdatenFragment();
break;
case R.id.kreditkarten:
fragment = new KreditkartenFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
return true;
}
};
#Override
public void onBackPressed() {
super.onBackPressed();
Fragment f = MainActivity.this.getSupportFragmentManager().findFragmentById(R.id.container);
if(f instanceof PasswortFragment)
recyclerView = findViewById(R.id.recyclerViewPasswoerter);
if(f instanceof KreditkartenFragment)
recyclerView = findViewById(R.id.recyclerViewKreditkarten);
if(f instanceof BankdatenFragment)
recyclerView = findViewById(R.id.recyclerViewBankdaten);
}
#Override
public boolean onCreateOptionsMenu(#NonNull Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
recyclerView.getAdapter().getFilter().filter(newText); //<--This is not working
return false;
}
});
return true;
}
Adapter:
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> implements Filterable{
String type;
List<String> dataAll, data1;
Context context;
public Adapter(Context ct, List<String> s1, String typ){
context = ct;
data1 = s1;
type = typ;
dataAll = new ArrayList<>(data1);
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.reihen, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
holder.mytext1.setText(data1.get(position));
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(type.equals("Passwoerter")){
Intent intent = new Intent(context, DetailsP.class);
intent.putExtra("data1", data1.get(position));
context.startActivity(intent);
} else if(type.equals("Kreditkarten")){
Intent intent = new Intent(context, DetailsK.class);
intent.putExtra("data1", data1.get(position));
context.startActivity(intent);
} else if(type.equals("Bankdaten")){
Intent intent = new Intent(context, DetailsB.class);
intent.putExtra("data1", data1.get(position));
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return data1.size();
}
#Override
public Filter getFilter() {
return filter;
}
private Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<String> filteredList = new ArrayList<>();
if(constraint == null || constraint.length() == 0){
filteredList.addAll(dataAll);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for(String item: dataAll){
if(item.toLowerCase().contains(filterPattern)){
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
data1.clear();
data1.addAll( (List) results.values);
notifyDataSetChanged();
}
};
;
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView mytext1;
ConstraintLayout mainLayout;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
mytext1 = itemView.findViewById(R.id.title);
mainLayout = itemView.findViewById(R.id.mainLayout);
}
}
PasswortFragment (the other two fragments are pretty much the same):
public class PasswortFragment extends Fragment {
public PasswortFragment() {
// Required empty public constructor
}
RecyclerView recyclerView;
String tabelle = "Passwort";
List<String> titel;
DatabaseHelper myDB;
Adapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_passwort, container, false);
myDB = new DatabaseHelper(getActivity());
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerViewPasswoerter);
titel = Arrays.asList(myDB.getItems(tabelle));
final LinearLayoutManager layoutManager = new LinearLayoutManager((getActivity()));
layoutManager.setOrientation((LinearLayoutManager.VERTICAL));
recyclerView.setLayoutManager(layoutManager);
adapter = new Adapter(getActivity(), titel, "Passwoerter");
recyclerView.setAdapter(adapter);
setHasOptionsMenu(true);
return view;
}

Stay login with using PhoneNumber [duplicate]

This question already has answers here:
One time login in app - FirebaseAuth
(3 answers)
Closed 4 years ago.
After I sign in with PhoneNumber Auth it's will take me into Profile activity, I want that stay log in into the application if I go out and close it from used apps and come back again to the application that I won't be still log in.
the following the Java Code of PhoneNumber Auth and the Profile
VerifyPhoneActivity.Java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verify_phone);
mAuth = FirebaseAuth.getInstance();
editText = findViewById(R.id.editTextCode);
String phonenumber = getIntent().getStringExtra("phoneNumber");
sendVerificationCode(phonenumber);
findViewById(R.id.buttonSignIn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String code = editText.getText().toString().trim();
if (code.isEmpty() || code.length()<6){
editText.setError("enter Code...");
editText.requestFocus();
return;
}
verifyCode(code);
}
});
}
private void verifyCode(String code){
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
signInWithCredential(credential);
}
private void signInWithCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Intent intent = new Intent(VerifyPhoneActivity.this, List.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}else{
Toast.makeText(VerifyPhoneActivity.this, task.getException().getMessage(),Toast.LENGTH_LONG).show();
}
}
});
}
private void sendVerificationCode(String phonenumber){
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phonenumber,
10,
TimeUnit.SECONDS,
this,
mCallbacks
);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationId = s;
}
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
if (code != null){
editText.setText(code);
verifyCode(code);
}
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(VerifyPhoneActivity.this,e.getMessage(), Toast.LENGTH_LONG).show();
}
};
Child_Profile.Java
public class Child_Profile extends AppCompatActivity {
private TextView name;
private TextView gender;
private TextView birth;
private TextView bload;
private TextView Text_Dates;
private TextView Text_Time;
private Button Button_record;
private TextView Text_record;
private TextView Text_hospial;
private TextView Text_Plan;
private TextView Text_Satus;
private TextView Text_Price;
private ImageView ImageView_choose_image;
private Button button_choose_image;
private Uri mUri;
private static final int GALLERY_INTENT = 1;
private StorageReference mStorage;
private DatabaseReference mData;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_sign_out)
signOut();
return true;
}
private void signOut() {
AuthUI.getInstance().signOut(this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
startActivity(new Intent(Child_Profile.this, User.class));
finish();
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_child__profile);
name = findViewById(R.id.text_view_Namee);
gender = findViewById(R.id.text_view_Gender);
birth = findViewById(R.id.text_view_Birth);
bload = findViewById(R.id.text_view_Blood);
Text_Dates = findViewById(R.id.Text_Dates);
Text_Time = findViewById(R.id.Text_Time);
Text_record = findViewById(R.id.Text_record);
Text_hospial = findViewById(R.id.Text_hospial);
Text_Plan = findViewById(R.id.Text_Plan);
Text_Satus = findViewById(R.id.Text_Satus);
Button_record = findViewById(R.id.Button_record);
Text_Price = findViewById(R.id.Text_Price);
button_choose_image = findViewById(R.id.button_choose_image);
ImageView_choose_image = findViewById(R.id.ImageView_choose_image);
mStorage = FirebaseStorage.getInstance().getReference("Photo");
mData = FirebaseDatabase.getInstance().getReference("Photo");
button_choose_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openFileChooser();
}
});
Intent in = getIntent();
final Bundle b = in.getExtras();
if (b != null) {
String n = (String) b.get("id");
db.collection("Child Profile").document(n).get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
String pName = documentSnapshot.getString("name");
String pgender = documentSnapshot.getString("gender");
String pbirth = documentSnapshot.getString("birth");
String pbload = documentSnapshot.getString("bload");
String pDates = documentSnapshot.getString("dates");
String pTime = documentSnapshot.getString("time");
String pHospital = documentSnapshot.getString("hospital");
String pPlan = documentSnapshot.getString("typeOfPlan");
String pSatus = documentSnapshot.getString("satus");
String pPrice = documentSnapshot.getString("price");
name.setText(pName);
gender.setText(pgender);
birth.setText(pbirth);
bload.setText(pbload);
Text_Dates.setText(pDates);
Text_Time.setText(pTime);
Text_hospial.setText(pHospital);
Text_Plan.setText(pPlan);
Text_Satus.setText(pSatus);
Text_Price.setText(pPrice);
}
});
}
}
List.Java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_List);
mAuth = FirebaseAuth.getInstance();
setUpRecyclerView();
FloatingActionButton aaa = findViewById(R.id.button_add_profile);
aaa.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), NewChild.class);
startActivity(i);
}
});
}
private void setUpRecyclerView() {
Query query = profileRef.whereEqualTo("user_id", FirebaseAuth.getInstance().getCurrentUser().getUid());
FirestoreRecyclerOptions<addp> options = new FirestoreRecyclerOptions.Builder<addp>()
.setQuery(query, addp.class)
.build();
adapter = new padapter(options);
RecyclerView recyclerView = findViewById(R.id.recycler_View);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(new padapter.OnItemClickListener()
{
#Override
public void onItemClick (DocumentSnapshot documentSnapshot,int position){
String id = documentSnapshot.getId();
Toast.makeText(Profile.this, "Position: " + position + "ID" + id, Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), Child_Profile.class);
i.putExtra("id", id);
startActivity(i);
}
});
ProfileActivity set as launcher activity and
add line of code at onCreate of ProfileAtivity
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user==null){
Intent intent=new Intent(ProfileActivity,this,LoginActivity.class);
startActivity(intent);
finish()
}
else{
//stay here
}`

I can not list the foods I have added to the cart

I can add foods,orderi adress and phone number information and see all of them under Firebase's Request/ID. However when I click on the Navigation drawer and the orders and cart buttons in the main menu, I can not list the foods I have added to the cart. There seems to be a problem in the query section. Please help me what to do
OrderStatus.java
public class OrderStatus extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
DatabaseReference requests;
FirebaseRecyclerAdapter<Request, OrderViewHolder> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_status);
//firebase
database = FirebaseDatabase.getInstance();
requests = database.getReference("Request");
recyclerView = findViewById(R.id.listOrders);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
loadOrders(user.getEmail().toString());
}
private void loadOrders(String email) {
Query query = FirebaseDatabase.getInstance()
.getReference("Request")
.orderByChild("email")
.startAt(email.toString()).equalTo(true,email)
.limitToLast(50);
FirebaseRecyclerOptions<Request> options = new FirebaseRecyclerOptions.Builder<Request>().setQuery(query, Request.class).build();
adapter = new FirebaseRecyclerAdapter<Request, OrderViewHolder>(options) {
#NonNull
#Override
public OrderViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.order_layout, parent, false);
return new OrderViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull OrderViewHolder viewHolder, int position, #NonNull Request model) {
viewHolder.txtOrderID.setText(adapter.getRef(position).getKey());
viewHolder.txtOrderStatus.setText(convertCarttoStatus(model.getStatus()));
viewHolder.txtOrderAddress.setText(model.getAddress());
viewHolder.txtOrderPhone.setText(model.getPhone());
}
};
recyclerView.setAdapter(adapter);
}
private String convertCarttoStatus(String status) {
if (status == "0")
return "PLaced";
else if (status == "1")
return "On My Way";
else
return "Shipped";
}
this worked. If you need you can use
public class OrderStatus extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
DatabaseReference requests;
FirebaseRecyclerAdapter<Request, OrderViewHolder> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_status);
//firebase
database = FirebaseDatabase.getInstance();
requests = database.getReference("Request");
recyclerView = findViewById(R.id.listOrders);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
phoneNumber = getIntent().getStringExtra("phoneNumber");
loadOrders(phoneNumber);
}
private void loadOrders(String email) {
Query query = FirebaseDatabase.getInstance()
.getReference("Request")
.limitToLast(50);
FirebaseRecyclerOptions<Request> options = new FirebaseRecyclerOptions.Builder<Request>().setQuery(query, Request.class).build();
adapter = new FirebaseRecyclerAdapter<Request, OrderViewHolder>(options) {
#NonNull
#Override
public OrderViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.order_layout, parent, false);
return new OrderViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull OrderViewHolder viewHolder, int position, #NonNull Request model) {
viewHolder.txtOrderID.setText(adapter.getRef(position).getKey());
viewHolder.txtOrderStatus.setText(convertCarttoStatus(model.getStatus()));
viewHolder.txtOrderAddress.setText(model.getAddress());
viewHolder.txtOrderPhone.setText(model.getPhone());
}
};
recyclerView.setAdapter(adapter);
}
protected void onStart() {
super.onStart();
adapter.startListening();
}
protected void onStop() {
super.onStop();
adapter.stopListening();
}
private String convertCarttoStatus(String status) {
if (status == "0")
return "PLaced";
else if (status == "1")
return "On My Way";
else
return "Shipped";
}

how to make 2 recyclerView beside each others using firebase UI?

hi I am using Firebase recyclerview UI and I succeed to perform one RecyclerView, but when I continue to add the second, the application creates error.
The question is how to add 2 recyclers in the same activity with very simple form? I just want them beside each others.
How can I do that?
this is my code
public class HarvestingActivity extends AppCompatActivity {
RecyclerView T;
RecyclerView S;
DatabaseReference mRefTot;
DatabaseReference mRefSin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.activity_harvesting);
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
assert currentUser != null;
T = (RecyclerView) findViewById(R.id.recyclerviewT);//this is for total
T.setLayoutManager(new LinearLayoutManager(this));
T.setHasFixedSize(true);
S = (RecyclerView) findViewById(R.id.recyclerviewS);//this is for single
S.setLayoutManager(new LinearLayoutManager(this));
S.setHasFixedSize(true);
mRefTot = FirebaseDatabase.getInstance().getReference()
.child("HarvestingActivity")
.child("TotalActivity");
FirebaseRecyclerAdapter<TotalUsers, TotalUsersHolder> T_Adapter = new FirebaseRecyclerAdapter<TotalUsers, TotalUsersHolder>(
TotalUsers.class,
R.layout.h_item_user_total,
TotalUsersHolder.class,
mRefTot
) {
#Override
protected void populateViewHolder(TotalUsersHolder viewHolder, TotalUsers model, int position) {
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
assert currentUser != null;
viewHolder.setName(model.getName());
}
};
mRefSin=FirebaseDatabase.getInstance().getReference()
.child("HarvestingActivity")
.child("SingleActivity");
FirebaseRecyclerAdapter<SingleUser,SingleUserHolder>
S_Adapter=new
FirebaseRecyclerAdapter<SingleUser,SingleUserHolder>(
SingleUser.class,
R.layout.h_item_users_single,
SingleUserHolder.class,
mRefSin
) {
#Override
protected void populateViewHolder(SingleUserHolder viewHolder,
SingleUser model, int position) {
FirebaseUser currentUser =
FirebaseAuth.getInstance().getCurrentUser();
assert currentUser != null;
viewHolder.setName(model.getName());
}
};
T.setAdapter(T_Adapter);
S.setAdapter(S_Adapter);
}
public static class TotalUsersHolder extends RecyclerView.ViewHolder {
View view;
public TotalUsersHolder(View itemView) {
super(itemView);
view = itemView;
}
public void setName(String name) {
TextView Harvester_Name = (TextView) view.findViewById(R.id.HarvesterName);
Harvester_Name.setText(name);
}
}
private class SingleUserHolder extends RecyclerView.ViewHolder {
View sview;
public SingleUserHolder(View itemView) {
super(itemView);
sview=itemView;
}
public void setName(String name) {
TextView Answer_Name = (TextView)
sview.findViewById(R.id.AnswerName);
Answer_Name.setText(name);
}
}
}

Resources