Cannot resolve method ´getDownloadUrl' - firebase

I am new to Android Studio. I am having a problem with the code, and I don't know what it is since I am following a YouTube tutorial
of creating a user in Android plus Firebase. The problem is about the storage on Firebase.
My code:
public class Profile extends AppCompatActivity {
private static final int CHOOSE_IMAGE = 101;
EditText editText;
ImageView imageView;
String profileimageurl;
Uri uriProfileImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile2);
editText = (EditText) findViewById(R.id.nome);
imageView = (ImageView) findViewById(R.id.foto);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showImageChooser();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CHOOSE_IMAGE && data != null && data.getData() != null) {
uriProfileImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uriProfileImage);
imageView.setImageBitmap(bitmap);
uploadImageToFirebaseStorage();
} catch(IOException e) {
e.printStackTrace();
}
}
}
private void uploadImageToFirebaseStorage() {
StorageReference profileImageRef = FirebaseStorage.getInstance().getReference("profilepics/" + System.currentTimeMillis() + ".jpg");
if (uriProfileImage != null) {
profileImageRef.putFile(uriProfileImage)
.addOnSuccessListener(new OnSuccessListener < UploadTask.TaskSnapshot > () {#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
profileimageurl = taskSnapshot.getDownloadUrl().toString();
}
}).addOnFailureListener(new OnFailureListener() {#Override
public void onFailure(#NonNull Exception e) {
}
});
}
}
private void showImageChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Escohe a imagem de perfil"), CHOOSE_IMAGE);
}
}

That method has been deprecated.
Use the storageReference to get the download url.
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
profileImageRef.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(final Uri uri) {
String downloadUri = uri;
} })
You can now use the downloadUri String to load the image.

Related

Using FirestoreRecyclerAdapter but phone's screen looks separately

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.

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

Retrieving images from firebase storage

I have uploaded some photos to firebase storage, and I need to connect each of those images with a document in my Cloud Firestore and then show them in my recyclerView. Do i get the url of each image, and add a field "image" to each of the documents in the firestore and use the url as a value? And then how do I put them in my RecyclerView?
I have successfully retrieved other data from the Firestore, using FirestoreUI, however I'm not sure how to do the same for images.
RecyclerViewAdapter Class
public class FirebaseRecyclerViewAdapter extends
FirestoreRecyclerAdapter<Buildings,
FirebaseRecyclerViewAdapter.FirebaseRecyclerViewHolder> {
public FirebaseRecyclerViewAdapter(FirestoreRecyclerOptions<Buildings>
options) {
super(options);
}
#Override
protected void onBindViewHolder(FirebaseRecyclerViewHolder holder, int
position, Buildings model) {
holder.textViewName.setText(model.getName());
}
#NonNull
#Override
public FirebaseRecyclerViewHolder onCreateViewHolder(#NonNull ViewGroup
parent, int viewType) {
View v =
LayoutInflater.from(parent.getContext()).inflate
(R.layout.buildings_row_item, parent, false);
return new FirebaseRecyclerViewHolder(v);
}
class FirebaseRecyclerViewHolder extends RecyclerView.ViewHolder {
TextView textViewName;
public FirebaseRecyclerViewHolder(View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.building_name);
}
}
}
MainActivity Class
public class MainActivity extends AppCompatActivity {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference buildingRef = db.collection("Building");
StorageReference storageReference =
FirebaseStorage.getInstance().getReference();
private FirebaseRecyclerViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_2);
setUpRecyclerView();
getSupportActionBar().hide();
}
private void setUpRecyclerView() {
Query query = buildingRef.orderBy("name", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<Buildings> options = new
FirestoreRecyclerOptions.Builder<Buildings>()
.setQuery(query, Buildings.class)
.build();
adapter = new FirebaseRecyclerViewAdapter(options);
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
first of all, you need to upload the image you want to the Firestore Storage using
StorageReference
then you have to save the URL using
getDownloadUrl()
Next Step is to save the URL into field in the document and here an Example
upload the image
private void uploadFile() {
if (mImageUri != null) {
StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
mUploadTask = fileReference.putFile(mImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(context, "Upload successful", Toast.LENGTH_LONG).show();
fileReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
image=new Images(mID+"",Objects.requireNonNull( uri.toString()));
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(context, "Upload Failed", Toast.LENGTH_LONG).show();
}
});
}
}
)
.addOnFailureListener(e ->
Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show())
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(context, "Uploading...", Toast.LENGTH_LONG).show();
}
});
} else {
Toast.makeText(context, "No file selected", Toast.LENGTH_SHORT).show();
}
}
save the URL to Firestore document
if(!TextUtils.isEmpty(image.getmImageUrl()))
mProperty = new Property(mID, username,mCity ,mDesc,mPrice,noRooms,noBathrooms,address,date,area,parking,Objects.requireNonNull(image.getmImageUrl()));
else
mProperty = new Property(mID, username,mCity ,mDesc,mPrice,noRooms,noBathrooms,address,date,area,parking);
db.collection("Property").document(mProperty.getmID() + "").set(mProperty)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(context, "done",
Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(context, "Failed",
Toast.LENGTH_SHORT).show();
}
});
boolean flag;
} else {
mError.setText("Empty Fields");
mError.setVisibility(View.VISIBLE);
}
i am using a model to insert data into firestore you should do that too
and in RecyclerAdapter you can bind the image to the Recyclerview using either Picasso or Bitmap
Picasso.get().load(model.getmImageDrawable()).
fit().placeholder(R.drawable.placeholder_image).
error(R.drawable.no_img).into(holder.mImage)

