not work condition onCheckedChanged - android

I have an issue with the following condition:
if (Cuadrado.isChecked() == true)
This is the full code:
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
String dato5 = DatoMath.getText().toString();
if (Cubo.isChecked()==true) {
if (dato5.equals("")) {
Toast toast = Toast.makeText(getApplicationContext(), "no hay datos", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER | Gravity.LEFT, 0, 0);
toast.show();
} else {
int datofinal = Integer.parseInt(dato5);
int final3 = (int) Math.pow(datofinal, 2);
Resultado.setText("" + final3);};
if (Cuadrado.isChecked() == true) {
if (dato5.equals("")) {
Toast toast = Toast.makeText(getApplicationContext(), "no hay datossssss", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT, 0, 0);
toast.show();
} else {
int datofinal2 = Integer.parseInt(dato5);
int final4 = (int) Math.pow(datofinal2, 3);
Resultado.setText("" + final4);
};

#Override
public void onCheckedChanged(RadioGroup group, int checkedId){
switch(checkedId){
case R.id.rbtn1:
// radio button 1 checked related code
break;
case R.id.rbtn2:
// radio button 2 checked related code
break;
}
}

Why are you intentionally complicating your code, you can simply write:
if (Cubo.isChecked())
{
//do whatever you want to do
}
The isChecked method returns a boolean so you can directly write it inside that if condition
And one more thing, why have you put a semi-colon[ ; ] after your else statements closing brace[ } ], replace that semicolon with another closing brace[ } ]

Related

How to change background of button on next click

