unable to get data in onActivityResult() in android on passing image URL - android

I want to upload multiple images through android application to firebase. I want to get the URL of the image which i got in my second activity(ie, B Activity) to my first activityIA activity). I have tried many answers posted but I could not solve the issue. Can anyone help me please. Here is my code
B Activity
mSelectBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), RESULT_LOAD_IMAGE);
} });
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK){
if(data.getClipData() != null){
totalItemsSelected = data.getClipData().getItemCount();
for(int i = 0; i < totalItemsSelected; i++){
Uri fileUri = data.getClipData().getItemAt(i).getUri();
String fileName = getFileName(fileUri);
fileNameList.add(fileName);
fileDoneList.add("uploading");
uploadListAdapter.notifyDataSetChanged();
StorageReference fileToUpload = mStorage.child("Images").child(fileName);
final int finalI = i;
fileToUpload.putFile(fileUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileDoneList.remove(finalI);
fileDoneList.add(finalI, "done");
uploadListAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Image Uploaded Successfully ", Toast.LENGTH_LONG).show();
ImageUploadInfo imageUploadInfo = new ImageUploadInfo(taskSnapshot.getDownloadUrl().toString());
imageURL=imageUploadInfo.getImageURL();
imagesList.add(imageURL);
Intent idata = new Intent()
idata.putExtra("imageURL", imageURL);
idata.putExtra("count",totalItemsSelected);
setResult(RESULT_OK, idata);
finish();
}
});
}
A activity
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (resultCode) {
case 1:
if (requestCode == 123) {
if (resultCode == RESULT_OK) {
imageURL = data.getStringExtra("imageURL");
this.orderItem.setImageURL(imageURL);
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
break;
case 2://added24
if(requestCode==100){//added24
if (resultCode == RESULT_OK) {
imageURL = data.getStringExtra("imageURL");
newString=data.getStringExtra("count");
}
}
break;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.order_item_update, menu);
FrameLayout image_viewCount = (FrameLayout) menu.findItem(R.id.star).getActionView();
TextView image_count = (TextView) image_viewCount.findViewById(R.id.cart_badge);
image_count.setText(newString);
image_viewCount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(getApplicationContext(),MultipleActivity.class);
Order.getInstance().getOrderItems();
startActivityForResult(intent,100);
}
});
I want to set the count (ie, "total selected" in image_count) but I am not able to get the value as I am not getting the value from Bactivity to A activity

change the onActivityResult in your A activity to,
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 123:
if (resultCode == RESULT_OK) {
imageURL = data.getStringExtra("imageURL");
this.orderItem.setImageURL(imageURL);
} else if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
break;
case 100:
if (resultCode == RESULT_OK) {
imageURL = data.getStringExtra("imageURL");
newString = data.getStringExtra("count");
} else {
//Write your code if there's no result
}
break;
}
}
You were switching resultCode and the cases you used were 1 and 2. The int constant for RESULT_OK is -1.
And in your MultipleActivity activity, the condition data.getClipData() != null will only be true when there are multiple Uris to send back. When there is just one you can get it with getData. You can do it like this
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK) {
if (data.getClipData() != null) {
totalItemsSelected = data.getClipData().getItemCount();
for (int i = 0; i < totalItemsSelected; i++) {
Uri fileUri = data.getClipData().getItemAt(i).getUri();
String fileName = getFileName(fileUri);
fileNameList.add(fileName);
fileDoneList.add("uploading");
uploadListAdapter.notifyDataSetChanged();
StorageReference fileToUpload = mStorage.child("Images").child(fileName);
final int finalI = i;
fileToUpload.putFile(fileUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileDoneList.remove(finalI);
fileDoneList.add(finalI, "done");
uploadListAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Image Uploaded Successfully ", Toast.LENGTH_LONG).show();
ImageUploadInfo imageUploadInfo = new ImageUploadInfo(taskSnapshot.getDownloadUrl().toString());
imageURL = imageUploadInfo.getImageURL();
imagesList.add(imageURL);
Intent idata = new Intent();
idata.putExtra("imageURL", imageURL);
idata.putExtra("count", totalItemsSelected);
setResult(RESULT_OK, idata);
finish();
}
});
}
} else {
Uri fileUri = data.getData();
String fileName = getFileName(fileUri);
fileNameList.add(fileName);
fileDoneList.add("uploading");
uploadListAdapter.notifyDataSetChanged();
StorageReference fileToUpload = mStorage.child("Images").child(fileName);
fileToUpload.putFile(fileUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileDoneList.remove(0);
fileDoneList.add(0, "done");
uploadListAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Image Uploaded Successfully ", Toast.LENGTH_LONG).show();
ImageUploadInfo imageUploadInfo = new ImageUploadInfo(taskSnapshot.getDownloadUrl().toString());
imageURL = imageUploadInfo.getImageURL();
imagesList.add(imageURL);
Intent idata = new Intent();
idata.putExtra("imageURL", imageURL);
idata.putExtra("count", 1);
setResult(RESULT_OK, idata);
finish();
}
});
}
}
}

