onActivityResult not working with onBackPressed? - java

I have two activities, Activity1.java and Activity2.java. Activity1.java starts Activity2.java and I need Activity2.java to return some data back to Activity1.java when the user presses the back button on the Action Bar. But for some reason, it is not working...
Activity1.java:
public class Activity1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_1);
Intent intent = new Intent(this, Activity1.class);
int requestCode = 100;
startActivityForResult(intent, requestCode);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
Log.i("TEST", "RequestCode:" + requestCode);
Log.i("TEST", "ResultCode:" + resultCode );
switch (resultCode) {
case RESULT_OK:
Log.i("TEST", data.getStringExtra("MESSAGE"));
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
Activity2.java
public class Activity2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(this, Activity1.class);
intent.putExtra("MESSAGE", "Hello from Activity 2!");
Log.i("TEST", "Setting result...");
setResult(RESULT_OK, intent);
finish();
super.onBackPressed();
}
}
When I run the app, only "Setting result..." is logged to Logcat. It seems like the onActivityResult override isn't even called. I've tried to change up the request code, result code, and setting the result in the onCreate() method of Activity2, but nothing works.
Could anybody help? Any help would be appreciated!

You are not calling the intent correctly:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_1);
Intent intent = new Intent(this, Activity1.class);
int requestCode = 100;
startActivityForResult(intent, requestCode);
}
should be:
Intent intent = new Intent(this, Activity2.class);

You need to return the result when you press the ActionBar back/home button, but you added the code in the bottom back button.
So, transfer the code in Activity2 to be handled when the ActionBar back button is pressed, so Override onOptionsItemSelected, and the home button has an id of android.R.id.home.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
Intent intent = new Intent(this, Activity1.class);
intent.putExtra("MESSAGE", "Hello from Activity 2!");
Log.i("TEST", "Setting result...");
setResult(RESULT_OK, intent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}

There are 3 problems with your code.
1. From Activity1, you start itself not Activity2. Change your code from
Intent intent = new Intent(this, Activity1.class);
to
Intent intent = new Intent(this, Activity2.class);
2. In onBackPressed() of Activity2, no need to declare Activity1 inside the intent, change your code from
Intent intent = new Intent(this, Activity1.class);
to
Intent intent = new Intent();
3. In Activity1, you should check requestCode before process further to make sure the data return from correct activity, because you might start more than one activity.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
Log.i("TEST", "RequestCode:" + requestCode);
Log.i("TEST", "ResultCode:" + resultCode);
if (requestCode == 100) {
switch (resultCode) {
case RESULT_OK:
Log.i("TEST", data.getStringExtra("MESSAGE"));
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}

Related

onBackPressed() back to Activity, not folder

I want to access the folder with other folders and files to see them and press the back button to return to the main view.
But when I press the back button, it returns me to the previous folder in the directory I am in. Only if I give it several times back, it returns to main view.
Is there a way to force it back to main view by pressing the Back button only once or maybe some way to create a floating button to create a new Intent once ACTION_GET_CONTENT is used?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
projectList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Just to see existing folders
Intent i = new Intent(Intent.ACTION_GET_CONTENT)
.setType("file/*");
setResult(RESULT_OK, i);
startActivityForResult(i, CODE_SEE_FOLDER);
}
});
}
...
#Override
public void onBackPressed() {
Intent intent = new Intent();
setResult(RESULT_CANCELED, intent);
startActivityForResult(intent, CODE_SEE_FOLDER);
super.onBackPressed();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CODE_SEE_FOLDER && requestCode == RESULT_OK){
Toast.makeText(context, "Your projects..", Toast.LENGTH_SHORT).show();
}else {
recreate();
}
}

Deleting back stack of activities

