addition of editext values always returns zero - android

i have 10 edittext values in activitya,i want to add them and show the result in newactivity.
my code
public class activitya extends Activity implements onclicklistener
{
private EditText editext1;
private EditText editext2;
private EditText editext3;
private EditText editext4;
private EditText editext5;
private Button calculate;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activitya);
calculate =(Button)findviewbyid(R.id.button1);
calculate.setonclicklistener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
onadd();
break;
default:
break;
}
}
public void onadd()
{
Bundle bundle = new Bundle();
String value1 = editext1.getText().toString();
String value2 =editext2.getText().toString();
bundle.putString("sendvalue1",value1));
bundle.putString("sendvalue2",value2));
try{
Double Total =Double.parseDouble(value1)+Double.parseDouble(value2);}
catch(NumberFormatException e)
{
e.printstacktrace();
}
bundle.putString("totalvalue",String.valueof(Total));
Intent a = new intent(this,newactivity.class);
a.putExtras(bundle);
startactivity(a);
}
}
in newactivity :
public class newactivity extends activity{
private TextView total;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
total =(TextView)findviewbyid(R.id.text1);
onview();
}
public void onview()
{
Bundle bundle = this.getIntent().getExtras();
String param1 = bundle.getString("totalvalue");
total.setText(param1);
}
it shows the addition correctly only if i enter all the 10 values, strange
if i dont enter even one value it shows zero,
couldnt understand where the problem is

You have a try-catch and you do nothing in the catch. This is usually bad practice since you do not know when anything happens in your code.
In this case, Double.parseDouble is throwing an exception as you are trying to parse empty Strings. "" cannot be parsed to a double. "0" can.
You need to make sure that every edit text contains a valid value which can parse to a double or, test each value before trying to parse it.

To check all EditText length before you add all the values.
Like,
if(EditText1.getText.length()==0){
Toast.makeText(YourActivity.this,"All fields are mandatory ",
Toast.LENGTH_LONG).show();
}else if(EditText2.getText.length()==0){
} else if(){
..........
}else{
}
You will avoid NullPointerException

Related

Value not getting assigned to double variable

I am trying to assign a value fetched from my EditText to a double variable.
I have done something like this:-
public class PersonalInfo extends Activity implements OnClickListener
{
private double height=0.0d, weight=0.0d;
private CheckBox cbCheck;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_personal_info);
try
{
height = Double.parseDouble(etHeight.getText().toString().trim());
weight = Double.parseDouble(etWeight.getText().toString().trim());
}
catch(NumberFormatException e)
{
e.printStackTrace();
}
cbCheck.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//is chkIos checked?
if (((CheckBox) v).isChecked()) {
Toast.makeText(PersonalInfo.this,height+weight), Toast.LENGTH_LONG).show();
}
}
});
}
}
}
When I debug the program, I get the value of Double.parseDouble(etHeight.getText().toString().trim()); perfectly. But somehow when I check the value of height and weight they remain null.
Thanks for any help,
You are getting text from editText early in onCreate. User interaction starts when activity resumes in onResume. So you need to get text from EditText when user has entered some value. Also you could do some checks
if(!TextUtils.isEmpty(etHeight.getText().toString())
{
// do something
}
So move the try catch block inside public void onClick(View v) {

Infinite loop when button is clicked on Android

What I'm trying to do is:
If the EditText input is equal to the random number generated, then stop the loop otherwise keep on the loop and reset input text.
For some reason, I'm getting an infinite loop. I am new to programming, any help is really appreciated.
Here is the code:
public class Main extends Activity implements OnClickListener{
private TextView tvResult;
private TextView tvRandTest;
private EditText et1;
private String randonNumber;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvResult = (TextView) findViewById(R.id.textView4);
tvRandTest = (TextView) findViewById(R.id.textView3);
et1 = (EditText) findViewById(R.id.editText1);
}//End Main
public void myClickHandler(View view)
{
if(view.getId() == R.id.button1)
{
//Generates 6 one digit Random Numbers
int randonNumber1 = (int) (0 + Math.random() * 9);
//Parse Numbers
String rd1 = Integer.toString(randonNumber1);
randonNumber = rd1;
boolean done = false;
do
{
et1.getText().toString();
if(et1.equals(randonNumber))
{
Toast.makeText(Main.this,"Equal Number", Toast.LENGTH_SHORT).show();
tvResult.setText(randonNumber);
done = true;
}//end if
else
{
Toast.makeText(Main.this,"Not Equal Number", Toast.LENGTH_SHORT).show();
et1.setText("");
}//end else
}//End While
while(!done);
}//End if
if(view.getId() == R.id.button2)
{
tvRandTest.setText(randonNumber);
}
}//End Method
#Override
public void onClick(View arg0) {
// TODO
}
}//End Class
if(et1.equals(randonNumber))
I will change it with
if(et1.equals(String.valueOf(randonNumber)))
you put directly the int value inside the equals method two things will happen:
the autboxing will create an Integer object starting from the int value
the toString() method will be called through this object.
the toString() method of Integer in android, as the doc stands:
Returns a string containing a concise, human-readable description of this object.
So you are compareing the address of the new object with the content of et1 and not with its real value. Here the reference
In this line et1.getText().toString(); you need to assign result to variable, for example String input = et1.getText().toString(); Then in next line you need to compare two strings, if(input.equals(randonNumber)) But your program can hang cause of infinity loop on UI thread. You should use TextWatcher
to handle when text in EditText was changed

EditText Not Reading Input in Android

The problem in EditText is, it is not returning the input value.I am using that input value to check condition.
I am giving the correct input so that i checks the if condition and go to next activity but
it always goes to else condition.
Please check the code below, i had commented the problem.
Here is the snippet
public class BuildWord extends Activity
{
String word = "word";
String finished = "Word Built";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.buildword);
EditText get = (EditText)findViewById(R.id.dataToSend);
String getdata = get.getText().toString(); //Here i am getting Data from EditText
displayIntentData();
if (getdata.equals("word"))
//Here i am checking with "word" but it goes to else condition.I am typing "word" only
{
findViewById(R.id.sendButton1).setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(BuildWord.this,MainActivity.class);
intent.putExtra("key", word);
startActivity(intent);
}
});
}
else
{
findViewById(R.id.sendButton1).setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(BuildWord.this,DropCard.class);
intent.putExtra("key", finished);
startActivity(intent);
}
});
}
}
#Override
protected void onNewIntent(Intent intent)
{
super.onNewIntent(intent);
setIntent(intent);
displayIntentData();
}
private void displayIntentData()
{
Intent intent = getIntent();
TextView tv = (TextView)findViewById(R.id.intentData1);
Bundle extras=intent.getExtras();
if(extras!=null)
{
tv.setText("Data received: "+extras.getString("key"));
}
else
{
tv.setText("No extradata received");
}
}
}
After displayIntentData(); declare String getdata = get.getText().toString();
you are getting the value in the EditText field ("get") immediately after inflating the view. you couldn't have time to enter any text yet, so it is empty. you then check if "getData" contains "word" (it doesn't!) therefore you're hitting the ELSE.
We will get the text when any click event is happened ....
String getdata = get.getText().toString(); //Here i am getting Data from EditText
above code always return empty string ...
try put the code in on click event and process so that you can get the string and compare it easily
You are getting input data right after when the view is being created.
Instead try to take input data inside your click listener

