Android Getting Extras from Intents - java

I'm trying to use startActivityForResult() to get a String from another activity, but I keep getting a NullPointerException whenever I try to retrieve the String from the Intent. Here's what I've got:
//To set up the Intent:
String in = mEditText.getText().toString(); //medittext is EditText that I want String from
Intent i = new Intent(this, ActivityLoaderActivity.class); //activity that started this one
i.putExtra("message", in);
setResult(1);
this.finish(); //cause I'm using startActivityForResult()
//To get the String
#Override
protected void onActivityResult( ... , Intent data) {
String s = data.getStringExtra("message"); //error here
}
I know the error is at getStringExtra() through debugging, but I still can't figure out why it's crashing. Anyone have any ideas?

Maybe you could try using setResult(1, i) and checking in onActivityResult() for the resultCode before getting the extra like this
if(resultCode == 1)
{
//get String extra
}
Hope it helps

Related

Bundle null onActivityResult

I have tried a couple of different solutions already given but none works as everything seems to work fine in another activity that I am returning a result from, here is the code.
My Main activity where City activity is called:
//this method gets called on a button click and it works as other activity shows up
public void getCity(View v){
Intent intent = new Intent(getApplicationContext(), City.class);
startActivityForResult(intent,1);
}
//receiving the data the first data is ok but the second one is null although doing the same thing in both files
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(resultCode == RESULT_OK && data != null && requestCode==0){
initializeUI(data.getExtras());
}
if(resultCode == RESULT_OK && data != null && requestCode==1){
//data is null here
}
super.onActivityResult(requestCode, resultCode, data);
}
My City Activity
public void addInput(View v){
Bundle bundle = new Bundle();
EditText cityBox = (EditText) findViewById(R.id.cityInput);
String cityName = cityBox.getText().toString();
Intent resultIntent = new Intent();
try {
EditText longBox = (EditText) findViewById(R.id.longitudeInput);
String longitude = longBox.getText().toString();
double longi = Double.parseDouble(longitude);
bundle.putDouble("LONGITUDE", longi);
EditText latBox = (EditText) findViewById(R.id.latitudeInput);
String latitude = latBox.getText().toString();
double lati = Double.parseDouble(latitude);
bundle.putDouble("LATITUDE", lati);
} catch (NumberFormatException e){
}
bundle.putString("CITY_NAME", cityName);
resultIntent.putExtra("DATA",bundle);
setResult(RESULT_OK, resultIntent);
finish(); //calling finish just in case tried without finish aswell
onBackPressed(); //calling onBackPressed tried without it as well doesn't work
}
Any help would be appreciated.
try this:
Then, in B, I do:
Intent intent = getIntent();
intent.putExtra("Date",dateSelected);
setResult(RESULT_OK, intent);
finish();
And, in A:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(resultCode==RESULT_OK && requestCode==1){
Bundle MBuddle = data.getExtras();
String MMessage = MBuddle .getString("Date");
}
}
the problem i have found in your code is use of wrong requestCode you are passing 1 as result code in startActivityForResult and in onActivityResult you are checking requestCode==0 means intializeUI etc. All you need to do is use this below code.
if(resultCode == RESULT_OK && data != null && requestCode==1){
//everything works fine
initializeUI(data.getExtras());
}
hope this will help you.
I recently faced same issue in my case. What i was doing wrong was that i was using startActivity() by mistake with startActivityForResult() then in child activity i was calling onBackPress() and finish() before setting the result. I can suggest you that you make sure you set the result before finish() the activity and make sure you're starting activity with startActivityForResult().
Here is snippet from my code.
setResult(RESULT_OK, getIntent().putExtra("country", "some result"));
And i made sure the above written code get excuted before onBackPressed() and onFinish() and it worked for me.
Hope this will help you.

Why am I getting a null pointer exception when passing an ArrayList of strings from one activity to another?