Your issue is that the fileToUpload is async and you are creating them in a loop; you close the current activity when one of those tasks ends (the first one). You can simulate a semaphore, to mark the completion of each fileToUpload tasks and store the result in it, and in the onSuccess method, just check if all task instances are completed before closing the current activity and passing the result (which should be an array of objects btw).

As I understood:
Activity-A opens Activity-B using startActivityForResult.
and you want image url which you got in Activity-B to Activity-A via onActivityResult().
If so then,
you have to add your activity finish code in some action not into onActivityResult() of Activity-B.
Because adding it to onActivityResult() means you are waiting for the response of any Activity you open from Activity-B using startActivityForResult.

Related

How can I send back the captured image taken from second activity back to the main activity?

This is my code from the main activity class named Account class wherein when I press the add entry button it will navigate to the next activity which is the AddEntry class
//ADD ENTRY BUTTON
accountBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Account.this, AddEntry.class);
startActivityForResult(intent,REQUEST_CODE_ADD);
}
});
After it goes to the second activity which is the AddEntry class, a picture would be captured using the user's camera when the ImageView named entryPhoto is clicked
entryPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent takePhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File tempImage = null;
try {
tempImage = createImage();
} catch (Exception e) {
e.printStackTrace();
}
if (tempImage != null){
Uri uriImage = FileProvider.getUriForFile(c,"com.example.login.fileprovider",
tempImage);
mCurrentPhotoUri = uriImage;
takePhoto.putExtra(MediaStore.EXTRA_OUTPUT,uriImage);
if (ContextCompat.checkSelfPermission(c, Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(AddEntry.this,
new String[]{Manifest.permission.CAMERA},
REQ_CODE_CAMERA);
}
else {
startActivityForResult(takePhoto,REQ_CODE_TAKE_PHOTO);
}
}
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQ_CODE_TAKE_PHOTO && resultCode == RESULT_OK) {
entryPhoto.setImageURI(mCurrentPhotoUri);
}
Here is the code where I put all the the information inputted by user then send it back to the main activity. In the addPhoto is where I am supposed to put the image to be passed. I only tried passing an image from my drawable because I really don't know how to pass the image captured.
Intent data = new Intent();
data.putExtra("addPhoto",R.drawable.anonymous);
data.putExtra("addName", entryName.getText().toString());
data.putExtra("addRemark", entryRemark.getText().toString());
data.putExtra("addBirthday", entryBirthday.getText().toString());
data.putExtra("addAddress", entryAddress.getText().toString());
data.putExtra("addGender", selectedGender);
data.putExtra("addContactNo", entryContactNo.getText().toString());
data.putExtra("addHobbies", entryHobbies.getText().toString());
data.putExtra("addOtherInfo", entryOtherInfo.getText().toString());
setResult(RESULT_OK,data);
finish();
And this is the code in the onActivityResult in the main activity
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data); //ONACTRESULT OF ADD ENTRY
if (requestCode == REQUEST_CODE_ADD && resultCode == RESULT_OK){
int addPhoto = data.getIntExtra("addPhoto",1);
String addName = data.getStringExtra("addName");
String addRemark = data.getStringExtra("addRemark");
String addBirthday = data.getStringExtra("addBirthday");
String addAddress = data.getStringExtra("addAddress");
String addContactNo = data.getStringExtra("addContactNo");
String addGender = data.getStringExtra("addGender");
String addHobbies = data.getStringExtra("addHobbies");
String addOtherInfo = data.getStringExtra("addOtherInfo");
entryList.add(0,new Entry(addPhoto,addName,addRemark,addBirthday,addGender,addAddress,addContactNo,addHobbies,addOtherInfo));
myAdapter.notifyDataSetChanged();
}
Please I hope you will help me. I am still a beginner but I really want to be good at programming. Thank you in advance.
I think you can pass the Uri directly in bundle of Intent as it extends Parcelable which means it can retrieved as is
Adding
data.putExtra("addPhoto", mCurrentPhotoUri);
Retrieving
Uri photoUri = getIntent().getParcelableExtra<Uri>("addPhoto");

Disable button in a Listview's row while getting response of a save?

