Android Send Camera Intent Image to Firebase - android

I have one ImageButton. Whenever We click on ImageButton Camera Intent is open and we take a snap. Everything is working till here is fine. So, How can I upload this camera Intent image to Firebase with authentication? I am not able to find any tutorial video which thought us this but I try to encode the image in a function name called submit. From here I don't know what to do
package com.example.android.besafe;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.Image;
import android.net.Uri;
import android.os.storage.StorageManager;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
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.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static com.example.android.besafe.R.id.imageview;
public class CameraActivity extends AppCompatActivity {
private ImageButton mProfileImage;
Bitmap photo;
private static final int CAMERA_REQ = 1;
StorageReference mstorageRef;
String userId;
private FirebaseAuth mAuth;
FirebaseUser firebaseUser;
FirebaseDatabase firebaseDatabase;
DatabaseReference ref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
mProfileImage = (ImageButton) findViewById(R.id.btnselect);
firebaseDatabase = FirebaseDatabase.getInstance();
ref = firebaseDatabase.getReference("ProfileInfo");
mAuth = FirebaseAuth.getInstance();
firebaseUser = mAuth.getCurrentUser();
userId = firebaseUser.getUid();
mProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQ);
}
});
}
public void submit(View v){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] b = stream.toByteArray();
StorageReference storageReference =mstorageRef.child("documentImages").child(userId).child("noplateImg");
//StorageReference filePath = FirebaseStorage.getInstance().getReference().child("profile_images").child(userID);
storageReference.putBytes(b).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(CameraActivity.this,"failed",Toast.LENGTH_LONG).show();
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQ && resultCode ==RESULT_OK) {
photo = (Bitmap) data.getExtras().get("data");
}
}
}

I found two errors in your code, you're not calling submit() method, so it never executes.
The second you did not make a instance of mstorageRef.
Check code below, i tested and uploaded an image. i am doing it without user authentication, for the sake of simplicity.
public class CameraActivity extends AppCompatActivity {
private ImageButton mProfileImage;
Bitmap photo;
private static final int CAMERA_REQ = 1;
StorageReference mstorageRef;
String userId;
private FirebaseAuth mAuth;
FirebaseUser firebaseUser;
FirebaseDatabase firebaseDatabase;
DatabaseReference ref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProfileImage = (ImageButton) findViewById(R.id.image_holder);
firebaseDatabase = FirebaseDatabase.getInstance();
ref = firebaseDatabase.getReference("ProfileInfo");
mAuth = FirebaseAuth.getInstance();
firebaseUser = mAuth.getCurrentUser();
// userId = firebaseUser.getUid();
mProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQ);
}
});
}
public void submit(){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] b = stream.toByteArray();
StorageReference storageReference =FirebaseStorage.getInstance().getReference().child("documentImages").child("noplateImg");
//StorageReference filePath = FirebaseStorage.getInstance().getReference().child("profile_images").child(userID);
storageReference.putBytes(b).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Toast.makeText(CameraActivity.this, "uploaded", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(CameraActivity.this,"failed",Toast.LENGTH_LONG).show();
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQ && resultCode ==RESULT_OK) {
photo = (Bitmap) data.getExtras().get("data");
submit();
}
}
}
something to keep in mind
check firebase storage read write permissions are set to allow if not using user authentication.
camera is dangerous permission, you need to ask permission from user to use it. add permission in manifest and code for using camera
make sure your internet/wifi is on

task.getDowloadUrl() not defined. You can use this i check , working perfectly.
private void firebaseUploadBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] data = stream.toByteArray();
StorageReference imageStorage = storage.getReference();
StorageReference imageRef = imageStorage.child("images/" + "imageName");
Task<Uri> urlTask = imageRef.putBytes(data).continueWithTask(task -> {
if (!task.isSuccessful()) {
throw task.getException();
}
// Continue with the task to get the download URL
return imageRef.getDownloadUrl();
}).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
String uri = downloadUri.toString();
sendMessageWithFile(uri);
} else {
// Handle failures
// ...
}
progressBar.setVisibility(View.GONE);
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK) {
// Bitmap imageBitmap = data.getData() ;
Bitmap photo = (Bitmap) data.getExtras().get("data");
if (photo != null)
firebaseUploadBitmap(photo);
} else if (requestCode == SELECT_IMAGE && resultCode == Activity.RESULT_OK) {
Uri uri = data.getData();
if (uri != null)
firebaseUploadImage(uri);
}
}

