Android: Start Activity after 5 or more clicks - android

I have a onClick listener which starts an activity using intent, but how to make the listener to fire the Activity intent only when the user click five times or more?
public boolean onClick(View v) {
Intent myIntent = new Intent(activity, loginActivity.class);
activity.startActivity(myIntent);
return false;
}
Here I am going to login Activity. How can I get back to previous activity after login successful?
public void onClick(View v) {
String username = Username.getText().toString();
String password = Password.getText().toString();
if(username.equals("guest") && password.equals("guest")) {
lResult.setText("Login successful.");
} else {
lResult.setText("Login failed");
}
}

Have a static variable in program which will increment on each click.
When you click count reach 5 then trigger code to start LoginActivity.
static int i = 0;
#override
public void onClick(View view) {
i++;
if (i == 5) {
i = 0;
Intent myIntent = new Intent(activity, loginActivity.class);
activity.startActivity(myIntent);
}
}

You can try to build a counter which count the clicks and from the 5th clicks let him go forward
To turn back to the previous activity just call
finish();

Add a static counter to your activity.
static int clickCount;
In your onClick:
if(clickCount++<5){return;}

For the fist question just a a counter variable on the class and increment in on onClick() and check it its >= 5 before starting the intent.
int clickCounter;
public boolean onClick(View v) {
clickCounter++;
if (clickCounter >= 5) {
Intent myIntent = new Intent(activity, loginActivity.class);
activity.startActivity(myIntent);
}
return false;
}
For the second question you must take into account whether previous Activity must keep exactly the same aspect or update with user data. Take a look at Activity.startActivityForResult (Intent intent, int requestCode) for calling an activity and get a result value from it.
-

Related

Preventing showing multiple intents for button press in android

I have implemented code in which the UI has a button. On button press, I will prompt an email chooser from an intent.
Problem is when I press the button multiple times, the intent popup shows one by one. Can I stop this by using flags? This is a Xamarin Android project.
Code:
Intent intent = new Intent();
intent.SetAction(Intent.ActionSend);
intent.SetType(FileType);
intent.PutExtra(Intent.ExtraSubject, emailMessage.Subject);
if (!emailMessage.IsLinkInclude && !emailMessage.IsAlternateFileInclude){
intent.PutExtra(Intent.ExtraStream, AssetPathHelper.GetAssetUri(item, context));
}
intent.AddFlags(ActivityFlags.GrantReadUriPermission);
intent.AddFlags(ActivityFlags.NewTask);
intent.AddFlags(ActivityFlags.ResetTaskIfNeeded);
intent.PutExtra(Intent.ExtraText, Html.FromHtml(emailMessage.Message));
if (intent.ResolveActivity(context.PackageManager) != null){
context.StartActivity(Intent.CreateChooser(intent, AndroidStringLoader.GetStringValue(Resource.String.SendEmailText)));
}
Disable the button in onClick() and once the intended operation is done, enable the button.
public void onClick(View view) {
btn.setEnabled(false);
//some operation may be async
}
public void onOperationFinished() {
btn.setEnabled(true);
}
I have faced the same problem, here is my solution to avoid it by placing a timer between two consecutive click.
private static final long INTERVAL = 1000;
private long lastClickTime = 0;
// onClick of your button code below
#Override
public final void onClick(View v) {
long currentTime = SystemClock.elapsedRealtime();
if (currentTime - lastClickTime > INTERVAL) {
lastClickTime = currentTime;
//perform the task here of click
}
}
The other way is setEnabled(false), but for a very fast tapping on button , is not efficient.
Seems there is no flag for the intent to passed in this scenario , So i have implemented it by following , we can get the fail and success status from it
https://developer.android.com/guide/components/activities.html#StartingAnActivityForResult
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (resultCode == Result.Canceled)
{
this.shareAssetPopup.isPopupWindowActive = false;
}
}

Android : How to make enable the button of one Activity in other Activity - without using static?

