Android Launching the current activity with different Intent Action - android

[Update Solution]
Referring to the post in the link
ViewPager PagerAdapter not updating the View
public void onSomeButtonClicked(View view) { // registered to Button's android:onClick in the layout xml file
Log.w(TAG,"Some button clicked !!");
getIntent().setAction(IntentManager.Intents.ACTION_SPAWN_LIST_BY_SOMETHING);
mViewPager.getAdapter().notifyDataSetChanged();
}
// And inside my PagerAdapter
#Override
public int getItemPosition(Object object) {
return 0;
}
Fixed all my problems, i just used Intent.setAction().
[Update to below Post]
My problem is i have a ViewPager PagerAdapter in my Main Activity. On clicking one of the 3 buttons., any specific intent will be fired (i used intent, i could have gone with just State variable as well, just that i pass some Uri with the intent). What happens is., i do
public void onSomeButtonClicked(View view) { // registered to Button's android:onClick in the layout xml file
Log.w(TAG,"Some button clicked !!");
getIntent().setAction(IntentManager.Intents.ACTION_SPAWN_LIST_BY_SOMETHING);
mViewPager.getAdapter().notifyDataSetChanged();
}
This is why i was guessing maybe i should just do startActivity again, with the new Intent Action on the same Activity.
Spawning a new Activity, i would have to redraw every other view in the layout which is basically the same code, for the most part in the current activity.
Any suggestions here? Please help
[Original Post]
I have a PagerAdapter and 3 Buttons in the my Main Activity. This activity is enter from Main Launcher.
When i press any one of the buttons, the Intent Action is changed.
My question:
The changed Intent action reflects some changed view in the ViewPager and does_not spawn a new Activity as such, only the view is updated.
What approach should i take to get this task?
Can i start the currentActivity using startActivity() and different Intent actions on button click?
or is there any other efficient way in android to do this?
[No need code, just explanation of logic / method would suffice]
Thanks in advance

If you are saying that you are trying to use startActivity to bring up the same activity again, and its not working, it could be because you set something like singleTop in your Android manifest.
If you are asking whether or not you should use an intent to change the state of your Activity, then the answer is "it depends". If the user would expect the back button to return your app to its previous state (instead of going back to the home screen), then it might be a good choice for you. If that is the case, however, I would ask why not just make 2 different Activities? Otherwise, just do as Dan S suggested and update the state of your Activity as the user interacts with it.

You can always use the onNewIntent() hook. Do something like this in your activity:
protected void onNewIntent(Intent intent){
//change your activity based on the new intent
}
Make sure to set the activity to singleTop in your manifest. Now whenever startActivity is called the onNewIntent() will be executed. Also, note that per the documentation:
Note that getIntent() still returns the original Intent. You can use setIntent(Intent) to update it to this new Intent.

Related

startActivityOnResult() in recycler view onitemClick()