Related

Upload photo to Firebase Storage

I'm trying to build a MainActivity that comprises two Buttons, one for taking a picture with the camera and uploading it to Firebase Storage, and the other one to download the image from Firebase Storage and show it on an ImageView.
Right now, I'm stuck with the upload function. I can take the picture and save it into the app directory. I would like to upload the saved picture into Firebase Storage.
My MainActivity.java (based on the Firebase developers tutorial) is the following:
package com.example.mathi.image;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
static final int REQUEST_TAKE_PHOTO = 1;
String mCurrentPhotoPath;
private Button btn_upload;
private Button btn_download;
//Firebase
FirebaseStorage storage;
StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_upload = (Button)findViewById(R.id.btn_upload);
btn_download = (Button)findViewById(R.id.btn_download);
btn_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
btn_download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.mathi.image.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
upload_photo();
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private void upload_photo(){
Uri file = Uri.fromFile(new File(mCurrentPhotoPath));
UploadTask uploadTask = storageReference.putFile(file);
// Register observers to listen for when the download is done or if
it fails
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, etc.
// ...
}
});
}
}
In the debugger I have the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.storage.UploadTask com.google.firebase.storage.StorageReference.putFile(android.net.Uri)' on a null object reference
at com.example.mathi.image.MainActivity.upload_photo(MainActivity.java:112)
Line 112 is the following line:
UploadTask uploadTask = storageReference.putFile(file);
The file is created on the local dir when I remove the upload() method. However, with the upload() method, the app crashes.
Does anyone knows what I am missing?
Try this code
btn_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CaptureImageFromCamera();
}
});
private void CaptureImageFromCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, 200);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
try {
if (requestCode == 200) {
Uri imageUri = data.getData();
sendImage(imageUri);
}
}
catch (Exception e) {
}
}else{
Toast.makeText(this, "Cancelled", Toast.LENGTH_SHORT).show();
}
}
private void sendImage(Uri imageUri){
UploadTask uploadTask = storageReference.putFile(imageUri);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
}
});
}

Unable to Store the image for the second time in to the firebase storage

I created a simple application in which the user can browse through his/her gallery and after selecting the image option for cropping the image appears for that I have used some image crop library which was available on GitHub.
All works fine I am able to crop the image and upload it after that image appears into the fire base storage, but when I try to upload the image for the second time with different image it doesn't get uploaded in the firebase storage and only the first uploaded image appears. Please help me anyone to do something with this code so that it could upload multiple images
XML Layout for MainActivity.java
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="imgcrop.example.com.androidimagecrop.MainActivity">
<ImageButton
android:id="#+id/imageview"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:background="#FFFFFF"
android:scaleType="centerCrop"
android:src="#android:drawable/ic_menu_report_image"
android:visibility="visible" />
<Button
android:id="#+id/uploadbutton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="UPLOAD IMAGE"
android:layout_marginTop="10dp"
/>
</LinearLayout>
MainActivity.java
package imgcrop.example.com.androidimagecrop;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
import com.firebase.client.Firebase;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.io.ByteArrayOutputStream;
public class MainActivity extends AppCompatActivity {
private ImageButton imageButton;
private Button uploadButton;
private static final int Image_request=1;
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://androidimagecrop.appspot.com");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Firebase.setAndroidContext(this);
//getting the reference of the views
imageButton = (ImageButton) findViewById(R.id.imageview);
uploadButton = (Button) findViewById(R.id.uploadbutton);
onImageViewClick(); // for selecting an Image from gallery.
onUploadButtonClick(); // for uploading the image to Firebase Storage.
}
protected void onImageViewClick(){
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent .setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,Image_request );
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == Image_request && resultCode == RESULT_OK){
Uri selectedImageUri = data.getData();
CropImage.activity(selectedImageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
if (null != selectedImageUri) {
// Get the path from the Uri
String path = getPathFromURI(selectedImageUri);
imageButton.setImageURI(selectedImageUri);
}
}
if (requestCode==CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
CropImage.ActivityResult result= CropImage.getActivityResult(data);
if(resultCode==RESULT_OK)
{
Uri resulturi=result.getUri();
imageButton.setImageURI(resulturi);
StorageReference filepath= storageRef.child(resulturi.getLastPathSegment());
}
else
{
if(resultCode==CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE)
{
Exception error=result.getError();
}
}
}
}
private String getPathFromURI(Uri contentUri) {
String res = null;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
protected void onUploadButtonClick(){
uploadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
storageRef = FirebaseStorage.getInstance().getReference().child("Profiles/image");
imageButton.setDrawingCacheEnabled(true);
imageButton.buildDrawingCache();
Bitmap bitmap = imageButton.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = storageRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(MainActivity.this, "TASK FAILED", Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Image Uploaded SucessFully", Toast.LENGTH_SHORT).show();
Uri downloadUrl =taskSnapshot.getDownloadUrl();
String DOWNLOAD_URL = downloadUrl.getPath();
}
});
}
});
}
}
But on changing the name of child reference which is in onUploadButtonClick() method, I am able to store different image
Here is my firebase storage section. I have created a root folder under which all images should get stored
replace
storageRef = FirebaseStorage.getInstance().getReference().child("Profiles/image"); with
replace storageRef = FirebaseStorage.getInstance().getReference().child("Profiles/"+System.currentTimeMillis());
Just provide different reference each time. For example use timestamp.

