How to send clicked button to another Activity optimally? - java

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.

Related

Is it possible to pass a value from Adapter to Activity?

I have Activity1, Activity1 Adapter and Activity2
I'm not able to pass value between an Adapter and Activity. When back button is pressed, I'm expecting a value to be coming from the Second Activity (Activity 2) to Activity1 Currently, it gives me null
Here are my code snippets.
Activity1 Adapter
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Activity origin = (Activity) context;
Intent intent = new Intent(context, PostActivity.class);
intent.putExtra("searchText", staggeredCustomCard.getSearchText());
origin.startActivityForResult(intent, 1);
}
});
Activity2
#Override
public void onBackPressed() {
super.onBackPressed();
Intent mIntent = new Intent();
mIntent.getStringExtra("searchText");
setResult(1, mIntent);
}
I'm expecting this searchText to be going to Activity1. Could anyone please guide me how to achieve this?
You are getting getStringExtra("searchText"); from a completely new intent, that's why it's returning null. You need to get search text from getIntent() like this:
#Override
public void onBackPressed() {
super.onBackPressed();
Intent mIntent = new Intent();
String search = getIntent().getStringExtra("searchText");
mIntent.putExtra("searchText", search);
setResult(1, mIntent);
}

How to send/detect a reference/flag to a specific activity from another

How can I send or detect a reference or flag if a specific Activity was started from another Activity or not? I actually need a form in which I can execute only a certain piece of code only if this code was called by a specific Activity, for example:
Activity 1:
Intent intent = new Intent(this,ranking.class);
startActivity(intent);
Activity2:
Intent intent = new Intent(this,ranking.class);
startActivity(intent);
Ranking.class (It's pseudocode since I don't really know how/what to do):
if(I was called by Activity 1) {
//do something
} else {
finish();
}
You can .putExtra a message to your Intent.
Activity 1
Intent intent = new Intent(this,ranking.class);
intent.putExtra("activity", 1);
startActivity(intent);
Activity 2
Intent intent = new Intent(this,ranking.class);
intent.putExtra("activity", 2);
startActivity(intent);
Ranking.class
Intent intent = getIntent();
int activityNumber = intent.getIntExtra("activity", 0);
if (activityNumber == 1) {
//do something
} else{
finish();
}
The answer by #israel-dela-cruz is correct, you need to use extra to differentiate the flags. Here the more compact version to avoid using magic number and magic key:
public class RankingActivity extends Activity {
private static final ACTIVITY_OPTION_KEY = "activityOptionKey";
private static final int FROM_ACTIVITY_ONE = 1;
private static final int FROM_ACTIVITY_TWO = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rating);
...
Bundle bundle = getIntent().getExtra();
int option = bundle.getInt(ACTIVITY_OPTION_KEY);
if(option == FROM_ACTIVITY_ONE) {
// do something when called from activity one
} else if(option == FROM_ACTIVITY_TWO) {
// do something when called from activity two
} else {
// is there something else?
}
...
}
// Use intent factory to remove dependency to magic number and magic key
public static Intent createIntentFromActivityOne(Activity activity) {
Intent intent = new Intent(activity, RatingActivity.class);
intent.putExtra(ACTIVITY_OPTION_KEY, FROM_ACTIVITY_ONE);
return intent;
}
public static Intent createIntentFromActivityTwo(Activity activity) {
Intent intent = new Intent(activity, RatingActivity.class);
intent.putExtra(ACTIVITY_OPTION_KEY, FROM_ACTIVITY_TWO);
return intent;
}
}
then you can create the intent without knowing the RatingActivity magic key and magic number:
// from activity one
Intent intent = RatingActivity.createIntentFromActivityOne(this);
startActivity(intent);
// from activity two
Intent intent = RatingActivity.createIntentFromActivityTwo(this);
startActivity(intent);

How to check if firstrun has been skipped?

