How to open a file from a URI/Uri in Android - java

I am trying to open a file from my emulator's internal storage (was trying to put it in sdcard but it put to internal storage?). I have the user choose a file, then pass that file's Uri (note the case) to a text editing activity via intent. In this activity, I've tried a few things. My current code looks like this (excuse the madness, I've been trying a LOT of things):
try {
Intent intent = getIntent();
File file;
Uri uri = Parcels.unwrap(intent.getParcelableExtra("uri"));
URI newUri = new URI("file://"+uri.toString());
Log.d("uri", uri.toString());
Log.d("newUri", newUri.toString());
file = new File(newUri);
if (intent != null) {
Log.d("uriPath", uri.toString());
if (uri != null) {
file = new File(uri.getPath());
String text = readTextFile(file);
if (text != null) {
Log.d("in if text not null", text);
mEditText.setText(text);
}
// mEditText.setText(readTextFile(file));
}
}
}
catch(URISyntaxException e) { e.printStackTrace(); }
I've tried a LOT of things, with no success. I'm either getting file not found (as it's not prefixing the file with anything, just trying to load "document/primary%3Aindex.html"), or other exceptions, currently:
06-06 05:43:18.826 10794-10794/net.a40two.pext E/AndroidRuntime: FATAL EXCEPTION: main
Process: net.a40two.pext, PID: 10794
java.lang.RuntimeException: Unable to start activity ComponentInfo{net.a40two.pext/net.a40two.pext.ui.EditorActivity}: java.lang.IllegalArgumentException: Found authority in URI: file://content://com.android.externalstorage.documents/document/primary%3Aindex.html
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalArgumentException: Found authority in URI: file://content://com.android.externalstorage.documents/document/primary%3Aindex.html
at java.io.File.checkURI(File.java:230)
at java.io.File.<init>(File.java:175)
at net.a40two.pext.ui.EditorActivity.onCreate(EditorActivity.java:67)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
This happens even without the file:// concatenation. Most anything I can find online is either incredibly old, doesn't work, or both. Any help is sincerely appreciated.
The code in my main activity where I'm getting this URI is straight from developers.android.com:
public void onActivityResult(int requestCode, int resultCode,
Intent resultData) {
// The ACTION_OPEN_DOCUMENT intent was sent with the request code
// READ_REQUEST_CODE. If the request code seen here doesn't match, it's the
// response to some other intent, and the code below shouldn't run at all.
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
// The document selected by the user won't be returned in the intent.
// Instead, a URI to that document will be contained in the return intent
// provided to this method as a parameter.
// Pull that URI using resultData.getData().
Uri uri = null;
if (resultData != null) {
uri = resultData.getData();
Log.i("onActivityResult", "Uri: " + uri.toString());
Intent intent = new Intent(MainActivity.this, EditorActivity.class);
intent.putExtra("uri", Parcels.wrap(uri));
startActivity(intent);
finish();
}
}
}

Related

Get GPS data from file metadata in Android 10