Android application starts from wrong activity & unable to upload image to firebase

First of all, sorry for any misunderstanding, typos since english is not my native language. I'm trying to write my first app in Android Studio.
What my app does: ( at least '' should do '' ) :
1 : User Login Screen as MainActivity
2 : if user credientals is true, user is directed to 2nd screen which is Request form.
3 : User puts his name-surname,subject,and explanation of subject.
4 : User CAN also upload pictures from imagebutton. it's not necessary.
5,6,7.... : this parts will be added to program. for now it's only 4 steps :D
Now my problems,
1 : When i run the app it starts from request form(2nd activity) even i clean project before running.
2 : When user type some input for name-surname,object and explanation and click send button, infos are stored in firebase database. But when i select an image for imagebutton it doesnt get stored in firebase. All authentication are set.
LOGIN SCREEN CODE
package com.example.jalea.requestingform;
import android.content.Intent;
import android.preference.EditTextPreference;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class MainActivity extends AppCompatActivity {
EditText edt_email,edt_sifre;
Button bt_giris;
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener authStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt_email = (EditText) findViewById(R.id.et_mail);
edt_sifre = (EditText) findViewById(R.id.et_sifre);
bt_giris = (Button) findViewById(R.id.btn_giris);
mAuth = FirebaseAuth.getInstance();
authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser() !=null){
Intent intent = new Intent(MainActivity.this,RequestActivity.class);
startActivity(intent);
//finish();
Log.w("1 : ","2.activity'e geçildi");
}
else{
Log.w("1 : ", "onAuthStateChanged:çıkış yaptı");
}
}
};
bt_giris.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SignIn();
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(authStateListener);
}
#Override
protected void onStop() {
super.onStop();
if(authStateListener != null) {
mAuth.removeAuthStateListener(authStateListener);
}
}
public void SignIn(){
String email = edt_email.getText().toString();
String sifre = edt_sifre.getText().toString();
if(TextUtils.isEmpty(email) || TextUtils.isEmpty(sifre)){
Toast.makeText(MainActivity.this,"Kullanıcı adı veya şifre alanı boş",Toast.LENGTH_LONG).show();
}
else{
mAuth.signInWithEmailAndPassword(email,sifre).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
Toast.makeText(MainActivity.this,"Kullanıcı adı veya şifre hatası ",Toast.LENGTH_LONG).show();
}
/**if(task.isSuccessful()){
Intent intent = new Intent(MainActivity.this,RequestActivity.class);
startActivity(intent);**/
}
});
}
}
}
REQUEST FORM CODE
package com.example.jalea.requestingform;
import android.content.Intent;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
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.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.File;
import java.net.URI;
public class RequestActivity extends AppCompatActivity {
FirebaseAuth mAuth;
FirebaseDatabase database;
DatabaseReference databaseReference;
FirebaseAuth.AuthStateListener authStateListener;
Button btn_cikis,btn_gonder;
ImageButton imgbutton;
EditText et_isim,et_konu,et_aciklama;
StorageReference storageReference;
Uri uri=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request);
btn_cikis = (Button) findViewById(R.id.btn_cikis);
storageReference = FirebaseStorage.getInstance().getReference();
et_isim= (EditText) findViewById(R.id.et_isim);
et_konu= (EditText) findViewById(R.id.et_konu);
et_aciklama = (EditText) findViewById(R.id.et_text);
database = FirebaseDatabase.getInstance();
btn_gonder = (Button) findViewById(R.id.btn_Send);
btn_cikis.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAuth = FirebaseAuth.getInstance();
mAuth.signOut();
startActivity(new Intent(RequestActivity.this,MainActivity.class));
}
});
btn_gonder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String isim = et_isim.getText().toString();
String konu = et_konu.getText().toString();
String aciklama = et_aciklama.getText().toString();
Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
databaseReference = database.getReference("Kullanicilar").child(isim);
if (!TextUtils.isEmpty(isim) && !TextUtils.isEmpty(konu) && !TextUtils.isEmpty(aciklama)) {
databaseReference.child("adSoyad").setValue(isim);
databaseReference.child("Konu").setValue(konu);
databaseReference.child("Aciklama").setValue(aciklama);
Toast.makeText(RequestActivity.this, "Talep gönderildi", Toast.LENGTH_LONG).show();
StorageReference filePath = storageReference.child("Resim").child(uri.getLastPathSegment());
filePath.putFile(uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
#SuppressWarnings("VisibleForTests")
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Toast.makeText(RequestActivity.this, "Resim eklendi", Toast.LENGTH_LONG).show();
}
});
filePath.putFile(uri).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w("İmage hata : ", e);
}
});
}
}
});
}
public void imageButtonClicked(View View){
Intent gallery_intent = new Intent(Intent.ACTION_GET_CONTENT);
gallery_intent.setType("image/*");
startActivityForResult(gallery_intent,2);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 2 && resultCode == RESULT_OK){
uri = data.getData();
imgbutton = (ImageButton) findViewById(R.id.imageButton);
imgbutton.setImageURI(uri);
}
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.jalea.requestingform">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".RequestActivity"></activity>
</application>
</manifest>
Your app bypasses the MainActivity since you have this the following code:
authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser() !=null){
Intent intent = new Intent(MainActivity.this,RequestActivity.class);
startActivity(intent);
//finish();
Log.w("1 : ","2.activity'e geçildi");
}
else{
Log.w("1 : ", "onAuthStateChanged:çıkış yaptı");
}
}
};
That code checks to see if the user is logged in and then skips the MainActivity and goes straight to RequestActivity. If you want the user to log in every time he/she opens the app then remove that code.
For your second problem, check out this sample code:
private void startPosting() {
mProgress.setMessage("Posting... ");
final String title_val = mPostTitle.getText().toString();
final String desc_val = mPostDesc.getText().toString();
final String cat_val = mPostCat.getSelectedItem().toString();
final String currency_val = mPostCurrency.getSelectedItem().toString();
final String amount_val = mPostAmount.getText().toString();
final String offer_val = mPostOffer.getText().toString();
final String pNumber_val = mPostPNumber.getText().toString();
if(!TextUtils.isEmpty(title_val) && !TextUtils.isEmpty(desc_val) && !TextUtils.isEmpty(cat_val)&& !TextUtils.isEmpty(currency_val) && !TextUtils.isEmpty(amount_val) &&!TextUtils.isEmpty(offer_val) && !TextUtils.isEmpty(pNumber_val) && mImageUri != null ){
mProgress.show();
StorageReference filepath = mStorage.child("Classifieds_Images").child(mImageUri.getLastPathSegment());
filepath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
final Uri downloadUrl = taskSnapshot.getDownloadUrl();
final DatabaseReference newPost = mDatabase.push();
mDatabaseUsers.child(mCurrentUser.getUid()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
newPost.child("name").setValue(title_val);
newPost.child("desc").setValue(desc_val);
newPost.child("category").setValue(cat_val);
newPost.child("currency").setValue(currency_val);
newPost.child("amount").setValue(amount_val);
newPost.child("offer").setValue(offer_val);
newPost.child("phone number").setValue(pNumber_val);
newPost.child("latitude").setValue(mLastKnownLocation.getLatitude());
newPost.child("longitude").setValue(mLastKnownLocation.getLongitude());
newPost.child("timestamp").setValue(ServerValue.TIMESTAMP);
newPost.child("image").setValue(downloadUrl.toString());
newPost.child("uid").setValue(mCurrentUser.getUid());
newPost.child("profileImage").setValue(dataSnapshot.child("profile_image").getValue());
newPost.child("username").setValue(dataSnapshot.child("username").getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
startActivity(new Intent(PostActivity.this, MainActivity.class));
}
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mProgress.dismiss();
}
});
}
}
#SuppressLint("NewApi")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
mImageUri = data.getData();
mSelectImage.setImageURI(mImageUri);
CropImage.activity(mImageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
}
break;
case 1:
if(resultCode == RESULT_OK){
mImageUri = data.getData();
activity(mImageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
mSelectImage.setImageURI(mImageUri);
}
break;
}
if (requestCode == CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
ActivityResult result = getActivityResult(data);
if (resultCode == RESULT_OK) {
mImageUri = result.getUri();
mSelectImage.setImageURI(mImageUri);
} else if (resultCode == CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
private void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Library",
"Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(
PostActivity.this);
builder.setTitle("Add Photo");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePicture.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePicture, 0);}
} else if (items[item].equals("Choose from Library")) {
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , 1);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
Hope this helps
For first :
It will start from your second activity only since you have written this
if(firebaseAuth.getCurrentUser() !=null){
Intent intent = new Intent(MainActivity.this,RequestActivity.class);
startActivity(intent);
//finish();
Log.w("1 : ","2.activity'e geçildi");
}
For sure reason you might have done sign in and its stores the auth to let the user directly go to next activity
For your second issue I am able to do it like this
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ConstantsCustomGallery.REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) {
//The array list has the image paths of the selected images
ArrayList<Image> images = data.getParcelableArrayListExtra(ConstantsCustomGallery.INTENT_EXTRA_IMAGES);
boolean showMinMax = true;
final MaterialDialog dialog = new MaterialDialog.Builder(this)
.title("Please wait")
.content("This won't take too long")
.progress(false, images.size(), showMinMax)
.show();
for (int i = 0; i < images.size(); i++) {
Uri uri = Uri.fromFile(new File(images.get(i).path));
StorageReference storage = FirebaseStorage.getInstance().getReference();
String Fpath = getFileName(uri) ;
//Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
StorageReference riversRef = storage.child(FirebaseAuth.getInstance().getCurrentUser().getEmail()+"/images/"+Fpath);
riversRef.putFile(uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
int maxUploading = dialog.getMaxProgress();
dialog.incrementProgress(1);
if(dialog.getCurrentProgress() == dialog.getMaxProgress()){
dialog.dismiss();
new MaterialDialog.Builder(HomePageActivity.this)
.title("DONE")
.content("Congratulations")
.show();
}
Uri downloadUrl = taskSnapshot.getDownloadUrl();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
String key = mDatabase.child("users").push().getKey();
Map<String, Object> postValues = new HashMap<String, Object>();
postValues.put("/user-profile/" + FirebaseAuth.getInstance().getCurrentUser().getEmail()
.substring(0, FirebaseAuth.getInstance().getCurrentUser().getEmail().indexOf("#"))+"/user-images/"+key,downloadUrl.toString());
postValues.put("/user-profile/" + FirebaseAuth.getInstance().getCurrentUser().getEmail()
.substring(0, FirebaseAuth.getInstance().getCurrentUser().getEmail().indexOf("#"))+"/imagesuploaded/",maxUploading);
mDatabase.updateChildren(postValues);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
}
});
}
dialog.setContent("Hurray!!!!");
}
}
For launching the app from the activity you want, enter below code in manifest.xml file for the activity
<activity
android:name="SpinnerActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