I am trying to get an arraylist in ScanLocate activity from an UpdateLocation activity.
I'm using startActivityForResult method to call the scan method which populates the ArrayList wifiList, I then want to send the ArrayList to the Update Location class.
I start by calling startActivityForResult in Update Location:
private void getScan(){
//Create an intent to start ScanLocate
final Intent i = new Intent(this, ScanLocate.class);
//Start scanLocate with request code
startActivityForResult(i, REQUEST_READINGS);
}
Next, in ScanLocate I created the sendData method (note: the check confirms that the ArrayList data is intact at that point):
private void sendData(){
//create a new intent as container for the result
final Intent readings = new Intent(this, UpdateLocation.class);
//check that data is in wifiList
for(String s:wifiList){
Log.v(TAG,"List Items: " + s);
}
//create bundle for string array
Bundle b = new Bundle();
b.putStringArrayList(key, wifiList);
//add readings to send to updateLoc
readings.putExtras(b);
//set code to indicate success and attach Intent
setResult(RESULT_OK, readings);
//call finish to return
finish();
}
The final part is back in UpdateLocation with the onActivityResult:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent readings){
super.onActivityResult(requestCode, resultCode, readings);
//check if request code matches the one set above
if(requestCode == REQUEST_READINGS){
//check if sendData() in ScanLocate was successful
if(resultCode == RESULT_OK){
//get the readings from the Intent
Log.v(TAG, "HERE");
result = getIntent().getExtras().getStringArrayList(ScanLocate.key);
Log.v(TAG, "HERE2");
for(String s : result) {
Log.v(TAG, "Location 5: " + s);
}
}else{
//ScanLocate was unsuccessful
}
}
}
The first "Here" is displayed however it then falls down on the next line, getStringArrayList() throws a null pointer exception.
I have looked through the documentation and at previous questions on here and I cannot see what is going wrong.
Any advice would be appreciated, thanks.
Previous questions:
startactivityforResult not working
How to pass an ArrayList to the StartActivityForResult activity
You don't need to call getIntent(), use the parameter provided by the method:
result = readings.getStringArrayListExtra(ScanLocate.key);

Can startActivityForResult() send data?

I am learning android and curious to know as if startActivityForResult() contains the properties of startActivity() too, i.e. can it be used to send data like startActivity() beside receiving data from called activity?
Here is the code:
SendData Activity:
Intent data= new Intent(SendData.this, RecieveData.class);
Bundle check = new Bundle();
check.putString("UmerData", cheese);
medt.setText(cheese);
data.putExtras(check);
startActivityForResult(data, 5);
Should receive data in this activity (RecieveData Activity)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recievedata);
Initializek();
Bundle got = getIntent().getExtras();
String ss= got.getString("UmerData");
if(getIntent()!=null && ss!=null ) {
rt1.setText("Is not Null");
}
}
Your help will be really appreciated !
Thanks
Yes, startActivity & startActivityForResult, both take intent as param. You can bundle launch data inside intent and pass it over to target activity.
When you use startActivityForResult(), you have to also create a onActivityResult() method within the Activity that called startActivityForResult(). onActivityResult() is where you can access the Intent stored by the Activity you start for a result.
In the Activity that is then started, you have to call setResult() to store the Intent that you store the data in.
Read over this: http://developer.android.com/reference/android/app/Activity.html#StartingActivities
edit: Misread your question. For passing a Bundle of options through, I would use this overload:
startActivity(Intent, int, Bundle)
I'm working in Xamarin Android so the code is C# but I had the same problem except I'm sending between separate apps. I eventually got it working so here is my example.
var intent = new Intent();
intent.SetComponent(new ComponentName("com.company.packageName", "com.company.packageName.activityName"));
intent.PutExtra(Intent.ExtraText, message);
StartActivityForResult(intent, 1);
// in app being started
protected override void OnResume()
{
base.OnResume();
Intent intent = Intent; // Equivalent to getIntent()
if (intent != null)
{
string str = intent.GetStringExtra(Intent.ExtraText);
if (str != null)
{
// Do stuff with str
}
else
{
//Show Error
}
}
else
{
//Show Error
}
}

How to pass String from 2 activities to one?

