How do I transfer data from one activity to another in Android? - java

I want to transfer my "result" data from my first (Main) acitivity to
my Custaddress activity, which has edit texts for customer details, and then this is sent to an email. The email/edit texts work perfectly - but I want to
add in "result.toString" into email body string. How do I transfer "result" to the second activity? I believe its something to do with arg?
Here's my code from first activity..
DecimalFormat decimalFormat = new DecimalFormat(COMMA_SEPERATED);
result.append("\nTotal: £"+decimalFormat.format(totalamount));
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setMessage(result.toString());
alertDialogBuilder.setTitle("YOUR ORDER");
alertDialogBuilder.setPositiveButton("Accept",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
//do what you want to do if user clicks ok
//Intent intent = new Intent(context, Custaddress.class);
// startActivity(intent);
Intent custaddress = new Intent(getApplicationContext(),com.example.frytest.Custaddress.class);
startActivity(custaddress);
}
});
alertDialogBuilder.setNegativeButton("Decline",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//do what you want to do if user clicks cancel.
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();

Write it in activity that passing data
Intent custaddress = new Intent(getApplicationContext(),com.example.frytest.Custaddress.class);
custaddress.putExtra("key",value);
startActivity(custaddress);
Write below code in activity that catching data
Intent intent=getIntent();
String mString=intent.getStringExtra("key");
hope this will help you

You should use intent (click here) :
Intent intent = new Intent(getBaseContext(), CustAdrresActivity.class);
intent.putExtra("text", mytext);
startActivity(intent);

You just need to replace your lines:
Intent custaddress = new Intent(getApplicationContext(),com.example.frytest.Custaddress.class);
startActivity(custaddress);
with these three lines:
Intent custaddress = new Intent(getApplicationContext(),com.example.frytest.Custaddress.class);
custaddress.putExtra("result", result.toString());
startActivity(custaddress);
and then, when you open the new activity (in your case the Custaddress Activity), you should do the following to get your result
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("result");
}

You should add Extra in the Intent object which you are passing in the startActivity(intent) method.
Example
String value = "String i want to send to next activity"
Intent intent = new Intent(getApplicationContext(),com.example.frytest.Custaddress.class);
intent.putExtra("KEY", value);
startActivity(intent);
In the Custaddress.java Activity class you need to get the data from the Bundle object that you get as a parameter in the onCreate(Bundle bundle) method
Bundle extras = getIntent().getExtras();
if (extras != null) {
// get data via the key
String valueFromPreviousActivity = extras.getString("KEY");
if(valueFromPreviousActivity != null){
// do something with the data
}
}

Check out this official doc Starting Another Activity.

Through the below code we can send the values between activities
use the below code in parent activity
Intent myintent=new Intent(Info.this, GraphDiag.class).putExtra("<StringName>", value);
startActivity(myintent);
use the below code in child activity
String s= getIntent().getStringExtra(<StringName>);

Related

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")`;

Android Studio: Passing variable through another variable doesn't work

I created a Method for my MainActivity to pass a String to my SecondActivity.
public void convertCurrency(View view)
{
intent.putExtra("NO", "My String");
startActivity(intent);
}
But in my SecondActivity in my OnCreate Method
Button back = (Button) findViewById(R.id.back);
TextView t = (TextView) findViewById(R.id.first_text);
Intent intent = new Intent(this, MainActivity.class);
String g = intent.getStringExtra("NO");
t.setText(g);
Nothing happens. But Why?
get Your variable in this way:
String yourVriable = getIntent().getStringExtra("NO")
don't new Your intent
Your are creating new intent.
In onCreate method call
String data = getIntent().getStringExtra(key);
replace Intent intent = new Intent(this, MainActivity.class);
by Intent intent = getIntent();
When you do intent.getStringExtra("NO"); your intent Object is new, so his Extra is empty.
You need to change the code in both the activities . You need to create intent and put your string into it, so your code will be.
public void convertCurrency(View view) {
Intent intent = new Intent(this, Main2Activity.class);
intent.putExtra("NO","My String");
startActivity(intent);
}
Note that in the intent constructor the first argument is the current activity and the second argument will be the activity that you are starting.So in the second activity you need to recieve the string. Code for that will be,
Button back = (Button) findViewById(R.id.back);
TextView t = (TextView) findViewById(R.id.first_text);
String g = getIntent().getStringExtra("NO")
t.setText(g);
I resolve the problem myself. There occurs an error if you have two Intent objects with the same name even if they are within separate methods.

Passing a string or a variable from a dialoguebox to an activity Android

