Can startActivityForResult() send data? - java

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
}
}

Related

Is there a way to check if I came from a specific activity before starting a new one?

Let's say I have 3 activities: A, B, and C. And all 3 activities can direct the user to one another. Is there a way to check if I came from a specific activity?
For example, to get to C, I can move from B -> C or A -> C. But is there a way for me to check if I came from B?
You can pass data payload through activity intent.pass your activity name for check where user came from.
start activity
Intent intent = new Intent(yourFromActivity.this,yourToActivity.class);
intent.putExtra(bundle_key,yourActivityName);
startActivity(intent)
In your second activity check intent extra and get the activity name where user came from.
#override
protected void onCreate(Bundle savedInstanceState){
//check extra key has in bundle.should same as host activity key
if(getIntent().hasExtra(bundle_key))
{
//get passed value from intent bundle
String activity = getIntent().getStringExtra(bundle_key,"");
if(activity.equel(yourActivityname)){
//put logic here
}
}
}
You can do it by 2 ways which are
Pass extra parameter in Intent when calling activity and in receiver
activity check received parameter and perform task accordingly.
Use startActivityForResult() instead of startActivity() when calling
activity & use getCallingActivity().getClassName() in receiver call to get
class name.
Passing Data in Intent:
Calling class A:
Intent intent = new Intent(A.this,C.class);
intent.putExtra("source","A");
startActivity(intent);
Receiver class C:
in onCreate method
String source;
Intent intent = getIntent();
if(intent.hasExtra("source"))
{
source = intent.getStringExtra("source");
}
//Now you received source class name you can check and perform action
//accordingly.
if(source.equals("A")
{
//For Class A
}
else{
// For Class B
}
Using startActivityForResult():
Sender Class:
Intent intent = new Intent(A.this,C.class);
startActivityForResult(intent);
Receiver Class:
//In onCreate Method get calling activity name
getCallingActivity().getClassName();
try this
Intent intent = new Intent();
intent.setClass(A.this,Receiveractivity.class);
intent.putExtra("Uniqid","From_Activity_A");
A.this.startActivity(intent);
Intent intent = new Intent();
intent.setClass(B.this,Receiveractivity.class);
intent.putExtra("Uniqid","From_Activity_B");
B.this.startActivity(intent);
Intent intent = new Intent();
intent.setClass(C.this,Receiveractivity.class);
intent.putExtra("Uniqid","From_Activity_C");
C.this.startActivity(intent);
Intent Activity
//obtain Intent Object send from SenderActivity
Intent intent = this.getIntent();
/* Obtain String from Intent */
if(intent !=null)
{
String strdata = intent.getExtras().getString("Uniqid");
if(strdata.equals("From_Activity_A"))
{
//Do Something here...
}
if(strdata.equals("From_Activity_B"))
{
//Do Something here...
}
if(strdata.equals("From_Activity_C"))
{
//Do Something here...
}
........
}
else
{
//do something here
}

Passing string between Android Activities

I have a List Activity that when the user presses a line item, it passes the ID of the record to the next activity.
Intent intent = new Intent(CustomerListActivity.this, CustomerEditActivity.class);
intent.putExtra("CUSTOMER_ID", id);
startActivity(intent);
I can see the data in the intent when debugging on that activity; however, when I get into the next activity, the data is not coming up with the below code.
Intent i = getIntent();
Bundle b = i.getExtras();
String s = b.getString("CUSTOMER_ID");
I have debugged and poked around in the variables window, but I do not see the Customer_ID=# value as I do on the previous activity.
You should call String s = b.getStringExtra("CUSTOMER_ID");
Try this.It will work.Paste it on your next activity where you want to get data from intent.
String s= getIntent().getExtras().get("CUSTOMER_ID")+"";
This is how you can do it in a right way
//main activity
Intent intent = new Intent(getActivity(), TargetActivity.class);
intent.putExtra("ParamKey", "key_value");
getActivity().startActivity(intent);
****
//TargetActivity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.target_activity_layout);
Bundle extras = getIntent().getExtras();
if (extras != null) {
if (extras.get("ParamKey") != null)
paramValue= extras.getString("ParamKey", "default_value");
}
You will have to call getStringExtra() method in New Activity to retrieve the value from Intent.
For example :
String custIdInNewAct= getIntent().getStringExtra("CUSTOMER_ID");
Bundle contains data sent by the calling activity so
Bundle b = getIntent().getExtras();
String s = b.getString("CUSTOMER_ID")`;

Sending messages to multiple contacts using Intent

I'm trying to send messages through in built sms app through Intent. Its working fine. Here is my code
public class Main_Act extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button startBtn = (Button) findViewById(R.id.button);
startBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if(sendSMS()) {
Intent intent = new Intent(Main_Act.this, Sample.class);
startActivity(intent);
}
}
});
}
protected boolean sendSMS() {
ArrayList<String> nums = new ArrayList<String>();
nums.add("111111111");
nums.add("222222222");
Log.i("Send SMS", "");
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address" ,nums);
smsIntent.putExtra("sms_body" , "Test ");
try {
startActivity(smsIntent);
finish();
return true;
}
catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(Main_Act.this,
"SMS faild, please try again later.", Toast.LENGTH_SHORT).show();
return false;
}
}
}
But the problem is it gets navigated to another activity without clicking send button in sms application. It should goto another activity only after clicking the send button in messaging app. Can anyone help me with this problem, Thanks in advance.
Let's clear out a slight misunderstanding in your code:
You should not try to start both intents in the same part/run of the code as you do here.
A startActivity will not execute directly going to the activity and then return to the same place in the code when activity execution finishes. In stead it asynchronously queues the intent for execution. Then your code queues another intent for execution. After the current code finishes (in this case when the button onClick() method ends) Android queue mgmt can start picking off the queue. Probably the first intent is executed shortly and then directly overrun by an immediate execution of the second.
So what happens in summary is that you first add one intent to the queue in sendSMS and then add intent 2 to the queue in onClick, before leaving. Now both the intents are executed.
What you need to do is to change the sendSMS code to something like:
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address" ,nums);
smsIntent.putExtra("sms_body" , "Test ");
// To force the SMS app to return immediately after sent SMS
smsIntent.putExtra("exit_on_sent", true);
startActivityForResult(smsIntent, MY_SMS_REQUEST_RESPONSE_CODE);
Note the startActivityForResult() method that indicates that we expect Android to return and the "exit_on_sent" extra, to force a swift return.
MY_SMS_REQUEST_RESPONSE_CODE is just any random code you select to recognize the returning result in the callback method (even if you currently do not expect any other returning results, you may have some in the future).
Next thing to do is to remove the second intent creation and queuing. In stead you implement the following callback method (added to this activity):
#Override
protected void onActivityResult(
int callbackIdentifier, int resultCode, Intent intent) {
// Is this the expected sendSMS callback ?
if (callbackIdentifier== MY_SMS_REQUEST_RESPONSE_CODE) {
if (resultCode == RESULT_OK) {
// Continue where you left off (e.g. execute intent 2)
Intent intent = new Intent(Main_Act.this, Sample.class);
startActivity(intent);
} else if (resultCode == RESULT_CANCELED) {
// Error handling/retrying etc
}
}
// Support inherited callback functions
super.onActivityResult(callbackIdentifier,resultCode,intent);
}
Note: if you want to pass data and type don't call method separately because will delete each other you must pass it in one method
wrong
smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");
true
smsIntent.setDataAndType(Uri.parse("smsto:"),"vnd.android-dir/mms-sms");

Android Getting Extras from Intents

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

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