Android Intent won't pass value from Switch - android

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

Related

App is crashing when I click the button - two intents in a button - using Enum

I need help with my code. Let me try to explain the problem:
At the first activity I have two fields where I'll set values from an Enum, for this I made a button for each field that basically shows me another activity, calls the value and brings it to the main activity. Still in the first activity I have a button that starts another activity and (at the same time) take all the values from the enum end sends to another activity. The point is, everything is working, but this last button no, when I click it the app crashes. What is happening and how can I solve it?
Here goes the code of the first activity:
public class MenuInicial extends AppCompatActivity {
public static final int CONSTANTE_BANZO = 1;
Button escolherM;
Button escolherB;
Button next;
TextView campoM;
TextView campoB;
Intent intent1;
Intent intent2;
Intent intentBundle;
Intent intentNext;
Bundle bundle;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_inicial);
intent1 = new Intent(MenuInicial.this, Montante.class);
campoM = (TextView) findViewById(R.id.fieldM);
escolherM = (Button) findViewById(R.id.chooseM);
String perfilM = getIntent().getExtras().getString("nameM");
campoM.setText(perfilM);
escolherM.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
startActivity(intent1);
}
});
intent2 = new Intent(MenuInicial.this, Banzo.class);
campoB = (TextView) findViewById(R.id.fieldB);
escolherB = (Button) findViewById(R.id.chooseB);
escolherB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
startActivityForResult(intent2, CONSTANTE_BANZO);
}
});
next = (Button) findViewById(R.id.prosseguir);
intentBundle = new Intent(MenuInicial.this, ConferenciaDosDados.class);
intentNext = new Intent(MenuInicial.this, Dados.class);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String perfilM = getIntent().getExtras().getString("nameM");
Float baseMt = getIntent().getExtras().getFloat("baseM");
Float alturaMt = getIntent().getExtras().getFloat("alturaM");
String perfilB = getIntent().getExtras().getString("nameB");
Float baseBz = getIntent().getExtras().getFloat("baseB");
Float alturaBz = getIntent().getExtras().getFloat("alturaB");
bundle.putString("nomeM",perfilM);
bundle.putFloat("baseM",baseMt);
bundle.putFloat("alturaM",alturaMt);
bundle.putString("nomeB",perfilB);
bundle.putFloat("baseB",baseBz);
bundle.putFloat("alturaB",alturaBz);
intentBundle.putExtras(bundle);
startActivity(intentBundle);
startActivity(intentNext);
}
});
}
protected void onActivityResult(int codigo, int resultado, Intent intent){
if(codigo == CONSTANTE_BANZO){
Bundle bundleB = intent.getExtras();
if(bundleB != null){
String perfilB = bundleB.getString("nameB");
campoB.setText(perfilB);
}
}
}
}
next = (Button) findViewById(R.id.prosseguir);
intentBundle = new Intent(MenuInicial.this, ConferenciaDosDados.class);
intentNext = new Intent(MenuInicial.this, Dados.class);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String perfilM = getIntent().getExtras().getString("nameM");
Float baseMt = getIntent().getExtras().getFloat("baseM");
Float alturaMt = getIntent().getExtras().getFloat("alturaM");
String perfilB = getIntent().getExtras().getString("nameB");
Float baseBz = getIntent().getExtras().getFloat("baseB");
Float alturaBz = getIntent().getExtras().getFloat("alturaB");
bundle.putString("nomeM",perfilM);
bundle.putFloat("baseM",baseMt);
bundle.putFloat("alturaM",alturaMt);
bundle.putString("nomeB",perfilB);
bundle.putFloat("baseB",baseBz);
bundle.putFloat("alturaB",alturaBz);
intentBundle.putExtras(bundle);
startActivity(intentBundle);
startActivity(intentNext);
}
});
Which activity do you want to go to? choose one. When you do, you can get those extras then when you need to goto the other activity, you can put those extras there too.
A better way to do it is to create a model (constructor with setters and getters) and put these in a list. At that point you can loop through the list and take what you need. It all depends on what you are doing though as the list will not be instantiated like intent extras would be.
Or, you can use SharedPref which is similar to a HashMap (which is also similar to the Intent Extras). SharedPref will store the key and value on the phones cache and then you can pull from that when you need it. Again, keep in mind that if the user clears the cache on the app, then it'll delete those shared pref.
Finally, you can also use a database such as Parse Server or Firebase.

I can't make new intent