I have two activitys with lists.
One for tablet's and one for regular density phones.
When an item in the list is clicked it launches the same activity for either activity with list's.
The problem is when an item is clicked i have getter and setter class that gets the URL for a particular item and passes it to the launching activity like this...
private String URL = null;
try{
URL = com.fttech.AbstractFeedsActivity.feed_url;
}
catch(IllegalArgumentException e){
e.printStackTrace();
URL = com.fttech.ItemsActivity.url;
}
As you see what i tried to do is try and catch.
So if the first one isnt found then the second one will be retrieved.
But it doesnt seem to work.
It returns null each time.
For what i have describe what is the best way to implement this?
Is my way logic? Or is there a better way.
Thanks
Try this,
private String URL = null;
try{
URL = com.fttech.AbstractFeedsActivity.feed_url;
if(TextUtils.isEmpty(URL)){
URL = com.fttech.ItemsActivity.url;
// Pass this URL
}
else{
// If its not empty then it will pass the first URL
}
}
catch(IllegalArgumentException e){
e.printStackTrace();
}
No need to pass String to 2 activities, if you want to just pass strings to one or as many activities as you want, just put them in SharedPreferences or declare a variable in static class and then set/get it whenever you want.
Passing values from one Activity to another:
Intent intent = new Intent(context, CalledActivity.class);
intent.putExtra(key, value);
startActivity(intent);
If you want some data back from called Activity then you can use startActivityForResult() as:
Intent intent = new Intent(context, CalledActivity.class);
intent.putExtra(key, value);
startActivityForResult(intent, requestCode);
In called activity you can set data as:
setResult(RESULT_OK, intent);
Note: Here you set the value in intent and pass it to setResult().
On returning back to calling Activity you can get data by overriding:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
//Get data from Intent "data" and do your task here....
}
}
Note: You can pass primitive data type values thru Intent and if you want to pass other types then you have to use Bundle like this.
Bundle data = new Bundle();
data.putIntArray(key, value);
//same way you can set other values.......
//Now set this Bundle value to Intent as you do for primitive type....
Intent intent = new Intent(context, CalledActivity.class);
intent.putExtra(data);
startActivity(intent);
Receiving data in Activity:
//For primitive values:
DataType var_name = getIntent().getExtras().get(key);
//For Bundle values:
Bundle var_name = getIntent().getExtras().getBundle(key);

Android: Passing data between activities - multiple intent.putExtra not working?

Having a very annoying problem with passing data between activities.
This is the code I use to successfully pass the value of a progress bar to a different activity:
public void WhenClicked(View view)
{
view.clearAnimation();
Intent intent = new Intent("com.android.Test.QUESTION");
if (progressBar != null)
{
if (progressBar.getProgress() != 0)
{
intent.putExtra("ProgressBarValue", progressBar.getProgress());
}
}
startActivity(intent);
}
Okay, so that worked. Now, when I change it to this, it blows up:
public void WhenClicked(View view, String category)
{
view.clearAnimation();
Intent intent = new Intent("com.android.Test.QUESTION");
intent.putExtra("Category", category);
if (progressBar != null)
{
if (progressBar.getProgress() != 0)
{
intent.putExtra("ProgressBarValue", progressBar.getProgress());
}
}
startActivity(intent);
}
I don't understand what the problem is. I've even tried sticking it all into a bundle and adding the bundle as an extra - that just made it crash as well. Maybe I'm being stupid and I've just been staring at my code too long, but any help would be great!
This is my first time with Android and it's killing me!
Thanks in advance guys!
first you need to create bundle object(Bundle bnd=new Bundle();) and next bnd.putString("param1", "test");
next create intent:
Intent myIntent = new Intent(current classname.this,nextactivity.class);
myIntent.putExtras(bnd);
startActivityForResult(myIntent, 0);
In 2nd activity u need to get bundel value like :
Bundle bundle = this.getIntent().getExtras();
String _getData=bundle.getString("param1");
Assuming that you have an activity called QUESTION, you might try to put .class on the end as well as "this" for first param:
Intent intent = new Intent(this, QUESTION.class);
if you don't have a QUESTION activity then that is another problem. I'm assuming your activities are in the same app?
I believe, the activity which should handle this intent action com.android.Test.QUESTION does not understand your category i.e intent.putExtra("Category", category);.
You can try fixing it in 2 ways:
If the receiving activity is from your own application, then try using explicit intent i.e Intent intent = new Intent("youCurrentClass","theClassYouWantToCall"); without feeding additional category, this will launch the specified activity. In case of explicit Intent Android system does not do a comparison with the intent-filters to match Intent Object.
Change the category section in relation to intent receiving Activity.
Hope this helps,
sku

Categories