Image not retaining on rotating the screen - android

I am trying to add an image from the gallery to an image view. It has been added but the image is disappearing from the image view on rotating the screen. The image has been saved to firebase. How to save the activity state? I have searched for it but did not find the relevant answer.Can anyone help me out to solve the problem.
public class skcreateac extends AppCompatActivity
{
static final int PICK_IMAGE_REQUEST = 1;
private EditText sketac1;
private EditText sksetac1;
private EditText sketac2;
private EditText sketac3;
private EditText sketac4;
private EditText sketac5;
private Button skbt;
private Spinner spac;
private ImageView skimg;
private StorageReference skdbimg, fp;
private Firebase skrootac1;
private String strsk, skurl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_skcreateac);
spac = (Spinner)findViewById(R.id.spinner2);
String cities[] = new String[]{"Hyderabad", "Warangal"};
ArrayAdapter<String> cityadapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, cities);
spac.setAdapter(cityadapter);
skimg = (ImageView) findViewById(R.id.skimg);
skdbimg = FirebaseStorage.getInstance().getReference();
sketac1 = (EditText) findViewById(R.id.skonac);
sksetac1 = (EditText) findViewById(R.id.sksncac);
sketac2 = (EditText) findViewById(R.id.skphcac);
sketac3 = (EditText) findViewById(R.id.sksaddress);
sketac4 = (EditText) findViewById(R.id.skpwcac);
sketac5 = (EditText) findViewById(R.id.skpwrcac);
skbt = (Button) findViewById(R.id.bsu);
strsk = getIntent().getExtras().getString("value");
String url1 = "https://my-app2-a14eb.firebaseio.com/Shopkeepers/";
String url2 = strsk;
skurl = url1 + url2;
skrootac1 = new Firebase(skurl);
skimg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent skimg = new Intent(Intent.ACTION_PICK);
skimg.setType("image/*");
startActivityForResult(skimg, PICK_IMAGE_REQUEST);
}
});
skbt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s1 = sketac1.getText().toString();
if (sketac1.getText().length() == 0) {
sketac1.setError("Kindly enter your Name");
}
Firebase childac1 = skrootac1.child("Name");
childac1.setValue(s1);
String ss1 = sksetac1.getText().toString();
if (sksetac1.getText().length() == 0) {
sksetac1.setError("Kindly enter your ShopName");
}
Firebase childsac1 = skrootac1.child("ShopName");
childsac1.setValue(ss1);
String s2 = sketac2.getText().toString();
long i = Long.parseLong(s2);
int j = 0;
while (i > 0) {
i = i / 10;
j++;
}
if (j == 10) {
Firebase childac2 = skrootac1.child("Phone");
childac2.setValue(s2);
} else {
Toast.makeText(skcreateac.this, "Enter valid Mobile number", Toast.LENGTH_LONG).show();
}
String s3 = spac.getSelectedItem().toString();
Firebase childac3 = skrootac1.child("City");
childac3.setValue(s3);
String s4 = sketac3.getText().toString();
Firebase childac4 = skrootac1.child("Address");
childac4.setValue(s4);
String s5 = sketac4.getText().toString();
String s6 = sketac5.getText().toString();
if (s5.equals(s6)) {
Firebase childac5 = skrootac1.child("Password");
childac5.setValue(s5);
} else {
Toast.makeText(skcreateac.this, "Confirm Password field doesnot match with Create Password field", Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
final Uri uri = data.getData();
fp = skdbimg.child("SKPhotos").child(strsk);
fp.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Picasso.get().load(uri).fit().centerCrop().into(skimg);
Toast.makeText(skcreateac.this, "Uploaded photo", Toast.LENGTH_LONG).show();
}
});
}
}

