Why I can not play google drive video using Exoplayer? - android

I can play any mp4 video using Exoplayer in my Android project. But the video uploaded to Google drive or blogspot site is not playing in Exoplayer. Is there any solution to this problem?
Here's the code I'm using:
public class MagicalExoplayer extends AppCompatActivity {
private AndExoPlayerView andExoPlayerView;
// private String TEST_URL_MP4 = "https://www.w3schools.com/html/mov_bbb.mp4";
//Blogger site video link but can't play this video
private String TEST_URL_MP4 = "https://bestmedicalpdf.blogspot.com/2020/05/mrcpwiz-free-mrcp-mcqs-mrcpwiz-your.html";
private String TEST_URL_HLS = "https://content.jwplatform.com/manifests/yp34SRmf.m3u8";
private String TEST_URL_MP3 = "https://host2.rj-mw1.com/media/podcast/mp3-192/Tehranto-41.mp3";
private int req_code = 129;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_magical_exoplayer);
andExoPlayerView = findViewById(R.id.andExoPlayerView);
findViewById(R.id.local).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectLocaleVideo();
}
});
findViewById(R.id.mp4).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadMP4ServerSide();
}
});
findViewById(R.id.hls).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadHls();
}
});
findViewById(R.id.mp3).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadMp3();
}
});
}
private void loadMp3() {
andExoPlayerView.setSource(TEST_URL_MP3);
}
private void loadHls() {
andExoPlayerView.setSource(TEST_URL_HLS);
}
private void loadMP4ServerSide() {
andExoPlayerView.setSource(TEST_URL_MP4);
}
private void selectLocaleVideo() {
if (PublicFunctions.checkAccessStoragePermission(this)) {
Intent intent = new Intent();
intent.setType("video/*");
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Video"), req_code);
}
}
private void loadMP4Locale(String filePath) {
andExoPlayerView.setSource(filePath);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == req_code && resultCode == RESULT_OK) {
Uri finalVideoUri = data.getData();
String filePath = null;
try {
filePath = PathUtil.getPath(this, finalVideoUri);
loadMP4Locale(filePath);
} catch (URISyntaxException e) {
e.printStackTrace();
Toast.makeText(this, "Failed: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
private class ChromeClient extends WebChromeClient {
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
protected FrameLayout mFullscreenContainer;
private int mOriginalOrientation;
private int mOriginalSystemUiVisibility;
ChromeClient() {
}
public Bitmap getDefaultVideoPoster() {
if (mCustomView == null) {
return null;
}
return BitmapFactory.decodeResource(getApplicationContext().getResources(), 2130837573);
}
public void onHideCustomView() {
((FrameLayout) getWindow().getDecorView()).removeView(this.mCustomView);
this.mCustomView = null;
getWindow().getDecorView().setSystemUiVisibility(this.mOriginalSystemUiVisibility);
setRequestedOrientation(this.mOriginalOrientation);
this.mCustomViewCallback.onCustomViewHidden();
this.mCustomViewCallback = null;
}
public void onShowCustomView(View paramView, WebChromeClient.CustomViewCallback paramCustomViewCallback) {
if (this.mCustomView != null) {
onHideCustomView();
return;
}
this.mCustomView = paramView;
this.mOriginalSystemUiVisibility = getWindow().getDecorView().getSystemUiVisibility();
this.mOriginalOrientation = getRequestedOrientation();
this.mCustomViewCallback = paramCustomViewCallback;
((FrameLayout) getWindow().getDecorView()).addView(this.mCustomView, new FrameLayout.LayoutParams(-1, -1));
getWindow().getDecorView().setSystemUiVisibility(3846 | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
}
}
But any other mp4 video easily play.

https://bestmedicalpdf.blogspot.com/2020/05/mrcpwiz-free-mrcp-mcqs-mrcpwiz-your.html is a webpage and not the url to a video or audio file.

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;

How to set sourceImagePath, outputFile in Image Editor

I am using a library implementation com.github.iamutkarshtiwari:Ananas:1.2.3. Everything is working fine but I am facing two errors sourceImagePath, outputFilePath. How can I solve it and remove log e and use camera to run app?
MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final int REQUEST_PERMISSON_SORAGE = 1;
public static final int REQUEST_PERMISSON_CAMERA = 2;
public static final int SELECT_GALLERY_IMAGE_CODE = 7;
public static final int TAKE_PHOTO_CODE = 8;
public static final int ACTION_REQUEST_EDITIMAGE = 9;
private ImageView imgView;
private Bitmap mainBitmap;
private Dialog loadingDialog;
private int imageWidth, imageHeight;
private String path;
private Uri photoURI = null;
private final int PHOTO_EDITOR_REQUEST_CODE = 123;
private CompositeDisposable compositeDisposable = new CompositeDisposable();
private Object BaseActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
#Override
protected void onPause() {
compositeDisposable.clear();
super.onPause();
}
#Override
protected void onDestroy() {
compositeDisposable.dispose();
super.onDestroy();
}
private void initView() {
DisplayMetrics metrics = getResources().getDisplayMetrics();
imageWidth = metrics.widthPixels;
imageHeight = metrics.heightPixels;
imgView = findViewById(R.id.img);
View selectAlbum = findViewById(R.id.select_album);
View editImage = findViewById(R.id.edit_image);
selectAlbum.setOnClickListener(this);
editImage.setOnClickListener(this);
View takenPhoto = findViewById(R.id.take_photo);
takenPhoto.setOnClickListener(this);
loadingDialog = BaseActivity.getLoadingDialog(this, R.string.iamutkarshtiwari_github_io_ananas_loading,
false);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.take_photo:
takePhotoClick();
break;
case R.id.edit_image:
editImageClick();
break;
case R.id.select_album:
selectFromAblum();
break;
}
}
protected void takePhotoClick() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
requestTakePhotoPermissions();
} else {
launchCamera();
}
}
private void requestTakePhotoPermissions() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSON_CAMERA);
return;
}
launchCamera();
}
public void launchCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
Uri outputFileUri = Uri.fromFile(FileUtils.genEditFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
} else {
File file = FileUtils.genEditFile();
Uri photoUri = FileProvider.getUriForFile(getApplicationContext(), getApplicationContext().getPackageName() + ".provider", file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
}
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (intent.resolveActivity(getApplicationContext().getPackageManager()) != null) {
startActivityForResult(intent, TAKE_PHOTO_CODE);
}
}
Facing Problem Here
private void editImageClick() {
File outputFile = FileUtils.genEditFile();
try {
Intent intent = new ImageEditorIntentBuilder(this, sourceImagePath, outputFilePath)
.withAddText() // Add the features you need
.withPaintFeature()
.withFilterFeature()
.withRotateFeature()
.withCropFeature()
.withBrightnessFeature()
.withSaturationFeature()
.withBeautyFeature()
.withStickerFeature()
.forcePortrait(true) // Add this to force portrait mode (It's set to false by default)
.build();
EditImageActivity.start(BaseActivity, intent, PHOTO_EDITOR_REQUEST_CODE);
} catch (Exception e) {
Log.e("Demo App", e.getMessage()); // This could throw if either `sourcePath` or `outputPath` is blank or Null
}
}
private void selectFromAblum() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
openAblumWithPermissionsCheck();
} else {
openAlbum();
}
}
private void openAlbum() {
MainActivity.this.startActivityForResult(new Intent(
MainActivity.this, SelectPictureActivity.class),
SELECT_GALLERY_IMAGE_CODE);
}
private void openAblumWithPermissionsCheck() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSON_SORAGE);
return;
}
openAlbum();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_PERMISSON_SORAGE
&& grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openAlbum();
} else if (requestCode == REQUEST_PERMISSON_CAMERA
&& grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
launchCamera();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PHOTO_EDITOR_REQUEST_CODE) { // same code you used while starting
String newFilePath = data.getStringExtra(EditImageActivity.OUTPUT_PATH);
boolean isImageEdit = data.getBooleanExtra(EditImageActivity.IMAGE_IS_EDIT, false);
}
if (resultCode == RESULT_OK) {
switch (requestCode) {
case SELECT_GALLERY_IMAGE_CODE:
handleSelectFromAblum(data);
break;
case TAKE_PHOTO_CODE:
handleTakePhoto();
break;
case ACTION_REQUEST_EDITIMAGE:
handleEditorImage(data);
break;
}
}
}
private void handleTakePhoto() {
if (photoURI != null) {
path = photoURI.getPath();
loadImage(path);
}
}
private void handleEditorImage(Intent data) {
String newFilePath = data.getStringExtra(ImageEditorIntentBuilder.OUTPUT_PATH);
boolean isImageEdit = data.getBooleanExtra(EditImageActivity.IS_IMAGE_EDITED, false);
if (isImageEdit) {
Toast.makeText(this, getString(R.string.save_path, newFilePath), Toast.LENGTH_LONG).show();
} else {
newFilePath = data.getStringExtra(ImageEditorIntentBuilder.SOURCE_PATH);
}
loadImage(newFilePath);
}
private void handleSelectFromAblum(Intent data) {
path = data.getStringExtra("imgPath");
loadImage(path);
}
private void loadImage(String imagePath) {
compositeDisposable.clear();
Disposable applyRotationDisposable = loadBitmapFromFile(imagePath)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(subscriber -> loadingDialog.show())
.doFinally(() -> loadingDialog.dismiss())
.subscribe(
this::setMainBitmap,
e -> Toast.makeText(
this, R.string.iamutkarshtiwari_github_io_ananas_load_error, Toast.LENGTH_SHORT).show()
);
compositeDisposable.add(applyRotationDisposable);
}
private void setMainBitmap(Bitmap sourceBitmap) {
if (mainBitmap != null) {
mainBitmap.recycle();
mainBitmap = null;
System.gc();
}
mainBitmap = sourceBitmap;
imgView.setImageBitmap(mainBitmap);
}
private Single<Bitmap> loadBitmapFromFile(String filePath) {
return Single.fromCallable(() ->
BitmapUtils.getSampledBitmap(
filePath,
imageWidth / 4,
imageHeight / 4
)
);
}
}

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);
}
}

