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
Related
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;
I have need some help to achieve the following:
When I click on my previous-button I want the application to go to the previous page without losing my data. I already added the previous-button to the application, but when I click it my application goes to the main page instead of the previous page.
My code:
Button next,previous;
next = (Button)findViewById(R.id.work_next);
previous = (Button)findViewById(R.id.work_previous);
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentSignUP = new Intent(getApplicationContext(), filldetails.class);
startActivity(intentSignUP);
finish();
}
});
next.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
boolean allValues = true;
String comp="",desg="",fromdate="",todate="",role_d="",technologies_used="";
if(companyName.getText().toString().equals(""))
{
allValues = false;
Toast.makeText(getApplicationContext(), "Please enter all the fields",Toast.LENGTH_SHORT).show();
}
else
{
comp= companyName.getText().toString();
//Toast.makeText(getApplicationContext(), "Please enter all the fields",Toast.LENGTH_SHORT).show();
}
if(designation.getText().toString().equals(""))
{
allValues = false;
Toast.makeText(getApplicationContext(), "Please enter all the fields",Toast.LENGTH_SHORT).show();
}
else
{
desg = designation.getText().toString();
//Toast.makeText(getApplicationContext(), "Please enter all the fields",Toast.LENGTH_SHORT).show();
}
if(fromDate.getText().toString().length()<8 || fromDate.getText().toString().length()>10 ||fromDate.getText().toString().equals(""))
{
allValues = false;
Toast.makeText(getApplicationContext(),"Please enter valid Date",Toast.LENGTH_SHORT).show();
}
else
{
fromdate = fromDate.getText().toString();
}
if(toDate.getText().toString().length()<8 || toDate.getText().toString().length()>10 ||toDate.getText().toString().equals(""))
{
allValues = false;
Toast.makeText(getApplicationContext(),"Please enter valid Date",Toast.LENGTH_SHORT).show();
}
else
{
todate = toDate.getText().toString();
}
if(role_desc.getText().toString().equals(""))
{
allValues = false;
Toast.makeText(getApplicationContext(), "Please enter all the fields",Toast.LENGTH_SHORT).show();
}
else
{
role_d = role_desc.getText().toString();
}
if(technologiesUsed.getText().toString().equals(""))
{
allValues = false;
Toast.makeText(getApplicationContext(), "Please enter all the fields",Toast.LENGTH_SHORT).show();
}
else
{
technologies_used = technologiesUsed.getText().toString();
}
if(allValues)
{
Intent moveToNext = new Intent(getApplicationContext(),skills.class);
moveToNext.putExtra("comp_name",comp);
moveToNext.putExtra("desc",desg);
moveToNext.putExtra("role_d",role_d);
moveToNext.putExtra("from_date",fromdate);
moveToNext.putExtra("to_date",todate);
moveToNext.putExtra("technologies_used",technologies_used);
moveToNext.putExtra("iscurrent",isCurrent.isChecked());
moveToNext.putExtra("aboutme",getIntent().getStringExtra("aboutme"));
moveToNext.putExtra("address",getIntent().getStringExtra("address"));
startActivity(moveToNext);
finish();
}
else
{
Toast.makeText(getApplicationContext(), "Please provide all values", Toast.LENGTH_SHORT).show();
}
}
});
}
You don't need to start the activity to go to previous activity (if you haven't called finish() on that), just close the current activity and it will go to previous activity and data will be intact.
Change your onClick method of previous button like this
#Override
public void onClick(View v) {
finish();
}
Note: If you have closed the previous activity by calling finish() then remove that code, otherwise data will not be intact without modifying your code in that activity.
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();
}
}
Here's the code snippet
s= e1.getText().toString();
iv1 = (ImageView) findViewById(R.id.imageView1);
iv1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if(s.matches("")){
int time=2000;
Toast.makeText(Loadscreen.this, "Please specify the level", time).show();
}
else{
int str= Integer.valueOf(s);
if(str>0 && str<11){
calculate(str);
r2=new Random();
int nxt = r2.nextInt(2);
if(nxt==0){
//do some work
}
else{
//do some work
}
}
else{
int time=2000;
Toast.makeText(Loadscreen.this, "Enter a valid level", time).show();
}
}
}
});
Control never goes to the else block. The output on the screen is the text of the Toast with the comment "Please specify the level".
Please suggest why else part is not executed?
probably you are not getting the correct result while getting the text from edit text
write this line in onclick method before any comparison
s= e1.getText().toString();
I'm developing an app which will do multiple method in a single input. For example calculating square circumference and area, I give only one EditText and two button. But when I run the app, if I give an input and click the area button it won't do the calculation until I click the circumference button. And same goes if I change the input. Here is the code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.square);
etSide = (EditText) findViewById(R.id.etSquare);
tvResult = (TextView) findViewById(R.id.tvSquare);
Button btnCir = (Button) findViewById(R.id.btnSqrCir);
btnCir.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countCir();
}
});
Button btnArea = (Button) findViewById(R.id.btnSqrArea);
btnArea.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
countArea();
}
});
}
private void countArea() {
try {
side = etSide.getText().toString();
s = parseInt(side);
area = s * s;
tvResult.setText("Area = " + cir);
} catch (NumberFormatException ex){
Toast.makeText(getApplicationContext(), "Oops, you seem haven't enter the side length", Toast.LENGTH_LONG).show();
}
}
private void countCir() {
try {
side = etSide.getText().toString();
s = parseInt(side);
cir = 4 * s;
tvResult.setText("Circumference = " + area);
} catch (NumberFormatException ex){
Toast.makeText(getApplicationContext(), "Oops, you seem haven't enter the side length", Toast.LENGTH_LONG).show();
}
}
Any better idea? Really need help...
It looks like you have your variables backwards. For example:
private void countArea() {
try {
side = etSide.getText().toString();
s = parseInt(side);
area = s * s;
tvResult.setText("Area = " + cir); // <-- here cir doesn't have a value until you click the circumference button
} catch (NumberFormatException ex){
Toast.makeText(getApplicationContext(), "Oops, you seem haven't enter the side length", Toast.LENGTH_LONG).show();
}
}
So your TextView would display ""Area = ""
It looks to me like you want
tvResult.setText("Area = " + cir);
to be
tvResult.setText("Area = " + area);
Let me know if I'm not understanding you correctly
Note:
For your Toast you should use this or YourActivityName.this for Context instead of getApplicationContext()
One other suggestion I might make since your onClick()s only call a method, to make it simpler you could use one listener like this
public void onCreate(...)
{
...
btnCir.setOnClickListener(this);
btnArea.setOnClickListener(this);
...
}
public void onClick(View v)
{
switch(v.getId()) // get the id of the Button clicked
{
case (R.id.btnSqrArea): // call appropriate method
countArea();
break;
case (R.id.btnSqrCir):
countCir();
break;
}
}
You would just have to remember to add implements OnClickListener to your class definition. That's just a preference but worth mentioning.