Photo by Camera Upload Exception (Firebase Storage) - java

I'm trying to upload an image taken by the camera in an android application to Firebase storage. The problem is that after I take the picture, in the confirmation activity, I pressed the confirm button and it says that "Unfortunately the application stopped".
This is the image when I press the check button, and the app crashes...
This is my code, the application has the option to upload pictures using the gallery and the camera.
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
public class MainActivity extends AppCompatActivity {
// Note: Your consumer key and secret should be obfuscated in your source code before shipping.
private Button selectImage;
private Button selectImageByCamera;
private ImageView imageView;
private StorageReference storageReference;
private ProgressDialog progressDialog;
private static final int CAMERA_REQUEST_CODE = 1;
private static final int GALLERY_INTENT= 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
storageReference=FirebaseStorage.getInstance().getReference();
/*
* Code section to upload an image using the Gallery.
*/
selectImage=(Button)findViewById(R.id.btn_uploadImg);
progressDialog = new ProgressDialog(this);
selectImage.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_INTENT);
}
});
/*
* Code section to upload an image using the Camera.
*/
selectImageByCamera=(Button)findViewById(R.id.btn_uploadImgCamera);
imageView=(ImageView)findViewById(R.id.imageView);
selectImageByCamera.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode,resultCode,data);
//Upload the image to Firebase Update
if(requestCode==GALLERY_INTENT && resultCode == RESULT_OK)
{
progressDialog.setMessage("Uploading Image...");
progressDialog.show();
Uri uri = data.getData();
StorageReference filepath = storageReference.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Upload done", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
});
}
//Code to upload image taken by the camera to firebase storage
if(requestCode==CAMERA_REQUEST_CODE && resultCode == RESULT_OK)
{
progressDialog.setMessage("Uploading Image...");
progressDialog.show();
Uri uri2 = data.getData();
StorageReference filepath = storageReference.child("Photos").child(uri2.getLastPathSegment());
filepath.putFile(uri2).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
{
Toast.makeText(MainActivity.this, "Upload done", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
}
});
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I have this USER PERMISSIONS in AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>
I have this Firebase dependencies in app/build.gradle
compile 'com.google.firebase:firebase-core:9.8.0'
compile 'com.google.firebase:firebase-database:9.8.0'
compile 'com.google.firebase:firebase-storage:9.8.0'
compile 'com.google.firebase:firebase-auth:9.8.0'
And finally this is the exception thrown when I run the app in my Moto G4 6.0.1 (The app has permissions to use Camera and Gallery)
FATAL EXCEPTION: main
Process: mx.com.jamba.jamba, PID: 16543
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=inline-data (has extras) }} to activity {mx.com.jamba.jamba/mx.com.jamba.jamba.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3720)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3763)
at android.app.ActivityThread.access$1400(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1403)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
at mx.com.jamba.jamba.MainActivity.onActivityResult(MainActivity.java:186)
at android.app.Activity.dispatchActivityResult(Activity.java:6470)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3716)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3763) 
at android.app.ActivityThread.access$1400(ActivityThread.java:154) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1403) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5443) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
I don't know what to do, it would be great if you guys to help me :)
Thank you!

The exception occurs because the Uri in onActivityResult() is null:
Uri uri = data.getData();
The documentation for capturing a camera image explains:
The Android Camera application saves a full-size photo if you give it
a file to save into. You must provide a fully qualified file name
where the camera app should save the photo.
Follow the example in the documentation to create a file Uri and add it to the intent for the camera app.

Please try this
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_INTENT);

if(requestCode == CAMERA_REQUEST && resultCode == RESULT_OK){
Bitmap mImageUri = (Bitmap) data.getExtras().get("data");
select.setImageBitmap(mImageUri);
}
then start posting

Related

Cannot load a java class/ layout file in android studio