Capturing Image from Camera and Upload to Firebase

I am working on a simple blog app that allows the user to upload photo from phone gallery and descriptions to the Firebase Server. I am trying to modify my current project to allow the user to capture photo from camera and uploading it to the firebase server.
Currently, I am able to display the image that i have captured into imagebutton, however i am unable to post my image to the firebase server (The "submit post" button does not react to my onclick function).
I am suspecting there is some error in my startPosting() function or i did not encode the image correctly? Please help.
package simpleblog2.emily.example.com.simpleblog2;
import android.app.ProgressDialog;
import android.content.ContentProvider;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
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 java.io.File;
public class PostActivity extends AppCompatActivity {
private ImageButton mSelectImage;
private EditText mPostTitle;
private EditText mPostDesc;
private Button mSubmitBtn;
private ProgressDialog mProgress;
private DatabaseReference mDatabase;
private Uri mImageUri = null;
private static final int GALLERY_REQUEST = 1;
private static final int CAMERA_REQUEST_CODE = 1;
private StorageReference mStorage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
mStorage = FirebaseStorage.getInstance().getReference();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
mSelectImage = (ImageButton) findViewById(R.id.imageSelect);
mPostTitle = (EditText) findViewById(R.id.titleField);
mPostDesc = (EditText) findViewById(R.id.descField);
mSubmitBtn = (Button) findViewById(R.id.submitBtn);
mProgress = new ProgressDialog(this);
mSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent1, CAMERA_REQUEST_CODE);
intent1.setType("image/*");
/*
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GALLERY_REQUEST);
*/
}
});
mSubmitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startPosting();
}
});
}
private void startPosting() {
mProgress.setMessage("Posting to blog...");
final String title_val = mPostTitle.getText().toString().trim();
final String desc_val = mPostDesc.getText().toString().trim();
if (!TextUtils.isEmpty(title_val) && !TextUtils.isEmpty(desc_val) && mImageUri != null) {
mProgress.show();
StorageReference filepath = mStorage.child("Blog_Images").child(mImageUri.getLastPathSegment());
filepath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
DatabaseReference newPost = mDatabase.push();
newPost.child("title").setValue(title_val);
newPost.child("desc").setValue(desc_val);
newPost.child("image").setValue(downloadUrl.toString());
mProgress.dismiss();
startActivity(new Intent(PostActivity.this, MainActivity.class));
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if(requestCode == GALLERY_REQUEST && resultCode == RESULT_OK){
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
/* mImageUri = data.getData();
mSelectImage.setImageURI(mImageUri);
CropImage.activity(mImageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
*/
Bitmap mImageUri = (Bitmap) data.getExtras().get("data");
mSelectImage.setImageBitmap(mImageUri);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
mSelectImage.setImageURI(resultUri);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
}
I have found a solution to my question, i realized that i can get my captured data using the function of data.getData() instead of using the Bitmap function:
mImageUri = data.getData();
mSelectImage.setImageURI(mImageUri);
Also, Previously i did not realized that my 'crop' function could not work because i am missing of:
mImageUri = resultUri;
I realized that there is an issue that if i did not crop my captured image, the fire-base could not handle the high resolution (Or storage size? and it will be loading very slow/image did not appear), This can be resolve by the 'cropping' function.
The final code is stated below:
Thanks all for your help.
package simpleblog2.emily.example.com.simpleblog2;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.Image;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
public class PostActivity extends AppCompatActivity {
private ImageButton mSelectImage;
private EditText mPostTitle;
private EditText mPostDesc;
private Button mSubmitBtn;
private ProgressDialog mProgress;
private DatabaseReference mDatabase;
private Uri mImageUri = null;
private static final int GALLERY_REQUEST =1;
private static final int CAMERA_REQUEST_CODE=1;
private StorageReference mStorage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
mStorage = FirebaseStorage.getInstance().getReference();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
mSelectImage = (ImageButton) findViewById(R.id.imageSelect);
mPostTitle = (EditText) findViewById(R.id.titleField);
mPostDesc = (EditText) findViewById(R.id.descField);
mSubmitBtn = (Button) findViewById(R.id.submitBtn);
mProgress = new ProgressDialog(this);
mSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
//startActivityForResult(intent,CAMERA_REQUEST_CODE);
/*
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GALLERY_REQUEST);
*/
}
});
mSubmitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startPosting();
}
});
}
private void startPosting(){
mProgress.setMessage("Posting to blog...");
final String title_val = mPostTitle.getText().toString().trim();
final String desc_val = mPostDesc.getText().toString().trim();
if(!TextUtils.isEmpty(title_val)&&!TextUtils.isEmpty(desc_val) && mImageUri != null){
mProgress.show();
StorageReference filepath = mStorage.child("Blog_Images").child(mImageUri.getLastPathSegment());
filepath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl =taskSnapshot.getDownloadUrl();
DatabaseReference newPost = mDatabase.push();
newPost.child("title").setValue(title_val);
newPost.child("desc").setValue(desc_val);
newPost.child("image").setValue(downloadUrl.toString());
mProgress.dismiss();
startActivity(new Intent(PostActivity.this,MainActivity.class));
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if(requestCode == GALLERY_REQUEST && resultCode == RESULT_OK){
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK){
mImageUri = data.getData();
mSelectImage.setImageURI(mImageUri);
CropImage.activity(mImageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(this);
/* Bitmap mImageUri1 = (Bitmap) data.getExtras().get("data");
mSelectImage.setImageBitmap(mImageUri1);
Toast.makeText(this, "Image saved to:\n" +
data.getExtras().get("data"), Toast.LENGTH_LONG).show();
*/
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
mSelectImage.setImageURI(resultUri);
mImageUri = resultUri;
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
}
Before it was if auth != null but I changed it to if true so the if will always evaluate true.
private void uploadFile() {
//if there is a file to upload
if (filePath != null) {
//displaying a progress dialog while upload is going on
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading");
progressDialog.show();
StorageReference riversRef = storageReference.child("Blog_Images.jpg");
riversRef.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//if the upload is successfull
//and displaying a success toast
Toast.makeText(getApplicationContext(), "File Uploaded ", Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
//if the upload is not successfull
//hiding the progress dialog
progressDialog.dismiss();
//and displaying error message
Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
//calculating progress percentage
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
//displaying percentage in progress dialog
progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
}
});
}
//if there is not any file
else {
//you can display an error toast
}
}
Your class field mImageUri is never initialized. You put received bitmap in local field, called the same as the class field.
Bitmap mImageUri = (Bitmap) data.getExtras().get("data");
mSelectImage.setImageBitmap(mImageUri);
Therefore, the condition is never true.
if (!TextUtils.isEmpty(title_val) && !TextUtils.isEmpty(desc_val) && mImageUri != null)
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
/* mImageUri = data.getData();
mSelectImage.setImageURI(mImageUri);
CropImage.activity(mImageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
*/
Bitmap mImageUri = (Bitmap) data.getExtras().get("data");
mSelectImage.setImageBitmap(mImageUri);
}
There is a chance that your URI is null. I assume, this is the problem.
Unless you do it somewhere else?
The image might be loaded because the requestCode = CAMERA_REQUEST_CODE but NOT CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE.
I am going to post below a code I used to do what you ask, but first few things you need to understand.
From android version 7 using Uri.parseFromFile(file) return a error because google want to restrict your access. From now on if you want to get file uri you should use FileProvider
declare permmisions and FileProvider in your manifest:
//File provider declaration in manifest.
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.hadas.yotam.manchworkers.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
//in new xml file define the location you need permmision to, the code below give you permmision for any external file.
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
so now when you upload use the global Uri variable if onActivityResault is successful, here is the code:
if(Build.VERSION.SDK_INT>=24) {
String file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/" + Calendar.getInstance().getTimeInMillis() + ".jpg";
File file1 = new File(file);
photoURI = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider", file1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
}
Then in your onActivityResult you do check if your photoURI = null, if its true (its null)
use photoURI = data.getData();
//if phone android version greater or equal to Marshmelo
if(Build.VERSION.SDK_INT>Build.VERSION_CODES.M){
//check if have permmission to write to external + permmision to camera
if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA)== PackageManager.PERMISSION_GRANTED){
//if its have permission then new intent to capture image
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//if android version >= 24 (Android Nugget)
if(Build.VERSION.SDK_INT>=24) {
//create new String to pictures directory and set the file name to current_time.jpg
String file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/" + Calendar.getInstance().getTimeInMillis() + ".jpg";
File file1 = new File(file);
//set GLOBAL variable Uri from the file using FileProvider
photoURI = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider", file1);
//add the file location the intent (the picture will be save to this file)
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
}
tagIntent = CAPTURE_RESAULT;
//else - dont have permission, request for permission
}else{
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA},CAPTURE_RESAULT);
}
else -
}else{
// same thing only without FileProvider (FileProvider only required since Nugget)
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/" + Calendar.getInstance().getTimeInMillis() + ".jpg";
File file1 = new File(file);
photoURI = Uri.fromFile(file1);
intent.putExtra(MediaStore.EXTRA_OUTPUT,photoURI);
tagIntent = CAPTURE_RESAULT;
}
//if phone can handle the intent, start the intent for resault.
if(intent.resolveActivity(getPackageManager())!=null) {
startActivityForResult(intent,tagIntent);
}

