How to start an activity in finish() - java

I want to start another activity in finish() depending on a condition. I got the same code working in onDestroy() but I think this is not the right place from the lifecycle point of view.
(Activities might be destroyed, although there were not actively left by the user).
The following code did not have any effect:
#Override
public void finish() {
if (mCondition) {
Intent intent = new Intent(this, OtherActivity.class);
startActivity(intent);
}
super.finish();
}
Why is it not working, are there alternatives?

I think the best option is starting the new activity then finish the current one:
if (mCondition) {
Intent intent = new Intent(this, OtherActivity.class);
startActivity(intent);
finish();
}

I have Used Myself this and it is working fine
public void ToBeClosed()
{
Intent a = new Intent(context,NewActivity.class);
startActivity(a);
OldActivity.this.finish();
}
and use the function in if statement body
if (mCondition) { ToBeClosed(); }

Related

Not able to go from one activity to other activity in android

I'm trying to use a button to change from Main Activity on android studio to Main Activity 2 and I get the error
no suitable constructor found for Intent(<anonymous OnClickListener>,Class<MainActivity2>)
Intent intent = new Intent(this, MainActivity2.class);
^
I'm on version 4.1 and I want to assume i'm following an old tutorial or I just missed some punctuation.
This is my code:
buttonPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openMainActivity2();
}
public void openMainActivity2(){
Intent intent = new Intent(this, MainActivity2.class);
startActivity(intent);
Just to give more clarity to Caio's answer, when you use this
Intent intent = new Intent(this, MainActivity2.class);
The intent is created in an anonymous inner class i.e. OnClickListener. Thus this does not refer the instance of your Activity (or Context) as intended. You need to provide the correct context of your class.
Hence , do this:
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
startActivity(intent);
You have to try getApplicationContext() or activity.this instead of this.
I think you are having this issue for "this". Cause, I can't see any other issue.
Intent intent = new Intent(getApplicationContext(),MainActivity2.class)
startActivity(intent);
you should provide the correct context of your class.
try this:
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
startActivity(intent);
This java code is for the old version, it does not work with android studio's latest version.
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
startActivities(intent);
here is code for the more recent versions:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openMainActivity();
}
public void openMainActivity() {
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
startActivity(intent);
};

android.content.Context.getPackageName() on a null object reference

I am getting this error when transtioning from a fragment to an activity as shown below:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference at android.content.ComponentName.<init>(ComponentName.java:130) at android.content.Intent.<init>(Intent.java:6108)
Below is my code for going to the next activity, The error occurs on the first line of the code below.
Intent mainIntent = new Intent (getContext(), MainActivity.class);
mainIntent.addFlags (Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity (mainIntent);
I don't see any solution so far online.
It seems that you're getting a wrong context that raises this NullPointerException
Try to replace the below line:
Intent mainIntent = new Intent (getContext(), MainActivity.class);
With: >> if you're within an activity
Intent mainIntent = new Intent (this, MainActivity.class);
with: >> if you're within a callback listener within the activity
Intent mainIntent = new Intent (MyActivityName.this, MainActivity.class);
With: >> if you're within a fragment
Intent mainIntent = new Intent (requireActivity(), MainActivity.class);
Please try with getActivity() intsead of getContext()
I work the transaction of the fragment with this code
private Context context;
context.startActivity(new Intent(context, MainActivity.class));
I have been able to find a work around this. I realised I am getting the error because I am creating the new Intent inside the firebase OnCompleteListener as shown below. So after i removed it from inside the listener and called it outside, my program works properly.
I instead created a global boolean variable that I updated to true on successful data storage. Then I can access it somewhere else and then transtion to another if true.
#BEFORE
PostsRef.child(key).updateChildren(postsMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(getActivity(), "New Post is updated successfully.", Toast.LENGTH_SHORT).show();
Intent mainIntent = new Intent (getActivity(), MainActivity.class);
mainIntent.addFlags (Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity (mainIntent);
} else {
Toast.makeText(context, "Error occured while updating your post.", Toast.LENGTH_SHORT).show();
}
}
});
#AFTER
PostsRef.child(key).updateChildren(postsMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
mSuccess = true;
Toast.makeText(getActivity(), "New Post is updated successfully.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Error occured while updating your post.", Toast.LENGTH_SHORT).show();
}
}
});
Hello guys I have also realised one of the big causes of this error is the lifecycle methods.So I was overriding them inside my fragment to update the user state on the firebase database. Because of this they caused the android.content.Context.getPackageName() on a null object reference error whenever I tried to move to the main activity managing it. Incase I used the fragment transition to move to another fragment, the MainActivity would get excecuted more than twice. After stopping to override them my application worked properly. If someone would explain why that happens it would be great.
#Override
public void onStart() {
super.onStart();
updateUserState("Online");
}
#Override
public void onResume() {
super.onResume();
updateUserState("Online");
}
Since, you are calling from a Fragment, you should use getActivity() here instead of getContext()
Intent mainIntent = new Intent (getActivity(), MainActivity.class);
mainIntent.addFlags (Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity (mainIntent);
This should help I hope.
Sometimes startActivity method throws an exception like:
Calling startActivity() from outside of an Activity context requires
the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
So you should intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK) method

