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);
}
Related
I am facing an issue which I do not understand. I am taking a picture then creating a PNG image file as per code that follows but somewhere down the line a random string is being added to the filename which causes me all sorts of issues. For example (as per tutorials I have found): I create an image called dimage_(generated timestamp) and save the string to shared preferences and the image in getExternalFilesDir(Environment.DIRECTORY_PICTURES). In shared preferences the string is correct but the file has the above mentioned string appended.
Eg:
The generated filename string saved in shared prefs:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="driver_picture">dimage_20190610_065509</string>
</map>
Whereas the file checked with adb results as:
127|generic_x86:/storage/emulated/0/Android/data/africa.mykagovehicledrivers/files/Pictures $ ls
dimage_20190610_0655091215099619.png
generic_x86:/storage/emulated/0/Android/data/africa.mykagovehicledrivers/files /Pictures $
I have no clue where the 1215099619 extra part comes from!
This is the code of the activity:
package africa.mykagovehicledrivers;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.yalantis.ucrop.UCrop;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class RegisterDriverImage extends AppCompatActivity {
String currentPhotoPath;
final int REQUEST_TAKE_PHOTO = 1;
final int CAMERA_PERMISSIONS = 3;
Activity activity = this;
ImageView imgTakePicture, imgDriver;
Button btnContinueDriver;
ProgressBar prgImage;
SharedPreferences prefs;
SharedPreferences.Editor edit;
String imageFileName;
Tools t;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == CAMERA_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// All good so launch take picture from here
dispatchTakePictureIntent();
} else {
// Permission denied. Warn the user and kick out of app
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.permsDeniedCameraTitle);
builder.setMessage(R.string.permsDeniedCameraMessage);
builder.setCancelable(false);
builder.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finishAffinity();
}
});
builder.create().show();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
Uri starturi = Uri.fromFile(new File(currentPhotoPath));
Uri destinationuri = Uri.fromFile(new File(currentPhotoPath));
UCrop.Options options = AppConstants.setUcropOptions(activity);
UCrop.of(starturi, destinationuri).withOptions(options).start(activity);
}
// On result from cropper add to image view
if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
prgImage.setVisibility(View.VISIBLE);
final Uri resultUri = UCrop.getOutput(data);
assert resultUri != null;
File imgFile = new File(resultUri.getPath());
Picasso.Builder builder = new Picasso.Builder(getApplicationContext());
builder.listener(new Picasso.Listener() {
#Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
exception.printStackTrace();
}
});
builder.build().load(imgFile).into(imgDriver, new Callback() {
#Override
public void onSuccess() {
Log.d("-------->", "onSuccess: CROPPED!");
prgImage.setVisibility(View.INVISIBLE);
btnContinueDriver.setEnabled(true);
}
#Override
public void onError(Exception e) {
e.printStackTrace();
}
});
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_driver_image);
prefs = getSharedPreferences("mykago-driver", Context.MODE_PRIVATE);
edit = prefs.edit();
imgTakePicture = findViewById(R.id.imgTakePicture);
imgDriver = findViewById(R.id.imgDriver);
btnContinueDriver = findViewById(R.id.btnContinueDriver);
prgImage = findViewById(R.id.prgImage);
t = new Tools(getApplication(), getApplicationContext(), this);
imgTakePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
imgDriver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
btnContinueDriver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edit.putString("driver_picture", imageFileName);
edit.putString("nextstep", "drivinglicense");
edit.apply();
Intent drivinglicense = new Intent(getApplicationContext(), RegisterDrivingLicense.class);
startActivity(drivinglicense);
finish();
}
});
// Always ask for camera permissions
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.CAMERA }, CAMERA_PERMISSIONS);
}
}
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
Log.d("IMAGE CREATION FAILED", ex.toString());
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"africa.mykagovehicledrivers.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
imageFileName = "dimage_" + timeStamp;
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName,
".png",
storageDir
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
}
As per code I am using String imageFileName; to save the path and then use it in the button click action to save it into shared preferences.
Thanks!
Found out the reasin. createTempFile does this. Switched to new File() and this solved the issue.
This is the error that I'm getting everytime I press the upload button after selecting an image from the device
I/System.out:e:java.lang.ClassNotFoundException:com.mediatek.cta.CtaHttp
W/System: ClassLoader referenced unknown path:system/framework/mediatek-cta.jar
While trying to upload an image with a text parameter from the app to SQL database.
MainAtivity.java
package com.example.veekalp.imageupload;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
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.Toast;
import net.gotev.uploadservice.MultipartUploadRequest;
import net.gotev.uploadservice.UploadNotificationConfig;
import java.io.IOException;
import java.util.UUID;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//Declaring views
private Button buttonChoose;
private Button buttonUpload;
private ImageView imageView;
private EditText editText;
//Image request code
private int PICK_IMAGE_REQUEST = 1;
//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
//Bitmap to get image from gallery
private Bitmap bitmap;
//Uri to store the image uri
private Uri filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Requesting storage permission
requestStoragePermission();
//Initializing views
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
imageView = (ImageView) findViewById(R.id.imageView);
editText = (EditText) findViewById(R.id.editTextName);
//Setting clicklistener
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
/*
* This is the method responsible for image upload
* We need the full image path and the name for the image in this method
* */
public void uploadMultipart() {
//getting name for the image
String name = editText.getText().toString().trim();
//getting the actual path of the image
String path = getPath(filePath);
//Uploading code
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL)
.addFileToUpload(path, "image") //Adding file
.addParameter("name", name) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
//method to show file chooser
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
//handling the image chooser activity result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
//method to get the file path from uri
public 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.close();
cursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
}
//Requesting permission
private void requestStoragePermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
return;
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
//And finally ask for the permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
//This method will be called when the user will tap on allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onClick(View v) {
if (v == buttonChoose) {
showFileChooser();
}
if (v == buttonUpload) {
uploadMultipart();
}
}
}
I am developing an android mobile application in which i am trying to upload the picture on server from android app. The .php files are working fine but the java code is not working and showing error that path is null. I have tried the several types of code but not working at all. Please help.
Thank you
Here is the code.
package com.example.pt_connect.attachmentuploadingandgetting;
import android.Manifest;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
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.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import net.gotev.uploadservice.MultipartUploadRequest;
import net.gotev.uploadservice.UploadNotificationConfig;
import java.io.IOException;
import java.util.UUID;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//Declaring views
private Button buttonChoose;
private Button buttonUpload;
private ImageView imageView;
private EditText editText;
//Image request code
private int PICK_IMAGE_REQUEST = 1;
//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
//Bitmap to get image from gallery
private Bitmap bitmap;
//Uri to store the image uri
private Uri filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Requesting storage permission
requestStoragePermission();
//Initializing views
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
imageView = (ImageView) findViewById(R.id.imageView);
editText = (EditText) findViewById(R.id.editTextName);
//Setting clicklistener
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
/*
* This is the method responsible for image upload
* We need the full image path and the name for the image in this method
* */
**public void uploadMultipart() {
//getting name for the image
String name = editText.getText().toString().trim();
//getting the actual path of the image
String path = getPath(MainActivity.this,filePath);
//Uploading code
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL)
.addFileToUpload(path, "image") //Adding file
.addParameter("name", name) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}**
//method to show file chooser
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
//handling the image chooser activity result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
//Bitmap photo = (Bitmap) data.getData().getPath();
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
//method to get the file path from uri
public String getPath(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
//Requesting permission
private void requestStoragePermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
return;
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
//And finally ask for the permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
//This method will be called when the user will tap on allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onClick(View v) {
if (v == buttonChoose) {
showFileChooser();
}
if (v == buttonUpload) {
uploadMultipart();
}Error
}
}
You have to get the file path like below
String FilePath = data.getData().getPath();
String FileName = data.getData().getLastPathSegment();
on the onActivityResult. I made change to your code. Check below
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
//Bitmap photo = (Bitmap) data.getData().getPath();
filePath = data.getData().getPath();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I think it will work. If not comment here, we will go for another method
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);
}
}
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>