Infinitely nested comments. How can I maintain a stack history? - java

I have a list adapter that allows the user to launch a new instance of the same Activity by pressing one of the items:
Intent intent = new Intent(mContext, CommentActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(ParseConstants.KEY_OBJECT_ID, commentId);
intent.putExtra(ParseConstants.KEY_SENDER_ID, userId);
mContext.startActivity(intent);
The problem is that I'm already in CommentActivity. If I write (Activity) mContext.finish() before launching the new Intent I will get to where I want to go, but then when the user presses back I return to very first Activity in the stack, which is MainActivity. I want to return the previous CommentActivity. How can I resolve this?
Manifest Entry:
<activity
android:name=".activity.CommentActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="#string/app_name"
android:launchMode="singleTask"
android:parentActivityName=".activity.CommentActivity"
android:screenOrientation="portrait"
tools:ignore="UnusedAttribute" />

When you use the Intent.FLAG_ACTIVITY_NEW_TASK flag you are telling Android to start a new Task (collection of Activities) to contain the new Activity rather than pushing the new Activity onto the stack associated with the current Task.
When the Activity exits, the Task is empty so you return from the root of the Application.
What you want to do is push the new Activity onto the existing stack. This is the default behavior, so remove the
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
line.
Read more about Tasks and Activities here.

Related

Going back to previous activity [duplicate]

This question already has answers here:
Android: Go back to previous activity
(24 answers)
Closed 3 years ago.
I have two activities, How is it possible to go back to a previous activity.
What code do I need to go back to previous activity
Assuming you started the new activity with
startActivity(new Intent(this, SecondActivity.class));
puts the SecondActivity in front and the FirstActivity in the backstack. To go back to the FirstActivity, put this in your second activity.
finish();
If you start the activity with result like below :
From 1st Activity :
startActivityForResult(new Intent(this, SecondActivity.class),requestCode);
You can finish the activity with required intents :
From 2nd Activity :
// Optional if you want to pass values from second activity to first
Intent data = new Intent();
data.putExtra("key","any_value");
setResult(RESULT_OK,data);
// Just finish
finish();
Refer the below link for more information like onActivityResult callback and more
https://developer.android.com/training/basics/intents/result
1st Method
If you are using Intent then make sure you don't call finish(); method after using the following code,
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
By this code, the Back Button you created will do its work and go to previous Activity.
And also don't override the onBackPressed() method in Activity.
2nd Method
There is another way that you can achieve this by setting Home Button to go to specific Activity, For that, you have to create Back Button in Action Bar in onCreate() method.
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
And in the AndroidManifest.xml file, you have to add the following,
<activity
android:name="com.example.yourapplication.SecondActivity"
android:label="#string/title_second_activity"
android:parentActivityName="com.example.yourapplication.MainActivity" >
<!-- Parent activity meta-data to support 4.0 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.yourapplication.MainActivity" />
</activity>
using intent
intent = new Intent(this, SecondActivity.class);
startActivity(intent);
Or you can use onBackPressed() if the activity added to backstack
onBackPressed();

How to set specific data from database in fields when launch through activity shortcut?

I am developing an android based note taking application with categories.I am supposed to create notes shortcuts on home screen. When user click on the shortcut the relevant activity should be open and the specific data should be set in Edit-texts i.e Its title and description.I unable to understand the logic to do that.
I tried all possible solutions that come into my mind. I passed Id of note in shortcut intent but when it launch from shortcut the fields are still empty.
This is my snippet of code to create shortcut:
Function to create shortcut:
private void createShortcutOfActivity() {
Intent shortcutIntent = new Intent(getApplicationContext(),
TextNotes.class);
shortcutIntent.setAction(Intent.ACTION_MAIN);
Intent addIntent = new Intent();
addIntent
.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, editTitle.getText().toString());
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(getApplicationContext(),
R.mipmap.ic_launcher));
addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
addIntent.putExtra("duplicate", false); //may it's already there so don't duplicate
getApplicationContext().sendBroadcast(addIntent);
}
This function is called when user click on option to create shortcut.
In Menifest use permission:
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
Also add intent filter and exported property in non launching activity:
<activity
android:name=".TextNotes"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.CREATE_SHORTCUT"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
The activity receive data from intent when open a note from another activity:
Intent newInt=getIntent();
isDoubleClicked=newInt.getBooleanExtra("Chk",false);
Cat=newInt.getStringExtra("Category");
Id=newInt.getIntExtra("Id",0);
String title=newInt.getStringExtra("Message");
String description=newInt.getStringExtra("Message2");
check=newInt.getStringExtra("Check");
editTitle.setText(title);
editText.setText(description);
I also tried to use this id in the shortcut intent of the function but having no change in result.
shortcutIntent.putExtra("key_primary",Id);
I want to keep the data when open using shortcut.For example for different note shortcut the rspected data should be set in fields just like in whatsapp the chat shortcuts of different contacts can be craeted . But unfortunately I am unable to understand that how should it be done because everytime I open using shortcut its fields become empty. Where should I pass id and how to set data when it launch from shortcut.
If you use shortcutIntent.putExtra("key_primary",Id); then you need to retrieve it using
Id=newInt.getIntExtra("key_primary",0);
That is the first parameter (key_primary) is the key that is used to identify the specific Intent Extra. Thus, the key value must match the key value used when putting the Intent Extra for a value (other than the default) to be retrieved.
As such coding Id=newInt.getIntExtra("Id",0); without using the matching/paired shortcutIntent.putExtra("Id",Id); will always result in 0 as the Intent Extra doesn't exist so the default value is returned.

Weird behaviour : Activity not getting started again when first started with FLAG_ACTIVITY_NEW_TASK