After successfully passing the login screen, I have called the AddJournalActivity.java class.. However, it crashes, as shown in the video.. What do I do? This is the code for AddJournalActivity.java
package com.project.journeyjournal;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.storage.StorageReference;
public class AddJournalActivity extends AppCompatActivity implements View.OnClickListener {
private static final int GALLERY_CODE = 1;
private Button saveButton;
private ImageView addPhotoButton;
private EditText titleEditText;
private EditText thoughtsEditText;
private ImageView imageView;
private FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener authStateListener;
private FirebaseUser user;
//connection to firestore
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private StorageReference storageReference;
private CollectionReference collectionReference = db.collection("Journal");
private Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_journal);
firebaseAuth = FirebaseAuth.getInstance();
titleEditText = findViewById(R.id.post_title_et);
thoughtsEditText = findViewById(R.id.post_description_et);
imageView = findViewById(R.id.post_imageView);
saveButton = findViewById(R.id.post_save_journal_button);
saveButton.setOnClickListener(this);
addPhotoButton = findViewById(R.id.postCameraButton);
addPhotoButton.setOnClickListener(this);
authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
user = firebaseAuth.getCurrentUser();
if (user != null){
} else{
}
}
};
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.post_save_journal_button:
//save Journal
break;
case R.id.postCameraButton:
//get image from camera or gallery
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GALLERY_CODE);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_CODE && resultCode == RESULT_OK ){
if (data != null){
imageUri = data.getData();
imageView.setImageURI(imageUri);//show image
}
}
}
#Override
protected void onStart() {
super.onStart();
user = firebaseAuth.getCurrentUser();
firebaseAuth.addAuthStateListener((authStateListener));
}
#Override
protected void onStop() {
super.onStop();
if (firebaseAuth!= null){
firebaseAuth.removeAuthStateListener(authStateListener);
}
}
}
I tried opening other pages instead of AddJournalActivity after the login activity, and it was working fine. If I delete all the code in the .java file, then the layout file opens just fine. So I assume that the problem is with AddJournalActivity.java. But I am unable to find it.
I have added the Logcat if it helps.2022-04-06 11:19:46.326 15573-15573/com.project.journeyjournal E/AndroidRuntime: FATAL EXCEPTION: main Process: com.project.journeyjournal, PID: 15573 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.project.journeyjournal/com.project.journeyjournal.AddJournalActivity}: java.lang.ClassCastException: androidx.cardview.widget.CardView cannot be cast to android.widget.ImageView at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3308) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3457) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2044) at android.os.Handler.dispatchMessage(Handler.java:107) at android.os.Looper.loop(Looper.java:224) at android.app.ActivityThread.main(ActivityThread.java:7560) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950) Caused by: java.lang.ClassCastException: androidx.cardview.widget.CardView cannot be cast to android.widget.ImageView at com.project.journeyjournal.AddJournalActivity.onCreate(AddJournalActivity.java:51) at android.app.Activity.performCreate(Activity.java:7893) at android.app.Activity.performCreate(Activity.java:7880) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3283) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3457)  at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)  at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)  at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2044)  at android.os.Handler.dispatchMessage(Handler.java:107)  at android.os.Looper.loop(Looper.java:224)  at android.app.ActivityThread.main(ActivityThread.java:7560)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950) 
I watched your video. Your app crashes after logging in.
By observing your logcat, I can see an error causing with CardView and ImageView. You didn't provide your XML Code, so I'm not sure what exactly is the cause.
Here check this line-
ComponentInfo{com.project.journeyjournal/com.project.journeyjournal.AddJournalActivity}:
java.lang.ClassCastException: androidx.cardview.widget.CardView cannot be cast to android.widget.ImageView
Solution
Possibly you have a CardView in XML which has an ID post_imageView or postCameraButton and you're binding this ID to ImageView by calling
imageView = findViewById(R.id.post_imageView);
or
addPhotoButton = findViewById(R.id.postCameraButton);
Check your IDs in XML and let me know the update.

App crashes after adding FirebaseAuth.getInstance

