Had a clarification to make: Can 2 intents be defined to pass the the same data to 2 different activities ? The second class (logout.class) is not getting accessed. The code is:
protected void onPostExecute(String result) {
if(result != null)
{
Intent tokenIntent = new Intent(mContext, tokenActivity.class);
Bundle bundle = new Bundle();
bundle.putString("responsedata",result.substring(result.indexOf("=")+1,result.length()));
tokenIntent.putExtras(bundle);
startActivity(tokenIntent);
Intent tokenIntent2 = new Intent(mContext,logout.class);
Bundle bundle2= new Bundle();
bundle2.putString("responsedata",result.substring(result.indexOf("=")+1,result.length()));
tokenIntent.putExtras(bundle2);
startActivity(tokenIntent2);
}
}
}
Maybe you can use this,
public abstract void startActivities (Intent[] intents, Bundle options)
Added in API level 16
Launch multiple new activities. This is generally the same as calling startActivity(Intent) for the first Intent in the array, that activity during its creation calling startActivity(Intent) for the second entry, etc. Note that unlike that approach, generally none of the activities except the last in the array will be created at this point, but rather will be created when the user first visits them (due to pressing back from the activity on top).
This method throws ActivityNotFoundException if there was no Activity found for any given Intent. In this case the state of the activity stack is undefined (some Intents in the list may be on it, some not), so you probably want to avoid such situations."
Related
I have an activity which can be accessed via different activities.
Like you have one activity containing a listview and the second containing a gridview and both shows the same data. When you click on an item a new activity with some details is shown. I need to somehow remember which activity was the initial one (with gridview or listview) so that I can set a button to redirect here. But it's not enough to just return to previous activity (like using finish() to close the current one), because there is a way to navigate among different objects from inside the details activity (I have a gridview on that screen). So I need to remember the initial view during moving through the details activity for various number of times.
Is there a way?
EDIT: omg why so many downvotes? At least tell me why it is so stupid, I'm learning coding for Android for 2 weeks how am I supposed to know everything??
This sounds like it would best be solved by using two Fragments within the same Activity
You can use a bundle object to pass data to the new activity (B) so you could know wich activity (listView or gridView) had started it.
In activity B:
private static final String ACTIVITY_TYPE = "activity_type";
public static Intent createIntent(Context context,String activityType)
{
Intent intent = new Intent(context, ActivityB.class);
Bundle b = new Bundle();
b.putString(ACTIVITY_TYPE,activityType);
intent.putExtras(b);
return intent;
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle b = getIntent().getExtras();
String activityType;
if (b != null)
{
activityType = b.getString(ACTIVITY_TYPE);
}
//the calling activity didn't use the createIntent method and didn't provide the activity type
else
{
activityType = "some_default_type";
}
//save activity type to use later
//rest of your code
}
In the calling activity:
Intent intent = ActivityB.createIntent(ActivityListView.this,"activity_list_view");
startActivity(intent);
how can I call MyActivitiy.this, but put arguments to it or to its Bundle?
My Code:
OnSwipeTouchListener onSwipeTouchListener = new OnSwipeTouchListener(MyActivitiy.this) {
#Override
public void onSwipeLeft() {
//your actions
}
};
The question doesn't seem to be very clear. But, consider declaring a Context ( set it equal to MyActivity.this) and using that as the parameter for your OnSwipeListener.
The way to communicate with an Activity is via Intents. In whatever code you use to start your Activity, go:
Intent intent = new Intent(someContext, MyActivity.class);
intent.putExtra("myKey", "whateverValue");
In your Activity's onCreate() method, use:
Intent intent = getIntent();
String message intent.getStringExtra("myKey", "aDefaultValueJustInCase");
Once that Activity is started, the String message will acquire the value "whateverValue".
As to using its Bundle, you probably only want to do that to recreate your Activity (say you're returning from another Activity, or pressed Back). Documentation for that is here.
Hope that answered your question. If not, please provide us more details and we will probably be able to provide more specific answers.
I am wondering about the best way to design / program this:
If I have a Boolean value (let's say whether the user has extra power or not) and I need to pass it from Activity A to B to C. Should I add it to an intent from each activity to another OR should I just store it in a static variable and access it every time?
Its is safer to pass it in the intent. sometimes android kills apps without warning when it needs memory and your static values will not be retained on the other hand intent extras are kept. if you want to push it a little further, use shared preference. its designed using Map data struct so speed will not be a problem.
Android Intents have a putExtra method that you can use to pass variables from one activity to another.
public class ActivityA extends Activity {
...
private void startActivityB() {
Intent intent = new Intent(this, ActivityB.class);
intent.putExtra("HAS EXTRA POWER", false);
startActivity(intent);
}
}
public class ActivityB exntends Activity {
Bundle bundle;
private void hasExtraPower() {
bundle = getIntent().getExtras();
if(!bundle.getBoolean("HAS EXTRA POWER")
// do something
else
// do something else
}
}
Passing data through Intent
If you use that only in that activity that's fine but
When u need to pass to other layer like viewmodel that will make your operation's speed slower
So I'm working on this project, and its rather large in size. I've have put a kind of 'behind the scenes' security login system in.
Pretty much, all the activities extend the subActivity class, and the subActivity extents Activity. This has allowed me to make every form automatically .putExtra() when it starts a new activity, and on every onCreate() it will check the incoming data and determine whether it should force the user to login (push them to the LoginActivity).
So right now, the login activity, on successful login, it loads to the MainActivity. I want it to dynamically load the activity the user was last at...
This means, store the class of the activity that launched the LoginActivity in the extras, and then have the LoginActivity, on successful login, get the class from the extras and use it to start the Activity.
I'm looking for the simplest way possible, I was trying serializable, but was having a lot of issues and thought there must be another way to just pass a reference to the 'destination' class.
Hope this makes sense!
Cheers
You could use Java reflection API:
Call your login activity like this:
Intent intent = new Intent(this, LoginActivity.class);
intent.putExtra("activity", getClass().getName());
startActivity(intent);
Then parse the calling activity's name in login activity and go back to it after successful log in:
private String mActivity;
#Override public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
// ...
mActivity = "";
Bundle extras = getIntent().getExtras();
if (extras != null)
mActivity = extras.getString("activity");
}
}
#Override public void onClick(View view)
{
try {
Class<?> cls = Class.forName(mActivity);
startActivity(new Intent(this, cls));
}
catch (Exception e) {
e.printStackTrace();
}
}
In the LoginActivity, simply call finish() which will return to the next Activity on the Stack, in your case going back to the previous one.
You can start your login activity by startActivityForResult and then check result of login activity in your main activity. Look here http://developer.android.com/reference/android/app/Activity.html#StartingActivities
I am new to android so please excuse the newbie question. I have a game I am trying to port from an old Java applet to android. My goal is to get this functional and then post an article on a site like CodeProject (or a better one if there are ones more appropriate). The idea is to show that a person brand new to android development can create an app in a reasonable amount of time.
I am making some progress but have run into a problem. I have the main activity in which the user interacts with. I then created a menu item that in turn starts a second activity (call it child) with a modest number of checkbox's, seekbar's etc to fill in parameters. I can successfully pass the class containing all the options from main to child. But I cannot get the child to pass this data back to the main.
First here is my main code that starts the child activity:
public void addBalls()
{
Intent myIntent = new Intent(this, GameOptions.class);
Bundle b = new Bundle();
b.putSerializable("options", gameParams);
myIntent.putExtras(b);
startActivityForResult(myIntent,STATIC_OPTIONS_VALUE);
}
The data passed to the child (and hopefully back again) is:
public class GameOptionParams implements Serializable
{
private static final long serialVersionUID = 1L;
public int speedBarPosition;
public int vgravityBarPosition;
public int mgravityBarPosition;
public int viscosityBarPosition;
public int restititionBarPosition;
public boolean trace;
public boolean collide;
public boolean mush;
public boolean wrap;
public boolean flicker;
}
And here is the expected return (again in main)
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode)
{
case (STATIC_OPTIONS_VALUE) :
{
if (resultCode == Activity.RESULT_OK)
{
//retrieve intended options
Bundle b = data.getExtras();
gameParams = (GameOptionParams) b.getSerializable("options");
}
break;
}
}
}
The child activity successfully receives the gameParams data. It then interacts with the user to update the values and then I attempt to return it but it does not seem to get sent to main. Here is the child code in the onStop() override.
Maybe this code should not be in the onStop() override but I can't determine where else to place it.
#Override
public void onStop()
{
super.onStop();
//read widget values
gameParams.speedBarPosition = speedBar.GetPosition();
gameParams.vgravityBarPosition = vgravityBar.GetPosition();
gameParams.mgravityBarPosition = mgravityBar.GetPosition();
gameParams.viscosityBarPosition = viscosityBar.GetPosition();
gameParams.restititionBarPosition = restititionBar.GetPosition();
//todo save to persistent
Intent resultIntent = new Intent(this, TiltBall2ImpactActivity.class);
Bundle b = new Bundle();
b.putSerializable("options", gameParams);
resultIntent.putExtras(b);
setResult(Activity.RESULT_OK, resultIntent);
}
Back in the main onActivityResult override I always see requestCode=0, resultCode=0, data=null. I assume this is a typical newbie problem, I have been reading the sdk documentation, user forums etc and have come close to a solution but just not quite there yet. Any help would be appreciated.
Since this is sort of a setting menu for the game, I assume you are going to need these values for more than one activity. If so you extend the android.app.Application class.
In that class you can create attributes to hold your values. In any activity you can call
MyApplication myApp = (MyApplication)getApplicationContext();
where myApp is a singleton. So you will get the values you set from another activity.
You will need to add this code to your application tag in the manifest file for it to work
android:name=".MyApplication"
If you need to keep these values for next startup of the application, you need to use SharedPreferences. This is a good tutorial for that
http://saigeethamn.blogspot.com/2009/10/shared-preferences-android-developer.html
Assuming in your 'child' activity, the user has to press an 'OK' or 'Save' button then put the code to set the gameParams parameters in the button's onClick(...) handler.
Use the default constructor for instantiating the Intent, example...
Intent resultIntent = new Intent();
...then after creating the Bundle and adding gameParams to it and calling setResult(...), simply call finish() to terminate the 'child' activity. There aren't many occasions that I can think of to override onStop() and I suspect you don't want to be using it to attempt returning the Intent.