My scenario is,
When application starts then after user logs in I am starting an activity in the following manner,
Intent rangeFinderScreen = new Intent(YourLocationScreen.this, RangeFinderScreen.class);
rangeFinderScreen.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(rangeFinderScreen);
I am using Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK so that all previous activity stack gets cleared and it starts as a new task.
Then I have bottom bar to navigate between activities, so I have made a common listener (Activity) and implemented that in all the activities. It looks like the following,
public class CommonListenerForBottomButtons extends Activity implements View.OnClickListener{
Context context;
String buttonName;
public CommonListenerForBottomButtons(Context context, String buttonName){
this.context = context;
this.buttonName = buttonName;
}
#Override
public void onClick(View v) {
switch(buttonName){
case "play":
Intent rangefinder = new Intent(context, RangeFinderScreen.class);
rangefinder.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(rangefinder);
break;
// and so on more cases
}
}
}
Concern
If while starting the activity for first time I do the following,
Intent rangeFinderScreen = new Intent(YourLocationScreen.this, RangeFinderScreen.class);
startActivity(rangeFinderScreen);
Then all works.
But if I do it the following way (as I am doing now), i.e. by using rangeFinderScreen.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
Then activity doesn't get started again.
However if I start activity from any other activity rather than the Common Listener Activity like,
Intent rangefinder = new Intent(MyGolflerScreen.this, RangeFinderScreen.class);
startActivity(rangefinder);
Then it starts.
EDIT
Below is how I am initializing Common Listener in all activities:
homeLinearLayout.setOnClickListener(new CommonListenerForBottomButtons(getApplicationContext(), "home"));
playLinearLayout.setOnClickListener(new CommonListenerForBottomButtons(getApplicationContext(), "play"));
weatherLinearLayout.setOnClickListener(new CommonListenerForBottomButtons(getApplicationContext(), "weather"));
messageLinearLayout.setOnClickListener(new CommonListenerForBottomButtons(getApplicationContext(), "message"));
myGolflerLinearLayout.setOnClickListener(new CommonListenerForBottomButtons(getApplicationContext(), "mygolfer"));
All other activities start except for the one which is initially started with the flag Intent.FLAG_ACTIVITY_NEW_TASK.
Manifest file entry
<activity
android:name=".RangeFinderScreen"
android:label="#string/title_activity_range_finder_screen"
android:screenOrientation="portrait" >
</activity>
If your concern is to manage all stacks i prefer to use all "singleTop" Activities and starting them with flag Intent.FLAG_ACTIVITY_CLEAR_TOP
It will manage all you want to do.
you can add launchMode in Manifest inside activity tag that is equal to "singleTop" .
Hope it works ...
Do not set the flag Intent.FLAG_ACTIVITY_NEW_TASK when you launch an Activity from another Activity within your application. This isn't necessary and is probably causing your problem.
Also, if you are starting a new Activity every time the user clicks on a button you will find that you are creating new instances of these activities every time, and will end up with a big stack of them after awhile. This probably isn't the desired behaviour either. To switch between activities that may already be in the task stack you can set the flag Intent.FLAG_ACTIVITY_REORDER_TO_FRONT.

calling another activity android manifest xml

I have two sperate applications and I want to call start an activity from the second application in the first, here is my code to do so :
Intent intent1 = new Intent(Intent.ACTION_MAIN);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent1.setComponent(new ComponentName("org.two.three.application","org.two.three.application.one));
Context H= context;
H.startActivity(intent1);
And in the android manifest of the project I have this code, I have the line :
<activity android:name=".one">
</activity>
But I keep getting a runtime error, logcat says :
"Unable to find explicit activity class
{org.two.three.application/org.two.three.application.one}; have you
declared this activity in your AndroidManifest.xml?"
Can anyone see my error? The only thing I can think of is my package of the first activity is org.two.three.Class while the second is org.two.three.application.SecondClass. Does this matter?
Thanks in advance
At first try removing those code that you are adding
**
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent1.setComponent(new ComponentName("org.two.three.application","org.two.three.application.one));
Context H= context;
**
Then add following code into an action method like onClick
Intent intent = new Intent(this, NewActivity.class);
startActivity(intent);
Add your Android Manifest configuration file
<activity android:name="NewActivity"></activity>
You just need to make your activity publicly available. To do that just add
android:exported="true"
to the <activity> tag in your manifest.
Normally, activities are not available to other components that are outside of the package. This is the standard default behaviour. But, of course, you can make them available if you want to.

Android activity stack control. Can't figure out how to remove history

I have following 2 activities(plus many more not important for this question):
<activity android:name=".activities.HomeActivity" android:excludeFromRecents="true" />
<activity android:name=".activities.AdHocActivity" android:noHistory="true"/>
HomeActivity is a first one and only one wich I keep history for. User can go differnt places from Home and click Back to come back to main HomeActivity.
I also have service running on alarm and checking for some specific things. When specific criteria met I'm displaying my AdHocActivity
Intent i = new Intent(context, AdHocActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra(BlockingActivity.INTENT_BLOCKED_PACKAGE_NAME, packageName);
context.startActivity(i);
FLAG_ACTIVITY_NEW_TASK was necessary to show Activity from BroadcastReceiver
Now, this AdHoc activity displays some message to user and has a button to take user back to HomeActivity
private void sendToMainApplication()
{
Intent i = new Intent(this, HomeActivity.class);
startActivity(i);
finish();
}
All this work, but I get second instance of HomeActivity in a stack. So now when user taps "Back" - my Home activity flashes and comes back (previous copy).
I want only one copy to stay on top. I want it to be like anchor one. If it doesn't exist - I want new one to be opened.
The trick to prevent HomeActivity from being doubled was to call it like this:
private void sendToMainApplication()
{
Intent i = new Intent(this, HomeActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}

Categories