Image not retaining on rotating the screen

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);
}
}

How to open fragment instead of activity

This is my app so far:
MapsActivity:
public class MapsActivity extends FragmentActivity implements GoogleMap.OnMarkerDragListener, OnMapReadyCallback, GoogleMap.OnMapLongClickListener, GoogleMap.OnMarkerClickListener, GoogleMap.OnMapLoadedCallback {
private GoogleMap mMap;
private HashMap<LatLng, CustomMarker> list;
public static String TAG = MapsActivity.class.getClass().getName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
list = new HashMap<>();
Log.e(TAG, "onCreate()");
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMarkerClickListener(this);
mMap.setOnMapLoadedCallback(this);
mMap.setOnMapLongClickListener(this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.setOnMarkerDragListener(this);
Log.e(TAG, "onMapReady");
}
#Override
public void onMapLoaded() {
retrieveMarkersFromDB();
Log.e(TAG, "onMapLoaded");
Toast.makeText(MapsActivity.this, "Touch and hold to create a marker", Toast.LENGTH_SHORT).show();
}
private void retrieveMarkersFromDB() {
new GetMarkers().execute();
}
#Override
public void onMapLongClick(LatLng latLng) {
mMap.addMarker(new MarkerOptions().position(latLng).draggable(true));
CustomMarker customMarker = getMarkerAddress(latLng);
addMarkerToList(customMarker,latLng);
Toast.makeText(MapsActivity.this, "Marker Added", Toast.LENGTH_SHORT).show();
}
private void addMarkerToList(CustomMarker customMarker, LatLng latLng) {
list.put(latLng, customMarker);
}
private CustomMarker getMarkerAddress(LatLng latLng) {
CustomMarker customMarker = null;
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> allAddresses = geocoder.getFromLocation(latLng.latitude,latLng.longitude,2);
Address oneAddress = allAddresses.get(0);
try{
if(!oneAddress.getLocality().equals("null")||!oneAddress.getLocality().isEmpty()){
customMarker = new CustomMarker(oneAddress.getAddressLine(0)+", "+oneAddress.getLocality(),oneAddress.getCountryName(),"","");
}
}catch (NullPointerException e){
customMarker = new CustomMarker(oneAddress.getAddressLine(0),oneAddress.getCountryName(),"","");
}
} catch (IOException e) {
e.printStackTrace();
}catch (IndexOutOfBoundsException er){
customMarker = new CustomMarker("N/A","N/A","","");
}
return customMarker;
}
#Override
public boolean onMarkerClick(Marker marker) {
Intent intent = new Intent(this,com.example.fixxxer.mapapp.MarkerScreen.class);
CustomMarker customMarker = list.get(new LatLng(marker.getPosition().latitude,marker.getPosition().longitude));
intent.putExtra("addressLine",customMarker.getAddressLine());
intent.putExtra("countryName",customMarker.getCountryName());
intent.putExtra("imageURL",customMarker.getImageURL());
intent.putExtra("comment",customMarker.getComment());
intent.putExtra("lat",marker.getPosition().latitude);
intent.putExtra("lng",marker.getPosition().longitude);
startActivityForResult(intent,1);
return true;
}
#Override
protected void onDestroy() {
new DatabaseHelper(this,null,null,1).addMarkers(list);
super.onDestroy();
}
#Override
public void onMarkerDragStart(Marker marker) {
marker.remove();
list.remove(marker.getPosition());
Toast.makeText(MapsActivity.this, "Marker removed", Toast.LENGTH_SHORT).show();
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
}
public class GetMarkers extends AsyncTask<Void,Void,Void>{
#Override
protected Void doInBackground(Void... params) {
Log.e(TAG,"background task started");
list=new DatabaseHelper(MapsActivity.this,null,null,1).getallmarkers();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
Log.e("onPostExecute","background task ready");
Log.e(TAG,String.valueOf(list.size()));
if (!list.isEmpty()){
for (LatLng position: list.keySet() ) {
mMap.addMarker(new MarkerOptions().position(position).draggable(true));
}
}
super.onPostExecute(aVoid);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.e("Main", "onActivityResult()");
if (requestCode == 1) {
if (resultCode == MarkerScreen.RESULT_COMMENT_ONLY) {
String comment = data.getStringExtra("Comment");
String[]split = data.getStringExtra("Index").split(",");
list.get(new LatLng(Double.valueOf(split[0]),Double.valueOf(split[1]))).setComment(comment);
}else if (resultCode == MarkerScreen.RESULT_IMAGE_ONLY) {
String imageURI = data.getStringExtra("Image");
String[]split = data.getStringExtra("Index").split(",");
list.get(new LatLng(Double.valueOf(split[0]), Double.valueOf(split[1]))).setImageURL(imageURI);
} else if (resultCode == MarkerScreen.RESULT_BOTH) {
String comment = data.getStringExtra("Comment");
String imageURI = data.getStringExtra("Image");
String[]split = data.getStringExtra("Index").split(",");
list.get(new LatLng(Double.valueOf(split[0]), Double.valueOf(split[1]))).setComment(comment);
list.get(new LatLng(Double.valueOf(split[0]), Double.valueOf(split[1]))).setImageURL(imageURI);
} else {
Log.e("Main", "Result - no change");
}
}
}
Marker Screen class(Activity)
public class MarkerScreen extends AppCompatActivity {
private static final int REQUEST_TAKE_PHOTO = 1;
private ImageView imageView;
private TextView addressView;
private TextView countryView;
private TextView latlngView;
private EditText commentView;
private Button saveButton;
private Button deleteButton;
private String addressFromIntent;
private String countryFromIntent;
private String commentFromIntent;
private double latFromIntent;
private double lngFromIntent;
private String photoPath;
private String newPhotoPath;
private int imageModified = 0;
private int commentModified = 0;
static final int RESULT_NONE = 0;
static final int RESULT_BOTH = 1;
static final int RESULT_COMMENT_ONLY = 2;
static final int RESULT_IMAGE_ONLY = 3;
static final int RESULT_DELETE=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_marker_screen);
//Initialising Views
addressView=(TextView)findViewById(R.id.textView);
countryView=(TextView)findViewById(R.id.textView2);
latlngView=(TextView)findViewById(R.id.textView3);
saveButton=(Button)findViewById(R.id.button);
saveButton.setText("Save");
imageView=(ImageView)findViewById(R.id.imageView);
commentView=(EditText)findViewById(R.id.editText);
//Getting intent information
addressFromIntent=getIntent().getStringExtra("addressLine");
countryFromIntent=getIntent().getStringExtra("countryName");
commentFromIntent=getIntent().getStringExtra("comment");
photoPath=getIntent().getStringExtra("imageURL");
latFromIntent=getIntent().getDoubleExtra("lat",0);
lngFromIntent=getIntent().getDoubleExtra("lng",0);
//Setting textFields
addressView.setText(addressFromIntent);
countryView.setText(countryFromIntent);
final String latlngTextField=String.valueOf(latFromIntent)+", "+String.valueOf(lngFromIntent);
latlngView.setText(latlngTextField);
if (photoPath.equals("")){
imageView.setImageResource(R.drawable.image);
} else {
imageView.setImageURI(Uri.parse(photoPath));
}
commentView.setText(commentFromIntent);
commentView.setHint("Enter comment here...");
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
Toast.makeText(MarkerScreen.this, photoPath, Toast.LENGTH_SHORT).show();
}
});
commentView.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
commentModified++;
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
if (imageModified == 0 && commentModified == 0) {
setResult(RESULT_NONE);
Log.e("MarkerActivity", "intentResult: RESULT_NONE");
finish();
} else if (imageModified > 0 && commentModified == 0) {
intent.putExtra("Image", newPhotoPath);
intent.putExtra("Index", latlngView.getText());
Log.e("MarkerActivity", "intentResult: RESULT_IMAGE ONLY");
setResult(RESULT_IMAGE_ONLY, intent);
finish();
} else if (imageModified == 0 && commentModified > 0) {
intent.putExtra("Comment", commentView.getText().toString());
intent.putExtra("Index", latlngView.getText());
setResult(RESULT_COMMENT_ONLY, intent);
Log.e("MarkerActivity", "intentResult: RESULT_COMMENT ONLY");
finish();
} else if (imageModified > 0 && commentModified > 0) {
intent.putExtra("Comment", commentView.getText().toString());
intent.putExtra("Image", newPhotoPath);
intent.putExtra("Index", latlngView.getText());
setResult(RESULT_BOTH, intent);
Log.e("MarkerActivity", "intentResult: RESULT_BOTH");
finish();
}
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
Log.e("markerActivity","back button pressed");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override public void onBackPressed(){
this.finish();
Log.e("markerActivity"," hardware back button pressed");
}
private File createImageFile() throws IOException {
#SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES+ "/MapApp/" + addressFromIntent);
if (!storageDir.exists()){
File wallpaperDirectory = new File(storageDir.getPath());
boolean photoStatus =wallpaperDirectory.mkdirs();
}
File image = File.createTempFile(
imageFileName,
".jpg",
storageDir
);
newPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
ex.printStackTrace();
}
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
Uri uri = Uri.parse(newPhotoPath);
imageView.setImageURI(uri);
imageModified++;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("photopath",newPhotoPath);
outState.putString("comment",commentView.getText().toString());
outState.putString("addressView",addressView.getText().toString());
outState.putString("countryView",countryView.getText().toString());
outState.putString("latlngView",latlngView.getText().toString());
outState.putInt("imageModified", imageModified);
outState.putInt("commentModified", commentModified);
Log.e("Saved","saved info");
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
photoPath=savedInstanceState.getString("photopath");
commentView.setText(savedInstanceState.getString("comment"));
addressView.setText(savedInstanceState.getString("addressView"));
countryView.setText(savedInstanceState.getString("countryView"));
latlngView.setText(savedInstanceState.getString("latlngView"));
imageModified=savedInstanceState.getInt("imageModified");
commentModified=savedInstanceState.getInt("commentModified");
Log.e("Restored","restored info");
}
activity_maps.xml
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.fixxxer.mapapp.MapsActivity">
<include layout="#layout/map_layout"/>
map_layout.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.fixxxer.mapapp.MapsActivity" />
I want to replace starting MarkerScreen Activity with a similar Fragment. How to do this? What i've tried so far is to create a new BlankFragment via menu and set this in the onMarkerClick() method:
getFragmentManager()
.beginTransaction()
.replace(R.id.layout.map_layout, BlankFragment.newInstance())
.addToBackStack(null) // enables back key
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) // if you need transition
.commit();
But i get an no view found error. Is there an easy way to do all this? I'm quite a noob with fragments.
Use R.id.map in place of containerViewId in your replace fragment code like this
getFragmentManager()
.beginTransaction()
.replace(R.id.map, BlankFragment.newInstance())
.addToBackStack(null) // enables back key
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) // if you need transition
.commit();

Categories

Resources