I wan to implicitly pass two string or variable from a dialoguebox to be used by another activity and at the same time opening that activity.
dialoguebox
String city = addresses.get(0).getLocality();
String category = "Hazard";
AlertDialog.Builder prompt = new
AlertDialog.Builder(MapsActivity.this);
prompt.setCancelable(false)
.setPositiveButton("Mineralization", new
DialogInterface.OnClickListener() {
.setPositivetiveButton("Geohazard", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
startActivity(new
Intent(getApplicationContext(),MapsActivity.class));
//i want to pass the String city and category here
}
}
)
AlertDialog alert = prompt.create();
alert.setTitle("Please select an option");
alert.show();
TextView myTextView = (TextView) findViewById(R.id.PSString);
myTextView.setText(city);
New activity
package com.example.boneyflesh.homepage;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class GeohazardResults extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_geohazard_results);
}
}
how do i do this? what do i write on the onClickListener and what do i do on the new activity so that i can get the strings?
Instead of doing something like this in your onClick method
startActivity(new Intent(getApplicationContext(),MapsActivity.class));
You can just pass the two strings through the intent to the MapsActivity inside your onClick method as shown below
Intent lIntent = new Intent(getApplicationContext(), MapsActivity.class);
lIntent.putExtra("city", city);
lIntent.putExtra("category", category);
startActivity(lIntent);
and retrieve those values in MapsActivity as shown below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_geohazard_results);
String city = getIntent().getStringExtra("city");
String category = getIntent().getStringExtra("category");
}
Pass Using Intent and Bundle like Below:
Intent intent = new Intent(getApplicationContext(),MapsActivity.class));
Bundle bundle =new Bundle();
bundle.putString("key1","value1");
bundle.putString("key2","value2");
intent.putExtras(bundle);
startActivity(intent );
And Retrieve value in next Activity like below:
Bundle bundle = getIntent().getExtras();
String value1= bundle.getString("key1");
String value2= bundle.getString("key2");
You need to use extras to send the data.
For example:
Intent intent = new Intent(getApplicationContext(),MapsActivity.class);
intent.putExtra("SOME_NAME_HERE", theString);
startActivity(intent);
Then, in the target activity you write - in onCreate:
Bundle extras = getIntent().getExtras();
if(extras == null) {
theString= null;
} else {
theString = extras.getString("SOME_NAME_HERE");
}
In your dialogbox:
Intent i = new Intent(MapsActivity.this, GeohazardResults.class);
i.putExtra("city", city);
i.putExtra("category", categoty);
startActivity(i);
In your new activity:
Intent i = getIntent();
Bundle extras = i.getExtras();
String city = extras.getString("city");
String category = extras.getString("category");
Instead of doing this -:
startActivity(new Intent(getApplicationContext(),MapsActivity.class));
Do something like this -:
Intent mapsActivityIntent = new Intent(getApplicationContext(), MapsActivity.class);
mapsActivityIntent.putExtra("CITY", city);
mapsActivityIntent.putExtra("CATEGORY", category);
startActivity(mapsActivityIntent);
In your activity you can then get them by doing :
getIntent().getStringExtra("CITY");
getIntent().getStringExtra("CATEGORY");
DialogInterface.OnClickListener() {
.setPositivetiveButton("Geohazard", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
Intent intent = new Intent(getApplicationContext(),MapsActivity.class))
// intent.putExtra(key,value);
intent.putExtra("String1","value1");
intent.putExtra("String2","value2");
startActitvity(intent);
}
}
)
in Acivity
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if(extras != null){
//intent.getStringExtra(key)
string1 = intent.getStringExtra("String1");
string2 = intent.getStringExtra("String2");
}
i would suggest define keys as constants and use those while passing values, to avoid any confusion
pass intent from your dialog like this
Intent intent=new Intent(context, GeohazardResults.class);
Bundle parameters=new Bundle();
parameters.putString("city",city);
parameters.putString("category",category);
intent.putExtra("key",parameters);
startActivity(intent);
and in the next activity receive thiese values like this.
Intent receivedIntent=getIntent();
if(receivedIntent!=null){
Bundle parameters=receivedIntent.getBundleExtra("key");
if(parameters!=null){
String city=parameters.getString("city");
String category=parameters.getString("category");
}
}

How to send clicked button to another Activity optimally?