How to add a picture from local storage to update Firebase user's photo profile using .setPhotoUri in Android?

I have an error while updating user's photo profile in Firebase. I want to upload user's local photo to Firebase user's profile. This is my activity.
package naufal.com.tugasakhir;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.bumptech.glide.util.Util;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.UserProfileChangeRequest;
import java.text.ParseException;
public class EditProfile extends AppCompatActivity {
private EditText mUsername;
private Button mUpdateProfileBtn;
private ImageButton mImageBtn;
FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser();
private static final int GALLERY_REQUEST = 1;
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
private Uri imageUri2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
mUsername = (EditText) findViewById(R.id.userName);
mUpdateProfileBtn = (Button) findViewById(R.id.updateProfileBtn);
mImageBtn = (ImageButton) findViewById(R.id.imageField);
String username = user.getDisplayName();
mUsername.setText(username);
mUpdateProfileBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//updating user's profile data
String nameUser = mUsername.getText().toString();
UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
.setPhotoUri(Uri.parse(imageUri2))
.setDisplayName(nameUser)
.build();
if(TextUtils.isEmpty(nameUser)){
mUsername.setError("Enter a username");
}
if(imageUri2 == null){
Toast.makeText(EditProfile.this, "Error updating image",
Toast.LENGTH_SHORT).show();
}
//if the field is not null, process continue to update profile
else {
mUser.updateProfile(profileUpdate)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(Task<Void> task) {
if (task.isSuccessful()) { //success on updating user profile
Toast.makeText(EditProfile.this, "Update Profile Succedeed",
Toast.LENGTH_SHORT).show();
startActivity(new Intent(EditProfile.this, HomePage.class));
} else { //failed on updating user profile
Toast.makeText(EditProfile.this, "Update Profile Failed",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
//setting image for user
mImageBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GALLERY_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK){
Uri imageUri = data.getData();
mImageBtn.setImageURI(imageUri);
imageUri2 = imageUri;
} else {
Toast.makeText(EditProfile.this, "Failed showing image",
Toast.LENGTH_SHORT).show();
}
}
}
This is how I get the user's profile from Firebase:
String email = user.getEmail();
String username = user.getDisplayName();
Uri uriImage = user.getPhotoUrl();
mUserName.setText(username);
mUserStat.setText(email);
mUriImageProfile.setImageURI(uriImage);
Thanks for the response.
You need to get this image from your device, put the file in firebase and then use it as a link
You can check my github to see it working https://github.com/chrystianmelo/appmodule
The code
**PROFILE_SERVICES**
public void putFile(Bitmap bitmap){
FirebaseStorage storage = FirebaseStorage.getInstance();
final StorageReference storageRef = storage.getReference();
final StorageReference mountainsRef = storageRef.child("images/"+getUID()+".jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = mountainsRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.i("chrys", "Img not set");
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mountainsRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onSuccess(Uri uri) {
setProfilePic(uri);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.i("chrys", "Img set but whereeee");
// Handle any errors
}
});
}
});
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void setProfilePic(Uri uri){
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setPhotoUri(uri)
.build();
user.updateProfile(profileUpdates);
}
**PROFILE_ACTIVITY**
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PICK_IMAGE) {
Bitmap bitmap;
try {
ProfileServices services = new ProfileServices();
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(Objects.requireNonNull(data.getData())));
services.putFile(bitmap);
Log.i("chrys", "GET FROM LOCAL.: OK");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("chrys", "GET FROM LOCAL.: RUIM");
}
}
}
}
#SuppressLint("IntentReset")
public void getImg(){
Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
getIntent.setType("image/*");
#SuppressLint("IntentReset") Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
Intent chooserIntent = Intent.createChooser(getIntent, "Select Image");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent});
startActivityForResult(chooserIntent, PICK_IMAGE);
}
private static class DownLoadImageTask extends AsyncTask<String,Void,Bitmap> {
#SuppressLint("StaticFieldLeak")
ImageView imageView;
DownLoadImageTask(ImageView imageView){
this.imageView = imageView;
}
/*
doInBackground(Params... params)
Override this method to perform a computation on a background thread.
*/
protected Bitmap doInBackground(String...urls){
String urlOfImage = urls[0];
Bitmap logo = null;
try{
InputStream is = new URL(urlOfImage).openStream();
/*
decodeStream(InputStream is)
Decode an input stream into a bitmap.
*/
logo = BitmapFactory.decodeStream(is);
}catch(Exception e){ // Catch the download exception
e.printStackTrace();
}
return logo;
}
/*
onPostExecute(Result result)
Runs on the UI thread after doInBackground(Params...).
*/
protected void onPostExecute(Bitmap result){
imageView.setImageBitmap(result);
}
}
}
<!-- begin snippet: js hide: false console: true babel: false -->

Categories

Resources