One of the Activities on an app i am building is a profile update activity with an option to upload display picture. I am trying to implement upload picture option using Picasso through the following code. So far i am unable to retrieve the picture from the phone with a constant null for Uri and failure to display picture in the ImageView due to that.
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.UserProfileChangeRequest;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
public class UploadProfilePicture extends AppCompatActivity {
private ProgressBar progressBar;
private ImageView imageViewUploadPic;
private FirebaseAuth authProfile;
private StorageReference storageReference;
private FirebaseUser firebaseUser;
private static final int PICK_IMAGE_REQUEST =1 ;
private Uri uriImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_profile_pciture);
getActionBar();
authProfile = FirebaseAuth.getInstance();
firebaseUser = authProfile.getCurrentUser();
Button buttonUploadPictureChoose = findViewById(R.id.upload_profile_pic_choose_button);
Button buttonUploadProfilePicture = findViewById(R.id.upload_profile_pic_upload_button);
progressBar = findViewById(R.id.progressBar);
imageViewUploadPic = findViewById(R.id.imageView_profile_pic_upload);
storageReference = FirebaseStorage.getInstance("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx").getReference("UsersDisplayPictures");
Uri uri = firebaseUser.getPhotoUrl();
//Set User's current DP in ImageView (if uploaded already). Will be using Picasso
//Regular URIs
Picasso.with(UploadProfilePicture.this).load(uri).into(imageViewUploadPic);
//choosing image from phone to upload
buttonUploadPictureChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
//upload image to app
buttonUploadProfilePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
UploadPic ();
}
});
}
private void openFileChooser(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,#Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null){
uriImage = data.getData();
imageViewUploadPic.setImageURI(uriImage);
Toast.makeText(UploadProfilePicture.this, "Picture was chosen, please click the upload button", Toast.LENGTH_SHORT).show();
} else if (uriImage == null){
Toast.makeText(UploadProfilePicture.this, "Uri is null", Toast.LENGTH_SHORT).show();
}
}
private void UploadPic(){
if (uriImage != null){
// save the image with uid of the currently logged user
StorageReference fileReference = storageReference.child(authProfile.getCurrentUser().getUid() + " . " + getFileExtension(uriImage));
//Upload image to storage
fileReference.putFile(uriImage).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Uri downloadUri = uri;
firebaseUser = authProfile.getCurrentUser();
//Finally set the display image of the user after upload
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder().setPhotoUri(downloadUri).build();
firebaseUser.updateProfile(profileUpdates);
}
});
progressBar.setVisibility(View.GONE);
Toast.makeText(UploadProfilePicture.this, "Picture Upload is successful", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(UploadProfilePicture.this, UserProfileActivity.class);
startActivity(intent);
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(UploadProfilePicture.this, e.getMessage(), Toast.LENGTH_SHORT).show();
Toast.makeText(UploadProfilePicture.this, "Something went wrong!" ,Toast.LENGTH_SHORT).show();
}
});
} else {
progressBar.setVisibility(View.GONE);
Toast.makeText(UploadProfilePicture.this, "No file was selected", Toast.LENGTH_SHORT).show();
}
}
//Obtaining File Extension of the image
private String getFileExtension(Uri uri){
ContentResolver CR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(CR.getType(uri));
}
No errors or noticeable Logcat line related. Simply it would exit the Picture picker and would not display the image in the imageView. Of course it would Toast the message of " Uri is null" since it is following the if statement included to follow the process steps to see the missing task !
Is my code of choosing and uploading picture is wrong or something is missing >
I guess it was a syntax error in the if statement within the onActivityResult
it was:
if (resultCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null){
Correction :
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null){
At the moment the issue is resolved and image could be chosen and displayed within the app.
Facing a new issue with this code but this should be for another question if needed
E/StorageException: StorageException has occurred.
User does not have permission to access this object.
Code: -13021 HttpResult: 403
Related
I am facing in android studio when i am upload image to the server its upload successfully but when i am select a pdf file and upload to the server the App will be crashed? How could i upload a pdf file to the server?
// #POST("User/UploadFiles?patientID=28609")
#Multipart
#POST("User/UploadFiles")
Call<ResponseBody> uploadFile(#Query("patientID") int patientID,
#Part MultipartBody.Part file);
This is my Code.
package com.maxvecare.itocean.pk.usersactivities;
import static com.maxvecare.itocean.pk.usersactivities.DoctorsActivity.TAG;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.maxvecare.itocean.pk.R;
import com.maxvecare.itocean.pk.apisutilities.ApiInterface;
import com.maxvecare.itocean.pk.apisutilities.ApiUtilities;
import com.maxvecare.itocean.pk.useradapters.DocumentAdapter;
import com.maxvecare.itocean.pk.usermodels.DocumentsClass;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class UploadClinicReports extends AppCompatActivity {
private Button mChooseFileBtn, mSaveFileBtn;
private RecyclerView recyclerView;
List<DocumentsClass> documentsClassList;
RecyclerView.LayoutManager layoutManager;
DocumentAdapter documentAdapter;
private ProgressDialog mProgress;
SharedPreferences sharedPreferences;
// this is the action code we use in our intent,
// this way we know we're looking at the response from our own action
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
ImageView imageView;
private static final int STORAGE_PERMISSION_CODE = 1234;
private int PICK_IMAGE_REQUEST = 1;
private Uri filePath;
private Bitmap bitmap;
TextView tv;
int patientID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_clinic_reports);
mProgress = new ProgressDialog(this);
sharedPreferences = getSharedPreferences("doctorApp", MODE_PRIVATE);
patientID = sharedPreferences.getInt("patientID", 0);
//Toast.makeText(this, "Pat"+patientID, Toast.LENGTH_SHORT).show();
Toolbar toolbar = findViewById(R.id.m_Toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Upload Documents");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.back_button);
mChooseFileBtn = findViewById(R.id.uploadBtn);
mSaveFileBtn = findViewById(R.id.SaveBtn);
tv = findViewById(R.id.showDocs);
imageView = findViewById(R.id.imagefile);
ActivityCompat.requestPermissions(UploadClinicReports.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, PackageManager.PERMISSION_GRANTED);
recyclerView = findViewById(R.id.recyclerViewSaveDocs);
documentsClassList = new ArrayList<>();
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
mChooseFileBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(UploadClinicReports.this);
alertDialog.setTitle("Clinic Report");
alertDialog.setMessage("Upload Your Clinic Report");
alertDialog.setPositiveButton("Image Pick", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// select image file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
});
alertDialog.setNegativeButton("Pdf Pick", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// select a file
Intent intent = new Intent();
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Pdf"), PICK_IMAGE_REQUEST);
}
});
AlertDialog dialog = alertDialog.create();
dialog.show();
}
});
mSaveFileBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (filePath != null) {
uploadImage();
} else {
Toast.makeText(UploadClinicReports.this, "Please Select a File", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && data != null && data.getData() != null) {
filePath = data.getData();
}
}
private String getPath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, MediaStore.Images.Media._ID + "=?", new String[]{document_id}, null);
cursor.moveToFirst();
#SuppressLint("Range") String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;// da se di
}
private void uploadImage() {
mProgress.setMessage("Loading...");
mProgress.show();
String path = getPath(filePath);
try {
String uploadId = UUID.randomUUID().toString();
File imageFile = new File(path); // Create a file using the absolute path of the image
RequestBody reqBody = RequestBody.create(MediaType.parse("*/*"), imageFile);
MultipartBody.Part partImage = MultipartBody.Part.createFormData("file", imageFile.getName(), reqBody);
Call<ResponseBody> upload = ApiUtilities.getService().uploadFile(patientID, partImage);
upload.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
mProgress.dismiss();
Toast.makeText(UploadClinicReports.this, "Image Uploaded", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onResponse: " + response);
} else {
mProgress.dismiss();
Toast.makeText(UploadClinicReports.this, "Failed" + response.code(), Toast.LENGTH_SHORT).show();
Log.d(TAG, "onResponse: " + response);
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
mProgress.dismiss();
Toast.makeText(UploadClinicReports.this, t.getMessage(), Toast.LENGTH_SHORT).show();
Log.d(TAG, "onResponse: " + t.getMessage());
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
**How could I upload a pdf file? I am struggling to get the absolute path of pdf file from URI.
I am facing the following issue when i am upload pdf file to the server in android studio java Using retrofit.**
This is where I import the image to(from gallery) and I want to save it to SQLite to hopefully display it in another activity, how would I go about doing so? I am kind of new to Android Studio so if there is some newbie kind of easy way that I would go about doing so would be very helpful.
(Update) So I have added this two lines marked by /* */ but now I can't get my app to work still have no idea how to do this.. any ideas?
Import image>Save to SQLite>Take Image to SQLite>Display in another activity
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class DataInput extends AppCompatActivity {
private EditText inputName;
private EditText inputAge;
private Button buttonSave;
private Button buttonGetLocation;
private Button buttonImportImage;
private ImageView mImageView;
private static final int IMAGE_PICK_CODE = 1000;
private static final int PERMISSION_CODE = 1001;
private InputHelper helper = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_input);
inputName = (EditText) findViewById(R.id.input_name);
inputAge = (EditText) findViewById(R.id.input_age);
address = (TextView) findViewById(R.id.address);
buttonSave = findViewById(R.id.button_save);
buttonSave.setOnClickListener(onSave);
buttonImportImage = findViewById(R.id.button_import_image);
mImageView = findViewById(R.id.image_view);
buttonImportImage.setOnClickListener(onImport);
helper = new InputHelper(this); }
private View.OnClickListener onSave = new View.OnClickListener() {
#Override
public void onClick(View v) {
String nameStr = inputName.getText().toString();
String ageStr = inputAge.getText().toString();
String addressStr = address.getText().toString();
String combineStr = nameStr + "\n" + ageStr + "\n" + addressStr;
Toast.makeText(v.getContext(), combineStr, Toast.LENGTH_LONG).show();
/*BitmapDrawable drawable = (BitmapDrawable)mImageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
byte[] image = getBitmapAsByteArray(bitmap);*/
Intent i = new Intent(DataInput.this,InformationDisplay.class);
startActivity(i);
helper.insert(nameStr,ageStr,addressStr,image);
finish();
}
/* public byte[] getBitmapAsByteArray(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, outputStream);
return outputStream.toByteArray(); */
}
};
private View.OnClickListener onImport = new View.OnClickListener() {
#Override
public void onClick(View v) {
//check runtime permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_DENIED) {
//permission not granted, request it.
String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};
//show popup for runtime permission
requestPermissions(permissions, PERMISSION_CODE);
} else {
//permission already granted
pickImageFromGallery();
}
} else {
//system os is less then marshmallow
pickImageFromGallery();
}
}
};
private void pickImageFromGallery() {
//intent to pick image
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, IMAGE_PICK_CODE);
}
//handle result of runtime permission
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSION_CODE: {
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
//permission was granted
pickImageFromGallery();
} else {
//permission was denied
Toast.makeText(this, "Permission denied...!", Toast.LENGTH_LONG).show();
}
}
}
}
//handle result of picked image
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == IMAGE_PICK_CODE) {
//set image to image view
mImageView.setImageURI(data.getData());
}
}
You can save an Image in SQLite database in the form of blob. Another simple way to storing the image is in the form of base64 string. This is what I tried in my previous project and this works:
public class Profile_Class extends AppCompatActivity {
private Bitmap photo, OutImage;
private AppPreferences preferences;
private CircularImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile__class);
EditText name = findViewById(R.id.name);
preferences = new AppPreferences(this);
Toolbar toolbar = findViewById(R.id.toolbar_t);
EditText userName = findViewById(R.id.userName);
EditText passWord = findViewById(R.id.passWord);
imageView = findViewById(R.id.iv_profile_auditor);
ImageView take_pic1 = findViewById(R.id.take_pic1);
if (prefernces.getProfileImage().equals(" ")) {
Log.e("TAG", "NoProfilePic");
} else {
imageView.setImageBitmap(decodeBase64(prefernces.getProfileImage()));
}
take_pic1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
photo = (Bitmap) data.getExtras().get("data");
OutImage = Bitmap.createScaledBitmap(photo, 300, 400, true);
prefernces.setProfileImage(encodeTobase64(OutImage));
Intent intent2 = new Intent("header_pic_update");
LocalBroadcastManager.getInstance(Profile_Class.this).sendBroadcast(intent2);
}
}
// method for bitmap to base64
public static String encodeTobase64(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
Log.d("Image Log:", imageEncoded);
return imageEncoded;
}
// method for base64 to bitmap
public static Bitmap decodeBase64(String input) {
byte[] decodedByte = Base64.decode(input, 0);
return BitmapFactory
.decodeByteArray(decodedByte, 0, decodedByte.length);
}
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return true;
}
If you see in OnActivityResult class, I'm converting the outImage into Base64 string. Here use the method encodeTobase64 and add the image string to your table.
Now in the other activity where you want to show the image, call the method decodeBase64 and decode the image. In the above code I'm decoding the string to image and setting it to imageview like this:
imageView.setImageBitmap(decodeBase64(prefernces.getProfileImage()));
There are numerous ways to store and retrieve the image. This is one way I did. Mind here that I'm storing the image in bitmap so the quality will not be good. If you want image with full quality than you have to use URI to store the image in your mobile and then call the image in required quality.
I want to allow the user to upload two images,Cover and Logo.Then have them saved in firestore.I get an error at
Picasso.get().load(uri).into(Logo); line saying
no suitable method found for into(Uri)
method RequestCreator.into(Target) is not applicable
(argument mismatch; Uri cannot be converted to Target)
method RequestCreator.into(ImageView) is not applicable
(argument mismatch; Uri cannot be converted to ImageView)
package com.example.littlemarketplaceapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
public class Shop extends AppCompatActivity {
private ImageButton Logoimage;
private ImageButton Cover;
private EditText ShopnameEditText;
private TextView ShowShopName;
private Button SaveButton;
DatabaseReference databaseReference1;
private FirebaseAuth mAuth;
StorageReference storageReference = FirebaseStorage.getInstance().getReference();
StorageReference storageReference1 = FirebaseStorage.getInstance().getReference();
Uri Logo;
Uri coverUri;
private Uri uri;
int coverOrLogo;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shop);
Intent intent = getIntent();
String emaila = intent.getExtras().getString("emaili");
String passworda = intent.getExtras().getString("passwordi");
String fullnamea = intent.getExtras().getString("fullnamei");
String usernamea = intent.getExtras().getString("usernamei");
String mobilea = intent.getExtras().getString("mobilei");
String Shopname;
Logoimage = findViewById(R.id.shoplogobutton);
Cover = findViewById(R.id.coverphotobutton);
ShowShopName = findViewById(R.id.shopname);
ShopnameEditText = findViewById(R.id.shopnameedittext);
Shopname = ShopnameEditText.getText().toString().trim();
String key = databaseReference1.push().getKey();
//Saves Owner's Data
SaveButton.setOnClickListener(v -> {
ForOwner s_owner = new ForOwner(fullnamea, usernamea, emaila, mobilea, passworda, Shopname);
databaseReference1.child(key).setValue(s_owner);
Toast.makeText(getApplicationContext(), "Registration complete", Toast.LENGTH_SHORT).show();
});
//Uploads the Logo
Logoimage.setOnClickListener(view -> {
//open Gallery
Intent openGalleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(openGalleryIntent, 1000);
});
//Uploads the Cover photo
Cover.setOnClickListener(view -> {
//open Gallery
Intent openGalleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(openGalleryIntent, 2000);
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #androidx.annotation.Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1000 && resultCode == Activity.RESULT_OK) {
Uri imageUri1 = data.getData();
Logoimage.setImageURI(imageUri1);
uploadImageToFirebase(imageUri1, 1);
} else if (requestCode == 2000 && resultCode == Activity.RESULT_OK) {
Uri imageUri2 = data.getData();
Cover.setImageURI(imageUri2);
uploadImageToFirebase(imageUri2, 0);
}
}
//}
private <final_fileRef> void uploadImageToFirebase(Uri imageUri1, int coverOrLogo) {
//upload image to firebase
StorageReference fileRef = null;
if (coverOrLogo == 1) {
fileRef = storageReference.child("logo.jpg");
} else if (coverOrLogo == 0) {
fileRef = storageReference.child("cover.jpg");
}
fileRef.putFile(imageUri1).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileRef.putFile(imageUri1).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(Uri uri) {
if (coverOrLogo == 1) {
Picasso.get().load(uri).into(Logo);
}
if (coverOrLogo == 0) {
Picasso.get().load(uri).into(Cover);
}
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Shop.this, "Failed", Toast.LENGTH_SHORT).show();
}
});
}
}
In your code Logo is Uri
You need this:
Picasso.get().load(uri).into(imageView);
where imageView is ImageView object in your layout
This question already has answers here:
How to use getdownloadurl in recent versions?
(5 answers)
How to get URL from Firebase Storage getDownloadURL
(13 answers)
Closed 2 years ago.
I make a chatting app with android studio. I want to create settings activity. I successfully load profile image to firebase storage. But when I retrieve profile image from storage it seems end of the onactivityresult. But when I go back to main activity the profile image is disappearing I want when I enter to settings activity profile image is retrieves. I try to do with picasso & glide but not working.
enter code here
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FileDownloadTask;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.io.File;
import java.net.URI;
import java.util.HashMap;
import de.hdodenhof.circleimageview.CircleImageView;
public class SettingsActivity extends AppCompatActivity {
private Toolbar mToolbar;
private CircleImageView set_profile_image;
private EditText set_user_name , set_profile_status;
private Button update_settings_button;
private String CurrentUserID;
private FirebaseAuth mAuth;
private DatabaseReference RootRef;
private static final int GalleryPick = 1;
private StorageReference UserProfileImagesRef;
private ProgressDialog loadingBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
define();
RetrieveUserInfo();
}
private void define() {
set_profile_image = (CircleImageView) findViewById(R.id.set_profile_image);
set_user_name = (EditText) findViewById(R.id.set_user_name);
set_profile_status = (EditText) findViewById(R.id.set_profile_status);
update_settings_button = (Button) findViewById(R.id.update_settings_button);
mAuth = FirebaseAuth.getInstance();
CurrentUserID = mAuth.getCurrentUser().getUid();
RootRef = FirebaseDatabase.getInstance().getReference();
UserProfileImagesRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
loadingBar = new ProgressDialog(this);
}
public void set_profile_image_click(View view){
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent , GalleryPick);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GalleryPick && resultCode == RESULT_OK && data != null){
Uri ImageUri = data.getData();
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1 , 1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK){
loadingBar.setTitle("Set Profile Image");
loadingBar.setMessage("Your Profile Image is Updating...");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
final Uri resultUri = result.getUri();
StorageReference FilePath = UserProfileImagesRef.child(CurrentUserID + ".jpg");
FilePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull final Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()){
Toast.makeText(SettingsActivity.this, "Profile Image Uploaded Successfully", Toast.LENGTH_SHORT).show();
final String downloadUrl = task.getResult().getUploadSessionUri().toString();
RootRef.child("Users").child(CurrentUserID).child("image").setValue(downloadUrl).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(SettingsActivity.this, "Image Uploaded Database Successfully", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}else {
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message , Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
Glide.with(SettingsActivity.this).load(new File(resultUri.getPath())).into(set_profile_image);
}
}
}
private void RetrieveUserInfo() {
RootRef.child("Users").child(CurrentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("image")))){
String RetrieveUserName = dataSnapshot.child("name").getValue().toString();
String RetrieveProfileStatus = dataSnapshot.child("status").getValue().toString();
String RetrieveProfileImage = dataSnapshot.child("image").getValue().toString();
set_user_name.setText(RetrieveUserName);
set_profile_status.setText(RetrieveProfileStatus);
//Picasso.get().load(RetrieveProfileImage).into(set_profile_image);
Glide.with(SettingsActivity.this).load(new File(RetrieveProfileImage.)).into(set_profile_image);
}
else if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name"))){
String RetrieveUserName = dataSnapshot.child("name").getValue().toString();
String RetrieveProfileStatus = dataSnapshot.child("status").getValue().toString();
set_user_name.setText(RetrieveUserName);
set_profile_status.setText(RetrieveProfileStatus);
}
else{
//set_user_name.setVisibility(View.VISIBLE);
Toast.makeText(SettingsActivity.this, "Please update your profile Settings", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void update_settings_button_click(View view){
UpdateSettings();
}
private void UpdateSettings() {
String setUserName = set_user_name.getText().toString();
String setProfileStatus = set_profile_status.getText().toString();
if (TextUtils.isEmpty(setUserName)){
Toast.makeText(this, "Please write your User Name", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(setProfileStatus)){
Toast.makeText(this, "Please write your Status", Toast.LENGTH_SHORT).show();
}
else {
HashMap<String , String> ProfileMap = new HashMap<>();
ProfileMap.put("uid" , CurrentUserID);
ProfileMap.put("name" , setUserName);
ProfileMap.put("status" , setProfileStatus);
RootRef.child("Users").child(CurrentUserID).setValue(ProfileMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
SendUserToMainActivity();
Toast.makeText(SettingsActivity.this, "Profile Updated Successfully", Toast.LENGTH_SHORT).show();
}else {
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message , Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(SettingsActivity.this , MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
}
In the register page, when a user clicks on the "ImageUserPhoto", he can pick an image from the gallery. My code works fine when he picks the photo and fills up all given fields. But if he doesn't pick any photo, the app crashes. How can I give a warning if he doesn't choose any photo in the same section where I check all the fields?
Thanks in advance!!
package com.ayon.austmart.activities;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.ayon.austmart.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.UserProfileChangeRequest;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import de.hdodenhof.circleimageview.CircleImageView;
public class RegisterActivity extends AppCompatActivity {
CircleImageView ImgUserPhoto;
static int PReqCode = 1;
static int REQUESCODE = 1;
Uri pickedImgUri;
private EditText userEmail, userPassword, userPassword2, userName;
private ProgressBar loadingProgress;
private Button regBtn;
private Intent homeIntent;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
userEmail = findViewById(R.id.Email);
userPassword = findViewById(R.id.Password);
userPassword2 = findViewById(R.id.ConfirmPassword);
userName = findViewById(R.id.Name);
loadingProgress = findViewById(R.id.progressBarRegister);
regBtn = findViewById(R.id.buttonRegister);
loadingProgress.setVisibility(View.INVISIBLE);
mAuth = FirebaseAuth.getInstance();
ImgUserPhoto = findViewById(R.id.avatar);
regBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
regBtn.setVisibility(View.INVISIBLE);
loadingProgress.setVisibility(View.VISIBLE);
final String email = userEmail.getText().toString();
final String password = userPassword.getText().toString();
final String password2 = userPassword2.getText().toString();
final String name =userName.getText().toString();
if(email.isEmpty() || name.isEmpty() || password.isEmpty() || password2.isEmpty() || !password.equals(password2))
{
//something goes wrong... display an error message
showMessage("Please verify full fields!!");
regBtn.setVisibility(View.VISIBLE);
loadingProgress.setVisibility(View.INVISIBLE);
}
else
{
//Everything is ok..
createUserAccount(email,name,password);
}
}
});
ImgUserPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Build.VERSION.SDK_INT >= 22)
{
checkAndRequestForPermission();
}
else
{
openGallery();
}
}
});
}
private void createUserAccount(String email, final String name, String password) {
//this method create user account with valid email and pass
mAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
//user account is created successfully
showMessage("Account Created!");
//now update the pro pic and username
updateUserInfo(name,pickedImgUri,mAuth.getCurrentUser());
}
else
{
showMessage("Account creation failed"+task.getException().getMessage());
regBtn.setVisibility(View.VISIBLE);
loadingProgress.setVisibility(View.INVISIBLE);
}
}
});
}
private void updateUserInfo(final String name, Uri pickedImgUri, final FirebaseUser currentUser){
StorageReference mStorage = FirebaseStorage.getInstance().getReference().child("user_photos");
final StorageReference imageFilePath = mStorage.child(pickedImgUri.getLastPathSegment());
imageFilePath.putFile(pickedImgUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//image uploaded successfully
//getting image url
imageFilePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// uri contains user image url
UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
.setDisplayName(name)
.setPhotoUri(uri)
.build();
currentUser.updateProfile(profileUpdate)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
//user info updated successfully
showMessage("Register Complete!");
updateUI();
}
}
});
}
});
}
});
}
private void updateUI() {
homeIntent = new Intent(getApplicationContext(), Home.class);
startActivity(homeIntent);
finish();
}
//message show
private void showMessage(String message) {
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
}
private void openGallery() {
//Open gallery intent and wait for user to pick an image
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,REQUESCODE);
}
public void checkAndRequestForPermission()
{
if(ContextCompat.checkSelfPermission(RegisterActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED)
{
if(ActivityCompat.shouldShowRequestPermissionRationale(RegisterActivity.this,Manifest.permission.READ_EXTERNAL_STORAGE))
{
Toast.makeText(RegisterActivity.this,"Please accept for required permission",Toast.LENGTH_SHORT ).show();
}
else
{
ActivityCompat.requestPermissions(RegisterActivity.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},PReqCode);
}
}
else
openGallery();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == REQUESCODE && data !=null)
{
//user has successfully picked an image...
//saving its reference to a Uri variable
pickedImgUri = data.getData();
ImgUserPhoto.setImageURI(pickedImgUri);
}
}
}
your pickedImgUri is null if the user does not select the image from gallery.
So when you call createUserAccount() when register button is clicked and user has not selected the image pickedImgUri is not updated as per your code.
Hence updateUserInfo() will fail calling an exception which causes the crash.
please add a null checker like
if(pickedImgUri!=null){
//then update the user account
}
If you are interested in forcing the user to select the profile photo then simply use above checker and alert user to please select a photo first but i'd advice against that. Not everyone likes to upload a photo. use any generic avatar png file instead when user does not want to update/remove the avatar.
Happy coding
Thanks a lot!! I have added a few lines and it worked!!! Thank you very much!!
if(email.isEmpty() || name.isEmpty() || password.isEmpty() || password2.isEmpty() || !password.equals(password2))
{
//something goes wrong... display an error message
showMessage("Please verify full fields!!");
regBtn.setVisibility(View.VISIBLE);
loadingProgress.setVisibility(View.INVISIBLE);
}
else
{
if(pickedImgUri == null)
{
showMessage("Please select an image");
regBtn.setVisibility(View.VISIBLE);
loadingProgress.setVisibility(View.INVISIBLE);
}
else {
createUserAccount(email, name, password);
//Everything is ok..
}
}
}
});