Issue:
I have a Listview in Mainactivity. Each row of listview has two buttons say SET and RUN.
Pressing SET will take you to SET activity and if the user clicks save button in SET Activity, I need to disable the SET button in the corresponding row position of the listview in mainactivity.
So Far Done:
For that I have a refresh function on a onclicklistener to requery the list with updated values. How to call that refresh function without keypress in the Mainactivity or is there any other way?
Activity MAIN :
viewHolder.ButtonSET.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = v.getTag().toString();
if (title.equals("SET")) {
if (Integer.parseInt((String) viewHolder.TDNQTY.getText()) > 0) {
if(scanoverornot(pos)<=0) {
Intent s = new Intent(DN.this, SETActivity.class);
s.putExtra("position", pos);
s.putExtra("mode", "SET");
try{
startActivityForResult(s, saverequestcode);
// getContext().startActivity(s);
}
catch(Exception e){
Toast.makeText(getContext(),""+e,Toast.LENGTH_LONG).show();
}
}
}
}
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null)
return;
switch (requestCode) {
case saverequestcode:
if (resultCode == RESULT_OK) {
String SItem= data.getStringExtra("SItem");
int SPos= data.getIntExtra("SPos", 0);
saved = 700;
Toast.makeText(getApplicationContext(), ""+ SItem+ SPos, Toast.LENGTH_LONG).show();
//btnvalidate.performClick();
}
}
}
Activity SET :
Intent sav = new Intent();
sav.putExtra("SItem", String.valueOf(itemno));
sav.putExtra("SPos", String.valueOf(pos));
setResult(RESULT_OK, sav);
finish();
You can use startActivityForResult to nail this purpose:
startActivityForResult(new Intent(this, DestinationActivity.class), MY_RESULT);
And then in your MainActivity:
public int MY_RESULT = 10;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_RESULT) {
if (resultCode == Activity.RESULT_OK) {
//refresh the list according to your logic
}
}
}
Don't forget to call setResult(Activity.RESULT_OK); when user clicks save button.
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setResult(Activity.RESULT_OK);
}
});
Issue Lines:
Have to add super.onActivityResult(requestCode, resultCode, data);
Removed switch case and used if condition for requestCode check
Solution:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data == null)
return;
if (requestCode == saverequestcode) {
if (resultCode == Activity.RESULT_OK) {
String SItem = data.getStringExtra("SItem");
String SPos = data.getStringExtra("SPos");
Toast.makeText(getApplicationContext(), "Item :" + SItem + "Position :" + SPos, Toast.LENGTH_LONG).show();
}
if (resultCode == Activity.RESULT_CANCELED) {
//Any methods
}
}
else if (requestCode == importrequestcode){
}
}
Activity SET :
Intent sav = new Intent();
sav.putExtra("SItem", String.valueOf(itemno));
sav.putExtra("SPos", String.valueOf(pos));
setResult(Activity.RESULT_OK,sav);
finish();

Two onActivityResults in one activity

Do you know how to handle two onActivityResult()s in one activity?
I need to use my camera and search for my photos in one activity.
public class MainActivity extends AppCompatActivity {
public static final int REQUEST_CAPTURE = 1;
Button button_Vyber_Fotku, button_Fotak;
ImageView imageView_VyberFotku, imageView_Fotak;
private static final int PICK_IMAGE = 100;
Uri imageUri_vybrana;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView_VyberFotku = (ImageView) findViewById(R.id.imageView_VyberFotku);
button_Vyber_Fotku = (Button) findViewById(R.id.button_Vyber_Fotku);
imageView_Fotak = (ImageView) findViewById(R.id.imageView_Fotak);
button_Fotak = (Button) findViewById(R.id.button_fotak);
if (!hasCamera())
{
button_Fotak.setEnabled(false);
}
}
public void Vyber_fotku_clicked(View v)
{
openGallery();
}
private void openGallery()
{
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE){
imageUri_vybrana = data.getData();
imageView_VyberFotku.setImageURI(imageUri_vybrana);
}
}
public boolean hasCamera()
{
return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
}
public void PouzijFotakClicked(View v)
{
Intent vyfot = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(vyfot , REQUEST_CAPTURE);
}
#Override
protected void onActivityResult(int requestCode1, int resultCode1, Intent data1)
{ if (requestCode1 == REQUEST_CAPTURE && resultCode1 == RESULT_OK)
{
Bundle extras = data1.getExtras();
Bitmap photo = (Bitmap) extras.get("data1");
imageView_Fotak.setImageBitmap(photo);
}
}
}
Instead of two different method for onActivityResults use single method and distinguish them according to their request code.
#Override
protected void onActivityResult(int requestCode1, int resultCode1, Intent data1){
if (requestCode1 == REQUEST_CAPTURE && resultCode1 == RESULT_OK){
Bundle extras = data1.getExtras();
Bitmap photo = (Bitmap) extras.get("data1");
imageView_Fotak.setImageBitmap(photo);
}
else if (resultCode1 == RESULT_OK && requestCode1 == PICK_IMAGE){
imageUri_vybrana = data1.getData();
imageView_VyberFotku.setImageURI(imageUri_vybrana);
}
}
Note: You can't have two declaration for single override method.
// define two variable camera and pick_image of int type pass value of request code of desired out put in activity onResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE){
//first one to pick image
//do somthing
}else if(resultCode == RESULT_OK && requestCode == Camera){
//use to take image from camera response
}
}
Check this
It works for me
private static final int CAMERA_ = 999;
private static final int GALLERY_ = 888;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_) {
if (resultCode == RESULT_OK) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
UtilsClass.mBitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
imageView.setImageBitmap(UtilsClass.mBitmap);
} 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();
}
}else if (requestCode == GALLERY_) {
if (resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
UtilsClass.mBitmap = (BitmapFactory.decodeFile(picturePath));
imageView.setImageBitmap(UtilsClass.mBitmap);
} 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();
}
}