Google Play Games Login with Firebase notworking

Hello here is my code for my App, and I try to login via Google Play Games, but it doesn't work. I hope you can tell me some solutions. I have Google Login working, on another activity but Play Games Login won't work.
public class start extends AppCompatActivity implements
View.OnClickListener{
private static final String TAG = "StartActivity";
GoogleApiClient mGoogleApiClient;
GoogleSignInClient mGoogleSignInClient;
SignInButton signInButton;
private AdView mAdview;
private InterstitialAd interstitialAd;
private FirebaseAnalytics mFirebaseAnalytics;
private ProgressDialog loadingBar;
private Status statusTextView;
TextView LoginUserName, LoginUserEmail;
private FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
private Button LogOutBtn;
private Button playgames;
private TextView mStatusTextView;
private TextView mDetailTextView;
private TextView mPlayername;
private boolean mResolvingConnectionFailure = false;
private boolean mAutoStartSignInflow = true;
private boolean mSignInClicked = false;
private final static int RC_SIGN_IN = 9001;
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
FirebaseUser currentUser = mAuth.getCurrentUser();
signInSilently();
mGoogleApiClient.connect();
updateUI(currentUser);
}
//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
signInButton = (SignInButton) findViewById(R.id.sign_in_button);
LogOutBtn = findViewById(R.id.logout);
mAuth = FirebaseAuth.getInstance();
mStatusTextView = findViewById(R.id.status);
mDetailTextView = findViewById(R.id.detail);
mPlayername = findViewById(R.id.mPlayername);
playgames = findViewById(R.id.playgames);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(start.this, SignIn.class));
}
});
LogOutBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(start.this, SignIn.class));
}
});
playgames.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startSignInIntent();
}
});
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
.requestServerAuthCode(XXXXXX)
.requestEmail()
.requestProfile()
.requestIdToken(XXXXXX)
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Toast.makeText(start.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
//End of Authentification
}
// Call this both in the silent sign-in task's OnCompleteListener and in the
// Activity's onActivityResult handler.
private void firebaseAuthWithPlayGames(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithPlayGames:" + acct.getId());
AuthCredential credential = PlayGamesAuthProvider.getCredential(acct.getServerAuthCode());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(start.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
// ...
}
});
}
private void signInSilently() {
GoogleSignInClient signInClient = GoogleSignIn.getClient(this,
GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
signInClient.silentSignIn().addOnCompleteListener(this,
new OnCompleteListener<GoogleSignInAccount>() {
#Override
public void onComplete(#NonNull Task<GoogleSignInAccount> task) {
if (task.isSuccessful()) {
// The signed in account is stored in the task's result.
GoogleSignInAccount signedInAccount = task.getResult();
firebaseAuthWithPlayGames(signedInAccount);
} else {
// Player will need to sign-in explicitly using via UI
Toast.makeText(start.this, "Cannot Connect", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onResume() {
super.onResume();
signInSilently();
}
private void startSignInIntent() {
GoogleSignInClient signInClient = GoogleSignIn.getClient(this,
GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
Intent intent = signInClient.getSignInIntent();
startActivityForResult(intent, RC_SIGN_IN);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// The signed in account is stored in the result.
GoogleSignInAccount signedInAccount = result.getSignInAccount();
firebaseAuthWithPlayGames(signedInAccount);
} else {
String message = result.getStatus().getStatusMessage();
if (message == null || message.isEmpty()) {
Toast.makeText(start.this, "Cannot Connect 1", Toast.LENGTH_SHORT).show();
}
new AlertDialog.Builder(this).setMessage(message)
.setNeutralButton(android.R.string.ok, null).show();
}
}
}
private void updateUI(FirebaseUser user) {
if (user != null) {
String playerName = user.getDisplayName();
mPlayername.setText(playerName);
// The user's Id, unique to the Firebase project.
// Do NOT use this value to authenticate with your backend server, if you
// have one; use FirebaseUser.getIdToken() instead.
findViewById(R.id.sign_in_button).setVisibility(View.GONE);
} else {
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
startActivity(new Intent(start.this, SignIn.class));
break;
case R.id.logout:
startActivity(new Intent(start.this, SignIn.class));
break;
case R.id.playgames:
startSignInIntent();
break;
// ...
}
}
}
I really hope someone has a working example, or can help me here, cause I'm stuck at this code for a month now.

ProgressDailog in asynctask from another Activity

I Have two Activity. The MainActivity is calling the another Activity which extends AsyncTask. In AsyncTask i had display ProgressDailog onPreExecute(), but ProgressDailog is not been display. The reason may be AyncTask execute for less time but the response but response takes time and therefore ProgressDialog should be displayed.
The Following code is provide.
Aysnc class
public class NewConnections extends AsyncTask<Void,Void,String>{
Context context;
String[] name,value;
String Geturl,para;
ProgressDialog progressDialog;
NewConnections(Context context,String[] name,String[] value,String Url){
this.context = context;
this.name = name;
this.value = value;
Geturl = Url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Please Wait");
progressDialog.show();
}
#Override
protected String doInBackground(Void... voids) {
try
{
para = DCBUtil.jsonCovertion(name,value);
URL url = new URL(Geturl);
String responseStr = XXX.callJsonHttp(url,para);
System.out.println("Response of Home Open FD :: "+responseStr);
return responseStr;
}catch(Exception e)
{
return "Error";
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
}
}
MainClass
public class FirstPage extends AppCompatActivity {
Button existUser,newUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first_page);
existUser = (Button)findViewById(R.id.existUser);
newUser = (Button)findViewById(R.id.newUser);
newUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String[] value = {"asdasd"};
String[] name = {"dprm"};
try {
NewConnections v= new NewConnections(FirstPage.this,name,value,"url is provided");
v.execute().get();
} catch (Exception e) {
e.printStackTrace();
}
}
});
try this :
public class NewConnections extends AsyncTask<Void,Void,String>{
Context context;
String[] name,value;
String Geturl,para;
public static ProgressDialog progressDialog;
NewConnections(Context context,String[] name,String[] value,String Url){
this.context = context;
this.name = name;
this.value = value;
Geturl = Url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setMessage("Please Wait");
progressDialog.show();
}
#Override
protected String doInBackground(Void... voids) {
try
{
para = DCBUtil.jsonCovertion(name,value);
URL url = new URL(Geturl);
String responseStr = XXX.callJsonHttp(url,para);
System.out.println("Response of Home Open FD :: "+responseStr);
return responseStr;
}catch(Exception e)
{
return "Error";
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(progressDialog!=null)
progressDialog.dismiss();
}
}
and when you exit from activity then write below code in onDestry() method of that Activity
#Override
protected void onDestroy() {
if(NewConnections.progressDialog!=null)
NewConnections.progressDialog.dismiss();
super.onDestroy();
}
Try this:: I hope this helps you.
Dialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgressBar();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try{
hideProgressBar();
}catch (Exception e){
e.printStackTrace();
}
}
public void showProgressBar() {
dialog = new Dialog(mContext, android.R.style.Theme_Translucent);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
dialog.setCancelable(false);
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewChild = inflater.inflate(R.layout.loader, null);
dialog.setContentView(viewChild);
Runtime.getRuntime().gc();
System.gc();
try {
dialog.show();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
/**
* Hide progress dialog
*/
public void hideProgressBar() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
loader.xml::
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:gravity="center">
<ProgressBar
android:id="#+id/loading_spinner"
android:layout_width="48dp"
android:layout_height="48dp"
android:indeterminateTintMode="src_atop"
android:indeterminateTint="#color/colorAccent"
android:layout_gravity="center" />
</RelativeLayout>

Resources