I'm still a beginner in programming. I'm developing an application for a college job. However, I came across this mistake. I do not know how I can fix it. This problem:
error: cannot find symbol method getDownloadUrl()
How can I solve this error?
Here is my code:
package com.valcirjr98.logindj;
$public class ProfileActivity extends AppCompatActivity {
private static final int CHOOSE_IMAGE = 101;
TextView textView;
ImageView imageView;
EditText editText;
Uri uriProfileImage;
ProgressBar progressBar;
String profileImageUrl;
FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
mAuth = FirebaseAuth.getInstance();
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
editText = (EditText) findViewById(R.id.editTextDisplayName);
imageView = (ImageView) findViewById(R.id.imageView);
progressBar = (ProgressBar) findViewById(R.id.progressbar);
textView = (TextView) findViewById(R.id.textViewVerified);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showImageChooser();
}
});
loadUserInformation();
findViewById(R.id.buttonSave).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveUserInformation();
}
});
}
#Override
protected void onStart() {
super.onStart();
if (mAuth.getCurrentUser() == null) {
finish();
startActivity(new Intent(this, MainActivity.class));
}
}
private void loadUserInformation() {
final FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
if (user.getPhotoUrl() != null) {
Glide.with(this)
.load(user.getPhotoUrl().toString())
.into(imageView);
}
if (user.getDisplayName() != null) {
editText.setText(user.getDisplayName());
}
if (user.isEmailVerified()) {
textView.setText("Email Verified");
} else {
textView.setText("Email Not Verified (Click to Verify)");
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(ProfileActivity.this, "Verification Email Sent", Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
}
private void saveUserInformation() {
String displayName = editText.getText().toString();
if (displayName.isEmpty()) {
editText.setError("Name required");
editText.requestFocus();
return;
}
FirebaseUser user = mAuth.getCurrentUser();
if (user != null && profileImageUrl != null) {
UserProfileChangeRequest profile = new UserProfileChangeRequest.Builder()
.setDisplayName(displayName)
.setPhotoUri(Uri.parse(profileImageUrl))
.build();
user.updateProfile(profile)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(ProfileActivity.this, "Profile Updated", Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CHOOSE_IMAGE && resultCode == RESULT_OK && 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) {
progressBar.setVisibility(View.VISIBLE);
profileImageRef.putFile(uriProfileImage)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressBar.setVisibility(View.GONE);
profileImageUrl = taskSnapshot.getDownloadUrl().toString();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressBar.setVisibility(View.GONE);
Toast.makeText(ProfileActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuLogout:
FirebaseAuth.getInstance().signOut();
finish();
startActivity(new Intent(this, MainActivity.class));
break;
}
return true;
}
private void showImageChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Profile Image"), CHOOSE_IMAGE);
}
}
profileImageRef.putFile(uriProfileImage).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
profileImageUrl= taskSnapshot.getDownloadUrl().toString();
}
});
*
This method worked for me.
profileImageRef.putFile(uriProfileImage).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful() && task != null) {
profileImageUrl = task.getResult().getDownloadUrl().toString();
}
}
});
Try this!
Related
I stored texts and images in firebase Storage, here's how my images path looks like in storage (1655329886202.jpg),
and here's ow they look in realtime database (https://firebasestorage.googleapis.com/v0/b/link-plus-8e35e.appspot.com/etc...)
I retrieved the texts but can't retrieve the images to the recycler view, I'm new to programming.
here is the code.
adapter :
public class ImageViewHolder extends RecyclerView.ViewHolder {
public TextView textViewName;
public ImageView imageView;
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.name);
imageView = itemView.findViewById(R.id.image_View_car);
}
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.dynamic_rv_item_layout, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ImageViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getName());
Glide.with(mContext)
.load(uploadCurrent.getImageUrl())
.into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
}
Main activity code
ActivityResultLauncher<String> mGetContent = registerForActivityResult(
new ActivityResultContracts.GetContent(), new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri result) {
if (result != null) {
mImageView.setImageURI(result);
mImageUri = result;
}
}
}
);
mButtonChooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mGetContent.launch("image/*");
}
});
mButtonUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mUploadTask != null && mUploadTask.isInProgress()) {
Toast.makeText(FireBaseImage.this, "Upload in progress", Toast.LENGTH_LONG).show();
} else {
uploadFile();
}
}
});
mTextViewShowUploads.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
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) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress(0);
}
}, 500);
Toast.makeText(FireBaseImage.this, "Upload Successful", Toast.LENGTH_LONG).show();
Upload upload = new Upload(mEditTextFileName.getText().toString().trim(),
taskSnapshot.getUploadSessionUri().toString());
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(upload);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(FireBaseImage.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot Snapshot) {
double progress = (100.0 * Snapshot.getBytesTransferred() / Snapshot.getTotalByteCount());
mProgressBar.setProgress((int) progress);
}
});
} else {
Toast.makeText(this, "No File Selected", Toast.LENGTH_SHORT).show();
}
}
}
I cannot log in to my application, and I found no error in the codes. It keeps showing, email is required every time I tried to log in. I connect this app with FireStore as well. So, I need help what did I did wrong here because it supposed to go to the main activity after my login page:
public class Login extends AppCompatActivity {
EditText mPassword,mEmail;
FirebaseAuth auth;
Button mlogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_user);
final TextView register = findViewById(R.id.register_txt);
mPassword = findViewById(R.id.password_et);
mEmail = findViewById(R.id.email_et);
mlogin = findViewById(R.id.login_bt);
auth = FirebaseAuth.getInstance();
String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
mlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(email)) {
mEmail.setError("Email is required.");
return;
}
if (TextUtils.isEmpty(password)) {
mPassword.setError("Password is required");
return;
}
if(password.length() < 6) {
mPassword.setError("6 or more character long");
return;
}
auth.signInWithEmailAndPassword(email,password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
Toast.makeText(Login.this,"Login",Toast.LENGTH_SHORT)
.show();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
} else {
Toast.makeText(Login.this, "Error" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),Register.class));
}
});
}
}
This is my register, firebase auth, and firestore connected to get information on the users.
public class Register extends AppCompatActivity {
public static final String TAG = "TAG";
EditText mfullname, mPassword, mphoneNo, mEmail;
TextView register;
FirebaseAuth auth;
FirebaseFirestore fstore;
String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_user);
final TextView login = findViewById(R.id.login_text);
register = findViewById(R.id.register_bt);
mEmail = findViewById(R.id.email_et);
mPassword = findViewById(R.id.password_et);
mfullname = findViewById(R.id.fullname_et);
mphoneNo = findViewById(R.id.phoneNum_et);
auth = FirebaseAuth.getInstance();
fstore = FirebaseFirestore.getInstance();
if(auth.getCurrentUser() != null)
{
startActivity(new Intent(getApplicationContext(),MainActivity.class));
finish();
}
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
String fullName = mfullname.getText().toString();
String phoneNo = mphoneNo.getText().toString();
if (TextUtils.isEmpty(email)) {
mEmail.setError("Email is required.");
return;
}
if (TextUtils.isEmpty(password)) {
mPassword.setError("Password is required");
return;
}
if(password.length() <6){
mPassword.setError("6 or more character long");
return;
}
auth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(Register.this,"User Created",Toast.LENGTH_SHORT).show();
userID = auth.getCurrentUser().getUid();
DocumentReference documentReference = fstore.collection("Users").document(userID);
Map<String,Object> user = new HashMap<>();
user.put("fName",fullName);
user.put("email",email);
user.put("phone",phoneNo);
documentReference.set(user).addOnSuccessListener(aVoid -> {
Log.d(TAG, "onSuccess: user profile is created for" + userID);}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: " + e.toString());
}
});
startActivity(new Intent(getApplicationContext(),Login.class));
} else {
Toast.makeText(Register.this, "Error" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),Login.class));
}
});
}
}
MainActivity class:
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList<HomeModel> homeModel;
MainAdapter mainAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navView = findViewById(R.id.nav_view);
navView.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).addToBackStack(null).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.navigation_home:
selectedFragment = new HomeFragment();
break;
case R.id.navigation_dashboard:
selectedFragment = new DashboardFragment();
break;
case R.id.navigation_notifications:
selectedFragment = new NotificationsFragment();
break;
case R.id.navigation_profile:
selectedFragment = new ProfileFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).addToBackStack(null).commit();
return true;
}
};
}
RETRIEVADATA CLASS
package com.dikolobe.salesagent;
public class RetrieveData extends AppCompatActivity implements View.OnClickListener,OnNoteClickListener{
private static final String TAG = "";
private FirebaseRecyclerAdapter<Product, ViewHolder> firebaseRecyclerAdapter;
//FirebaseRecyclerAdapter adapter;
FirebaseDatabase mDatabase;
DatabaseReference mRef;
FirebaseStorage mStorage;
ItemsAdapter itemsAdapter;
List<Product> productList=new ArrayList<>();
RecyclerView recyclerView;
TextView phone_num;
ViewHolder viewHolder;
private static final int PERMISSION_REQUEST_CODE = 1;
ImageView img;
OnNoteClickListener onNoteClickListener;
Context context;
private List<Product> listItems= new ArrayList<>();
private List<Product> listItemsFull;
public ArrayList<Product> filterList = new ArrayList<>();
private int progressStatus = 0;
private Handler handler = new Handler();
String imageUrl = null;
SearchView searchView;
//ImageView delete;
String productId;
String image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retrieve_data);
// delete =findViewById(R.id.delete);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.SEND_SMS)
== PackageManager.PERMISSION_DENIED) {
Log.d("permission", "permission denied to SEND_SMS - requesting it");
String[] permissions = {Manifest.permission.SEND_SMS};
requestPermissions(permissions, PERMISSION_REQUEST_CODE);
}
}
searchView=findViewById(R.id.search);
FirebaseRecyclerOptions<Product> options = new FirebaseRecyclerOptions.Builder<Product>()
.setQuery(FirebaseDatabase.getInstance().getReference()
.child("Items"),Product.class)
.build();
mDatabase = FirebaseDatabase.getInstance();
mRef = mDatabase.getReference().child("Items");
mStorage = FirebaseStorage.getInstance();
recyclerView = findViewById(R.id.recyclerview_id);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
productList = new ArrayList<Product>();
itemsAdapter = new ItemsAdapter(RetrieveData.this, productList,this,options);
recyclerView.setAdapter(itemsAdapter);
mRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Product product = dataSnapshot.getValue(Product.class);
productList.add(product);
itemsAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
protected void onStart(){
super.onStart();
FirebaseRecyclerOptions<Product> options = new FirebaseRecyclerOptions.Builder<Product>()
.setQuery(FirebaseDatabase.getInstance()
.getReference().child("Items"), Product.class)
.build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Product, ViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull com.dikolobe.salesagent.ViewHolder holder, final int
position, #NonNull Product product) {
}
#NonNull
#Override
public com.dikolobe.salesagent.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int
viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.design_row_for_recyclerview, parent, false);
return new com.dikolobe.salesagent.ViewHolder(view,onNoteClickListener);
}
public void deleteProduct(int position) {
try{
FirebaseDatabase.getInstance().getReference().child("Items")
.child(getRef(position).getKey())
.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(context,"Deleted succesfully",Toast.LENGTH_SHORT).show();
}
});
}
catch (Exception e){
Log.e("error", e.getMessage());
}
}
};
firebaseRecyclerAdapter.startListening();
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
#Override
protected void onStop() {
super.onStop();
firebaseRecyclerAdapter.stopListening();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
MenuItem menuItem=menu.findItem(R.id.search);
SearchView searchView=(SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
search_product(query);
// itemsAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
search_product(newText);
//itemsAdapter.getFilter().filter(newText.toString());
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.add_product) {
startActivity(new Intent(this, MainActivity.class));
Toast.makeText(this, "post a product", Toast.LENGTH_SHORT).show();
} else if (item.getItemId() == R.id.tutorial) {
// startActivity(new Intent(this, AddRider.class));
// Toast.makeText(this,"Add a rider to an Event",Toast.LENGTH_SHORT).show();
} else if (item.getItemId() == R.id.logOut) {
startActivity(new Intent(this, MainActivity.class));
Toast.makeText(this, "bye", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
ItemTouchHelper.SimpleCallback simpleCallback=new
ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT) {
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, Re
cyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
removeItem((long) viewHolder.itemView.getTag());
productList.remove(viewHolder.getAdapterPosition());
itemsAdapter.notifyDataSetChanged();
}
private void removeItem(long id) {
}
};
private boolean updateItem(String seller, String description, String price,String location,String
phone,String productId,String image,String posted_date) {
//getting the specified product reference
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("Items").child(productId);
//updating product
Product product = new Product(productId, seller,
description,price,phone,location,image,posted_date);
dR.setValue(product);
Toast.makeText(getApplicationContext(), "Product Updated", Toast.LENGTH_LONG).show();
return true;
}
#Override
public void onNoteClick(final int position) {
CharSequence[] items = {"Update", "Delete"};
AlertDialog.Builder dialog = new AlertDialog.Builder(RetrieveData.this);
dialog.setTitle("Choose Action");
dialog.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0){
Intent update_activty = new Intent(getApplicationContext(),Update_Product.class);
startActivity(update_activty);
}
if (i==1){
Product product=productList.get(position);
productId =product.getProductId();
image =product.getImage();
final AlertDialog.Builder dialogdelete = new
AlertDialog.Builder(RetrieveData.this);
dialogdelete.setTitle("Warning");
dialogdelete.setMessage("Are You Sure You Want to Delete?");
dialogdelete.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Query mQuery = mRef.orderByChild("productId").equalTo(productId);
mQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren()){
ds.getRef().removeValue();
}
Toast.makeText(RetrieveData.this,"deleted..!",Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(RetrieveData.this,databaseError.getMessage(),Toast.LENGTH_SHORT).show();
}
});
Query mPictureReference =
FirebaseDatabase.getInstance().getReference("Items").orderByChild("image").equalTo(image);
mPictureReference.getRef().removeValue().addOnSuccessListener(new
OnSuccessListener() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(RetrieveData.this,"Image
deleted",Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RetrieveData.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
});
dialogdelete.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
dialogdelete.show();
}
}
});
dialog.show();
// Toast.makeText(getApplicationContext(),"cliked",Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View v) {
}
public static String getTimeDate(long timestamp){
try{
DateFormat dateFormat = getDateTimeInstance();
Date netDate = (new Date(timestamp));
return dateFormat.format(netDate);
} catch(Exception e) {
return "date";
}
}
}
ADAPTER CLASS
package com.dikolobe.salesagent;
public class ItemsAdapter extends RecyclerView.Adapter implements Filterable {
public ArrayList<Product> filterList = new ArrayList<>();
private int progressStatus = 0;
private Handler handler = new Handler();
private OnNoteClickListener onNoteClickListener;
Context context;
private List<Product> listItems;
private List<Product> listItemsFull;
private Product product;
FirebaseRecyclerOptions<Product> options;
String imageUrl = null;
public ItemsAdapter(Context context, List<Product> listItems,OnNoteClickListener
onNoteClickListener,FirebaseRecyclerOptions options) {
this.context = context;
this.listItems = listItems;
listItemsFull = new ArrayList<>(listItems);
this.onNoteClickListener = onNoteClickListener;
this.options=options;
}
public ItemsAdapter(FirebaseRecyclerOptions<Product> options) {
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v =
LayoutInflater.from(parent.getContext()).inflate(R.layout.design_row_for_recyclerview,parent,false);
return new ViewHolder(v,onNoteClickListener);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
product = listItems.get(position);
holder.seller.setText(listItems.get(position).getSeller());
holder.desc.setText(listItems.get(position).getDescription());
holder.price.setText(listItems.get(position).getPrice());
holder.location.setText(listItems.get(position).getLocation());
holder.phone.setText(listItems.get(position).getPhone());
holder.time.setText((CharSequence) listItems.get(position).getPosted_date());
holder.progress_Bar = new ProgressBar(context);
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
handler.post(new Runnable() {
public void run() {
holder.progressBar.setProgress(progressStatus);
holder.textView.setText(progressStatus+"/"+holder.progressBar.getMax());
}
});
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
imageUrl = product.getImage();
Picasso.get().load(imageUrl).into(holder.imageView, new Callback() {
#Override
public void onSuccess() {
holder.image_layout.setVisibility(View.INVISIBLE);
}
#Override
public void onError(Exception e) {
Toast.makeText(context, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
holder.phone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id=v.getId();
if (id==R.id.phoneTv){
String phoneNumber = product.getPhone();
String message = "I am interested";
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null, null);
Toast.makeText(context,"Interest message sent successfully",
Toast.LENGTH_LONG).show();
}
}
});
holder.call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id=v.getId();
if(id==R.id.call){
String phoneNumber = product.getPhone();
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+phoneNumber));
context.startActivity(intent);
}
}
}); }
#Override
public int getItemCount() {
return listItems.size();
}
#Override
public Filter getFilter() {
return filterProducts;
}
private Filter filterProducts = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
///*to delete*/String search_text = constraint.toString().toLowerCase();
List<Product> productFiltrate = new ArrayList<>();
if (constraint.length()==0 ){
productFiltrate.addAll(listItemsFull);
}else
{
String pattern = constraint.toString().toLowerCase().trim();
for (Product product:listItemsFull){
if(product.getSeller().toLowerCase().contains(pattern)){
productFiltrate.add(product);
}
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = productFiltrate;
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filterList.clear();
filterList.addAll((List) results.values);
notifyDataSetChanged();
}
};
}
INSERT DATA/MAIN_ACTIVITY
package com.dikolobe.salesagent;
public class MainActivity extends AppCompatActivity {
FirebaseRecyclerAdapter firebaseRecyclerAdapter;
ItemsAdapter itemsAdapter;
FirebaseDatabase mDatabase;
DatabaseReference mRef;
FirebaseStorage mStorage;
EditText seller_name,desc,price,location,phone;
Button btnInsert,list;
ImageButton imageButton,take_Photo;
ProgressBar progressBar;
private ProgressDialog mProgress;
Uri imageUri = null;
final int REQUEST_CODE_IMAGE=999;
static final int REQUEST_IMAGE_CAPTURE = 1;
private int progressStatus = 0;
private TextView textView;
private Handler handler = new Handler();
ViewHolder holder;
FrameLayout image_layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seller_name = findViewById(R.id.seller_nameEt);
desc = findViewById(R.id.descEt);
price = findViewById(R.id.priceEt);
location = findViewById(R.id.locationEt);
phone = findViewById(R.id.phoneEt);
btnInsert = findViewById(R.id.save);
//list = findViewById(R.id.list);
imageButton = findViewById(R.id.imageButton);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
textView = (TextView) findViewById(R.id.textView);
image_layout = (FrameLayout) findViewById(R.id.layout_image);
take_Photo = (ImageButton) findViewById(R.id.take_pic);
take_Photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = v.getId();
if (id==R.id.take_pic){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
}
});
mDatabase = FirebaseDatabase.getInstance();
mRef = mDatabase.getReference().child("Items");
mStorage = FirebaseStorage.getInstance();
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_IMAGE);
}
});
progressBar = new ProgressBar(MainActivity.this);
image_layout.setVisibility(View.INVISIBLE);
btnInsert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
image_layout.setVisibility(View.VISIBLE);
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
// Update the progress bar and display the
//current value in the text view
handler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressStatus);
textView.setText(progressStatus+"/"+progressBar.getMax());
}
});
try {
// Sleep for 200 milliseconds.
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
final String seller = seller_name.getText().toString().trim();
final String fn = desc.getText().toString().trim();
final String ln = price.getText().toString().trim();
final String place = location.getText().toString().trim();
final String phon = phone.getText().toString().trim();
final String id = mRef.push().getKey();
if (!(seller.isEmpty() && fn.isEmpty() && ln.isEmpty() && place.isEmpty() &&
phon.isEmpty() && imageUri!=null)){
StorageReference filepath =
mStorage.getReference().child("images").child(imageUri.getLastPathSegment());
filepath.putFile(imageUri).addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
image_layout.setVisibility(View.INVISIBLE);
Task<Uri> downloadUrl =
taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
String t=task.getResult().toString();
final DatabaseReference newPost=mRef.push();
newPost.child("seller").setValue(seller);
newPost.child("description").setValue(fn);
newPost.child("price").setValue(ln);
newPost.child("location").setValue(place);
newPost.child("phone").setValue(phon);
newPost.child("productId").setValue(id);
newPost.child("image").setValue(task.getResult().toString());
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String strDate = dateFormat.format(date).toString();
newPost.child("posted_date").setValue(strDate);
Toast.makeText(MainActivity.this,"successfully uploaded",
Toast.LENGTH_SHORT).show();
seller_name.setText("");
desc.setText("");
price.setText("");
location.setText("");
phone.setText("");
imageButton.setImageURI(null);
goToRetrieveDataClass();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(),"Failed to
upload..!",Toast.LENGTH_LONG).show();
}
});
}
});
}else Toast.makeText(MainActivity.this,"Please write all your
details..!",Toast.LENGTH_LONG).show();
}
});
if (!hasCamera())
take_Photo.setEnabled(false);
}
#Override
protected void onStart() {
super.onStart();
// firebaseRecyclerAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
// firebaseRecyclerAdapter.stopListening();
}
private Boolean hasCamera() {
return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
}
public void launchCamera(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[]
grantResults) {
if (requestCode == REQUEST_CODE_IMAGE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent gallery = new Intent(Intent.ACTION_GET_CONTENT);
gallery.setType("image/*");
startActivityForResult(gallery, REQUEST_CODE_IMAGE);
} else {
Toast.makeText(this, "no permission", Toast.LENGTH_SHORT).show();
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_IMAGE && resultCode == RESULT_OK) {
imageUri = data.getData();
CropImage.activity(imageUri).setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1).start(this);
imageButton.setImageURI(imageUri);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK){
}
else if(resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE){
Exception error = result.getError();
}
}
super.onActivityResult(requestCode, resultCode,data);
}
}
I have a list that I get from firebase, this list is about posts and what I need is when user like it or unlike it, the list updated through adapter. as I used recyclerview and adapter to show my data after receiving it from firebase. Actually, everything works so fine with me but just this issue when user like or unlike the post it goes crazy. I tried to make a toast to make sure that I'm working with the same position as I expected and it proved me right.
the photo of the post appears and disappears by clicking like button like the vides shows and it does not updating the data in a proper way like it mess with the number of likes
You can find my code below with a video to illustrate the problem I am facing.
I hope somebody can help me out.
private void read_posts() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
reference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
//post_models.clear();
Post_Model post_model = dataSnapshot.getValue(Post_Model.class);
post_models.add(post_model);
post_adapter = new Post_Adapter(post_models, getContext());
recyclerviewNewsfeed.setAdapter(post_adapter);
progressBar.setVisibility(View.GONE);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Post_Model post_model = dataSnapshot.getValue(Post_Model.class);
for (int i=0;i<post_models.size();i++){
if(post_models.get(i).getId().equals(post_model.getId())){
post_models.set(i,post_model);
post_adapter.notifyItemChanged(i);
break;
}
}
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
It's my post adapter
public class Post_Adapter extends RecyclerView.Adapter<Post_Adapter.Viewholder> {
private Context context;
private List<Post_Model> post_models;
FirebaseUser firebaseUser;
List<Like_Model> like_modelList, likeblue_modelList;
View_Photos_Adapter view_Photos_adapter;
boolean userlikeit;
public static int positionn=-1;
public Post_Adapter(List<Post_Model> post_models, Context context) {
this.context = context;
this.post_models = post_models;
}
#NonNull
#Override
public Viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.post_item, parent, false);
return new Viewholder(view);
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull final Viewholder holder, final int position) {
final Post_Model post_model = post_models.get(position);
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference referencee = FirebaseDatabase.getInstance().getReference("Posts").child(post_model.getId());
referencee.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//Toast.makeText(CommentActivity.this, post_id+"", Toast.LENGTH_SHORT).show();
Post_Model post_modell = dataSnapshot.getValue(Post_Model.class);
// Toast.makeText(CommentActivity.this, post_id+"", Toast.LENGTH_SHORT).show();
if (post_modell.getLikeModels() != null) {
for (int i = 0; i < post_modell.getLikeModels().size(); i++) {
if (post_modell.getLikeModels().get(i).getUserid().equals(firebaseUser.getUid())) {
userlikeit = true;
break;
} else {
userlikeit = false;
}
}
} else {
userlikeit = false;
}
//snapshot.getRef().removeValue();
// Toast.makeText(context, userlikeit+"58", Toast.LENGTH_SHORT).show();
//Toast.makeText(CommentActivity.this, comment_models.size()+"", Toast.LENGTH_SHORT).show();
if (userlikeit) {
holder.likebluebtn.setVisibility(View.VISIBLE);
holder.likebtn.setVisibility(View.GONE);
} else {
holder.likebtn.setVisibility(View.VISIBLE);
holder.likebluebtn.setVisibility(View.GONE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
if (post_model.getUserid().equals(firebaseUser.getUid())) {
holder.editbtn.setVisibility(View.VISIBLE);
holder.deletebtn.setVisibility(View.VISIBLE);
} else {
holder.editbtn.setVisibility(View.GONE);
holder.deletebtn.setVisibility(View.GONE);
}
holder.editbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.postTextView.setVisibility(View.GONE);
holder.postEditText.setVisibility(View.VISIBLE);
holder.postEditText.setText(post_model.getPost());
holder.editbtn.setVisibility(View.GONE);
holder.savebtn.setVisibility(View.VISIBLE);
}
});
holder.savebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Post_Model post_modell = new Post_Model(post_model.getId(), post_model.getUserid()
, holder.postEditText.getText().toString(), post_model.getTime()
, post_model.getCommentModels(), post_model.getPostphotos(), post_model.getLikeModels());
FirebaseDatabase.getInstance().getReference("Posts")
.child(post_model.getId())
.setValue(post_modell);
holder.postTextView.setVisibility(View.VISIBLE);
holder.postEditText.setVisibility(View.GONE);
holder.editbtn.setVisibility(View.VISIBLE);
holder.savebtn.setVisibility(View.GONE);
Toast.makeText(context, "Post has been edited successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, NewsfeedActivity.class);
context.startActivity(intent);
((Activity) context).overridePendingTransition(R.anim.slide_in_right, R.anim.slide_in_left);
((Activity) context).finish();
}
});
holder.deletebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new AlertDialog.Builder(context)
.setTitle("Delete Post")
.setMessage("Are you sure you want to delete this post?")
// Specifying a listener allows you to take an action before dismissing the dialog.
// The dialog is automatically dismissed when a dialog button is clicked.
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
final DatabaseReference referencee = FirebaseDatabase.getInstance().getReference("Posts")
.child(post_model.getId());
referencee.removeValue();
Toast.makeText(context, "Post deleted successfully", Toast.LENGTH_LONG).show();
Intent intent = new Intent(context, NewsfeedActivity.class);
context.startActivity(intent);
((Activity) context).overridePendingTransition(R.anim.slide_in_right, R.anim.slide_in_left);
((Activity) context).finish();
}
})
// A null listener allows the button to dismiss the dialog and take no further action.
.setNegativeButton(android.R.string.no, null)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
});
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
like_modelList = new ArrayList<>();
likeblue_modelList = new ArrayList<>();
//Toast.makeText(context, read_likes(post_model.getId())+"", Toast.LENGTH_SHORT).show();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
// Toast.makeText(Create_Coworking_SpaceActivity.this, "111111111", Toast.LENGTH_LONG).show();
if (user.getId().equals(post_model.getUserid())) {
if (user.getImageURL().equals("default")) {
holder.userImage.setImageResource(R.drawable.ic_imgprofile);
} else {
Glide.with(holder.itemView).load(user.getImageURL()).into( holder.userImage);
}
holder.username.setText(user.getUsername());
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
if (post_model.getPostphotos() == null) {
holder.postPhotosRC.setVisibility(View.GONE);
} else {
holder.postPhotosRC.setHasFixedSize(true);
holder.postPhotosRC.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
view_Photos_adapter = new View_Photos_Adapter(post_model.getPostphotos(), context);
holder.postPhotosRC.setAdapter(view_Photos_adapter);
}
holder.postTextView.setText(post_model.getPost());
holder.posttimeTextView.setText(post_model.getTime());
holder.commentbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, CommentActivity.class);
intent.putExtra("post_id", post_model.getId());
context.startActivity(intent);
((Activity) context).overridePendingTransition(R.anim.slide_in_right, R.anim.slide_in_left);
}
});
if (post_model.getCommentModels() != null) {
holder.numofcommentsEditText.setText(post_model.getCommentModels().size() + "");
holder.numofcommentsTextView.setText(post_model.getCommentModels().size() + "");
}
final int[] li = {0};
holder.likebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
like(post_model.getId());
// Post_Adapter.this.notifyItemChanged(position);
positionn=position;
}
});
holder.likebluebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context, userlikeit+"5", Toast.LENGTH_SHORT).show();
unlike(post_model.getId());
// Post_Adapter.this.notifyItemChanged(position);
positionn=position;
}
});
if (post_model.getLikeModels() != null) {
holder.numoflikesEditText.setText(post_model.getLikeModels().size() + "");
holder.numoflikesTextView.setText(post_model.getLikeModels().size() + "");
}
holder.likesTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, LikeActivity.class);
intent.putExtra("post_id", post_model.getId());
context.startActivity(intent);
((Activity) context).overridePendingTransition(R.anim.slide_in_right, R.anim.slide_in_left);
}
});
holder.commentsTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, CommentActivity.class);
intent.putExtra("post_id", post_model.getId());
context.startActivity(intent);
((Activity)
context).overridePendingTransition(R.anim.slide_in_right,
R.anim.slide_in_left);
}
});
}
#Override
public int getItemCount() {
return post_models == null ? 0 : post_models.size();
}
Hello I'm trying to create a profile screen where the user can upload their own profile image and change the ImageView into something that they've uploaded. But upon using this Upload profile image for a user Firebase as a reference I encountered an error when I'm starting to upload the images to the database.
My Code
public class userMain extends Fragment {
private TextView userfirstName,usersecondName,userNumber,userGender,userEmail,userDate;
private Button btnChoose, btnUpload;
private ImageView imageView;
private Uri filePath;
private FirebaseStorage storage;
private StorageReference storageReference;
private final int PICK_IMAGE_REQUEST = 71;
public userMain() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_user_main, container, false);
btnUpload = (Button) view.findViewById(R.id.savePhoto);
imageView = (ImageView) view.findViewById(R.id.imageView3);
userfirstName = (TextView) view.findViewById(R.id.firstnametv);
usersecondName = (TextView) view.findViewById(R.id.secondnametv);
userNumber = (TextView) view.findViewById(R.id.numbertv);
userGender = (TextView) view.findViewById(R.id.gendertv);
userEmail = (TextView) view.findViewById(R.id.emailtv);
userDate = (TextView) view.findViewById(R.id.datetv);
FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
String useruid=user.getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Accounts").child("Users").child(useruid);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chooseImage();
}
});
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadImage();
}
});
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String firstname = dataSnapshot.child("first").getValue(String.class);
String secondname = dataSnapshot.child("second").getValue(String.class);
String number = dataSnapshot.child("number").getValue(String.class);
String gender = dataSnapshot.child("gender").getValue(String.class);
String email = dataSnapshot.child("email").getValue(String.class);
String date = dataSnapshot.child("date").getValue(String.class);
userfirstName.setText(firstname);
usersecondName.setText(secondname);
userNumber.setText(number);
userGender.setText(gender);
userEmail.setText(email);
userDate.setText(date);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return view;
}
private void uploadImage() {
if(filePath != null)
{
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(getContext(), "Uploaded", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getContext(), "Failed "+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());
progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
}
}
private void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
String useruid=user.getUid();
final DatabaseReference img = FirebaseDatabase.getInstance().getReference().child("Accounts").child("Users").child(useruid);
if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null )
{
filePath = data.getData();
StorageReference filepath= storageReference.child("Images").child(filePath.getLastPathSegment());
filepath.putFile(filePath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
img.child("image").setValue(downloadUrl);
}
});
}
}
}
Change this:
StorageReference filepath= storageReference.child("Images").child(filePath.getLastPathSegment());
filepath.putFile(filePath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
img.child("image").setValue(downloadUrl);
}
to this:
StorageReference filepath= storageReference.child("Images").child(filePath.getLastPathSegment());
filepath.putFile(filePath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String downloadUrl = taskSnapshot.getDownloadUrl().toString()
img.child("image").setValue(downloadUrl);
}
saving the downloadUrl as string in your firebase database