I had added firebase authentication yesterday and it was working fine but today after editing some files it is crashing.
App only crashes when I add "firebaseAuth =FirebaseAuth.getInstance()".
If I remove it then all things work fine but now I cannot add firebase.
SignUp.java
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
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.TextView;
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 SignUp extends AppCompatActivity implements View.OnClickListener {
private TextView alreadyRegistered;
private EditText mEmailView;
private EditText mPasswordView;
private Button signup;
private FirebaseAuth firebaseAuth;
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
progressDialog=new ProgressDialog(this);
mEmailView = (EditText) findViewById(R.id.email_signup);
mPasswordView = (EditText) findViewById(R.id.password_signup);
signup=(Button)findViewById(R.id.signup);
alreadyRegistered=(TextView)findViewById(R.id.already_registered);
// firebaseAuth =FirebaseAuth.getInstance();
//// if(firebaseAuth.getCurrentUser() != null){
//// //that means user is already logged in
//// //so close this activity
//// finish();
////
//// //and open profile activity
//// startActivity(new Intent(getApplicationContext(), Home.class));
//// }
alreadyRegistered.setOnClickListener(this);
signup.setOnClickListener(this);
}
private void registerUser() {
//getting email and password from edit texts
String email = mEmailView.getText().toString().trim();
String password = mPasswordView.getText().toString().trim();
//checking if email and passwords are empty
if (TextUtils.isEmpty(email)) {
Toast.makeText(this, "Please enter email", Toast.LENGTH_LONG).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(this, "Please enter password", Toast.LENGTH_LONG).show();
return;
}
//if the email and password are not empty
//displaying a progress dialog
progressDialog.setMessage("Registering Please Wait...");
progressDialog.show();
//creating a new user
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//checking if success
if (task.isSuccessful()) {
//display some message here
Toast.makeText(SignUp.this, "Successfully registered", Toast.LENGTH_LONG).show();
Intent intent = new Intent(SignUp.this, MainActivity.class);
startActivity(intent);
} else {
//display some message here
Toast.makeText(SignUp.this, "Registration Error", Toast.LENGTH_LONG).show();
}
// progressDialog.dismiss();
}
});
}
#Override
public void onClick(View v) {
if(v==signup)
{
registerUser();
}
if(v==alreadyRegistered)
{
Intent intent = new Intent(SignUp.this,MainActivity.class);
startActivity(intent);
}
}
}
I tried debugging and it crashes when I run that particular line.
Crash Logs
2019-02-16 14:43:23.569 25053-25053/com.example.android.nirog E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.nirog, PID: 25053
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.nirog/com.example.android.nirog.SignUp}: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.example.android.nirog. Make sure to call FirebaseApp.initializeApp(Context) first.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2949)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3027)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1745)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:200)
at android.app.ActivityThread.main(ActivityThread.java:6956)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:519)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:836)
Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.example.android.nirog. Make sure to call FirebaseApp.initializeApp(Context) first.
at com.google.firebase.FirebaseApp.getInstance(com.google.firebase:firebase-common##16.0.2:240)
at com.google.firebase.auth.FirebaseAuth.getInstance(Unknown Source:1)
at com.example.android.nirog.SignUp.onCreate(SignUp.java:44)
at android.app.Activity.performCreate(Activity.java:7225)
at android.app.Activity.performCreate(Activity.java:7216)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1215)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2902)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3027) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1745) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:200) 
at android.app.ActivityThread.main(ActivityThread.java:6956) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:519) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:836) 
2019-02-16 14:43:23.623 25053-25053/com.example.android.nirog I/Process: Sending signal. PID: 25053 SIG: 9
This is most helpful in android with fluuter and firebase
in app level build.gradle
defaultConfig {
minSdkVersion 23
}
in project level gradle.properties add
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
android.enableR8=true
in build.gradle add
dependencies {
classpath 'com.android.tools.build:gradle:3.4.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.gms:google-services:4.2.0'
}
you can skip that Kotlin plugin if you are not using Kotlin support
Dont forget to run flutter clean and then flutter pub upgrade
These changes helped me preventing my app crashes, It should help you too.
You have not initialised firebase. Add this in onCreate of your SignUp class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
FirebaseApp.initializeApp(Context)
Make sure to call FirebaseApp.initializeApp(Context) first in Android method added in MyApplication class in your project like :
override fun onCreate() {
super.onCreate()
{
FirebaseApp.initializeApp(Context);
}

Can't load image from uri after reload app

*//Sorry for bad eng, but in stackoverflow.ru I have no answers you my last chance*
I have app with 1 activity, which should take image\photo from galery, save uri of this image\photo in sharedPreferences, and after reload, app load image from saved uri in imageView
So, after reload uri successfully saved and load in app, but app can't load photo from uri and instead image I have empty space, but ImageView exist and with loaded uri all ok(I compare loaded uri and uri from galery, they equals).
Below I attach my code and screenshots:
xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="ua.bellkross.testapp.MainActivity">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
app:srcCompat="#drawable/myphoto2" />
</LinearLayout>
java:
package ua.bellkross.testapp;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
ImageView imageView;
SharedPreferences sharedPreferences;
String photoUri;
boolean can;
final int GALLERY_REQUEST = 1;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
loadPhoto();
imageView.setOnClickListener(this);
}
#Override
protected void onStop() {
super.onStop();
savePhoto();
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.imageView :
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, GALLERY_REQUEST);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri selectedImage = data.getData();
imageView.setImageURI(selectedImage);
photoUri = selectedImage.toString();
Log.d("myLog", "savedURI == " + photoUri);
can = true;
}
private void savePhoto(){
sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("uri",photoUri);
editor.putBoolean("edited",can);
editor.commit();
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void loadPhoto(){
sharedPreferences = getPreferences(MODE_PRIVATE);
if(sharedPreferences.getBoolean("edited",false)) {
String savedURI = sharedPreferences.getString("uri", null);
if (!savedURI.equals(null)) {
Log.d("myLog", "savedURI!=null");
imageView.setImageURI(Uri.parse(savedURI));
Log.d("myLog", "savedURI == " + savedURI);
}
}
can = false;
}
}
//I have no reputation to post images and more than 2 links
https://i.stack.imgur.com/hveS0.jpg - start app
https://i.stack.imgur.com/UrzHF.jpg - take image from galery
https://i.stack.imgur.com/Cwy37.jpg - after reload app
That I did for fix it?
1)Check saved and loaded uri with uri from galery - they equals, I did this with logs
05-09 22:05:24.893 524-524/ua.bellkross.testapp D/myLog: savedURI(OnActivityResult) == content://media/external/images/media/16493
05-09 22:05:29.505 1294-1294/? D/myLog: savedURI!=null
05-09 22:05:29.510 1294-1294/? D/myLog: savedURI == content://media/external/images/media/16493
2)Try use getSharedPreferences instead sharedPreferences - it's don't help
3)Try use imageView.setImageURI(null), imageView.invalidate(), imageView.postInvalidate(), before load of image - don't help.
4)Checked version of my Android and version from #RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) - they equals, all ok
5)Try change uri from content://media/external/images/media/16493 to media/external/images/media/16493 - didn't help
6)Try use onRestoreInstanceState and onSaveInstanceState - it's don't help and onRestoreInstanceState started only when you change orientation of screen, but not after reload.
Maybe, if u run it yourself or just write similar app(it takes 5-10 min) and this app will work - in compare becomes clear, which mistake I have.
Guys, I find answer, thank for this - greenapps
I try open stream InputStream is = getContentResolver().openInputStream(uri);
and get stack trace and found some string
05-10 16:13:40.081 1264-1286/? E/DatabaseUtils: Writing exception to parcel
java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/18553 from pid=8465, uid=10268 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
So, just write in AndroidManifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
try to set imageView to null at first and then set it normally like this:
imageView.setImageURI(null);
imageView.setImageURI(Uri.parse(savedURI));
I try open stream InputStream is = getContentResolver().openInputStream(uri);
and get stack trace and found some string
05-10 16:13:40.081 1264-1286/? E/DatabaseUtils: Writing exception to parcel
java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/18553 from pid=8465, uid=10268 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
So, just write in AndroidManifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>

