Calling code (run in service):
Intent textIntent = new Intent(this, TextActivity.class);
textIntent.putExtra("text_seq", message.xfer.seq);
textIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(textIntent);
Called code (in TextActivity):
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
Log.d(TAG, "" + bundle.getInt("text_seq"))
...
In fact the whole bundle is lost - the code above throws an NPE when calling bundle.getInt().
I'm sure there's something obvious I have missed...
Bundle you are reading is NOT for that purpose. As per docs
void onCreate (Bundle savedInstanceState)
Bundle: If the activity is being re-initialized after previously being
shut down then this Bundle contains the data it most recently supplied
in onSaveInstanceState(Bundle). Note: Otherwise it is null.
If you need to get extras you need to call:
Bundle extras = getIntent().getExtra();
and then you can try to get your values:
int myVal = extras.getInt(key);
Alternatively you can try to use:
int myVal = getIntent().getIntExtra(key, defaultVal);
Have you tried using getIntent().getInt("text_seq") ?
get your bundle like this
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
Bundle intentBundle = getIntent().getExtra();
Log.d(TAG, "" + intentBundle.getExtra(“text_seq"))
}
The bundle you're using is the savedInstanceState you can read more about it here.
What you need to use is this:
Bundle intentBundle = getIntent().getExtra();
Since you added the bundle to Intent extras, so you need to get it from the getIntent().getExtra()
also you can get individual items like this :
getIntent().getIntExtra("text_seq", defaultValToReturn);
Related
Im developing a small android application, i was using shared preference in order to transfer data between fragments. now i want to use bundle but the problem is the bundle in the second fragment getting null value how do i solve that problem ?
here are some part of code
... some usefull Code in first fragment
args.putLong("favoriteCountry", countryListSpinnerData.get(favoriteCountrySpinner.getSelectedItemPosition()).getId());
args.putInt("favoriteCurrency", currencySpinner.getSelectedItemPosition());
args.putDouble("favoriteBudget", Double.parseDouble(budgetEditText.getText().toString()));
args.putString("additionalInformation", additionalInformationEditText.getText().toString());
MoneyPartnerShipStepTwo moneyPartnerShipStepTwo = new MoneyPartnerShipStepTwo();
moneyPartnerShipStepTwo.setArguments(args);
FragmentHelper.NAVIGATE_FRAGMENT(new MoneyPartnerShipStepTwo(), getActivity())
Now the second fragment
#Override
public void onCreate(Bundle savedInstanceState) { // savedInstanceState is null why ???
super.onCreate(savedInstanceState);
if (getArguments() != null) {
this.bundle = savedInstanceState;
}
setHasOptionsMenu(true);
}
you create new MoneyPartnerShipStepTwo(), not instance with your argument.
so, please change FragmentHelper.NAVIGATE_FRAGMENT(moneyPartnerShipStepTwo, getActivity())
I have this code:
Rechercher.java:
public void doOnResult(String json){
if ( json.equals("Aucune propostion pour le mois")||json.equals("Aucune propostion pour cette date")) {
Toast.makeText(Rechercher.this, "Aucune proposition actuellement.", Toast.LENGTH_LONG).show();
finish();
} else {
Intent iAfficher = new Intent(this, Afficher.class);
extras.putString("json", json);
extras.putInt("nbplaces", mCounter);
iAfficher.putExtras(extras);
this.startActivityForResult(iAfficher, 10);
}
}
Afficher.java:
Integer places = extras.getInt("nbplaces");
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.afficher);
ListView lvTrajets = (ListView)findViewById(R.id.lvTrajets);
Bundle bundle = getIntent().getExtras();
.......
proposition.put("Date",propId);
proposition.put("Trajet", propLieu+" de "+propVille+" --> "+propGare+" Places : "+places);
The places variable is always equal to 0.
I don't know why I can't get the right value.
You need to get the value from the Bundle in your Afficher.java file in your onCreate method as below:
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.afficher);
ListView lvTrajets = (ListView)findViewById(R.id.lvTrajets);
Bundle bundle = getIntent().getExtras();
Integer places = bundle.getInt("nbplaces"); //get value here
String jsonval=bundle.getString("json");
put the following line after the bundle declaration inside onCreate() method
Integer places = bundle.getInt("nbplaces");
and remove the following line
Integer places = extras.getInt("nbplaces");
try this please:
Integer places ;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.afficher);
Bundle bundle = getIntent().getExtras();
places = bundle.getInt("nbplaces")
...........
Move this Integer places = extras.getInt("nbplaces"); inside onCreate. Also initialization of extras.
public Intent getIntent ()
Added in API level 1
Return the intent that started this activity.
Instead of Integer places use int places. int is a primitive data type so use int instead of Integer for primitive data types.
int places;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.afficher);
Bundle extras = getIntent().getExtras();
places = extras.getInt("nbplaces");
You need to wait till the activity is created then use getIntent()
http://developer.android.com/reference/android/os/Bundle.html#getInt(java.lang.String)
public int getInt (String key)
Added in API level 1
Returns the value associated with the given key, or 0 if no mapping of the desired type exists for the given key.
Parameters
key a String
Returns
an int value
i have question about two different Bundle object in below methods :
onSaveInstanceState(Bundle outState);
onCreate (Bundle savedInstanceState);
how android system know that bundle object in onCreate method is object that programmer used for save his/her activity states and onCreate method use that Bundle object to get activity state that is killed by system?
is the Bundle object one of the Activity class Members and super.saveInstanceState(outState);
save the Bundle in the Bundle object of Activity and when an activity call onCreate(Bundle ) method this member send to onCreate method?how can i use Bundle in onCreate( ) method?
please help me...
The values you save in the onSaveInstanceState method's bundle will be sent back to you in onCreate. As an example of how this works.
You get a phone call.
Your Activity is stopped and onSaveInstanceState is called. You put a value into this bundle.
Android finishes your activity and destroys that instance because the OS needs memory.
The user returns to your application.
The bundle is recreated from some type of persistent storage that Android maintains on your behalf. Now your onCreate can grab the value you placed in the bundle during onSaveInstanceState
EXAMPLE
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.lldr_activity);
mFilterCheckbox = (CheckBox) findViewById(R.id.checkbox_id);
if(savedInstanceState != null) {
mFilterCheckbox.setChecked(savedInstanceState.getBoolean("FILTER_STATE", false));
}
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putParcelable("FILTER_STATE", mFilterCheckbox.isChecked());
}
I have a search screen which can be launched from clicking on a "name" field of another screen.
If the user follows this workflow, I add an extra to the Intent's Extras called "search". This extra uses the text populating the "name" field as its value. When the search screen is created, that extra is used as a search parameter and a search is automatically launched for the user.
However, since Android destroys and recreates Activitys when the screen rotates, rotating the phone causes an auto-search again. Because of this, I'd like to remove the "search" extra from the Activity's Intent when the initial search is executed.
I've tried doing this like so:
Bundle extras = getIntent().getExtras();
if (extras != null) {
if (extras.containsKey("search")) {
mFilter.setText(extras.getString("search"));
launchSearchThread(true);
extras.remove("search");
}
}
However, this isn't working. If I rotate the screen again, the "search" extra still exists in the Activity's Intent's Extras.
Any ideas?
I have it working.
It appears getExtras() creates a copy of the Intent's extras.
If I use the following line, this works fine:
getIntent().removeExtra("search");
Source code of getExtras()
/**
* Retrieves a map of extended data from the intent.
*
* #return the map of all extras previously added with putExtra(),
* or null if none have been added.
*/
public Bundle getExtras() {
return (mExtras != null)
? new Bundle(mExtras)
: null;
}
While #Andrew's answer may provide a means for removing a specific Intent extra, sometimes it is necessary to clear ALL of the intent extras and, in this case, you will want to use
Intent.replaceExtras(new Bundle())
Source code of replaceExtras:
/**
* Completely replace the extras in the Intent with the given Bundle of
* extras.
*
* #param extras The new set of extras in the Intent, or null to erase
* all extras.
*/
public #NonNull Intent replaceExtras(#NonNull Bundle extras) {
mExtras = extras != null ? new Bundle(extras) : null;
return this;
}
The problem can be solved using extra flag which is persistent during destroys and recreations. Here is the narrowed down code:
boolean mProcessed;
#Override
protected void onCreate(Bundle state) {
super.onCreate(state);
mProcessed = (null != state) && state.getBoolean("state-processed");
processIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
mProcessed = false;
processIntent(intent);
}
#Override
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
state.putBoolean("state-processed", mProcessed);
}
protected void processIntent(Intent intent) {
// do your processing
mProcessed = true;
}
Kotlin
activity?.intent?.removeExtra("key")
can any one guide me what mistake am i doing in this code??? it not seems to be working..
i have two activies
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = new Intent(DataPassing.this, DataPassing2.class);
Bundle b = new Bundle();
b.putInt("key", 1123);
intent.putExtras(b);
startActivity(intent);
finish();
}
and in second activity i have written
public void onCreate(Bundle savedInstanceState) {
Bundle b = getIntent().getExtras();
int value = b.getInt("key", 0);
Toast.makeText(this, value, Toast.LENGTH_SHORT).show();
}
but the code is giving me error i dont know why.. i have added second activity to manifest file.. please guide what mistake i am doing ???
any help would be appriciated..
Can you debug the code, or perhaps include some try/catch-blocks, to try and detect where the error is happening, and what the error message is?
Other than that, try doing it this way instead:
Intent intent = new Intent(DataPassing.this, DataPassing2.class);
intent.putExtra("key", 1123);
startActivity(intent);
... and still fetch the bundle in DataPassing2 as you have been before. I don't know if it'll help, because I don't know much about what your error is, but it might.
Try this one may be it work.
public void onCreate(Bundle savedInstanceState) {
Bundle b = getIntent().getExtras();
int value = b.getInt("key");
Toast.makeText(this, value, Toast.LENGTH_SHORT).show();
}