Add following -
#Override
protected void onSaveInstanceState (Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("outputFileUri", photoURI);
}
Make a private URI photoURI = null; in your activity.
Then in your onCreate() add do
#Override
protected void onCreate(Bundle savedInstanceState){
// your other codes
skrootac1 = new Firebase(skurl);
// your other codes
if (savedInstanceState != null)
{
photoURI= savedInstanceState.getParcelable("outputFileUri");
setImage(photoURI);
}
}
private void setImage(final Uri uri){
fp = skdbimg.child("SKPhotos").child(strsk);
fp.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Picasso.get().load(uri).fit().centerCrop().into(skimg);
Toast.makeText(skcreateac.this, "Uploaded photo", Toast.LENGTH_LONG).show();
}
});
}
And finally, change your onActivityResult()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
photoURI = data.getData();
setImage(photoURI);
}
}

Related

How can I upload videos in Firebase Storage?

I'm trying to upload some pictures and videos from the gallery to the Firebase Storage. I tried For the images I had no problems, but for the videos yes. I tried with several tutorial found on google but none worked.
How could I do? This is the code I have written so far:
public class GalleryActivity extends AppCompatActivity {
private Button chooseImage;
private Button chooseVideo;
private Button sendToCloud;
private ImageView selectedImage;
private VideoView selectedVideo;
private TextView txtDescription;
private static final int PICK_IMAGE = 100;
private static final int PICK_VIDEO = 200;
private Uri mImageUri;
//Firebase stuff
private FirebaseStorage storage;
private StorageReference storageReference;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
txtDescription = findViewById(R.id.diplay);
selectedImage = findViewById(R.id.image_taken);
selectedVideo = findViewById(R.id.video_taken);
chooseImage = findViewById(R.id.imageBtn);
chooseVideo = findViewById(R.id.videoBtn);
sendToCloud = findViewById(R.id.send_to_cloud);
// get the Firebase storage reference
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
chooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chooseImageFromGallery();
}
});
chooseVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chooseVideoFromGallery();
}
});
sendToCloud.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(selectedImage.getDrawable() != null) {
uploadImage();
}
//check if videoview is empty and call uploadVideo()
}
});
}
private void chooseVideoFromGallery() {
Intent i = new Intent();
i.setType("video/*");
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(i, "choose App"), PICK_VIDEO);
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && data != null) {
if (requestCode == PICK_IMAGE) {// img from gallery
previewImage(data);
} else if (requestCode == PICK_VIDEO) {
previewVideo(data);
}
}
}
private void previewVideo() {
try {
txtDescription.setVisibility(View.GONE);
selectedImage.setVisibility(View.GONE);
selectedVideo.setVisibility(View.VISIBLE);
selectedVideo.start();
} catch (Exception e) {
e.printStackTrace();
}
}
private void previewImage(Intent data) {
try {
txtDescription.setVisibility(View.GONE);
selectedVideo.setVisibility(View.GONE);
selectedImage.setVisibility(View.VISIBLE);
Uri imgUri = data.getData();
InputStream imageStream = GalleryActivity.this.getContentResolver().openInputStream(imgUri);//2
Bitmap selectedImageBitmap = BitmapFactory.decodeStream(imageStream);//3}
mImageUri = imgUri;
selectedImage.setImageBitmap(selectedImageBitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Thanks in advance to everyone
This is the working code:
if (resultCode == RESULT_OK) {
if (requestCode == PICK_VIDEO) {
Uri videoUri= data.getData();
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
StorageReference storageRef = FirebaseStorage.getInstance().getReference();
String filename = "give a unique filename for each";
videoRef = storageRef.child("/videos/" + uid+ "/" + filename);
uploadVideo(videoUri);
}
}
Upload Video here:
private void uploadVideo(Uri videoUri) {
if(videoUri != null){
UploadTask uploadTask = videoRef.putFile(videoUri);
uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>({
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful())
Toast.makeText(getContext(), "Video Upload Completed", Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
updateProgress(taskSnapshot);
}
});
}else {
Toast.makeText(getContext(), "upload failed!", Toast.LENGTH_SHORT).show();
}
}
// StorageReference videoRef;

Keep getting error when trying to select profile pic for current user Firebase Auth

I keep getting the same error and the app stops working when I try and select an image to upload for user using google firease firebaseAuth on android. Here is the error I keep getting: Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.common.internal.zzbq"
My code is as follows:
public class StudentAccount extends AppCompatActivity {
private static final int CHOOSE_IMAGE = 101;
public static final int CAMERA_REQUEST_CODE = 10;
public static final int PROFILE_PIC_REQUEST_CODE = 20;
private Button button, signout;
private FirebaseAuth mAuth;
TextView username;
ImageView imageView;
EditText editText;
Uri uriProfileImage;
ProgressBar progressBar;
String profileImageUrl;
ListView listView;
private List<String> userList = new ArrayList<>();
private final int BARCODE_RECO_REQ_CODE = 200;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_account);
mAuth = FirebaseAuth.getInstance();
signout = (Button) findViewById(R.id.SIGNOUT3);
username = (TextView) findViewById(R.id.welcomeText2);
//Check if user i already logged in or not
if (mAuth.getCurrentUser() == null){
finish();
startActivity(new Intent(getApplicationContext(),SignInActivity.class));
}
//Fetching display name of current user and setting to activity
FirebaseUser user = mAuth.getCurrentUser();
if (user != null){
username.setText("Welcome " +user.getEmail());
}
signout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAuth.signOut();
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
imageView = findViewById(R.id.imageView);
progressBar = findViewById(R.id.progressbar);
mAuth = FirebaseAuth.getInstance();
button = findViewById(R.id.VIEW_ATTENDANCE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openViewMyAttendance();
}
});
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showImageChooser();
}
});
findViewById(R.id.buttonSave).setOnClickListener( new View.OnClickListener(){
#Override
public void onClick(View view) {
saveUserInformation();
}
private void saveUserInformation() {
String displayName = editText.getText().toString();
if (displayName.isEmpty()){
editText.setError("Username required");
editText.requestFocus();
return;
}
FirebaseUser user = mAuth.getCurrentUser();
if (user != null && profileImageUrl != null){
UserProfileChangeRequest profile = new UserProfileChangeRequest.Builder()
.setDisplayName(displayName).setPhotoUri(Uri.parse(profileImageUrl)).build();
user.updateProfile(profile).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(StudentAccount.this, "Profile Updated", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CHOOSE_IMAGE && resultCode == RESULT_OK && data != null && data.getData() !=null){
uriProfileImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uriProfileImage);
imageView.setImageBitmap(bitmap);
uploadImageToFirebaseStorage();
} catch (IOException e) {
e.printStackTrace();
}
}
if (requestCode == BARCODE_RECO_REQ_CODE){
if (resultCode == RESULT_OK){
Bitmap photo = (Bitmap)data.getExtras().get("data");
barcodeRecognition(photo);
}
}
}
private void barcodeRecognition(Bitmap photo) {
FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(photo);
FirebaseVisionBarcodeDetector detector = FirebaseVision.getInstance()
.getVisionBarcodeDetector();
Task<List<FirebaseVisionBarcode>> result = detector.detectInImage(image)
.addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionBarcode>>() {
#Override
public void onSuccess(List<FirebaseVisionBarcode> barcodes) {
for (FirebaseVisionBarcode barcode: barcodes) {
Rect bounds = barcode.getBoundingBox();
Point[] corners = barcode.getCornerPoints();
String rawValue = barcode.getRawValue();
int valueType = barcode.getValueType();
Toast.makeText(StudentAccount.this, rawValue, Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(StudentAccount.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
});
}
private void uploadImageToFirebaseStorage() {
final StorageReference profileImageRef = FirebaseStorage.getInstance().getReference
("profilepics/"+System.currentTimeMillis() + ".jpg");
if (uriProfileImage != null){
progressBar.setVisibility(View.VISIBLE);
profileImageRef.putFile(uriProfileImage).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressBar.setVisibility(View.GONE);
profileImageUrl = taskSnapshot.getDownloadUrl().toString();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressBar.setVisibility(View.GONE);
Toast.makeText(StudentAccount.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
private void loadUserInformation() {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
updateProfilePermissions();
} else {
String[] permissionRequested = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissionRequested, PROFILE_PIC_REQUEST_CODE);
}
}
private void updateProfilePermissions() {
FirebaseUser user = mAuth.getCurrentUser();
if (user.getPhotoUrl() != null) {
Glide.with(this).load(user.getPhotoUrl().toString()).into(imageView);
}
if (user.getDisplayName() != null) {
editText.setText(user.getDisplayName());
}
}
private void showImageChooser(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Profile Image"),CHOOSE_IMAGE);
}
#Override
protected void onPause(){
super.onPause();
}
public void barcodeReco(View v) {
if(checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
callsCamera();
} else {
String[] permissionRequested = {Manifest.permission.CAMERA};
requestPermissions(permissionRequested, CAMERA_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == CAMERA_REQUEST_CODE){
if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
callsCamera();
} else {
Toast.makeText(this, getString(R.string.unable_to_invoke_camera), Toast.LENGTH_LONG).show();
}
} else if (requestCode == PROFILE_PIC_REQUEST_CODE){
if (grantResults [0] == PackageManager.PERMISSION_GRANTED){
loadUserInformation();
} else {
Toast.makeText( this, getString(R.string.Unable_to_update_profile), Toast.LENGTH_LONG).show();
}
}
}
private void callsCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,BARCODE_RECO_REQ_CODE);
}
public void openViewMyAttendance () {
Intent intent = new Intent(this, ViewMyAttendance.class);
startActivity(intent);
}
}

How to set up an image upload button?

I want to build this app, where you can select one picture from camera or from gallery. This picture is not set as ImageView. Now how can I build an OnClickListener with the uploadbutton, which uploads the image to firebase?
public class MainActivity extends AppCompatActivity {
private StorageReference mStorage;
private static final int GALLERY_INTENT = 2;
private ImageButton mCamera;
private ImageButton mGallery;
private ImageView mImageview;
private static final int CAMERA_REQUEST_CODE = 1;
private ImageButton mUpload;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStorage = FirebaseStorage.getInstance().getReference();
mGallery = (ImageButton) findViewById(R.id.UpGallery);
mUpload = (ImageButton) findViewById(R.id.UpImage);
mCamera = (ImageButton) findViewById(R.id.UpCamera);
mImageview = (ImageView) findViewById(R.id.imageView1);
mImageview.buildDrawingCache();
mImageview.setDrawingCacheEnabled(true);
mImageview.buildDrawingCache();
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
File newdir = new File(dir);
newdir.mkdirs();
mGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_INTENT);
}
});
mCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent1, CAMERA_REQUEST_CODE);
}
});
mUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK){
final Uri uri = data.getData();
Picasso.with(MainActivity.this).load(uri).fit().centerCrop().into(mImageview);
}
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK){
Bitmap photo = (Bitmap) data.getExtras().get("data");
mImageview.setImageBitmap(photo);
Uri uri1 = data.getData();
Picasso.with(MainActivity.this).load(uri1).fit().centerCrop().into(mImageview);
}
}
}
final StorageReference storageRef = FirebaseStorage.getInstance().getReferenceFromUrl("gs://{your-storage-name-from-firebase}.appspot.com");
mImageview.setDrawingCacheEnabled(true);
mImageview.buildDrawingCache();
Bitmap bitmap = mImageview .getDrawingCache();
ByteArrayOutputStream baas = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baas);
byte[] data = baas.toByteArray();
UploadTask uploadTask = storageRef.child("{image-folder}").child("unique-id-image").putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(MainActivity.this, "Picture upload failed", Toast.LENGTH_LONG).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String downloadUrl = taskSnapshot.getDownloadUrl();
}
});
Hope this helps.