Image disappears from ImageView in Android App

I am absolutely new to Android as well as Java (only some basic knowledge). I am trying to develop a simple app as per a youtube video. In this app, I have a button which is clickable and call the method launchCamera(). The image captured by the camera has to be displayed in the ImageView.
PROBLEM: I installed the .apk file in my mobile. When I click the "Take Photo" button, my camera starts. When I capture a image from my camera and save it, that image gets displayed in the ImageView only for a second (even less then a second). How can I keep that photo in the ImageView till the user does not press the "Take Photo" button again?
UPDATE: With the same code, I just noticed something strange. Mostly the image captured while holding the phone vertically rotates itself inside the ImageView and disappears. But sometimes it stays in the ImageView vertically and doesn't get disappeared till the "Take Photo" button is pressed again (Desired case).
My Code:
package com.siddexample.buttonimage;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.content.pm.PackageInfo;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class ButtonImageMainActivity extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
ImageView siddImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_button_image_main);
Button siddButton = (Button) findViewById(R.id.siddButton);
siddImageView = (ImageView) findViewById(R.id.siddImageView);
}//////-------------///////////////
public void launchCamera(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//Take a picture by your intent
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap photo = (Bitmap) extras.get("data");
siddImageView.setImageBitmap(photo);
}
}
}
Try using this tutorial here , as follows:
Taking a picture:
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
Receiving the picture:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
}
and displaying the picture:
/*
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// hide video preview
videoPreview.setVisibility(View.GONE);
imgPreview.setVisibility(View.VISIBLE);
// 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);
imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
As #stkent said, maybe the onActivityResult is called twice.

How to play a video from gallery in Android?

I am trying to play a video from the gallery, but i can only reach the gallery.
I have a button and when i press it i am redirected to the gallery. I can see that there are videos, but when i press the video the application crashes.
This is the "On activity result".
public void onActivityResult(int requestCode,int resultCode,Intent data){
super.onActivityResult(requestCode,resultCode,data);
if (requestCode == SELECT_PHOTO ) {
Uri mVideoURI = data.getData();
video_player_view.setMediaController(media_Controller);
video_player_view.setVideoURI(mVideoURI);
video_player_view.requestFocus();
video_player_view.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
video_player_view.start();
}
});
}
}
And this is "On Create"
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn_camera = (Button)findViewById(R.id.btn_camera);
Button btn_arhiva = (Button)findViewById(R.id.btn_arhiva);
video_player_view = (VideoView)findViewById(R.id.video_player_view);
media_Controller = new MediaController(this);
media_Controller.setAnchorView(video_player_view);
btn_camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(intent,CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
}
});
btn_arhiva.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*,video/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
});
The Exception:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=199, result=-1, data=Intent { dat=content://media/external/video/media/39 }} to activity {licenta.licenta/licenta.licenta.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.VideoView.setMediaController(android.widget.MediaController)' on a null object reference`
I searched online and tutorials are made using a video from "Raw" directory. But i want it dynamically. If i record a video now, i want to be able to play it through the app.
Thank you!

Categories