my problem with new intent , the problem is with this: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.test.test1/com.test.test1.facebook}; have you declared this activity in your AndroidManifest.xml?
`package com.test.test1;
public class SampleActivity extends Activity implements OnItemSelectedListener,
OnItemClickListener, OnRotationFinishedListener, OnCenterClickListener {
public static final String ARG_LAYOUT = "layout";
private TextView selectedTextView;
#Override
protected void onCreate(android.os.Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set content view by passed extra
Bundle extras = getIntent().getExtras();
int layoutId = extras.getInt(ARG_LAYOUT);
setContentView(R.layout.sample_with_background);
// Set listeners
CircleLayout circleMenu = (CircleLayout) findViewById(R.id.main_circle_layout);
circleMenu.setOnItemSelectedListener(this);
circleMenu.setOnItemClickListener(this);
circleMenu.setOnRotationFinishedListener(this);
circleMenu.setOnCenterClickListener(this);
selectedTextView = (TextView) findViewById(R.id.main_selected_textView);
selectedTextView.setText(((CircleImageView) circleMenu
.getSelectedItem()).getName());
}
#Override
public void onItemSelected(View view, String name) {
selectedTextView.setText(name);
switch (view.getId()) {
case R.id.main_calendar_image:
// Handle calendar selection
break;
case R.id.main_cloud_image:
// Handle cloud selection
break;
case R.id.main_facebook_image:
// Handle facebook selection
break;
case R.id.main_key_image:
// Handle key selection
break;
case R.id.main_profile_image:
// Handle profile selection
break;
case R.id.main_tap_image:
// Handle tap selection
break;
}
}
#Override
public void onItemClick(View view, String name) {
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.start_app) + " " + name,
Toast.LENGTH_SHORT).show();
switch (view.getId()) {
case R.id.main_calendar_image:
// Here is my problem i cant start a new intent why ?
Intent myIntent = new Intent(view.getContext(), facebook.class);
startActivityForResult(myIntent, 0);
break;
case R.id.main_cloud_image:
// Handle cloud click
break;
case R.id.main_facebook_image:
// Handle facebook click
break;}
}
#Override
public void onRotationFinished(View view, String name) {
Animation animation = new RotateAnimation(0, 360, view.getWidth() / 2,
view.getHeight() / 2);
animation.setDuration(250);
view.startAnimation(animation);
}
#Override
public void onCenterClick() {
Toast.makeText(getApplicationContext(), R.string.center_click,
Toast.LENGTH_SHORT).show();
}
}
`
change this line in your code.
Intent myIntent = new Intent(SampleActivity.this, facebook.class);
you have declare Facebook activity in your manifestfile.xml
I guess the reason why you can't start the new intent is because you are using lowercase instead of uppercase for that facebook class.
Intent myIntent = new Intent(this, Facebook.class);
I think in your manifest have not facebook activity if have declared it but still can not start intent then you can check R.id.main_calendar_image view really get clicked
Instead of using view.getContext() use the full Activity.this way.
Intent myIntent = new Intent(SampleActivity.this, Facebook.class);
Oh and do ensure that it is declared in your manifest

How to check if a user has already clicked a Button?