So, I have to get GPS data from file MetaData. "No problem", I said, "This will only take an hour or two". Six hour later, here I am searching through all Android Documentation and Stack exchange questions I can yet I still cant get it to work.
My Code is straight forward:
I am using a ACTION_PICK to select a video (ACTION_OPEN_DOCUMENT Doesn't work either).
I Have already requested the following permissions and added to the Manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION" />
Below is code from the button listener
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK , MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
//intent.setType("video/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
startActivityForResult(Intent.createChooser(intent,"Select A Video"),REQUEST_VIDEO_CONTENT);
}
});
And From the OnActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent vIntent) {
super.onActivityResult(requestCode, resultCode, vIntent);
if ((requestCode == REQUEST_VIDEO_CAPTURE || requestCode == REQUEST_VIDEO_CONTENT) && resultCode == RESULT_OK) {
//Attempt to get Content Data
vIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
vIntent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
Uri vUri = vIntent.getData();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
vUri = MediaStore.setRequireOriginal(vUri);
}
try {
InputStream vIS = getContentResolver().openInputStream(vUri);
ExifInterface vExif = new ExifInterface(vIS);
} catch (SecurityException | IOException e) {
e.printStackTrace();
}
And finally, the lovely SecurityException:
W/System.err: java.lang.SecurityException: Permission Denial: reading com.google.android.apps.photos.contentprovider.impl.MediaContentProvider uri content://com.google.android.apps.photos.contentprovider/0/2/content%3A%2F%2Fmedia%2Fexternal%2Fvideo%2Fmedia%2F198668/ORIGINAL/NONE/video%2Fmp4/328149382?requireOriginal=1 from pid=6190, uid=10146 requires the provider be exported, or grantUriPermission()
W/System.err: at android.os.Parcel.createException(Parcel.java:2071)
at android.os.Parcel.readException(Parcel.java:2039)
W/System.err: at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:188)
at android.database.DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(DatabaseUtils.java:151)
W/System.err: at android.content.ContentProviderProxy.openTypedAssetFile(ContentProviderNative.java:705)
at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1710)
W/System.err: at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1526)
W/System.err: at android.content.ContentResolver.openFileDescriptor(ContentResolver.java:1345)
at android.content.ContentResolver.openFileDescriptor(ContentResolver.java:1293)
W/System.err: at com.equinox.openeyes.VideoSubmission.onActivityResult(VideoSubmission.java:117)
at android.app.Activity.dispatchActivityResult(Activity.java:8147)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4883)
W/System.err: at android.app.ActivityThread.handleSendResult(ActivityThread.java:4931)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
W/System.err: 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:2022)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:235)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:7441)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
I get that the Error is saying the provider needs to be exported, or grantUriPermission which sounds like an easy fix, except I cannot find a way to implement what they ask. All the places I have looked have suggested adding flags.. as you can see it didnt work.
Please Help :-(

App crashes when calling dispatchTakePictureIntent

My app is crashing when I click on the following button to use dispatchTakePictureIntent
My code:
ic_img_item.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dispatchTakePictureIntent(PHOTO);
}
});
private void dispatchTakePictureIntent(int requestCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(activity.getPackageManager()) != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, PHOTO_TEMP);
takePictureIntent.putExtra("return-data", true);
startActivityForResult(takePictureIntent, requestCode);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
try {
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 2;
Bitmap bitmap = RotateBitmap(BitmapFactory.decodeStream(activity.getContentResolver().openInputStream(PHOTO_TEMP), null, bmOptions), getPictureOrientation(PHOTO_TEMP));
thumb = getThumbnail(bitmap);
setThumbnail(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Log:
--------- beginning of crash
2020-09-10 17:41:31.769 25093-25093/ubisolutions.net.datacenterinventory.debug E/AndroidRuntime: FATAL EXCEPTION: main
Process: ubisolutions.net.datacenterinventory.debug, PID: 25093
java.lang.RuntimeException: android.os.TransactionTooLargeException: data parcel size 3087012 bytes
at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3782)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
Caused by: android.os.TransactionTooLargeException: data parcel size 3087012 bytes
at android.os.BinderProxy.transactNative(Native Method)
at android.os.BinderProxy.transact(Binder.java:615)
at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3653)
at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3774)
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6123) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779) 
2020-09-10 17:41:31.775 1239-1239/? E/NotificationService: Suppressing notification from package by user request.
2020-09-10 17:41:31.775 1239-25274/? I/QCALOG: [MessageQ_Client] connecting to server [/data/misc/location/mq/location-mq-s]
2020-09-10 17:41:31.776 1239-25274/? E/QCALOG: [MessageQ_Client] connect error: 111, [Connection refused]
I have seen some responses about similar issues but none of them helped me to solve it.
thanks.
Your code line
takePictureIntent.putExtra("return-data", true);
requests, that the picture data is returned directly, but it is too large to be passed back in the result. You should instead get it from PHOTO_TMP you are passing in the intent too.
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, PHOTO_TEMP)

Storage Access Framework - failing to obtain document tree from uri (returned from Drive app)