push data camera to firebase android studio

Hi i'm having trouble entering data into firebase.
I can insert image data from album to firebase but i can not put image data from camera to firebase that i just photo. Please help me :)
//activitylapor
public class Lapor extends AppCompatActivity {
private ImageButton mSelectImage;
private EditText mPostNamaPelapor;
private EditText mPostNoTelpon;
private EditText mPostLokasiKejadian;
private EditText mPostKeteranganBencana;
private EditText mPostWaktuBencana;
private Uri mImageUri = null;
//private static final int GALLERY_REQUEST = 1;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private String userChoosenTask;
private ImageView ivImage;
private StorageReference mStorage;
private DatabaseReference mDatabase;
private ProgressDialog mProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mStorage = FirebaseStorage.getInstance().getReference();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Lapor");
mSelectImage = (ImageButton) findViewById(R.id.imageSelect);
mPostNamaPelapor = (EditText) findViewById(R.id.namaPelapor);
mPostNoTelpon = (EditText) findViewById(R.id.noTelpon);
mPostLokasiKejadian = (EditText) findViewById(R.id.lokasiKejadian);
mPostKeteranganBencana = (EditText) findViewById(R.id.keteranganBencana);
ivImage = (ImageView) findViewById(R.id.ivImage);
Button mSubmitBtn = (Button) findViewById(R.id.submitBtn);
mProgress = new ProgressDialog(this);
mSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
mSubmitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startPosting();
}
});
}
private void startPosting() {
mProgress.setMessage("Posting Lapor");
mProgress.show();
final String namapelapor_val = mPostNamaPelapor.getText().toString().trim();
final String notelpon_val = mPostNoTelpon.getText().toString().trim();
final String lokasikejadian_val = mPostLokasiKejadian.getText().toString().trim();
final String keteranganbencana_val = mPostKeteranganBencana.getText().toString().trim();
if (!TextUtils.isEmpty(namapelapor_val) && !TextUtils.isEmpty(notelpon_val) && !TextUtils.isEmpty(lokasikejadian_val)
&& !TextUtils.isEmpty(keteranganbencana_val) && mImageUri != null) {
StorageReference filepath = mStorage.child("Foto_Lapor").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("namapelapor").setValue(namapelapor_val);
newPost.child("nomortelpon").setValue(notelpon_val);
newPost.child("lokasikejadian").setValue(lokasikejadian_val);
newPost.child("keteranganbencana").setValue(keteranganbencana_val);
assert downloadUrl != null;
newPost.child("foto").setValue(downloadUrl.toString());
mProgress.dismiss();
startActivity(new Intent(Lapor.this, Terimakasih.class));
finish();
}
});
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
switch (requestCode) {
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (userChoosenTask.equals("Ambil Foto"))
cameraIntent();
else if (userChoosenTask.equals("Ambil dari Album"))
galleryIntent();
} else {
//code for deny
}
break;
}
}
private void selectImage() {
final CharSequence[] items = {"Ambil Foto", "Ambil dari Album",
"Batal"};
AlertDialog.Builder builder = new AlertDialog.Builder(Lapor.this);
builder.setTitle("Ambil Gambar");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result = Utility.checkPermission(Lapor.this);
if (items[item].equals("Ambil Foto")) {
userChoosenTask = "Ambil Foto";
if (result)
cameraIntent();
} else if (items[item].equals("Ambil dari Album")) {
userChoosenTask = "Ambil dari Album";
if (result)
galleryIntent();
} else if (items[item].equals("Batal")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
}
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE) {
Uri mImageUri = data.getData();
CropImage.activity(mImageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(4, 3)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
mImageUri = result.getUri();
ivImage.setImageURI(mImageUri);
}
else if (requestCode == REQUEST_CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
ivImage.setImageBitmap(thumbnail);
}
}
}
}
Thanks
Here is how i have done,its working for me,
In OnActivity Result,
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl(AppConstants.STORAGE_BUCKET);
final String imageName = "INSTA_"+System.currentTimeMillis()+".JPEG";
StorageReference imagePathReference;
imagePathReference = storageRef.child("---your storage path---"+ imageName);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options);
ByteArrayOutputStream bos2 = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 60, bos2);
byte[] dataNew2 = bos2.toByteArray();
uploadTask = imagePathReference2.putBytes(dataNew2);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
if(FirebaseAuth.getInstance().getCurrentUser() != null){
initToSendMessageToFirebase(fileUri, MESSAGE_TYPE_IMAGE,taskSnapshot,"",imageName);
}
}
});
On Clicking launch Camera,
Declare Uri fileUri ; -- global
private void launchCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
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) {
try {
fileUri = Uri.fromFile(createImageFile());
} catch (IOException e) {
e.printStackTrace();
}
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(takePictureIntent, RC_CAMERA);
}
}
}