how to properly execute if in android?

Can anyone please tell why the if statement never gets executed even though I enter ran in the edit text field and press ok? When the user enters ran and presses the button ok, I want another button to become visible which enables him to stop the current activity. Basically I want to know why the if is skipped.
public class Reciever extends Activity{
protected static final String TAG = null;
private Button ok,stp;
private TextView tv;
private EditText ev;
private String s1,s2,s3,s4;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
s1="nar";
setContentView(R.layout.stop);
tv=(TextView) findViewById(R.id.textView1);
tv.setText(s1);
ev=(EditText) findViewById(R.id.editText1);
ok=(Button) findViewById(R.id.ok_button);
ok.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
s2="ran";
tv.setText(ev.getText().toString());
s3=ev.getText().toString();
if(s3==s2)//not going inside this loop
{
stp=(Button) findViewById(R.id.stopb);
stp.setVisibility(View.VISIBLE);
stp.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
}
});
}
}
if(s3==s2)//no
just replace the above line with below
if(s3.equalsIgnoreCase(s2))//no
Use .equals instead of == to compare the value of two strings.
if (s2.equals(s3))
Using == tests for reference equality. Two strings can contain the same characters but have different references.
You can't compare text with ==, you need to use equals.
if(s3.equals(s2))

how to get one class transparent variable value into another class in android

hi i am doing one app here.user click button once means in another activity i need to perform one action,user again come back to same page agian click that same button means i need to perform different action. i take 2 activities in activity1 i have 1 button ,i treid using one count variable in activity1 button click that time i incremented count variable,using putextra i get that count value into acticity2 here based on count i perform actions,but count one time is in incresed,if i come back to same activty1 then i click button that also count is '1'only,it is not incresed to 2.so how to solve that issue any one having idea suggest me.
Activity1 .class:
public class Activity1 extends Activity implements OnClickListener{
Button b1,b2;
int countk4=0;
SharedPreferences share;
String bol3;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.home1);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==b1)
{
countk4++;
share=getSharedPreferences("shared", MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor=share.edit();
editor.putInt("roll", countk4);
editor.commit();
show();
Intent i=new Intent(Activity1 .this,Activity2.class);
i.putExtra("k", 1);
i.putExtra("k1", 13);
i.putExtra("ks", val1);
startActivity(i);
}
}
Integer val1,val2;
private void show() {
// TODO Auto-generated method stub
share=getSharedPreferences("shared", MODE_WORLD_READABLE);
val1=share.getInt("roll",0);
}
}
Activity2 .class:
public class Activity2 extends Activity implements OnClickListener{
Button back;
int countkv;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.home2);
back=(Button)findViewById(R.id.button1);
back.setOnClickListener(this);
countkv = getIntent().getIntExtra("ks", 0);
if(countkv =1)
{
Toast.makeText(getApplicationContext(), "hai.......i am first", Toast.LENGTH_LONG).show();
}
if(countkv =2)
{
Toast.makeText(getApplicationContext(), "hai.......1 am second", Toast.LENGTH_LONG).show();
}
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==back)
{
Intent i=new Intent(Activity2.this,Activity1.class);
startActivity(i);
}
}
}
}
but above every time first toast message displayed becz countkv is every time 1 only..
At Receiving side make an object of Bundle.
Bundle myBundle = new Bundle(); // Declare above
String temp;
myBundle = getIntent().getIntExtra();
temp = myBundle.getString("ks"); // temp will have the val1.
Hope you can get it now.

Categories

Resources