I have 3 activities: A->B->C
The user starts from activity A. When going to B he can press back and return to A.
But... When user goes to C from B. I wish that A and B will be removed and user will exit the app when clicking back.
I tried:
Intent intent = new Intent(B.this, C.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
but on back it still goes to B. If doing so:
Intent intent = new Intent(VerifyPhoneActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
The user goes back to A, so.. It is not what I need.
Override onBackPressed() in Activity C
#Override
public void onBackPressed() {
finishAffinity();
}
This will cause all Activitys running in the same task to finish. If the user starts the app again by tapping on it in the recent tasks window, Activity A will be shown.
100% working.
try to start Activity C like this.
Intent intent = new Intent(this,ActivityC.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity();
Start B activity with startActivityForResult():
Intent intent = new Intent(A.this, B.class);
startActivityForResult(intent, 100);
and override in class A startActivityForResult():
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 100) {
if (resultCode == 1) {
finish();
}
}
}
Now in B class set the result to be sent back to activity A:
Intent intent = new Intent(VerifyPhoneActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
setResult(1);
finish();
If I understood you right, You could achieve this is using SharedPreferences:
In Your Activity A add this:
public class ActivityA extends AppCompatActivity {
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
if (savedInstanceState == null){
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putBoolean("CloseApp", false);
editor.commit();
}
}
#Override
protected void onResume() {
super.onResume();
boolean finish = prefs.getBoolean("CloseApp", false);
if (finish){
this.finish();
}
}
In Activity B:
public class ActivityB extends AppCompatActivity {
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
}
#Override
protected void onResume() {
super.onResume();
boolean finish = prefs.getBoolean("CloseApp", false);
if (finish){
this.finish();
}
}
And Activity C:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putBoolean("CloseApp", true);
editor.commit();
}
#Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}
That should work.
you can just write this in Activity C if your application work from JELLY_BEAN to up .
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onBackPressed() {
super.onBackPressed();
finishAffinity();
}
if your app work under JELLY_BEAN you can use this solution :
Activity C :
#Override
public void onBackPressed() {
Intent i = new Intent(C.this,A.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("BackFromC",true);
startActivity(i);
super.onBackPressed();
}
Activity A in onCreate :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
if(getIntent() != null){
if(getIntent().getBooleanExtra("BackFromC",false)){
finish();
}
}
... your Code
}

finish() does not close current activity at first time

I'm trying to develop an app with two activities which they send data to each other. the problem is that I want tofinish(); second activity. when I click on goBackButton_ which I defined in XML_ SecondActivity comes up, when I click on the button again, it comes back to MainActivity as I wanted. why? and How to solve it?why it doesn't work at first time?
public class MainActivity extends AppCompatActivity {
Button button;
int REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
intent.putExtra("FirstActivity", "Hello from first activity");
startActivity(intent);
startActivityForResult(intent, REQUEST_CODE);
Log.d("TAG", "onClickListener: done!");
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
Log.d("TAG", "onActivityResult: Entered");
if(requestCode == REQUEST_CODE) {
Log.d("TAG", "onActivityResult: requestCode is OK");
if (resultCode == RESULT_OK) {
Log.d("TAG", "onActivityResult: result is returned OK");
String result = data.getStringExtra("SecondActivity");
Toast.makeText(this, result, Toast.LENGTH_LONG).show();
Log.d("TAG", "onActivityResult: done!");
}
}
}
}
public class SecondActivity extends AppCompatActivity {
TextView textView;
Button goBackButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
goBackButton = (Button) findViewById(R.id.goBackButton);
goBackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("TAG", "onClick: Entered");
Intent returnIntent = getIntent();
returnIntent.putExtra("SecondActivity", "from second Activity");
setResult(RESULT_OK, returnIntent);
Log.d("TAG", "onClick: Message sent");
finish();
Log.d("TAG", "onClick: Activity finished");
//Intent myIntent = new Intent(SecondActivity.this,MainActivity.class);
//startActivity(myIntent);
}
});
textView = (TextView)findViewById(R.id.textView);
Bundle extras = getIntent().getExtras();
if(extras != null){
String string = extras.getString("FirstActivity");
textView.setText(string);
}
}
}
solved
The problem is in your code -
startActivity(intent);
startActivityForResult(intent, REQUEST_CODE);
When you want to do startActivityForResult you don't have to do startActivity as this will first open your second activity without looking for result.
Remove startActivity(intent);
you have added startActivity(intent) as well as startActivityforResult(intent, REQUEST_CODE) which creates double instance of an activity use only startActivityforResult(intent, REQUEST_CODE);
Try remove startActivity(intent);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
intent.putExtra("FirstActivity", "Hello from first activity");
startActivityForResult(intent, REQUEST_CODE);
Log.d("TAG", "onClickListener: done!");
}
});