My Android app wants to create a folder in Google Drive and get the uri from the Drive app on the device.
It sends an intent, you can see the code below:
private void createFolder(String folderName) {
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
// Create a file with the requested MIME type.
intent.setType("vnd.android.document/directory");
intent.putExtra(Intent.EXTRA_TITLE, folderName);
startActivityForResult(intent, WRITE_REQUEST_CODE);
}
then it gets the returned data, you can see the code below:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent resultData)
{
if (requestCode == WRITE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri uri = null;
if (resultData != null) {
uri = resultData.getData();
Log.i("result", "Uri: " + uri.toString());
DocumentFile pickedDir = DocumentFile.fromTreeUri(this, uri); //this line gives the error
}
}
}
I used a mimetype found on the internet that seems to be a standard type. The same error is issued when using "application/vnd.google-apps.folder".
The goal is to have a document tree but in logcat I get the following error:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=43, result=-1, data=Intent { dat=content://com.google.android.apps.docs.storage/document/acc=1;doc=encoded=LongStringWithRandomCharactersHere/j flg=0x43 }} to activity {com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.IllegalArgumentException: Invalid URI: content://com.google.android.apps.docs.storage/document/acc%3D1%3Bdoc%3Dencoded%3DSameLongStringWithRandomCharactersHere%2Fj
and below
Caused by: java.lang.IllegalArgumentException: Invalid URI: content://com.google.android.apps.docs.storage/document/acc%3D1%3Bdoc%3Dencoded%3DAnotherLongStringWithDifferentRandomDataHere
Here's the complete stack trace:
2019-05-31 15:06:50.167 31184-31184/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 31184
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=43, result=-1, data=Intent { dat=content://com.google.android.apps.docs.storage/document/acc=1;doc=encoded=randomcharacters flg=0x43 }} to activity {com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.IllegalArgumentException: Invalid URI: content://com.google.android.apps.docs.storage/document/acc%3D1%3Bdoc%3Dencoded%3Drandomcharacters
at android.app.ActivityThread.deliverResults(ActivityThread.java:4365)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4409)
at android.app.ActivityThread.-wrap19(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1670)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6687)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:810)
Caused by: java.lang.IllegalArgumentException: Invalid URI: content://com.google.android.apps.docs.storage/document/acc%3D1%3Bdoc%3Dencoded%3Drandomcharacters
at android.provider.DocumentsContract.getTreeDocumentId(DocumentsContract.java:1023)
at android.support.v4.provider.DocumentFile.fromTreeUri(DocumentFile.java:138)
at com.example.myapplication.MainActivity.onActivityResult(MainActivity.java:254)
at android.app.Activity.dispatchActivityResult(Activity.java:7295)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4361)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4409) 
at android.app.ActivityThread.-wrap19(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1670) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6687) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:810) 
The uri is not wrong because I can further extract the name of the folder (and the size=0), that is successfully created on the Drive cloud.
What's wrong instead? It seems that my app cannot handle it as a document tree.
This is working with Google Drive cloud space but maybe it's a hack. It is not guaranteed to always work.
This example creates a cloud file in a cloud folder that was created by the user (the SAF picker is opened by the app).
Creating the cloud folder (the user has to select the cloud root first from the picker UI)
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.setType("vnd.android.document/directory");
intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(intent, CREATE_DIRECTORY_REQUEST_CODE);
onActivityResult
#Override
protected void onActivityResult(int requestCode,int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CREATE_DIRECTORY_REQUEST_CODE)
{
if (resultCode == Activity.RESULT_OK) {
int takeFlags = data.getFlags()
&
(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
ContentResolver resolver = this.getContentResolver();
resolver.takePersistableUriPermission(data.getData(),takeFlags);
archiveUri(data.getData().toString()); //important to save the toString() result, not getPath()
archiveAuthority(data.getData().getAuthority());
}
else
{
// The user cancelled the request.
}
}
}
using the Uri next time
ContentResolver contentResolver;
contentResolver = this.getContentResolver();
uriPath=retrieveArchivedUri();
Uri tempUri;
Uri uri;
String authority;
tempUri=Uri.parse(uriPath);
authority=retrieveArchivedAuthority();
uri= DocumentsContract.buildDocumentUri(authority,
DocumentsContract.getDocumentId(tempUri)); //folder Uri
try
{
DocumentsContract.createDocument(contentResolver,uri,"plain/text","fileName");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}

