How to check existence Extras in Intent - android

When I try to get Extras, I get Fatal Eroorr
try{
Sdacha=getIntent().getExtras().getString("Sdacha");
}
catch(NullPointerException e){}
How can I check existence Extras?

Try this,
if(getIntent().getExtras().containsKey("Sdacha"))
{
String preview=getIntent().getExtras().getString("Sdacha");
}
EDIT
Also as Evos suggested, one more layer of Null check can also be added to the above code.If you are sure that the extras will not be null, then the above approach is good. If not follow the below one.
if(getIntent().getExtras()!=null)
{
if(getIntent().getExtras().containsKey("Sdacha"))
{
String preview=getIntent().getExtras().getString("Sdacha");
}
}

It's easy just check that Extras is not null before getting something from it:
if (getIntent().getExtras() != null){
Sdacha=getIntent().getExtras().getString("Sdacha");
}

Bundle bundle = getIntent().getExtras();
if (bundle != null) {
String preview = bundle.getString("Sdacha");
if (preview != null) {
// do anything .....
}
}

To prevent this from happening, I like to encapsulate my calls into a static startActivity method, the same pattern as the newInstance() in fragments:
public static void startActivity(Activity activity, int param, int flags){
Intent intent = new Intent(activity, MainActivity.class);
intent.setFlags(flags);
intent.putExtra(PARAM, param);
activity.startActivity(intent);
}
And of course if you use this method from other activities, you'll never have a NPE.

Related

Crashes in Android 6.0.1 after restart because of Bundle extras = getIntent().getExtras()

I am trying retrieve variables with this code
Here's my MainActivity
public class MainActivity extends AppCompatActivity {
String Variable1 = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle extras = getIntent().getExtras();
if (extras != null) {
Variable1 = extras.getString("Variable1");
EditText1_ET.setText(Variable1);
}
}
}
I am creating Variable1 in another Activity
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("Variable1", textview.getText().toString());
startActivity(i);
Its working great until I reboot OS (Android 6.0.1) and start my app, I get error that my app stopped working.
I tried it on Android 5.1 and its working without error.
Can anyone help me please?
You should do this, and check for nullability :
if (extras != null) {
String variable1 = extras.getString("Variable1");
if (variable1 != null) {
EditText EditText1_ET = (EditText) findViewById(R.id.xxxx);
if (EditText1_ET != null)
EditText1_ET.setText(variable1);
}
}
Also init your EdiText variable before setting text !
Well it is better to change the following:
SearchQueryTerm = extras.getString("Variable1");
EditText1_ET.setText(Variable1);
to:
Variable1 = extras.getString("Variable1");
if(EditText1_ET != null) {EditText1_ET.setText(Variable1);}
in your code you just assign null to your EditText every time.
Looks like you've solved your problem. Yet, I though I need to put my suggestion here.
From the Activity2 where you're passing the parameter value, do you really need to get the text from a TextView? Because, you already have set some String value in your TextView somewhere. Just use that String variable to pass the value to another Activity.
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("Variable1", myString);
startActivity(i);
Now in the MainActivity, check if the Variable1 is null and initialize your EditText first.
public class MainActivity extends AppCompatActivity {
String Variable1 = null;
private EditText EditText1_ET; // Declare an EditText first
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize your EditText here
EditText1_ET = (EditText) findViewById(R.id.your_edit_text_id);
Bundle extras = getIntent().getExtras();
if (extras != null) {
Variable1 = extras.getString("Variable1");
// Here check if Variable1 is null
if(Variable1 != null) EditText1_ET.setText(Variable1);
}
}
}
Had the same problem, it was still crashing even after checking for null.
I used a try-catch block and that solved the problem for me.

Android cant tell intents apart