Currently I have a list of TextViews whose background get changed when click for the first time. But I also want when user clicks on the second time its background should again change and vice versa.
With my existing code I am only able to change background for the first click, when I am clicking it again its background is not changing.
Here is my code:
public void onClick(View v) {
switch (v.getId()) {
case R.id.goalText1:
if (count <= 2) {
goals.add(mGoal1.getText().toString());
mGoal1.setTextColor(getResources().getColor(R.color.black));
mGoal1.setBackgroundColor(getResources().getColor(R.color.white));
count++;
} else {
Toast.makeText(SelectGoal.this, "cant select more", Toast.LENGTH_SHORT).show();
}
break;
case R.id.goalText2:
if (count <= 2) {
goals.add(mGoal2.getText().toString());
mGoal2.setTextColor(getResources().getColor(R.color.black));
mGoal2.setBackgroundColor(getResources().getColor(R.color.white));
count++;
} else {
Toast.makeText(SelectGoal.this, "cant select more", Toast.LENGTH_SHORT).show();
}
break;
case R.id.goalText3:
if (count <= 2) {
goals.add(mGoal3.getText().toString());
mGoal3.setTextColor(getResources().getColor(R.color.black));
mGoal3.setBackgroundColor(getResources().getColor(R.color.white));
count++;
} else {
Toast.makeText(SelectGoal.this, "cant select more", Toast.LENGTH_SHORT).show();
}
break;
case R.id.goalText4:
if (count <= 2) {
goals.add(mGoal4.getText().toString());
mGoal4.setTextColor(getResources().getColor(R.color.black));
mGoal4.setBackgroundColor(getResources().getColor(R.color.white));
count++;
} else {
Toast.makeText(SelectGoal.this, "cant select more", Toast.LENGTH_SHORT).show();
}
break;
case R.id.goalText5:
if (count <= 2) {
goals.add(mGoal5.getText().toString());
mGoal5.setTextColor(getResources().getColor(R.color.black));
mGoal5.setBackgroundColor(getResources().getColor(R.color.white));
count++;
} else {
Toast.makeText(SelectGoal.this, "cant select more", Toast.LENGTH_SHORT).show();
}
break;
case R.id.goalText6:
if (count <= 2) {
goals.add(mGoal6.getText().toString());
mGoal6.setTextColor(getResources().getColor(R.color.black));
mGoal6.setBackgroundColor(getResources().getColor(R.color.white));
count++;
} else {
Toast.makeText(SelectGoal.this, "cant select more", Toast.LENGTH_SHORT).show();
}
break;
case R.id.goalText7:
if (count <= 2) {
goals.add(mGoal7.getText().toString());
mGoal7.setTextColor(getResources().getColor(R.color.black));
mGoal7.setBackgroundColor(getResources().getColor(R.color.white));
count++;
} else {
Toast.makeText(SelectGoal.this, "cant select more", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btnGoal:
Intent intent = new Intent(this, fiteness_level_selection.class);
try {
obj.put("SelectedGoal", goals);
} catch (Exception e) {
e.printStackTrace();
}
intent.putExtra("GoalJson", obj.toString());
startActivity(intent);
break;
}
So can anybody suggest me any easy way to achieve it.
Set a boolean array in your activity.
//suppose you've 3 textviews within listview
public boolean isTransparent[] = {false,false,false};
And then do this in your onClick method.
public void onOnclick(View v){
switch (v.getId()) {
//foreach textview do this
case R.id.textView1 :
int color;
if (isTransparent[0])
color = getResources().getColor(android.R.color.transparent);
else
color = getResources().getColor(R.color.white);
isTransparent[0]=!isTransparent[0];
textview1.setBackgroundColor(color);
break;
case R.id.textView2:
// now check for isTransparent[1]
and so on ...
...
}
}
As What I am understand is you want Change background for that you have take bool variable and in Button click you have to check the bool value.
Boolean click_firsttime = false;
Inside your Button click
use this way
If(click_firsttime == false){
//perform task
// and set bool value to true
click_firsttime = true;
}else{
// perform task and set bool value
click_firsttime = false;
}
First create a boolean :
private boolean foo = true;
Then change your code like this :
public void onClick(View v) {
switch (v.getId()) {
case R.id.goalText1:
if (foo) {
goals.add(mGoal1.getText().toString());
mGoal1.setTextColor(getResources().getColor(R.color.black));
mGoal1.setBackgroundColor(getResources().getColor(R.color.white));
count++;
foo = false;
} else {
// set background to another color
foo = true;
}
break;

How to ensure only even numbers are entered in edittext in textwatcher?

I need to enter only even numbers(range:0-20) in edittext in textwatcher. However, when i did the following, it remained same that is it is allowing both even and odd numbers to be entered. I want when a user enters an odd number the toast is displayed. guide me please!
even
#Override
public void afterTextChanged(Editable s) {
try {
int v = Integer.parseInt(s.toString());
if(v%2!=0){
if (v > 20) {
s.replace(0, s.length(), "", 0, 2);
} else if (v < 0) {
s.replace(0, s.length(), "", 0, 1);
}
}
} catch (NumberFormatException ex)
{
Toast.makeText(MainActivity.this, "invalid", Toast.LENGTH_LONG).show();
}
}
You are just showing the Toast when a NumberFormatException exception is thrown, meaning that the string does not contain a number.
So you have to show the toast also when the number is even, and you will do it on the else condition of
if(v%2 != 0){
//Number is odd
}else{
//Number is even
}
Try like the following:
#Override
public void afterTextChanged(Editable s)
try {
int v = Integer.parseInt(s.toString());
if(v>0 && v<20){
if(v%2 != 0){
Toast.makeText(getContext(), "ODD", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getContext(), "EVEN", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(getContext(), "OUT OF RANGE", Toast.LENGTH_SHORT).show();
}
}catch (NumberFormatException e){
Toast.makeText(getContext(), "INVALID", Toast.LENGTH_SHORT).show();
}
}

Android: check the edit text isempty and submit issue

In my app i have dailog with edittext and submit button, if the edittext is empty
i gave a toast message "please enter something" ..my code is below
Button reviewPost = (Button) dialog.findViewById(R.id.submit);
reviewPost.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
v.setEnabled(false);
EditText ratingComment = (EditText) dialog
.findViewById(R.id.reviewcomment);
String comment = ratingComment.getText().toString();
String postStatus = "Y";
if (spinner.getSelectedItemPosition() > 0) {
postStatus = "N";
}
RadioGroup rating = (RadioGroup) dialog
.findViewById(R.id.customrating);
int radioButtonID = rating.getCheckedRadioButtonId();
View radioButton = rating.findViewById(radioButtonID);
int ratingNo = rating.indexOfChild(radioButton);
String ratingValue = (ratingNo + 1) + "";
if (comment != null && !comment.equalsIgnoreCase("")){
new PostReviewMessage().execute(activity, comment,
ratingValue, postStatus);
activity.finish();
}else{
Toast.makeText(activity, "Please enter your comment", Toast.LENGTH_SHORT).show();
}
Constants.rivewDialog = new ProgressDialog(activity);
Constants.rivewDialog.setCanceledOnTouchOutside(false);
Constants.rivewDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
Constants.rivewDialog.setMessage(activity.getString(R.string.postingrivew));
Constants.rivewDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
}
});
Constants.rivewDialog.show();
dialog.dismiss();
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return false;
}
});
But even if the edittext is empty it is submitting which should not happen.i am checking the condition as follows but its not working
if (comment != null && !comment.equalsIgnoreCase("")){
new PostReviewMessage().execute(activity, comment,
ratingValue, postStatus);
activity.finish();
}else{
Toast.makeText(activity, "Please enter your comment", Toast.LENGTH_SHORT).show();
}
use comment.trim().equals("") instead of comment.equalsIgnoreCase("")
or put a check on comment string length that it should exceed the minimum characters.
use
if(comment != null && !comment.isEmpty())
You can used this.
if(comment != null && !comment.isEmpty() && comment.length()!=0){
//your task
}else{
//give some message
}
Solved with below code..the problem is with the v.setEnabled(false);...i moved it into the if condition
if (comment != null && !comment.equalsIgnoreCase("")){
v.setEnabled(false);
new PostReviewMessage().execute(activity, comment,
ratingValue, postStatus);
Constants.rivewDialog = new ProgressDialog(activity);
Constants.rivewDialog.setCanceledOnTouchOutside(false);
Constants.rivewDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
Constants.rivewDialog.setMessage(activity.getString(R.string.postingrivew));
Constants.rivewDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
}
});
Constants.rivewDialog.show();
dialog.dismiss();
}else{
Toast.makeText(activity, "Please enter your comment", Toast.LENGTH_SHORT).show();
}