I have a login Activity where I can give username and password. If both are true then just am disabling the button and calling other Activity (MainActivity).
If I press back from MainActivity then I want to make enable submit button in the LoginActivity and am setting the username and password as empty.
This is my code.
private Boolean exit = false;
#Override
public void onBackPressed() {
if (exit)
{
}
else {
MainActivity.this.finish();
Toast.makeText(this, "Press Back again to Exit.",
Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit = false;
LoginActivity.user_name.setText("");
LoginActivity.password.setText("");
LoginActivity.loginsubmit.setEnabled(true);
}
}, 100);
}
}
Here am using static. But I want to do this without using static. Could someone give me an idea?
Add below code to onBackPressed() of MainActivity,
Intent loginIntent= new Intent(MainActivity.this,LoginActivity.class);
loginIntent.putExtra("username", "");
loginIntent.putExtra("password", "");
loginIntent.putExtra("isSubmitEnabled", true);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
And add below code to onCreate() of LoginActivity,
Intent intent = getIntent();
if (intent != null) {
String username = intent.getStringExtra("username");
String password = intent.getStringExtra("password");
boolean isSubmitEnabled = intent.getBooleanExtra("isSubmitEnabled",
false);
}
Using above username, password, and isSubmitEnabled flag you can achieve the required.
You can use below code,
user_name.setText(username);
password.setText(password);
loginsubmit.setEnabled(isSubmitEnabled );
No need to static just override onResume() in LoginActivity like :
#Override
protected void onResume() {
super.onResume();
user_name.setText("");
password.setText("");
loginsubmit.setEnabled(true);
}

Android Intent won't pass value from Switch

I have a Switch button, from which I want to pass different values (1 or 2) to next activity for calculations. But I always get 0. Any help?
Switch mySwitch = (Switch) findViewById(R.id.edit_home);
// set the switch to ON
mySwitch.setChecked(true);
// attach a listener to check for changes in state
mySwitch.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
double input5 = 2;
Intent intentx=new Intent(MainActivity.this,Main2Activity.class);
intentx.putExtra("IFValue",input5);
startActivity(intentx);
Toast.makeText(getApplicationContext(), "Home field is important advantage",
Toast.LENGTH_SHORT).show();
} else {
double input5 = 1;
Intent intenty=new Intent(MainActivity.this,Main2Activity.class);
intenty.putExtra("IFValue",input5);
startActivity(intentx);
Toast.makeText(getApplicationContext(),
"Home field is not advantage", Toast.LENGTH_SHORT).show();
}
}
});
In next activity:
Bundle bundle = getIntent().getExtras();
double input5 = bundle.getDouble("IFValue");
EDITED: I want to send values (input5) to the next activity, but if I add startActivity(intentx) inside of switch; then goes there imediately and not when I press next Button (buttonForward) as I want to.
Rest of the code:
Switch mySwitch = (Switch) findViewById(R.id.edit_home);
// set the switch to ON
mySwitch.setChecked(true);
// attach a listener to check for changes in state
mySwitch.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked == true) {
double input5 = 2;
Intent intentx=new Intent(MainActivity.this,Main2Activity.class);
intentx.putExtra("IFValue",input5);
startActivity(intentx);
Toast.makeText(getApplicationContext(), "Home field is important advantage",
Toast.LENGTH_SHORT).show();
} else {
double input5 = 1;
Intent intenty=new Intent(MainActivity.this,Main2Activity.class);
intenty.putExtra("IFValue",input5);
startActivity(intenty);
Toast.makeText(getApplicationContext(),
"Home field is not advantage", Toast.LENGTH_SHORT).show();
}
}
});
Button buttonForward = (Button) findViewById(R.id.buttonToMain2);
buttonForward.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
EditText edit_team = (EditText) findViewById(R.id.edit_team);
EditText edit_form = (EditText) findViewById(R.id.edit_form);
EditText edit_import = (EditText) findViewById(R.id.edit_import);
String ekipa1 = edit_team.getText().toString();
final double input2 = Double.valueOf(qualityControl.getProgress());
final double input3 = Double.valueOf(edit_form.getText().toString());
final double input4 = Double.valueOf(ratingBar.getRating());
final double input6 = Double.valueOf(edit_import.getText().toString());
Intent intent=new Intent(MainActivity.this,Main2Activity.class);
intent.putExtra("Value",input2);
intent.putExtra("Value1",input3);
intent.putExtra("Value2",input4);
intent.putExtra("Value4",input6);
intent.putExtra("team1", ekipa1);
startActivity(intent);
}
});
You are creating a local instance of the Intent (intentx & intenty) inside the listener (I do not see you calling startActivity() inside the listener). The passed Extras only apply to the local copy not to the one you are using outside the listener with startActivity().
Update 1
Character case matters when using Extra keys:
You are using intentx.putExtra("IFvalue",input5);
while in the next Activity you are using double input5 = bundle.getDouble("IFValue"); which is a different key.
Update 2
I want to send values (input5) to the next activity, but if I add
startActivity(intentx) inside of switch; then goes there imediately
and not when I press next Button (buttonForward) as I want to.
Then, you will need to have only one Intent instance in the whole Activity (define it before onCreate() and then do not start the Activity from the switch listener, but add the Extra for the single Intent instance:
Intent intent = new Intent(MainActivity.this,Main2Activity.class); // Class level variable
then change the following in the switch listener:
// Intent intentx=new Intent(MainActivity.this,Main2Activity.class); remove this
intent.putExtra("IFValue",input5);
and in the buttonForward click listener:
//Intent intent=new Intent(MainActivity.this,Main2Activity.class); remove this
intent.putExtra("Value",input2);
intent.putExtra("Value1",input3);
intent.putExtra("Value2",input4);
intent.putExtra("Value4",input6);
intent.putExtra("team1", ekipa1);
startActivity(intent);

How Can I Pass Value Of Edittext From One Activity To Other in Android?

I want to pass the value of an EditText in one activity to another activity on button press and use that value in my code. However, there is one more activity between those activities in which I don't want to use that value
My Activity1 has:
textOut = (EditText)findViewById(R.id.ipadd);
Button ip = (Button) findViewById(R.id.ipad);
ip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent("com.shaz.hello"));
}});
From the Activity1 the user goes to the Activity2
Activity2
if ( x ==10 ) {
startActivity(new Intent("com.shaz.hello2"));
}
From the Activity2 the user goes to the Activity3
Activity3
Here I want to use that value as a String.
this is an another solution;
create one Bean class like this,
public class Bean {
public static String value;
public static String getValue() {
return value;
}
public static void setValue(String value) {
Bean.value = value;
}
}
On first Activity set the variable in Bean.
Bean bean = new Bean();
bean.setValue("your value");
And get the variable value on last or any Activity
Bean bean = new Bean();
String yourValue=bean.getValue();
You can using putExtra() and getExtra(), Add this in your current activity:
ip.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent mIntent = new Intent(currentActivity.this, hello.class);
mIntent.putExtra("valuename", Integer.valueOf(textOut.getText.toString));
startActivity(mIntent);
}
}
To get result from last activity put this line after onCreate():
int myValue = getIntent().getIntExtra("valuename", 0);
if (myValue == 10)
{
Intent mIntent = new Intent(currentActivity.this, hello2.class);
startActivity(mIntent);
}
Edited
You need to add your activities in android manifest file, e.g:
<activity android:name=".hello2"></activity>