How to upload multiple images to firebase in android?

I know this question has been asked here and answered but for some reasons, provided solutions are not working for me.
So here is how I'm trying to do this. I have two buttons in my layout one to open gallery and other to upload the images.
Defined members
int SELECT_PICTURES = 1;
ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
Uri imageUri;
int up = 0;
int k =0;
Gallery button code
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURES);
On Activity result code
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == SELECT_PICTURES) {
if (resultCode == MainActivity.RESULT_OK) {
if (data.getClipData() != null) {
int count = data.getClipData().getItemCount();
Log.i("count", String.valueOf(count));
int currentItem = 0;
while (currentItem < count) {
imageUri = data.getClipData().getItemAt(currentItem).getUri();
Log.i("uri", imageUri.toString());
mArrayUri.add(imageUri);
currentItem = currentItem + 1;
}
Log.i("listsize", String.valueOf(mArrayUri.size()));
} else if (data.getData() != null) {
String imagePath = data.getData().getPath();
}
}
}
}
Upload button code
StorageReference filepath = FirebaseStorage.getInstance().getReference().child("gpic");
while (up < mArrayUri.size()){
// error is pointing to this line, line 82
filepath.child(mArrayUri.get(k).getLastPathSegment()).putFile(mArrayUri.get(k)).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadURL = taskSnapshot.getDownloadUrl();
Toast.makeText(TestingActivity.this, downloadURL.toString(), Toast.LENGTH_SHORT).show();
up++;
k++;
}
});
}
}
The above code uploads one image and then crashes with the following error
01-24 12:37:37.416 8336-8336/com.codenemesis.uploading E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.codenemesis.uploading, PID: 8336
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5610) 
at android.view.View$PerformClick.run(View.java:22265) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 
Caused by: java.util.concurrent.RejectedExecutionException: Task com.google.firebase.storage.zzs#c59b7fe rejected from java.util.concurrent.ThreadPoolExecutor#4b6eb5f[Running, pool size = 2, active threads = 2, queued tasks = 128, completed tasks = 0]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2049)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:814)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1360)
at com.google.firebase.storage.zzu.zzt(Unknown Source)
at com.google.firebase.storage.UploadTask.schedule(Unknown Source)
at com.google.firebase.storage.StorageTask.zzcls(Unknown Source)
at com.google.firebase.storage.StorageReference.putFile(Unknown Source)
at **com.codenemesis.uploading.TestingActivity.up(TestingActivity.java:82)**
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:5610) 
at android.view.View$PerformClick.run(View.java:22265) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 
Found what was causing the problem. I was incrementing the variables "up" and "k" within the onSuccessListener. That might be changing their values before uploading the URI, so I incremented them outside the onSuccessListener and it worked perfectly fine.
Upload button code
StorageReference filepath = FirebaseStorage.getInstance().getReference().child("gpic");
while (up < mArrayUri.size()){
filepath.child(mArrayUri.get(k).getLastPathSegment()).putFile(mArrayUri.get(k)).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadURL = taskSnapshot.getDownloadUrl();
Toast.makeText(TestingActivity.this, downloadURL.toString(), Toast.LENGTH_SHORT).show();
}
});
up++;
k++;
}
}
Completable futures is much better approach for this problem.
Below upload method returns a completable future.
fun uploadImage(
path: String, imageUrl: Uri): CompletableFuture<String> {
val productImagesRef = storage.reference.child("$path/${imageUrl.lastPathSegment}")
val uploadTask = productImagesRef.putFile(imageUrl)
val promise = CompletableFuture<String>()
uploadTask.addOnFailureListener {
promise.completeExceptionally(it)
}.addOnSuccessListener {
productImagesRef.downloadUrl.addOnSuccessListener {
promise.complete(it.toString())
}.addOnFailureListener {
promise.completeExceptionally(it)
}
}
return promise
}
The caller can wait on multiple upload completable futures as below. Further, in android it would be ideal for the caller to spawn a new thread for multiple uploads to not block the UI main thread.
Thread {
val imageUploadPromises = imageUris.map {
uploadImage(product.group, product.type, product.name, it)
}
// wait for all uploads to finish. join() makes it wait.
CompletableFuture.allOf(*imageUploadPromises.toTypedArray()).join()
//To get individual downloadUrls
val downloadUrls = imageUploadPromises.map { it.get() }
}.start()