I have a button in my menu with a “promo code” inside. I need to check if a user already clicked it so I can tell him (the next time he clicks it) “You already redeemed this promo code!” How do I do that? I need only the piece of code where I can check for button clicked.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean clicked = false;
switch (item.getItemId()) {
case R.id.getcode:
SharedPreferences pref = getSharedPreferences("promo", MODE_PRIVATE);
boolean activated = pref.getBoolean("activated", false);
if(activated == false) { Button btn = (Button) findViewById(R.id.getcode);
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage(getString(R.string.congrats) + "\n" + getString(R.string.promcd) + "\n" + "ASC2013-"+Build.ID+"-"+android.os.Build.SERIAL.charAt(3)+"-"+Build.SERIAL.charAt(6)+"-"+Build.SERIAL.charAt(9)+"-"+Build.SERIAL.charAt(12));
dlgAlert.setPositiveButton(R.string.go,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {"lorenzocascio#gmail.com"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, getString(R.string.validreq)+Build.BOOTLOADER);
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, getString(R.string.why) + "\n" + getString(R.string.validreq1) +"\n"+getString(R.string.dialogMSG1);
emailIntent.setType("plain/text");
startActivity(emailIntent);
}
});
dlgAlert.setCancelable(true);
dlgAlert.create().show();
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("activated", true);
editor.commit();
}
break;
}
switch (item.getItemId()) {
case R.id.settings:
Intent settings = new Intent(MainActivity.this, Settings.class);
MainActivity.this.startActivity(settings);
}
return true;
}
How about a simple boolean flag?
Set it to false in the beginning - as soon as the user clicks - set it to true.
private boolean clicked = false; // this is a member variable
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(clicked) {
Toast.makeText(getActivity(), "You already clicked!", 1000).show();
} else {
Toast.makeText(getActivity(), "You clicked for the first time!", 1000).show();
}
clicked = true;
}
}
}
Please be aware that the "clicked" boolean variable must be a member variable of your Activity, otherwise it will not be visible inside onClick(). A variable being a member variable simply means that it belongs to the class it is in, and not just occurs in a specific method. In the above code, "btn" would be a "normal" variable since it only appears inside onCreate() (a method), whereas "clicked" is declared for the Activity (the class it is in), and is therefore a member variable.
If you want to save if the user has clicked even after the app was closed and gets reopened, take a look at the SharedPreferences.
SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
boolean clicked;
clicked = prefs.getBoolean("yourkey", false); // get a value, use whatever key you want
prefs.edit().putBoolean("yourkey", clicked).commit(); // save a value, use same key
You can save a flag in shared preferences if the user clicks the button. Next time, you can check in the shared preferences if there exists the flag.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences pref = getSharedPreferences("promo", MODE_PRIVATE);
boolean activated = pref.getBoolean("activated", false);
if(activated == false) { // User hasn't actived the promocode -> activate it
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("activated", true);
editor.commit();
}
}

Android: Start Activity after 5 or more clicks

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

Check RadioGroup checked or not and get value to static int

GOAL 1: When click the button, if there isn't any radiobutton checked, it will warning user by Toast; if a radiobutton checked, it will take user to new activity (or do smt up on you).
First
public class hanh1_2 extends Activity{
public static int ButID;
#Override
Second, set the button action:
final Button ok2 = (Button) findViewById(R.id.ok2);
ok2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Set int of ButID = checkedradiobuttonID
//If ButID = -1 --> there isn't bt checked
int ButID = tieng.getCheckedRadioButtonId();
if (ButID == -1){
Toast.makeText(hanh1_2.this, "Check a butt pls", Toast.LENGTH_SHORT).show();
}
else {
Intent intent2 = new Intent(hanh1_2.this,hanh1_3.class);
startActivity(intent2);
}
}
});
Meaningless to advanced, but may helpful for some newbie like me :)
Have a look at the Form stuff tutorial on the Android dev site. You can supply an OnClickListener to all RadioButtons and keep track of the one selected (if any).
private OnClickListener radio_listener = new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
RadioButton rb = (RadioButton) v;
Toast.makeText(HelloFormStuff.this, rb.getText(), Toast.LENGTH_SHORT).show();
}
};
Alternatively, you can potentially use the RadioGroup's getCheckedRadioButtonId() method.
As illustrated in one of the other answers: pass the int value as an extra to the Intent you use to launch your second Activity:
// In first activity
Intent i = new Intent(FirstActivity.this, SecondActivity.class);
i.putInt("selected_index", selectedIndex);
startActivity(i);
// In second activity
int selectedIndex = getIntent().getExtras().getInt("selected_index");
Take all your RadioButton and RadioGroup to class level.
initialize them inside onCreate()
now inside onClick() get id of checked RadioButton and compare like this:
public void onClick(View v) {
int checked = tieng.getCheckedRadioButtonId(); // tieng is your RadioGroup
switch(checked)
{
case R.id.tieng1:
Toast.makeText(hanh1_2.this, "First is selected", Toast.LENGTH_SHORT).show();
break;
case R.id.tieng1:
Toast.makeText(hanh1_2.this, "Second is selected", Toast.LENGTH_SHORT).show();
break;
case R.id.tieng1:
Toast.makeText(hanh1_2.this, "Third is selected", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(hanh1_2.this, "pleas check any button", Toast.LENGTH_SHORT).show();
break;
}
}
put extra along with intent :
else {
Intent intent2 = new Intent(hanh1_2.this,hanh1_3.class);
intent2.putInt(Index1, index1);
startActivity(intent2);
}
now inside second activity onCreate() read this extra :
{
int Index1 = getIntent().getExtras().getInt("Index1");
//do stuff here
}

Categories

Resources