How to pass values statically from one page to other in android?

In my projects I kept different images for categories. When I click on each category image I am passing its category id to other page statically and setting the drawable image of that category in the new page.
My Code:
Firstpage.java
public static String categoryid;
category1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
categoryid="0";
Intent myIntent = new Intent(view.getContext(),Nextpage.class);
startActivityForResult(myIntent, 0);
}
});
category2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
categoryid="1";
Intent myIntent = new Intent(view.getContext(),Nextpage.class);
startActivityForResult(myIntent, 0);
}
});
category3.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
categoryid="2";
Intent myIntent = new Intent(view.getContext(),Nextpage.class);
startActivityForResult(myIntent, 0);
}
});
Nextpage.java
public static String catid = Firstpage.categoryid;
ImageView categorytype=(ImageView)findViewById(R.id.imageView1);
if(catid=="0")
{
categorytype.setBackgroundResource(R.drawable.image1);
}
else if(catid=="1")
{
categorytype.setBackgroundResource(R.drawable.image2);
}
else if(catid=="2")
{
categorytype.setBackgroundResource(R.drawable.image3);
}
First time when I am clicking on the category image it is passing the category id to the next page and that particular image is setting in the nextpage. After that I clicked the back button(android back button) and went to Firstpage.java and again clicked on other image. But this time also the same image stored. The category id didnt changed. The category id is not refreshing...How to refresh the category id? Any suggestion will be thankful.....
You are comparing two strings by == operator, instead you should compare by equals method, try following:
if(catid.equals("0"))
{
categorytype.setBackgroundResource(R.drawable.image1);
}
else if(catid.equals("1"))
{
categorytype.setBackgroundResource(R.drawable.image2);
}
else if(catid.equals(2"))
{
categorytype.setBackgroundResource(R.drawable.image3);
}
Don't use static variables for this. Pass the category ID to your Nextpage activity through the intent. In Firstpage.java:
public static final String CATEGORY_KEY = "category";
category1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(this,Nextpage.class);
myIntent.putExtra(CATEGORY_KEY, "0");
startActivityForResult(myIntent, 0);
}
});
Then retrieve it in the onCreate(Bundle) method of Nextpage.java:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String categoryid = intent.getStringExtra(Firstpage.CATEGORY_KEY);
. . .
}
The reason your method doesn't work is that Nextpage.catid is initialized when the class is loaded, but the assignment statement is not executed again unless the class is unloaded and needs to be reloaded.
I think problem is here you are comparing String values using this if(catid=="0") Which you should be compare it using if(catid.trim().equals("0"))
Update this change in your code and check it.

Categories

Resources