Paasing value from onActivityResult to Another method - android

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

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

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

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.

onActivityResult error when I press "cancel" button on my second Activity

I have the next activities:
Activity1
//declare
private static final int SAVE_DATA_FROM_ACTIVITY = 203;
//........... not important code
//button to open second Activity
public void btn_openSecondActivity(View view)
{
Intent intent = new Intent(Activity2.this, Activity1.class);
startActivityForResult(intent, SAVE_DATA_FROM_ACTIVITY);
}
}
protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
if (requestCode == SAVE_DATA_FROM_activity)
{
name= data.getStringExtra("Name");
}
}
//....... not important code
Activity2
On Second Activity I have two buttons:
Cancel
Save
//............
//declare
private static final int OK_RESULT_CODE = 1;
//Cancel button
public void btn_cancel(View view)
{
finish();
}
//Save button
public void btn_save (View view)
{
Intent intent = new Intent();
intent.putExtra("Name",et_name.getText().toString());
setResult(OK_RESULT_CODE, intent);
finish();
}
PROBLEM
When I click Save button all works perfect, but the problem it's when I click Cancel button, then it's reports an error:
Failure delivering result ResultInfo{who=null, request=203, result=0, data=null} to activity {com.example.alvaro.project/com.alvaro.project.Activity1}: java.lang.NullPointerException
I understand the problem, when I cancel is not the same result code but i don't know how I can solve it
Any suggestions?
You have issue in onActivityResult method. You don't check result.
Change your condition from :
if (requestCode == SAVE_DATA_FROM_activity)
to:
if (resultCode == OK_RESULT_CODE && requestCode == SAVE_DATA_FROM_activity)
Change this
if (requestCode == SAVE_DATA_FROM_activity)
{
name= data.getStringExtra("Name");
}
into
if (requestCode == SAVE_DATA_FROM_activity&&resultCode==RESULT_OK)
{
name= data.getStringExtra("Name");
}
and
Your cancel method is like
public void btn_cancel(View view)
{
setResult(RESULT_CANCELED);
finish();
}
And instead of OK_RESULT_CODE use Android default ok like Activity.RESULT_OK
Check if you manage to set the result
protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
if (requestCode == SAVE_DATA_FROM_activity && resultCode = Activity2.OK_RESULT_CODE)
{
name= data.getStringExtra("Name");
} else {
//probably btn_cancel pressed
}
}
check resultCode in onActivityResult
protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
if (resultCode == 1/*OK_RESULT_CODE from Second Activity */ && requestCode == SAVE_DATA_FROM_activity)
{
name= data.getStringExtra("Name");
}
}
Activity1
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SAVE_DATA_FROM_activity) {
if (resultCode == Activity.RESULT_OK) {
name = data.getStringExtra("Name");
} else if (resultCode == Activity.RESULT_CANCELED){
// TODO something
}
}
}
Activity2
delete field OK_RESULT_CODE
//Cancel button
public void btn_cancel(View view) {
setResult(Activity.RESULT_CANCELED, new Intent());
finish();
}
//Save button
public void btn_save(View view) {
Intent intent = new Intent();
intent.putExtra("Name", et_name.getText().toString());
setResult(Activity.RESULT_OK, intent);
finish();
}

Trying to read barcodes with Zxing, but it seems the onActivityResult is not beeing called

as the title says, I'm trying to scan 1D barcodes, so far I have thet following code:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void test(View view){
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "1D_CODE_MODE");
startActivityForResult(intent, 0);
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
switch (requestCode) {
case IntentIntegrator.REQUEST_CODE:
if (resultCode == Activity.RESULT_OK) {
IntentResult intentResult =
IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (intentResult != null) {
String contents = intentResult.getContents();
String format = intentResult.getFormatName();
TextView uno = (TextView) findViewById(R.id.textView1);
uno.setText(contents);
Toast.makeText(this, "Numero: " + contents, Toast.LENGTH_LONG).show();
Log.d("SEARCH_EAN", "OK, EAN: " + contents + ", FORMAT: " + format);
} else {
Log.e("SEARCH_EAN", "IntentResult je NULL!");
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.e("SEARCH_EAN", "CANCEL");
}
}
}
}
And of course, I have both IntentResult and IntentIntegrator added to the project.
So, the scanner is beeing called correctly when a button is pressed and it seems to scan the code perfectly (it says "Text found" after it scans it), but it seems that the onActivityResult is not called, since the TextView is not beeing updated and the Toast is not appearing.
Any idea on what the mistake could be?
Thanks in advance!
Your first mistake is not using IntentIntegrator.initiateScan(), replacing it with your own hand-rolled call to startActivityForResult().
Your second mistake is in assuming that IntentIntegrator.REQUEST_CODE is 0. It is not.
Hence, with your current code, you are sending out a request with request code of 0, which is coming back to onActivityResult() with request code of 0, which you are ignoring, because you are only looking for IntentIntegrator.REQUEST_CODE.
Simply replace the body of your test() method with a call to initiateScan(), and you should be in better shape. Here is a sample project that demonstrates the use of IntentIntegrator.
I resolve your same problem so.
public class MainActivity extends Activity {
private TextView tvStatus, tvResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.tvStatus = (TextView) findViewById(R.id.tvStatus);
this.tvResult = (TextView) findViewById(R.id.tvResult);
Button scanBtn = (Button) findViewById(R.id.btnScan);
scanBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(
"com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_FORMATS", "QR_CODE_MODE");
startActivityForResult(intent,
IntentIntegrator.REQUEST_CODE);
} catch (Exception e) {
Log.e("BARCODE_ERROR", e.getMessage());
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(
requestCode, resultCode, intent);
if (scanResult != null) {
this.tvStatus.setText(scanResult.getContents());
this.tvResult.setText(scanResult.getFormatName());
}
}
}
The onActivityResault function must be overridden. just add an #Override before the function declaration and it will be solved.

Categories

Resources