Using intent to go back previous page instead go in to the previous page...

I'm using intent go back to the previous page and put finish(); But It goes like B page go in A page instead of B page back to A page. Do I type wrong code?
Here is the code
Intent intent = new Intent(Donation_Page.this, MainActivity.class);
startActivity(intent);
finish();
Change your code from
Intent intent = new Intent(Donation_Page.this, MainActivity.class);
startActivity(intent);
finish();
to
finish();
That's it
you can also try #Override onBackPressed to go back to previous Activity
#Override
public void onBackPressed() {
super.onBackPressed();
}

build a "fake" stake using startActivity()

I need to build a fake back stack in my application. I am starting an activity using aContext.startActivity(aIntent) and would like to build a stack to allow the user to go to the HomeActivity instead of exiting the application.
Now I know about the TaskStackBuilder but I am not sure on how to implement it when it comes to startActivity method.
This is what I got so far when building the stack but I am not sure how to use it in startActivity method
Intent detailActivity = new Intent(aContext, DetailsActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(aContext);
stackBuilder.addNextIntentWithParentStack(detailActivity);
PendingIntent pendingIntent = stackBuilder
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
Why don't you just use onBackPressed
Context context = this;
#Override
public void onBackPressed()
{
Intent intent = new Intent(context,YourActivity.class);
startActivity(intent);
}
You need to start activity without adding to back stack, then override the onBackpressed
//Start activity without adding to history stack
Intent i = new Intent(...); // Your list's Intent
i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NO_HISTORY); // Adds the FLAG_ACTIVITY_NO_HISTORY flag
startActivity(i);
//Override the newly open activity onBackPressed()
#Override
public void onBackPressed()
{
Intent i= new Intent(getApplicationContext(),HomeActivity.class);
startActivity(i);
}
The fix that i found to work without having to use onBackPressed was to add a flag to the intent
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
For building fake stack use TaskStackBuilder.This will help you to create back stack.
Suppose you activities are 'ActivityA', ActivityB, ActivityC, ActivityD. Now you are in ActivityB and from ActivityB you want launch ActivityD and want a back stack like this:
ActivityA -> ActivityC -> ActivityD
That means back press from ActivityD will go to ActivityC and back press from ActivityC wil go to ActivityA
In ActivityB you can use this
TaskStackBuilder.create(this)
.addParentStack(ActivityA.class)
.addNextIntent(new Intent(this, ActivityA.class))
.addNextIntent(new Intent(this, ActivityC.class))
.addNextIntent(new Intent(this, ActivityD.class))
.startActivities();
To use TaskStackBuilder you min sdk version should be 16 or higher.
For sdk less than 16 you can manually check in onBackPressed and start Activity.
In Activity D:
#Override
public void onBackPressed(){
Bundle extras = getIntent().getExtras();
if (extras.containsKey("FROM_ACTIVITY_B_FOR_STACK")){
// start Activity C
}else{
super.onBackPressed();
}
}
Do this for other activities where you want to add back stack

Restart MainActivity or application with singleTop.

How can I restart my application or MainActivity when the activity have:
android:launchMode="singleTop"
I have tried:
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
But because of singleTop this not working, there is an other way to do this?
I did my theme switcher like this:
Intent intent = getIntent();
finish();
startActivity(intent);
Basically, I'm calling finish() first, and I'm using the exact same intent this activity was started with. That seems to do the trick?
UPDATE: As pointed out by Ralf below, Activity.recreate() is the way to go in API 11 and beyond. This is preferable if you're in an API11+ environment. You can still check the current version and call the code snippet above if you're in API 10 or below. (Please don't forget to up-vote Ralf's answer!)
public void reload() {
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
or
private void restartFirstActivity()
{
Intent i = getApplicationContext().getPackageManager()
.getLaunchIntentForPackage(getApplicationContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK );
startActivity(i);
}
try to restart with this may this will help u
Intent i = cntxt.getPackageManager().getLaunchIntentForPackage(cntxt.getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addCategory(Intent.CATEGORY_HOME);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
cntxt.startActivity(i);
Use this:
Intent finishIntent = new Intent( this,
activity_that_you_want_to_return.class);
finishIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(finishIntent);

Categories