Paasing value from onActivityResult to Another method

Question:- I want to pass Fullpath to uploadfile i want to use it in uploadfile
So i have try to catch it with creating the object but it dont work. SO if any solution will really appreciated
public void uploadfile(View view){
edittext = (EditText)findViewById(R.id.txtFile);
/* Intent sharingIntent = new Intent(Intent.ACTION_SEND);
*/ if(edittext != null)
{
Intent intent1 = new Intent(this, CreateDB.class);
startActivity(intent1);
}
else
{
Toast.makeText(NewMessage.this, "No File Selected", 2000).show();
}
}
// Listen for results.
public void onActivityResult(int requestCode, int resultCode, Intent data){
// See which child activity is calling us back.
if (requestCode == REQUEST_PATH){
if (resultCode == RESULT_OK) {
curPathName = data.getStringExtra("GetPath");
curFileName = data.getStringExtra("GetFileName");
FullPath = curPathName+"/"+curFileName;
edittext.setText(curFileName);
/* Toast.makeText(NewMessage.this, resId, duration);*/
}
}
}
Try this way,hope this will help you to solve your problem.
move EditText intialization in onCreate()
edittext = (EditText)findViewById(R.id.txtFile);
public void uploadfile(String fullPath) {
// write your upload file code here
}
public void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == REQUEST_PATH){
if (resultCode == RESULT_OK) {
if(data.getStringExtra("GetPath")!=null && data.getStringExtra("GetFileName")!=null){
edittext.setText(data.getStringExtra("GetFileName"));
uploadfile(data.getStringExtra("GetPath")+"/"+data.getStringExtra("GetFileName"));
}else{
Toast.makeText(NewMessage.this, "No File Selected", 2000).show();
}
}
}
}
change your uploadfile parameter from View to String and remove edittext.
public void uploadfile(String fullPath){
//do something
}
Then add this to your onActivityResult method
if(!TextUtil.isEmpty(curFileName)){
tv.setText(curFileName); // show curFileName in textView
uploadfile(fullPath); // pass fullPath to uploadfile
}else{
// show Toast, curFileName is empty
}
ps: tv is your textView

Intent to take picture, if i press back, the application crashes

I call this function:
private void TakePhoto() {
LogService.log(TAG, "inTakePicture");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/BlueSkyBio/media/", "test.jpg");
outputFileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, TAKE_PICTURE);
}
Which takes me on the next onActivityResult:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TAKE_PICTURE) {
if(outputFileUri != null){
LogService.log("MainFragment", outputFileUri.toString());
String path = outputFileUri.toString();
selectedVideoPath = path.substring(7);
LogService.log("in take pic", "selectedImagePath: " + selectedVideoPath);
Intent paintActivity = new Intent(getActivity(), PaintActivity.class);
paintActivity.putExtra("selectedImagePath", selectedVideoPath);
paintActivity.putExtra("isVideo", false);
startActivity(paintActivity);
((FragmentActivity) getActivity()).finish();
} else{
// Toast.makeText(getActivity(), "No picture taken", Toast.LENGTH_SHORT).show();
Intent main = new Intent(getActivity(), FragmentActivity.class);
startActivity(main);
((FragmentActivity) getActivity()).finish();
}
}
}
This works ok, but if i call the intent to take a picture, and then press the back button, if i already took a picture before, it will load that picture, if not, it will crash, because by pressing back, it will not take a picture. What can i do to escape this situation?
I have tried to test:
if(data != null) // instead of: if(outputFileUri != null){
But this will never enter the "else" part of the code.
use these conditions:
private static final int CAMERA_PIC_REQUEST = 1337;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==CAMERA_PIC_REQUEST && resultCode == RESULT_OK){
log.d("something","something");
}
else if (resultCode == Activity.RESULT_CANCELED)
{
log.d("something","something");
}
}

Categories

Resources