In my main activity (where everything happens in my application) I call a variety as of now just two other activities which end up calling back to my MainActivity via button press. How do I distinguish between these two Intents back to my MainActivity? I have seperate operations I want to prefrom based on things I did back in the two seperate activites.
Heres what I tried:
Intent intent = getIntent();
String s_message = intent.getStringExtra(AppSettings.EXTRA_MESSAGE);
String f_message = intent.getStringExtra(ViewFavorites.EXTRA_MESSAGE);
if(s_message != null) {
//do something
} else if (f_message != null) {
//do something
}
But when I run my application I find when exiting the two activities that they are prefroming the methods I do not wish them to...am I going about this wrong?
What I do is simply set an Extra in my passing Intent then compare that. Something like this. When creating the Intent add an Extra to compare to
intent.putExtra("source", "appSettings");
then in your Activity check what that value is
Intent intent = getIntent();
String source = intent.getStringExtra("source"); // get that value here
if(s_message != null) {
if ("appSettings".equals(source)){
//do something
} else if (viewFavorites.equals(source)) {
//do something else
}
}
You could use variations of this as far as how you assign the Extra but this is a simple example that works well for me, especially when there are just a few Activites that will be calling this one.
Set a different ACTION on each intent, then use if(getIntent().getAction().equals(ACTION)) to distinguish between intents.
public class MainActivity extends Activity {
public static final String ACTION_ONE = "com.yourpackage.ACTION_ONE";
public static final String ACTION_TWO = "com.yourpackage.ACTION_TWO";
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Intent intent = getIntent();
if(intent.getAction() != null){
if(intent.getAction.equals(ACTION_ONE){
//DO SOMETHING
} else if (intent.getAction.equals(ACTION_TWO){
//DO SOMETHING
}
}
}
.....
}
Then when you start your main activity with an intent:
Intent intent = new Intent(MY_CURRENT_CONTEXT, MainActivity.class); //Or MainActivity subclass
add
intent.setAction(ACTION_ONE);
or whichever action is specific to what your intent is trying to accomplish.

Passing data from Fragment to Activity null pointer exception

I know this is a very asked question but i have done my research on it and still didn't manage to come up with a valid solution.
Problem is i try to send data from fragment like this:
Intent intent = new Intent(getActivity(),EditReceiptActivity.class);
System.out.println("RECEIPT IN SETTINGS: "+ receipt);
intent.putExtra("receipt_to_be_edited", receipt);
startActivity(intent);
this is done in a fragment context.
and then when i try to retrive this data in an activity context:
#Override
protected void onResume() {
Bundle extras = getIntent().getExtras();
if (extras != null) {
Receipt value = (Receipt) extras.getSerializable("receipt_to_be_edited");
System.out.println("RECEIPT ON RESUME: "+ value);
FolderDataSource f = new FolderDataSource(getApplicationContext());
f.open();
String name = f.getFolderName(value.getId());
f.close();
folder_title.setText(name);
details_txt.setText(value.getDetails());
value_txt.setText(value.getValue());
category_picked_txt.setText(value.getCategory());
folder_picked_txt.setText(name);
currency_picked_txt.setText(value.getCurrency());
location_picked_txt.setText(value.getLocation());
setImageView();
}
super.onResume();
}
I get a null pointer exception... even though the prints are there... the null pointer exception is on the line:
String name = f.getFolderName(value.getId());
EDIT
The problem was my method getFolderName(), that was returning null, so there is nothing wrong with my passing information code!
So this could turn out to be yet another example of how to pass information from fragment to activity via Intent!
Thanks!

getIntent.getExtras() does not return null but has no values.

Question is simple, I am not exactly new to Android but I cannot, for the life of me, retrieve the extras passed via an intent from Activity A to Activity B.
See Activity A: This is actually a ListFragment, that implements onListItemClick() to start another activity via an intent.
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.i("FragmentList", "Item clicked: " + id);
Intent i = new Intent(getActivity(), ExpandedTweetView.class);
twitter4j.Status status = adapter.getItem(position);
Bundle extras = new Bundle();
extras.putString(KEY_TEXT, status.getText());
extras.putString(KEY_HANDLE, status.getUser().getScreenName());
extras.putString(KEY_NAME, status.getUser().getName());
extras.putString(KEY_TIMESTAMPS, status.getCreatedAt().toString());
extras.putLong(KEY_RETWEETS, status.getRetweetCount());
i.putExtra(KEY_EXTRAS, extras);
startActivity(i);
}
This part just works, I tested it usng Log.v(TAG, "status.getText()" to make sure that the error was not coming from the Adapter passing an empty item via getItem().
Here is the code on Activity B:
public class ExpandedTweetView extends Activity {
TextView text;
TextView name;
TextView handle;
TextView createdAt;
TextView retweets;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.expanded_list_item);
Bundle extras = getIntent().getExtras();
ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
text = (TextView) findViewById(R.id.h_content);
name = (TextView) findViewById(R.id.h_name);
handle = (TextView) findViewById(R.id.h_handle);
createdAt = (TextView) findViewById(R.id.h_timestamp);
retweets = (TextView) findViewById(R.id.h_retweet_count);
if(extras != null) {
text.setText(extras.getString(TimelineFragment.KEY_TEXT));
name.setText(extras.getString(TimelineFragment.KEY_NAME));
handle.setText(extras.getString(TimelineFragment.KEY_HANDLE));
createdAt.setText(extras.getString(TimelineFragment.KEY_TIMESTAMPS));
retweets.setText(String.valueOf(extras.getLong(TimelineFragment.KEY_RETWEETS)));
}
}
As you can see, I believe I am using the right code to obtain the extras, using the same code on other applications worked. Not sure why, when the ExpandedTweetView is created via an intent, ALL of the textViews are empty. See: https://www.dropbox.com/s/pso6jbyn6rpks9n/empty_activity.png
What is even MORE strange is that I had initially tried checking to see if the bundle was null by calling this:
if (extras == null) {
Log.v(TAG, "Extras are empty :(");
}
But that line was never executed, meaning the bundle is not null. I also thought that maybe the keys being used to retrieve the individual Strings from the bundle were mismatching; however, in order to remedy that I decided to create constants that could be used on both sides. As you can see on the code, both the key to set the Extra and the Key to retrieve the Extra are the same.
Any ideas as to what the heck is going on?
Bundle extras = getIntent().getExtras();
if (extras != null) {
extras = extras.getBundle("KEY_EXTRAS");
String status = extras.getString("KEY_TEXT");
}
Try adding the extra variable to intent rather than in Bundle
Ex:
i.putExtra(KEY_1, a);
i.putExtra(KEY_2, b);
i.putExtra(KEY_3, c);
Then retrieve it from other activity from intent
Ex:
getIntent().getStringExtra(KEY_1) ;
In Activity A:
Intent i = new Intent(MainActivity.this, AnotherActivity.class);
Bundle b = new Bundle();
b.putString("thisc", "my name");
i.putExtra("bundle", b);
startActivity(i);
In Activity B:
**Bundle bun = getIntent().getBundleExtra("bundle");
if (bun.containsKey("thisc")) {
Log.i("TAG", bun.getString("thisc"));
} else {
Log.i("TAG", "no thisc");
}**
Check the first line of code in Activity B, that's the main difference actually!!
//put value
Intent inatent = new Intent(this,text.class);
inatent_logo.putExtra("message","hello");
startActivity(inatent);
//get vale
String msg = getIntent().getStringExtra("message").toString();
It's Difficult to maintain intent to Bundle and Bundle to Intent if number of data you want ti share from one Activity to Other Activity.
just Simply use Intent with PuExtra() with different argument.
you can pass number of data in intent like :
Sender's Side :
Create your Intent.
Intent My_Intent = new Intent(FromClass.this,ToClass.class);
Add your value which you want to share with other activity.
My_Intent.putExtra("VAR_A",a_value);
My_Intent.putExtra("VAR_B",b_value);
My_Intent.putExtra("VAR_C",c_value);
Call your Intent.
StartActivity(My_Intent);
Receiver's Side :
Intent My_Intent = getIntent();
First_Value=My_Intent.getStringExtra("VAR_A");
Sec_Value=My_Intent.getStringExtra("VAR_B");
Thred_Value=My_Intent.getStringExtra("VAR_C");
I Think its Easy for you to Handel your data from one Activity to other .