I have in my firstrun activity, a button that says "continue" and starts new activity (MainActivity intent), but I've found out it's possible skip that button and firstrun activity by restarting the app. So I would like to make sure it will be impossible to skip the activity.
That's what I have been thinking about:
firstEntry.java - In this method I'm putting new value in the shared preference that confirm that firstrun haven't been skipped (it only add the value if the button is clicked).
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(skip, false);
editor.commit();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
finish();
}
OnCreate() method in MainActivity
boolean skipper = prefs.getBoolean(skip, false);
if(skipper == true){
Intent i = new Intent(getApplicationContext(), firstEntry.class);
startActivity(i);
}
OnResume function:
#Override
protected void onResume() {
super.onResume();
if (prefs.getBoolean("firstrun", true)) {// Checks if application is on its first run
Intent i = new Intent(getApplicationContext(), firstEntry.class);
startActivityForResult(i, 1);
prefs.edit().putBoolean("firstrun", false).commit();
finish();
}
}
How can I check if shared preference method "firstrun" has skipped the continue button by using shared preference values?
change following line in btn.setOnClickListener(new View.OnClickListener()
editor.putBoolean(skip, false);
to
editor.putBoolean(skip, true);
And then in OnCreate() method of firstEntry.java
boolean skipper = prefs.getBoolean(skip, false);
if(skipper == true){
Intent i = new Intent(getApplicationContext(), MainActivity.class);
Log.i("firstEntry.java","skipped the activity");
startActivity(i);
}

How to call one activity multiple times based on from which the activity has been called?

I have one activity which is common for all other activities. I want to call this activity and want to set some conditions based on from which activity it has been called. I thought of bundle for this. How can I call a condition based on bundle value? I have another activity in between. I am not calling the activity directly. So how can we pass data by using bundle?
txt_from.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i = new Intent(getApplicationContext(), PickLocationActivity.class);
GoSendData.instance.addressType = 0;
i.putExtra("type",1);
startActivity(i);
}
});
From this I am calling second activity.
In common activity I have a view I am calling the activity back from this. The activity from which it has been called , it should be called back from this view.
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle extras = intent.getExtras();
activityType = extras.getInt("type");
if(activityType==0) {
intent = new Intent(ChooseFromMapActivity.this, GoSend.class);
startActivity(intent);
}
if(activityType == 1)
{
intent = new Intent(ChooseFromMapActivity.this, GoRideActivity.class);
startActivity(intent);
}
}
});
How to achieve this...?
How can I do this with shared preferences?
Change
Bundle extras = intent.getExtras();
to
Bundle extras = getIntent().getExtras();
Hope this helps :)
Check the below code
Activity_1. : This will send the data to the Common Activity.
Intent i = new Intent(Activity_1.this, CommonActivity.class);
i.putExtra("type",1);
startActivity(i);
Activity_2. : This will send the data to the Common Activity.
Intent i = new Intent(Activity_2.this, CommonActivity.class);
i.putExtra("type",2);
startActivity(i);
Then on your Common Activity write this code in the onCreate function.
int receivedValue = getIntent().getIntExtra("type", 0);
// here 0 is the default value when there is no data in the particular key.
now you can check the condition like this
if(receivedValue==1)
{
// do something here
}
if(receivedValue==2)
{
// do something here
}
This will definitely work for you. Try it..!!
Happy coding.
Activity1,
txt_from.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i = new Intent(getApplicationContext(), PickLocationActivity.class);
GoSendData.instance.addressType = 0;
i.putExtra("type",1);
startActivity(i);
}
});
Activity2,
txt_from.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i = new Intent(getApplicationContext(), PickLocationActivity.class);
GoSendData.instance.addressType = 0;
i.putExtra("type",2);
startActivity(i);
}
});
Common Activity
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = getIntent();
int type = i.getInt("type");
if(type==1) {
Intent intent = new Intent(ChooseFromMapActivity.this, Activity1.class);
startActivity(intent);
}
if(type == 2)
{
Intent intent = new Intent(ChooseFromMapActivity.this, Activity2.class);
startActivity(intent);
}
}
});

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

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

Categories