I have 2 Tabs - Tab1 and Tab2, Tab1Activity and Tab2Activity.
I want to pass values from Tab1Actvity to Tab2Activity but dont want to start Tab2Activity.
When i try below code it gives null value:
In Tab1Activity
getParent().getIntent().putExtra("key", "value");
In Tab2Activity
String valueString=getParent().getIntent().getStringExtra("key");
System.out.println("Testing.....: "+valueString);
I really discourage you from using global variables by extending the Application class. If your application goes to the background, (e.g. due a phone call) the android system might decide to kill your application. When the call is finished your application and the activity stack will be restored, but your activity state will be lost.
I'd rather suggest you to use broadcasts to send data to another activity.
In your Tab1Activity:
Intent dataIntent = new Intent();
dataIntent.setAction("com.your.app.DATA_BROADCAST");
dataIntent.putExtra("tag", "your data");
sendBroadcast(dataIntent);
Tab2Activity:
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String yourData = intent.getStringExtra("tag");
}
};
IntentFilter filter = new IntentFilter();
filter.addAction("com.your.app.DATA_BROADCAST");
registerReceiver(receiver, filter);
You definitely want to reconsider using Activities as the content of your tabs. The more standard approach is to use one Activity that uses Tabs to only show part of the layout when a particular tab is selected.
The Android documentation has an excellent worked example, check out Hello, TabWidget.
Alternative
If for some reason you do need to use Activities, you can pass information between them by either adding values to the extras bundle within the Intent your using to open each Activity, or by extending the Application class.
By extending the Application class (and implementing it as a Singleton) you get an object that will exist whenever any of your application components exist, providing a centralized place to store and transfer complex object data between application components.
Also you can use static classes or SharedPreferences for data transfer between tabs.
the correct way is setting a static field into the activity that creates the tabs
public class greformanews extends TabActivity {
public static String JorgesysTitle;
...
...
...
so in your Activity defined in tab 1
#Override
protected void onPause() {
greformanews.JorgesysTitle = "JORGESYS =)";
super.onPause();
}
in your Activity defined in tab 2
//get value defined in Activity 1 !:)
String Title = greformanews.JorgesysTitle
Related
I searched in site and there were similar questions as mine but none of theme were not my answer
look at this picture:
so it is clear that i want to start CrimeActivity by sending an intent from CrimeListFragment + an extra in its intent
the book that i read for android programming its author said:
Starting an activity from a fragment works nearly the same as starting an activity from another activity.
You call the Fragment.startActivity(Intent) method, which calls the corresponding Activity
method behind the scenes
CrimeListFragment.java :
public void onListItemClick(ListView l, View v, int position, long id) {
// Get the Crime from the adapter
Crime c = ((CrimeAdapter)getListAdapter()).getItem(position);
// Start CrimeActivity
Intent i = new Intent(getActivity(), CrimeActivity.class);
i.putExtra(CrimeFragment.EXTRA_CRIME_ID, c.getId());
startActivity(i);
}
the second part is now retrieving the intent and its extra and the author said about that:
There are two ways a fragment can access data in its activity’s intent: an easy, direct shortcut and a
complex, flexible implementation. First, you are going to try out the shortcut. Then you will implement
the complex and flexible solution that involves fragment arguments.
and my problem is about the first way, the shortcut
In the shortcut, CrimeFragment will simply use the getActivity() method to access the
CrimeActivity’s intent directly. Return to CrimeFragment and add the key for the extra. Then, in
onCreate(Bundle), retrieve the extra from CrimeActivity’s intent and use it to fetch the Crime
CrimeFragment.java :
public class CrimeFragment extends Fragment {
public static final String EXTRA_CRIME_ID =
"com.bignerdranch.android.criminalintent.crime_id";
private Crime mCrime;
...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCrime = new Crime();
UUID crimeId = (UUID)getActivity().getIntent()
.getSerializableExtra(EXTRA_CRIME_ID);
mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);
}
The downside to direct retrieval
Having the fragment access the intent that belongs to the hosting activity makes for simple code.
However, it costs you the encapsulation of your fragment. CrimeFragment is no longer a reusable
building block because it expects that it will always be hosted by an activity whose Intent defines an
extra named EXTRA_CRIME_ID.
This may be a reasonable expectation on CrimeFragment’s part, but it
means that CrimeFragment, as currently written, cannot be used with
just any activity.
My question and problem is the last sentence, why this Fragment (CrimeFragment) cannot be used with just any Activity???
The author explains it. Your CrimeFragment, in its onCreate() method, gets its hosting activity (through getActivity()) and then attempts to get an UUID from the Intent used to start that Activity.
This means that any activity containing your CrimeFragment now has to obey this rule, i.e. its intent should have (in it) an extra defined by the name EXTRA_CRIME_ID. If that activity does not comply, you'll see an exception being thrown in CrimeFragment's onCreate().
Try having this fragment in a new activity created by yourself to see what happens.
retrieval in onActivityCreated()
#Override
public void onActivityCreated(Bundle savedInstanceState) {
if (savedInstanceState != null) {
....
}
else {
UUID crimeId = (UUID)getActivity().getIntent().getSerializableExtra(EXTRA_CRIME_ID);
}
}
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
I want to send data from one tab to another. The one which will receive the data contains a spinner. When that data is passed on, I want to the spinner to change its selection to the one given within the data (it'll be the same as one of the spinner items).
Any ideas how I can use Bundle to do this?
is this in same activity or in a new activity ?
Same activity:
make an onClickListener and change the items in the spinner.
New Activity:
use
Inten intent = new Intent(yourclassname.this, targetClassname.class);
intent.putExtra("ID",DATA);
this.startActivity(intent);
it would help if you provide some code, but for now I hope this helps
As option make array holding data for a spinner static and then create a static method in you destination activity something like this:
public static void setSpinnerData (String[] data) {
spinnerData = data;
}
Then call something like this YourActivity.setSpinnerData (myArray);
Alternativerly you can consider saving data to the application object which is the same for all activities.
You may send the data (something small like a string or an ID) using a broadcast.
In the tab where the data is generated
final Intent i = new Intent(IConstants.UPDATE_SPINNER);
i.putExtra(IConstants.DATA_UPDATE, data);
this.sendBroadcast(i)
IConstants.UPDATE_SPINNER and DATA_UPDATE are just Strings used to identify your message by the receiver. You may also put them in your main activity instead of the interface I used.
In the tab with your spinner, declare an inner class for a broadcast receiver, it can access the spinner of the outer class.
private final class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
if( IConstants.UPDATE_SPINNER.equals(intent.getAction()) ) {
final String data = intent.getIntExtra(IConstants.DATA_UPDATE, "");
// update your spinner
return;
}
// process other messages ...
}
}
Register the broadcast receiver like this, e.g. in onCreate() or onResume()
this.broadcastReceiver = new MyBroadcastReceiver();
final IntentFilter f = new IntentFilter(IConstants.UPDATE_SPINNER);
// for more actions you can add them like this:
// f.addAction(IConstants.UPDATE_ONOTHER_WIDGET);
this.registerReceiver(this.broadcastReceiver, f);
Remember to unregister in onDestroy() or onPause().
Another option would be to use a handler and send messages to the handler. However, you would need the handler, which is located in the receiver, to be accessible in the sender. This way your fragments or activities (the tabs) would be stronger coupled.
I got list of checked contacts.However, i need to pass these selected contacts to another activity and display in edit Text.Please help.Thanks
You have a few solutions...
You can use static fields in your Java classes
You can pack the data into Intents via Intent.putExtra
Option (1) is probably going to be the easiest and quickest if you are trying to send data between your own activities. Option (2) is what you must do if you wish to send data to Activities of another applications.
I suggest you read these Q&A first though as some cover this question in more depth...
Passing data of a non-primitive type between activities in android
Passing data between activities in Android
Switching activities/passing data between activities
You have to use an Intent to do so.
Example, to pass the data to an activity already running:
public void sendToActivity(Object data){
Intent i = new Intent("SEND_DATA");
i.putExtra("data", this.catchReports.get(data));
sendBroadcast(i);
}
Then, you have to setup a listener in your receiving activity to catch the Broadcasted signal:
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
// Sets the View of the Activity
setContentView(R.layout.activity_layout);
registerReceiver(new CustomReceiver(this), new IntentFilter("SEND_DATA"));
}
With the following customreceiver:
public class CustomReceiver extends BroadcastReceiver {
private MyActivity activity;
public ReceiverEvent(MyActivity activity) {
this.activity = activity;
}
public void onReceive(Context context, Intent i) {
this.activity.doWhateverWithYourData(i.getParcelableExtra("newEvent"));
}
}
Note that if you want to transport Objects other than integers, floats and strings, you have to make them Parcelable.
I am getting some glitches while making a tab enabled application.
I want to share data, between two tabs of my application.
How can I achieve the same?
Rgds
Robert
the correct way is setting a static field into the activity that creates the tabs
public class greformanews extends TabActivity {
public static String JorgesysTitle;
...
...
...
so in your Activity defined in tab 1
#Override
protected void onPause() {
greformanews.JorgesysTitle = "JORGESYS =)";
super.onPause();
}
in your Activity defined in tab 2
//get value defined in Activity 1 !:)
String Title = greformanews.JorgesysTitle
You need to use intents to different activities, or in that case of tabs.
Go to Android Common Tasks
And look at the subject below "some intent examples". This will get you started.
You basically need to put whatever values you want into a bundle and pass that over to the new activity using intent.putextras();