Program Execution is not in proper way

When I click on button in my program without entering data it shows both errors parallely (I have Highlighted in below prog). here i need to get only one error at a time i mean when it is null it has show appropriate one.vice versa..
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(v==findViewById(R.id.button1)) {
et1 = (EditText) findViewById(R.id.editText1);
if(et1.getText()!=null ) {
try {
radius = Double.valueOf(et1.getText().toString());
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Please enter correct value", Toast.LENGTH_SHORT).show();
}
}
if(radius==0.0) {
Toast.makeText(getApplicationContext(), "Value cannot be 0", Toast.LENGTH_SHORT).show();
}
try {
output = (double) Math.round(Math.PI * radius * radius);
String s = Double.toString(output);
tv1.setText(s);
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Please enter correct value", Toast.LENGTH_SHORT).show();
}
}
}
});
do not make things more complicated as they actually are. You can be sure that a correct value was entered without any try/catch blocks. Possible approach:
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
Pattern p = Pattern.compile("([0-9]*)");
if (et1.getText().toString().trim().length() > 0) {
Matcher m = p.matcher(et1.getText().toString().trim());
if (m.matches()) {
radius = Double.valueOf(et1.getText().toString());
output = (double) Math.round(Math.PI * radius
* radius);
tv1.setText(Double.toString(output));
} else
Toast.makeText(getApplicationContext(),
"incorrect value", Toast.LENGTH_SHORT)
.show();
} else
Toast.makeText(getApplicationContext(),
"input is empty", Toast.LENGTH_SHORT).show();
break;
default:
}
}
});
In the above code you check if there was any text entered. The second if checks whether the input is numeric using a java regex. When both requirements are met you can be sure the output is calculated correctly.
BTW, using switch-case is a better approach for click listeners