App crashes when calling startActivityForResult

I'm working on my first Android app, specifically in this case something to help me cook better. I have 2 activities that I'm currently struggling with, my MainActivity.java and whatCanIMake.java. When I start whatCanIMake from MainActivity using startActivity(intent), I'm able to pass objects using parcelables and generally use whatCanIMake. My issue is that I want to be able to pass back a list of everything that I've changed in my whatCanIMake activity. For example: I pass in a list of all the ingredients I currently have, and then whatCanIMake removes the ingredients that a recipe uses. I'd like to pass back the updated list of remaining ingredients.
The problem I'm having is with startActivityForResult(). Previously I was successfully able to use startActivity(), pass it the intent with the extra parcelables, and Bob's your uncle. When I changed over to startActivityForResult(), the new activity fails to launch, as the app crashes before hitting onCreate(). Obviously this points to my implementation of startActivityForResult(), so I've read basically every stack overflow question related to startActivityForResult() and now I'm here!
My code for starting whatCanIMake is below, as well as the onActivityResult() and corresponding code inside whatCanIMake.
It's just so odd to me that I can simply change out startActivityForResult() for startActivity() and the app works again! Thanks for any help in advance.
MainActivity.java:
public void searchRecipe(View view) {
crossViewVariables.setMakeSort('a');
Intent recipe = new Intent(this, whatCanIMake.class);
recipe.putExtra("Pantry",stock);
recipe.putExtra("Cookbook",activeCookbook);
recipe.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
startActivityForResult(recipe,R.integer.search_by_recipe);
//startActivity(recipe);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case (R.integer.search_by_recipe)://comes from Recipe Search?
if (resultCode == Activity.RESULT_OK) {
Bundle b = data.getExtras();
stock = b.getParcelable("Pantry");
}
if (resultCode == Activity.RESULT_CANCELED) {
}
case (R.integer.search_by_ingredient)://comes from Recipe Search?
if (resultCode == Activity.RESULT_OK) {
Bundle b = data.getExtras();
stock = b.getParcelable("Pantry");
}
if (resultCode == Activity.RESULT_CANCELED) {
}
case (R.integer.make_recipe)://comes from seeRecipe?
if (resultCode == Activity.RESULT_OK) {
Bundle b = data.getExtras();
stock = b.getParcelable("Pantry");
}
if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Cancelled", Toast.LENGTH_LONG).show();
}
case (R.integer.edit_pantry):
if (resultCode == Activity.RESULT_OK) {
Bundle b = data.getExtras();
stock = b.getParcelable("Pantry");
}
}
}
whatCanIMake.java:
Intent result = new Intent();
result.putExtra("Pantry", stock);
setResult(Activity.RESULT_OK,result);
finish();
LogCat:
FATAL EXCEPTION: main
Process: com.example.schre.mememachine, PID: 26721
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10826)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5697) 
at android.widget.TextView.performClick(TextView.java:10826) 
at android.view.View$PerformClick.run(View.java:22526) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:158) 
at android.app.ActivityThread.main(ActivityThread.java:7224) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
Caused by: android.util.AndroidRuntimeException: FORWARD_RESULT_FLAG used while also requesting a result
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1884)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1545)
at android.app.Activity.startActivityForResult(Activity.java:4283)
at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
at android.app.Activity.startActivityForResult(Activity.java:4230)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
at com.example.schre.mememachine.MainActivity.searchRecipe(MainActivity.java:91)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:5697) 
at android.widget.TextView.performClick(TextView.java:10826) 
at android.view.View$PerformClick.run(View.java:22526) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:158) 
at android.app.ActivityThread.main(ActivityThread.java:7224) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Remove this line:
recipe.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
You do not need it for startActivityForResult(), and it's what is causing your crash.
Instead of:
startActivityForResult(recipe,R.integer.search_by_recipe);
Try this:
startActivityForResult(recipe, getResources().getInteger(R.integer.search_by_recipe));

Categories

Resources