I'm have one activity with 10 buttons, and transfer info about button clicked to next activity.
View.OnLongClickListener olongBtn = new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if (v == btn1) {
Intent intent = new Intent(MainActivity.this, AddContact.class);
intent.putExtra("slot", "slot1");
startActivity(intent);
} else if (v == btn2) {
Intent intent = new Intent(MainActivity.this, AddContact.class);
intent.putExtra("slot", "slot2");
startActivity(intent);
} else if (v == btn3) {
Intent intent = new Intent(MainActivity.this, AddContact.class);
intent.putExtra("slot", "slot3");
startActivity(intent);
}
return false;
}
};
btn1.setOnLongClickListener(olongBtn);
btn2.setOnLongClickListener(olongBtn);
btn3.setOnLongClickListener(olongBtn);
}
I want to change it like this
String slot = toString(v);
Intent intent = new Intent(MainActivity.this, AddContact.class);
intent.putExtra("slot", slot);
startActivity(intent);
But when I do it, I get in next activity something like this:
android.widget.Button{6548fcd}VFED..CL...P....17.0-147.130 #7f08004f app:id/btnPayman}
But i'm expectation name of button object.
To get name of clicked button use ((Button)v).getText() method instead of v.toString() which return String representation of calling Object:
String slot = (Button)v).getText().toString();
Intent intent = new Intent(MainActivity.this, AddContact.class);
intent.putExtra("slot", slot);
startActivity(intent);
You can simply send button id.
View.OnLongClickListener olongBtn = new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Intent intent = new Intent(MainActivity.this, AddContact.class);
intent.putExtra("slot", v.getId());
startActivity(intent);
return false;
}
};
On next Activity, you can use a switch in order to know what Button has been pressed:
int buttonId = getIntent().getIntExtra("slot", 0);
switch() {
case R.id.firstbutton:
//Do what you want
break;
case R.id.secondbutton:
//Do What you whant
}
Sending int is better than sending a String because you can use a switch on the receiver activity which is faster than anidated if/else
-----------------------EDIT----------------------
While you are using include tag in order to compose your layout, you should set a different id to every button (at the same time your are setting Button text). You can also use an Integer as a tag for every button, and send that tag to the next activity (instead of id).
Look about view tags here: View setTag() method
If you want to send the name of the button, try this:
String slot = ((Button) v).getText().toString();
Intent intent = new Intent(MainActivity.this, AddContact.class);
intent.putExtra("slot", slot);
startActivity(intent);
Thanks user pozuelog for solution.
I'm use separate xml files for layout and attach it by include to main_activity.
Result of it, that getId method don't work for me.
solution is set Tag for my buttons.
btn1.setTag(1);
btn2.setTag(2);
btn3.setTag(3);
View.OnLongClickListener olongBtn = new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Intent intent = new Intent(MainActivity.this, AddContact.class);
intent.putExtra("slot", String.valueOf(v.getTag()));
startActivity(intent);
return false;
}
};
btn1.setOnLongClickListener(olongBtn);
btn2.setOnLongClickListener(olongBtn);
btn3.setOnLongClickListener(olongBtn);
I think that solution may be optimize, but I'm googlecoder and leave it as is for this time.

How to use startActivityForResult() through a DialogFragment?

My app requires a username to be added to function properly.
The mainActivity displays the username on the top which it retrieves form the database.
The mainActivity also has a button which leads to 'addusername' activity through startActivityForResult() method; when the user actually enters a username then only username on the main activity gets refreshed and displayed.
There is a submit button on the 'addusername' activity which adds the username and does setResult(RESULT_OK);
Everything works fine if the username is entered by clicking the 'addusername' button.
Now, I have added a dialogue in mainActivity which gets displayed when the app starts only if no username exists on the database. The dialogue gives an option to add username, which if clicked, leads to the 'addusername' activity. But upon pressing the 'submit' button the mainActivity does get called but the username is not refreshed (though, the database does get updated)
Here is the code for 'addusername' activity:
public void submitusername(View view) {
userdatabase name = new userdatabase(this);
name.open();
String user = name.getusername();
name.close();
EditText cinone = (EditText) findViewById(R.id.username);
username = cinone.getText().toString();
if(user.equals("")) {
userdatabase entry = new userdatabase(Editprofile.this);
entry.open();
entry.createEntry(username, null, null, null);
entry.close();
Context context = getApplicationContext();
CharSequence text = "Added new user!";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else {
userdatabase update = new userdatabase(Editprofile.this);
update.open();
update.updateUsername(username);
update.close();
Context context = getApplicationContext();
CharSequence text = "Username updated!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
setResult(RESULT_OK);
finish();
}
Here is the code for Dialog:
public class NouserFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.nouseralert)
.setPositiveButton(R.string.add, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(getActivity().getBaseContext(), Editprofile.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.ignore, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
I understand this is happening because the Dialog does not call startActivityForResult() method. But even if I change my code, like this:
Intent intent = new Intent(getActivity().getBaseContext(), Editprofile.class);
startActivityForResult(intent, 0);
It still does not help. Probably because, onActivityResult() method does not lie in the same class from which startActivityForResult() has been called, but I don't know how to get after that.
EDIT 1: Tried using
Intent intent = new Intent(getActivity(), Editprofile.class);
startActivityForResult(intent, 0);
No use.
Have you tried this way:
Intent intent = new Intent(getActivity(), Editprofile.class);
startActivityForResult(intent, 0);
When you create your the Intent object you use the BaseContext, instead of using the reference to the activity itself.
Using
Intent intent = new Intent(getActivity(), Editprofile.class);
getActivity().startActivityForResult(intent, 0);
worked!

Categories