Android: Toast won't delay on spinner

I want to delay the toast on selected delay times like (15, 30, 60 seconds and no delay) but it won't work. Here's the code:
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
if(FirstLoad){
FirstLoad = false;
return;
}
Toast.makeText(parent.getContext(), "You chose " +
parent.getItemAtPosition(pos).toString()+ " to delay", Toast.LENGTH_LONG).show();
Message message = new Message();
Bundle bun = new Bundle();
bun.putString("delay", parent.getItemAtPosition(pos).toString());
message.obj = bun;
if (pos == 0) {
handler.sendMessageDelayed(message, 0);
}
else if (pos == 1) {
handler.sendMessageDelayed(message, 15000);
}
else if (pos == 2) {
handler.sendMessageDelayed(message, 30000);
}
else if (pos == 3) {
handler.sendMessageDelayed(message, 60000);
}
//handler.sendMessageDelayed(message, 15000);
}
public void onNothingSelected(AdapterView<?> parent) {
return;
}
Help Please.
Try this :
final Toast toast = Toast.makeText(parent.getContext(), "You chose "
+ parent.getItemAtPosition(pos).toString() + " to delay",
Toast.LENGTH_LONG);
Runnable showToastRunnable = new Runnable() {
public void run() {
toast.show();
}
};
if (pos == 0) {
handler.postDelayed(showToastRunnable, 0);
} else if (pos == 1) {
handler.postDelayed(showToastRunnable, 15000);
} else if (pos == 2) {
handler.postDelayed(showToastRunnable, 30000);
} else if (pos == 3) {
handler.postDelayed(showToastRunnable, 60000);
}
Edit:
By the way, I want to transfer this to the send button, i want to delay the toast of "Message sent" according to the delay the user chose. How should I implement it?
How are you fetching the delay? Is it something the user enters in an EditText?
In that case you could just get the delay like this :
int delay = Integer.parseInt(delayEditText.getText().toString());
and then use that delay amount to post the runnable to the handler like this :
handler.postDelayed(showToastRunnable, delay);
You can remove your entire if-else block in this case.
for this you can use custom dialog and hide it after a particular time.
class CustomDialog extends Dialog
{
setContentView(R.layout.dialogxml);
txtview=(TextView)findViewById(R.id.txtmsg);
}
Customdialog dialog= CustomDialog.show();
dialog.hide();
Handler hl_DelayedToast = new Handler(); // scope global
public void onItemSelected(AdapterView<?> parent,View view, int pos, long id)
{
if(FirstLoad)
{
FirstLoad = false;
return;
}
//if else logic to check the time
// if 0
hl_DelayedToast.postDelayed(mytoastshower,0);
// if 1
hl_DelayedToast.postDelayed(mytoastshower,1000);
}
public Runnable mytoastshower = new Runnable
{
public void run()
{
Toast.show();// show the toast
}
}
hope it helps.
Declare your handler this way:
Hanlder handlder=new Handler() {
public void handleMessage (Message msg) {
Toast.makeText(YOUR_ACTIVITY_CLASS_NAME.this,"You chose"+(Bundle(msg.obj)).getString("delay","DEFAULT_VALUE")+"to delay",Toast.LENGTH_LONG).show();
}
};
Simply, you don't have to use a bundle, but you can call msg.what=THE DELEY TIME.
Also, you can call handler.obtainMessage to get a message. See http://developer.android.com/reference/android/os/Handler.html#obtainMessage%28%29
So every time you send a message, it will be handled here, and thus you call show the toast.
Sorry that I don't have Eclipse installed on this laptop, so I can not test the code. However, I believe it works.

Categories

Resources