Bundle extras returning null

I'm having some problems.
In a class "A" I have the code:
Bundle extras = getIntent().getExtras();
if ( extras == null ){
Log.e("extras", "Extra NULL");
}
String arrayWatt = extras.getString("valoresWatt");
String arrayHorario = extras.getString("valoresHorario");
Bundle extras = getIntent().getExtras(); --> this is returning NULL`
This method throws NUllPointerException. What is the problem here? Syntax?
---EDIT----
So sorry, I forgot this code:
(This code is from another class that starts the activity)
Intent i = new Intent();
i.setClassName("org.me.android",
"org.me.android.GraphViewDemo");
i.putExtra("valoresWatt", watt);
i.putExtra("valoresHorario", hora);
startActivity(i);
If you want to get the extras, this is what I would do:
Intent i = getIntent();
String arrayWatt = i.getStringExtra("valoresWatt");
String arrayHorario = i.getStringExtra("valoresHorario");
Where is the code you listed for getting the Extras located? Are you overriding the onCreate method? If so, make sure you call super.onCreate(bundleVariableName) before trying to work with the Extras. So...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myLayout);
// ...
Bundle data = getIntent().getExtras();
if (data != null ) {
// should actually verify that the key exists, so:
// if (data.containsKey("valoresWatt")) {
// ... do something with the value
String watt = data.getString("valoresWatt");
String horario = data.getString("valoresHorario");
}
// ...
}
In your original code, you say that this first line is returning null:
Bundle extras = getIntent().getExtras(); // --> this is returning NULL
From the Android docs for Intent, it seems that the getExtras() method will return null if no extras have been added yet.
In that case, you may have to add your String extras by calling .putExtra(key, value) on the Intent object directly, rather than on its Map of extras, which doesn't exist yet.
For the NPE crash
Bundle extras = getIntent().getExtras();
if ( extras == null ){
Log.e("extras", "Extra NULL");
} else {
String arrayWatt = extras.getString("valoresWatt");
String arrayHorario = extras.getString("valoresHorario");
}
Instead of
i.putExtra("valoresWatt", watt);
i.putExtra("valoresHorario", hora);
try
i.putStringArrayListExtra("valoresWatt", watt);
i.putStringArrayListExtra("valoresHorario", hora);
if it is an arraylist of strings.

Categories

Resources