Display text to another class

I have a showAddForm button like the imej below in Claims.java.
When the + button is pressed, it will show Alert Dialog Window with radio buttons. When the radio button is checked, it will goes to specific activity. In the activity, it has an editText and a save button. I want the value on the editText display on the showAddForm button when the save button in the activity is clicked. How can I do to achieve this?
Claims.java
public class Claims extends Fragment {
private TextView c;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View claims = inflater.inflate(R.layout.claims, container, false);
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
AlertDialogRadio();
}
};
Button button1 = (Button) claims.findViewById(R.id.button10);
Button button = (Button) claims.findViewById(R.id.button8);
button1.setOnClickListener(listener);
c=(TextView)claims.findViewById(R.id.textView49);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(getActivity().getApplicationContext(), CameraMain.class);
startActivity(intent);
}
});
return claims;
}
public void AlertDialogRadio() {
final CharSequence[] ClaimsModel = {"Project", "Petrol", "Car Maintenance"
, "Medical", "Other"};
AlertDialog.Builder alt_bld = new AlertDialog.Builder(getActivity());
alt_bld.setTitle("Select a Claims");
alt_bld.setSingleChoiceItems(ClaimsModel, -1, new DialogInterface
.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(getActivity().getApplicationContext(), Project1.class);
startActivity(intent);
} else if (item == 1) {
Intent intent = new Intent(getActivity().getApplicationContext(), Petrol.class);
startActivity(intent);
} else if (item == 2) {
Intent intent = new Intent(getActivity().getApplicationContext(), CarMainten.class);
startActivity(intent);
} else if (item == 3) {
Intent intent = new Intent(getActivity().getApplicationContext(), Medical.class);
startActivity(intent);
} else if (item == 4) {
Intent intent = new Intent(getActivity().getApplicationContext(), Other.class);
startActivity(intent);
}
}
});
AlertDialog alert = alt_bld.create();
alert.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("text");
c.setText(result);
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}//onActivityResult
}
Assume the user choose Project.
Project1.java
public class Project1 extends AppCompatActivity {
private static String text;
private static EditText txt;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project);
txt= (EditText)findViewById(R.id.editText36);
Button b=(Button)findViewById(R.id.button17);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent returnIntent = new Intent();
text = txt.getText().toString();
returnIntent.putExtra("text", text);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
}
Now when I click save button in Project1.java, it return to the AlertDialogRadio which is not I want and the text still not displaying on the textView!!! ANYONE CAN HELP?????
You can use startActivityForResult() and override onActivityResult() in your activity. You can use setResult() in the second activity to pass whatever you want to your caller activity.
Example here and here
edit:
If you want it to use from a Fragment, you have to write this in your Activity that is holding the Fragment:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
This will pass the result to your fragment, so you can handle the result inside your fragment.
And as I already mentioned, you have to use startActivityForResult() instead of startActivity()
as #keybee said you should use startActivityForResult() to start the project.class from your dialog.
In the Project1.Class when you click save use setResult() to send the value back to the claims.class(Dont do startActivity() again. just use finish() ).
and in your Claims.class use onActivityResult(int requestCode, int resultCode, Intent data) to recieve the value sent from the project1.class.
you can do a setText() on showAddForm button in the onActivityResult(int requestCode, int resultCode, Intent data) function

onActivityResult (Re) called

I have the following situation:
Parent Activity:
ParentActivityClass
{
private Intent intent;
#Override
public void onCreate(Bundle savedInstanceState)
{
.....
intent = new Intent(this, ChildActivity.class);
startActivityForResult(intent, 202);
button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
startActivity(intent);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
Log.d("Log", "OK");
}
Child Activity
button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
finish();
}
});
#Override
public void finish()
{
Intent intent = new Intent();
intent.putExtra("extra", ".....");
setResult(RESULT_OK, intent);
super.finish();
}
When calling the finish() method of child activity, onActivityResult is called in the parent activity. When the child activity is open for the 2nd time, onActivityResult is not called.
Where is the mistake?
The problem I see is that you are calling startActivity(intent) instead of startActivityForResult(intent, 202) within you View.OnClickListener.
Edit:
I'm assuming that you are going to the ChildActivity through the button.
Hope it helps ;)
Best Regards

Categories

Resources