How to go to next activity after sending email in Android by clicking one button?

After sending email, I need to go other activity. But I'm going to next activity before sending email. the same question having answer that tells to use startactivityforresult.bt I'm new to Android. I don't know how to use that.
public class GetQuoteact extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private ProgressDialog loadDialog;
Button btsub;
private String mobilee, namee, emailide, statee, citye, pine, subjecte, streete, success,endresp;
EditText name_c, mobile_c, emailid_c, state_c, city_c, street_c, pin_c, subject_c;
public String batter_feat_id,Modelname,Batterytype = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
// requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_getquote2);
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
}
name_c = (EditText) findViewById(R.id.name);
mobile_c = (EditText) findViewById(R.id.mobile);
emailid_c = (EditText) findViewById(R.id.email_id);
state_c = (EditText) findViewById(R.id.state);
city_c = (EditText) findViewById(R.id.city);
street_c = (EditText) findViewById(R.id.street);
pin_c = (EditText) findViewById(R.id.pincode);
subject_c = (EditText) findViewById(R.id.subject);
btsub = (Button) findViewById(R.id.bt_sub);
Intent in1 = getIntent();
batter_feat_id = in1.getStringExtra("battery_featuer_idc");
Modelname = in1.getStringExtra("Model_name");
Batterytype = in1.getStringExtra("Battery_type");
btsub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
inilize();
try {
if (!validate()) {
Toast.makeText(GetQuoteact.this, "Enter necessary details!!!", Toast.LENGTH_SHORT).show();
} else {
showDialog();
onfetch(batter_feat_id);}
} catch (Exception e) {
Toast.makeText(GetQuoteact.this, "" + e, Toast.LENGTH_SHORT).show();
}
}
});
}
public void inilize() {
namee = name_c.getText().toString();
mobilee = mobile_c.getText().toString();
emailide = emailid_c.getText().toString();
statee = state_c.getText().toString();
citye = city_c.getText().toString();
pine = pin_c.getText().toString();
subjecte = subject_c.getText().toString();
streete = street_c.getText().toString();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
Intent intent=new Intent(getApplicationContext(),Lastpage.class);
startActivity(intent);
}
else{
Toast.makeText(GetQuoteact.this, "error on sending mail...", Toast.LENGTH_SHORT).show();
}
}
private void onfetch(String batter_feat_id) {
Intent ithh =new Intent(Intent.ACTION_SENDTO);
ithh.setData(Uri.parse("mailto:"));
String[] to={"abc#gmail.com"};
ithh.putExtra(ithh.EXTRA_EMAIL,to);
ithh.putExtra(ithh.EXTRA_SUBJECT,"Email From JC APP");
ithh.putExtra(ithh.EXTRA_TEXT,"Model Name :"+Modelname
+"\nBattery Type:"+Batterytype
+"\nName :"+namee
+"\nContact no :"+mobilee
+"\nmailid="+emailide
+"\nstate="+statee
+"\ncity="+citye
+"\narea="+streete
+"\npincode="+pine
+"\nsubject="+subjecte);
startActivityForResult(ithh.createChooser(ithh,"Sent!!!"),1);
}
else{
Toast.makeText(GetQuoteact.this, "error!!! ", Toast.LENGTH_SHORT).show();
}
}
}
change your onActivityResult to something like this
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//autocompleteFragment.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
// success open your activity
}
}
}
I hope this helps

Categories

Resources