so I need to create a notes app, in which user opens and sees a RecyclerView-grid of notes. on clicking any note, it opens a new activity SecondActivity with 2 edit texts title and data.
On closing secondActivity, I want the user to see the title he had set in secondActivity on the grid he clicked on the main page.HOW?
After searching for a white, i got this startActivityForResult(). i understood its working, but it is not available in the adapter/holder, where my onitemclicklistener is present.
So how can i get to recieve this title? can I use the saveInstanceState bundle for this work?I also researched and observed that a child Acticvity's(SecondActivity) onSaveInstanceState is not called when the secondActivity is destroyed. so maybe that bundle thing would be a wrong path.In my OnBindHolder() function, i was using myholder.itemview.getContext().startActivity(...,...) for calling the secondActivity. I also tried passing the context for main Activity in adapter and using it for starting activity, but it still didn't show startActivityForResult() ...
UPDATE:
here are the java classes from my app(I have explained in detail about my problem in a comment in Main Activity.java):
MainActivity.java
Details.java
(Reycler View Files:)
RVadapter.java
RVholder.java
RVdata.java
RVfeeder.java
githubLink
You need to cast Context to Activity because it has startActivityForResult.
((Activity) context).startActivityForResult()
or
(((Activity) itemView.getContext()).startActivityForResult()

startActivityForResult from ActivityGroup

I am using ActivityGroup. I use the following code from ActivityGroup in order to replace view and launch a new activity.
Intent i = new Intent(SummaryCostScreen.this,PermissionsScreen.class);
replaceContentView("activity1",i);
public void replaceContentView(String id, Intent newIntent) {
View view = getLocalActivityManager().startActivity(id,
newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView();
}
The problem with the above code is that, I need to have startActivityForResult in place of startActivity, since I need to update the UI of launcher activity when coming back from the launched activity.
getLocalActivityManager() does not have startActivityForResult. How should I address this situation, such that, I am able to update UI from onActivityResult?
Any help is much appreciated.
PS: I cannot change the replaceContentView approach for launching new screen, since that has been used at numerous other places and this is the only scenario in which I need to call startActivityForResult
Converting comments as answer,
Try using onResume() to update UI of SummerCostScreen

How to make the back function and set the last contentView

I hawe many view's in my application and now the problem is how to go back from one view to another.
What I could do it by set back Buttons in every view but i would like to use the android back hard button.
I have tried something like this:
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode==KeyEvent.KEYCODE_BACK)
{
finish();
}
return false;
}
But the problem is that this will close my application.
Could you please guide me for a proper solution, for example to memorize the last view was set and then to come back to this view or something like this.
Here is the code with which I am changing the view (it's a method in my main activity):
public void CheckIfUserIsLogedIn ()
{
int userPresence = localDatabase.CheckUserPresence();
if (userPresence == 0)
{
setContentView(R.layout.main);
}
else
{
setContentView(R.layout.userlogedon);
}
}
Thank you.
Look!
You are doing this wrong way..
An Activity class should only have on content View. (because it is recommended way and easy to use and implement).
And if you want to go to next View, show it under another separate Activity.
when you will finish it, you will be automatically redirected to previous Activity.
(and you don't need to memorize the Previous View :) )
See here, how to work with Activity Stacks.
I am not sure to understand your problem correctly because Android do all that for you automatically. Once a view is opened when you switch to another view it is paused (on screen but has not focus) or stopped (has no focus)
http://developer.android.com/reference/android/app/Activity.html
If the current view (activity) has been launched by the previous view (activity), pressing the back button will make you "close" the current view and go back to the previous one automatically.
Now two things :
Perhaps your are simply opening all views wihtin the same activity by showing on or off components which is a bad way of doing and is not recommended by android. What you should do is 1 view = 1 activity.
You are thinking like "iPhone/iPad" where you have to implements back buttons in the "views". In android you don't need to do so. Putting the "finish" command in your code at that point seem to close the application which make me think you have programmed as explained in point 1.
Hope it helps
EDIT:
To start a new activity do it like this
startActivity(new Intent(this, MyOtherActivity.class));
you put this in your code where you want to load the new view (activity)
Now if you want to transfer some information between activities you must do something like this :
Intent myIntent; //intent declaration
int aNumber = 10; // info to send to other activity
String aString = "abcd"; // info to send to other activity
// link Intent to the other activity
myIntent = new Intent(view.getContext(), MyOtherActivity.class)
//put the extra info
myIntent.putExtra("myNumber", aNumber);
myIntent.putExtra("myString", aString);
//start the new view/activity
startActivity(myIntent);
and in the new opened activity you retrieve the infos like this (in the oncreate usually)
int aNumber;
String aString;
#Override
public void onCreate(Bundle savedInstanceState) {
aNumber= getIntent().getExtras().getInt("myNumber");
aString= getIntent().getExtras().getString("myString");
}
Actually i m not sure that understand exactly but..
take a map or a shared preference and at the back button set last View on map or Shared preference .
At the calling or at start activity fetch the data which have stored you.
this will helps you.

How to check if an activity is the last one in the activity stack for an application?

I want to know if user would return to the home screen if he exit the current activity.
I'm going to improve on the comment of #H9kDroid as the best answer here for people that have a similar question. (Original link)
You can use isTaskRoot() to know whether the activity is the root of a task.
UPDATE (Jul 2015):
Since getRunningTasks() get deprecated, from API 21 it's better to follow raukodraug answer or Ed Burnette one (I would prefer second one).
There's possibility to check current tasks and their stack using ActivityManager.
So, to determine if an activity is the last one:
request android.permission.GET_TASKS permissions in the manifest.
Use the following code:
ActivityManager mngr = (ActivityManager) getSystemService( ACTIVITY_SERVICE );
List<ActivityManager.RunningTaskInfo> taskList = mngr.getRunningTasks(10);
if(taskList.get(0).numActivities == 1 &&
taskList.get(0).topActivity.getClassName().equals(this.getClass().getName())) {
Log.i(TAG, "This is last activity in the stack");
}
Please note, that above code will be valid only if You have single task. If there's possibility that number of tasks will exist for Your application - You'll need to check other taskList elements. Read more about tasks Tasks and Back Stack
Hope this will help new beginners, Based above answers which works for me fine, i am also sharing code snippet so it will be easy to implement.
solution : i used isTaskRoot() which return true if current activity is only activity in your stack and other than i also handle case in which if i have some activity in stack go to last activity in stack instead of opening new custom one.
In your activity
#Override
public void onBackPressed() {
if(isTaskRoot()){
startActivity(new Intent(currentActivityName.this,ActivityNameYouWantToOpen.class));
// using finish() is optional, use it if you do not want to keep currentActivity in stack
finish();
}else{
super.onBackPressed();
}
}
there is an easiest solution to this, you can use isTaskRoot()
in your activity
One way to keep track of this is to include a marker when you start a new activity and check if the marker exists.
Whenever you start a new activity, insert the marker:
newIntent=new Intent(this, NextOne.class);
newIntent.putExtra(this.getPackageName()+"myself", 0);
startActivity(newIntent);
And you can then check for it like this:
boolean islast=!getIntent().hasExtra(this.getPackageName()+"myself")
While there may be a way to achieve this (see other answers) I would suggest that you shouldn't do that. Normal Android applications shouldn't need to know if the Home screen is about to display or not.
If you're trying to save data, put the data saving code in your onPause() method. If you're trying to give the user a way to change their mind about existing the application, you could intercept the key up/down for the Back key and the onBackPressed() method and present them with an "Are you sure?" prompt.
I've created a base class for all my activities, extending the AppCompatActivity, and which has a static counter:
public abstract class BasicActivity extends AppCompatActivity {
private static int activityCounter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
++activityCounter;
...
}
#Override
public void onDestroy() {
super.onDestroy();
--activityCounter;
if(activityCounter==0) {
// Last instance code...
}
}
public boolean isLastInstance() { return (activityCounter==1); }
}
This has worked well enough, so far; and regardless of API version. It requires of course that all activities extends this base class - which they do, in my case.
Edit: I've noticed one instance when the counter goes down to zero before the app completely exits, which is when the orientation is changed and only one activity is open. When the orientation changes, the activity is closed and another is created, so onDestroyed is called for the last activity, and then onCreate is called when the same activity is created with the changed orientation. This behaviour must be accounted for; OrientationEventListener could possibly be used.
The Problem with sandrstar's solution using ActivityManager is: you need a permission to get the tasks this way.
I found a better way:
getIntent().hasCategory(Intent.CATEGORY_LAUNCHER)
The Activity on the Stack bottom should allways get this category by default while other Activities should not get it.
But even if this fails on some devices you can set it while starting your Activity:
Intent intent = new Intent(startingActivity, SomeActivityClass.class);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
activity.startActivity(intent);
Android implements an Activity stack, I suggest you read about it here. It looks like all you want to do though is retrieve the calling activity: getCallingActivity(). If the current activity is the first activity in your application and the application was launched from the home screen it should (I assume) return null.
The one thing that missed here, is the "Home key" click, when activated, you can't detect this from your activity, so it would better to control activity stack programmatically with handling "Back key" press and moving to required activity or just doing necessary steps.
In addition, you can't be sure, that starting your activity from "Recent Activity" list can be detected with presetting some extra data into intent for opening activity, as it being reused in that case.

Android Activity Update

I am calling an activity from within itself - basically i've a list of new storys and two filter buttons that when clicked restart the activity with an intent passed that changes the news stories.
When i run the app it works, but for a second i get the old activity UI while the app reads from the new xml feed and then the UI updates. Is there any way to stop this from happening and get the activity to restart cold.
here's the code I am currently attaching to the onclicklistener
public void openFootballNews(View v) {
Intent i = new Intent(this, News_Landing.class); // News_landing class is the class this code is in
Bundle bundle = new Bundle();
bundle.putString("code", "football"); // this, if set, changes the xml feed to read
i.putExtras(bundle);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.onCreate(null); //this has halved the time the old UI is on the screen for but I cant get rid of it completely
startActivity(i);
}
any help would be great, thanks!
Starting an activity from itself doesn't make much sense (unless your aim is to do something esoterically recursive ;) ). Also, I may be mistaken, but I believe activities are kept in a stack so that as you flip between news stories, you're piling up one nearly-identical activity after another. I'd similarly think calling onCreate() by hand is bad form.
Would need to see all of your code, but my guess is that you are reading your feed and creating your list inside onCreate(), and that your best bet is to refactor that into a openNews(String sport) method, which you call once in onCreate() and again in your listener(s).

Categories

Resources