Why it didn't get current EditText value - android

I'm doing basic demo of android related to login, update user
I used user's id from login page to load user's information to update page
username = (EditText) findViewById(R.id.txtUsername);
age = (EditText) findViewById(R.id.txtAge);
weight = (EditText) findViewById(R.id.txtWeight);
height = (EditText) findViewById(R.id.txtHeight);
username.setText(db_username);
age.setText(db_age);
weight.setText(db_weight);
height.setText(db_height);
and update button
update.setOnClickListener(new View.OnClickListener() {
int sweight = Integer.parseInt(weight.getText().toString());
double sheight = Double.parseDouble(height.getText().toString());
int sage = Integer.parseInt(age.getText().toString());
#Override
public void onClick(View v) {
if (weight.equals("")) {
Toast.makeText(getApplicationContext(), "Please input weight!",
Toast.LENGTH_LONG).show();
return;
}else if(height.equals("")){
Toast.makeText(getApplicationContext(), "Please input height!",
Toast.LENGTH_LONG).show();
return;
}else if(age.equals("")){
Toast.makeText(getApplicationContext(), "Please input age!",
Toast.LENGTH_LONG).show();
return;
}else{
dbHandler.updateUser(sid,sweight,sheight,sage);
Toast.makeText(getApplicationContext(),
"User's information updated! ", Toast.LENGTH_LONG)
.show();
Toast.makeText(getApplicationContext(),
sid+sweight+sheight+sage+" and test", Toast.LENGTH_LONG)
.show();
Intent i = new Intent(UserUpdate.this, MainActivity.class);
startActivity(i);
finish();
}
}
});
For exam: weight: 70,height:1,65,age:21
when i changed it to: weight:50,height:1,65,age:21
the 2nd Toast show me that weight : 70 but not 50

You need to move these top three lines inside of the click method, not declare them as member variables of the anonymous class.
int sweight = Integer.parseInt(weight.getText().toString());
double sheight = Double.parseDouble(height.getText().toString());
int sage = Integer.parseInt(age.getText().toString());
#Override
public void onClick(View v) {
// Move them here

put this :
int sweight = Integer.parseInt(weight.getText().toString());
double sheight = Double.parseDouble(height.getText().toString());
int sage = Integer.parseInt(age.getText().toString());
in onclick method , before -> if (weight.equals(""))

Related

in my calculator app i have introduced four buttons but when i click them before entering values app crashes down. how to solve this problem

Add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
float firstValue , secondValue , ans ;
firstValue = Float.parseFloat( etFirstValue.getText().toString());
secondValue = Float.parseFloat( etSecondValue.getText().toString());
ans = firstValue + secondValue;
tvAnswer.setText("Ans = " + ans);
}
});
this is the coding for my addition button click, all buttons are working fine after entering values. but the problem occurs when I click the button before entering values my app suddenly stops working. solve this issue, make it something like nothing happens when I click the button before entering values.
Add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
float firstValue=0 , secondValue=0 , ans=0 ;
if (etFirstValue.length()>0&& (etSecondValue.length()>0)
{
firstValue = Float.parseFloat(etFirstValue.getText().toString());
secondValue = Float.parseFloat(etSecondValue.getText().toString());
tvAnswer.setText("Ans = " + ans);
} else {
Toast.makeText(MainActivity.this, "Enter the Values First", Toast.LENGTH_SHORT).show();
}
ans = firstValue + secondValue;
tvAnswer.setText("Ans = " + ans);
}
});
I have solved this on my own.
Now it is not crashing just giving a warning message "Enter the values First"
Thanks to all for giving your precious time.
Just Do Like This
First Convert Your Values To String And Then Do This:
if(value1.matches("")){
Toast(context, "Please Fill First Value", LENGTH_SHORT).show();
return;
}
else if(value2.matches("")){
Toast(context, "Please Fill First Value", LENGTH_SHORT).show();
return;
}
else{
//Continue With Your Code
//Do Calculations Or Anything
}
Note: Change Value1, Value2 With Your Own Values Which Came From EditText
Add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
float firstValue=null , secondValue=null, ans=0; //initialise the value here
firstValue = Float.parseFloat( etFirstValue.getText().toString());
secondValue = Float.parseFloat( etSecondValue.getText().toString());
if(firstValue==null&&secondvValue==null)
{
tvAnswer.setText("Ans = " + ans);
} else{
ans = firstValue + secondValue;
tvAnswer.setText("Ans = " + ans);
}
}
});
If the above doesnt work initialise all above value to zero instead of null.

User Input of int won't be null

I made a code where user put value between some range and my code generate random number for them. Randomization working properly but when fields are blank my app is crash how should I fix it.
randNum.java
Button generateNum = findViewById(R.id.generate_number);
generateNum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText et = findViewById(R.id.fromNum);
String sTextFromET = et.getText().toString();
int fNum = Integer.valueOf(sTextFromET);
EditText et1 = findViewById(R.id.toNum);
String sTextFromET1 = et1.getText().toString();
int sNum = Integer.valueOf(sTextFromET1);
TextView ans = findViewById(R.id.ans);
// if(sNum == null || fNum == null){
//
// ans.setText(getString(R.string.enterNumError));
//
// }
// else
if(sNum < fNum){
ans.setText(getString(R.string.max_min_error));
}else {
final int random = new Random().nextInt((sNum - fNum) + 1) + fNum;
String ras = Integer.toString(random);
ans.setText(ras);
}
}
});
I try to use null but it is not working.
You need to put validation first on button click. (For checking if user has entered nothing or just spaces in any of edittexts).
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strNum1 = edtl.getText().toString().trim();
strNum2 = edt2.getText().toString().trim();
if (strNum1.length() == 0)
{
showAlert("Please enter Num 1");
}
else if (strNum2.length() == 0)
{
showAlert("Please enter Num 2");
}
else
{
int numvalue1 = Integer.parseInt(strNum1);
int numvalue2 = Integer.parseInt(strNum2);
generateNum (numvalue1, numvalue2); //Call your function for generation of random number here
//do your stuff here
}
}
});
Hope this helps you understand the validation of forms for empty input fields.
P.S: I would recommend you put inputType attribute for your EditTexts if you have not added it already in xml file like:
android:inputType="number"
So you can avoid exception at Integer.parseInt if user enters any alphabet or symbol.
You need to handle NumberFormatException thrown by Integer.valueOf() function
try {
EditText et = findViewById(R.id.fromNum);
String sTextFromET = et.getText().toString();
int fNum = Integer.valueOf(sTextFromET);
EditText et1 = findViewById(R.id.toNum);
String sTextFromET1 = et1.getText().toString();
int sNum = Integer.valueOf(sTextFromET1);
TextView ans = findViewById(R.id.ans);
if(sNum < fNum){
ans.setText(getString(R.string.max_min_error));
}else {
final int random = new Random().nextInt((sNum - fNum) + 1) + fNum;
String ras = Integer.toString(random);
ans.setText(ras);
}
}catch(NumberFormatException e){
Toast.makeText(this, "Invalid Input", Toast.LENGTH_SHORT).show();
}

Toast not working,App stops when toast is to be displayed

I have created a small application to check whether the password entered by user is valid or not. it is being able to check , but its not displaying the toast and as soon as i click the button , it shows "Unfortunately , your app has stopped working". I am using my device for deployment. Please help me find out , why the toast is not working. I have used a command which sets the value of variable a,b,c in the edit text field , to check whether it is coming correct. And yes it was coming correct. So the problem lies in the toast as per i think.
public class second extends AppCompatActivity {
public EditText fname ;
public EditText lname ;
public EditText email ;
public EditText pass ;
public EditText blood;
public EditText cpass;
public EditText add ;
public EditText mob ;
public Toast t ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
fname = (EditText) findViewById(R.id.fname);
lname = (EditText) findViewById(R.id.lname);
email = (EditText) findViewById(R.id.email);
pass = (EditText) findViewById(R.id.pass);
add = (EditText) findViewById(R.id.add);
cpass = (EditText) findViewById(R.id.cpass);
mob = (EditText) findViewById(R.id.mob);
blood = (EditText) findViewById(R.id.blood);
Button sign = (Button) findViewById(R.id.sign);
sign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String sfname = fname.getText().toString();
String spass = pass.getText().toString();
String scpass = cpass.getText().toString();
validate(spass, scpass);
}
});
}
public void validate(String spass ,String scpass){
int a =0;
int b =0;
int c =0;
t = new Toast(this);
int len = spass.length();
for(int i =0;i<len;i++){
char d = spass.charAt(i);
if(d>=48 && d<=57){
a++;
}
if(d>=65 && d<=90){
b++;
}
if(d>=33 && d<=47){
c++;
}
}
email.setText(a+" "+b+" "+c);
if(a==0 || b==0 || c==0){
t.makeText(this, "Password should contain atleast one special character , one capital letter and one number", Toast.LENGTH_LONG);
t.show();
} else {
if(spass.equals(scpass)){
t.makeText(this,"login succesful",Toast.LENGTH_SHORT);
t.show();
} else {
t.makeText(this,"passwords dont match",Toast.LENGTH_SHORT).show();
}
}
}
}
try this
Toast toast = Toast.makeText(context, text, duration);
toast.show()
or
Toast.makeText(context, text, duration).show();
From the Docs, it says
Toast (Context context) Construct an empty Toast object. You must call
setView(View) before you can call show().
So when you create Toast object from its constructor, it is considered that you are trying to create Custom Toast
If you are not creating any, then use like:
public Toast t; // Global variable
Now inside your validate method:
t = Toast.makeText(this, "Password should contain atleast one special character , one capital letter and one number", Toast.LENGTH_LONG);
t.show();
I have made some changes to you method , try using this one .
You can find more details on https://stackoverflow.com/a/21963343
public void validate(String spass ,String scpass){
int a =0;
int b =0;
int c =0;
// Toast t = new Toast(this);
int len = spass.length();
for(int i =0;i<len;i++){
char d = spass.charAt(i);
if(d>=48 && d<=57){
a++;
}
if(d>=65 && d<=90){
b++;
}
if(d>=33 && d<=47){
c++;
}
}
email.setText(a+" "+b+" "+c);
if(a==0 || b==0 || c==0){
/*
* updated
* */
Toast.makeText(this, "Password should contain atleast one special character , one capital letter and one number", Toast.LENGTH_LONG).show();
} else {
if(spass.equals(scpass)){
/*Updated*/
Toast.makeText(this,"login succesful",Toast.LENGTH_SHORT).show();
} else {
/*Updated*/
Toast.makeText(this,"passwords dont match",Toast.LENGTH_SHORT).show();
}
}
}

requiring editView boxes be completed before moving to another activity

Here is my current AddDebt.java section I'm looking at:
public void ButtonOnClick(View v) {
Intent intent = new Intent(this, MainActivity.class);
EditText debtors = (EditText) findViewById(R.id.editDebtor);
String debtor = debtors.getText().toString();
EditText myEdit = (EditText) findViewById(R.id.editBalance);
String myEditValue = myEdit.getText().toString();
double loanAmount = Double.parseDouble(myEditValue);
EditText myEdit2 = (EditText) findViewById(R.id.editRate);
String myEditValue2 = myEdit2.getText().toString();
double interestRate = Double.parseDouble(myEditValue2);
EditText myEdit3 = (EditText) findViewById(R.id.editTerm);
String myEditValue3 = myEdit3.getText().toString();
Double loanPeriod = Double.parseDouble(myEditValue3);
double r = interestRate/1200;
double r1 = Math.pow(r+1,loanPeriod);
double editMnthlypmt = (double) ((r+(r/(r1-1))) * loanAmount);
DecimalFormat df = new DecimalFormat("#.##");
editMnthlypmt = Double.valueOf(df.format(editMnthlypmt));
TextView textMnthlypmt = (TextView)findViewById(R.id.textMntlypmt);
switch (v.getId()) {
case R.id.calculate:
textMnthlypmt.setText("" + String.valueOf(editMnthlypmt));
break;
case R.id.addDebt:
if(debtors.getText().length() == 0){
Toast.makeText(getApplicationContext(), "Please enter debtors value", Toast.LENGTH_SHORT).show();
debtors.requestFocus();
}else if(myEdit.getText().length() == 0){
Toast.makeText(getApplicationContext(), "Please enter myedit value", Toast.LENGTH_SHORT).show();
myEdit.requestFocus();
}
else
{
//Transferring data to MainActivity
intent.putExtra("debtor",debtor);
intent.putExtra("loanAmount",loanAmount);
intent.putExtra("editMnthlypmt",editMnthlypmt);
//Next moves back to MainActivity
startActivity(intent);
}
break;
}
}
when "case R.id.addDebt:" is being chosen, I want to ensure that editDebtor, editBalance, editRate, and editTerm are all completed. If not, I want it to set focus on the topmost box that is incomplete. If completed I want it to switch to my intent.
Any suggestions.
try this,
case R.id.addDebt:
if(debtors.getText().length() == 0){
Toast.makeText(Activityname, "Please enter debtors value", Toast.LENGTH_SHORT).show();
debtors.requestFocus();
}else if(myEdit.getText().length() == 0){
Toast.makeText(Activityname, "Please enter myedit value", Toast.LENGTH_SHORT).show();
myEdit.requestFocus();
}else if().......
}else{
//Add your Intent here
}

android: How to change ListViewItem Background on runtime? (Not for selection)

In my android app, I need to change the Background color of each Item of my ListView seperately.
I found no examples or helpful documentation. The background should change if the value of a double is 0. I set the ListView Property: android:drawSelectorOnTop="true" and used following code:
(All of it functions, only the background doesn't change!) How can I solve this problem?
public void onClickButtonOKStand (View view) {
EditAusgabe = (EditText) findViewById(R.id.EditText01);
if (EditAusgabe.getText().toString().length() <= 0) {
Toast T = Toast.makeText(getApplicationContext(), "Eingabe ungültig! Geben Sie einen Betrag ein", Toast.LENGTH_LONG);
T.show();
return;
}
if (EditAusgabe.getText().toString() == ".") {
Toast T = Toast.makeText(getApplicationContext(), "Eingabe ungültig! Geben Sie einen Betrag ein", Toast.LENGTH_LONG);
T.show();
return;
}
Z = Double.parseDouble(EditAusgabe.getText().toString());
if (VArt == "Down") {
if (VStand >= Z) {
VStand = VStand - Z;
if (VStand <= 0.39) {
Toast T = Toast.makeText(getApplicationContext(), "Ihr Guthaben ist aufgebraucht!", Toast.LENGTH_strong textLONG);
T.show();
VStand = 0.00;
****************** The next line is my problem: ******************************
StartListe.getChildAt(Position).setBackgroundColor(color.holo_red_light);
}
}
else if (VStand < Z) {
Toast T = Toast.makeText(getApplicationContext(), "Vorgang nicht möglich! Ihr Konto liegt bei " + FORMAT.format(VStand) + " €.", Toast.LENGTH_LONG);
T.show();
EditAusgabe.setText("");
return;
}
}
if (VArt == "Up") {
VStand = VStand + Z;
}
Stand.set(Position, FORMAT.format(VStand));
Liste.set(Position, (VName + " " + FORMAT.format(VStand) + " € / " + FORMAT.format(VWert) + " €"));
ListeAktualisieren();
}
public void ListeAktualisieren () {
setContentView(R.layout.activity_ausgabenkontrolle);
ArrayAdapter<String> ListenAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, Liste);
StartListe = (ListView) findViewById(R.id.listView1);
StartListe.setAdapter(ListenAdapter);
StartListe.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> ListenAdapter, View view, int i, long ID) {
// TODO Auto-generated method stub
Item = view;
Position = ListenAdapter.getPositionForView(view);
VName = Namen.get(Position);
VArt = Arten.get(Position);
VWert = Double.parseDouble(Werte.get(Position).toString());
VStand = Double.parseDouble(Stand.get(Position).toString());
setContentView(R.layout.activity_stand);
if (VArt == "Down") {
if (VStand == 0) {
Toast T = Toast.makeText(getApplicationContext(), "Ihr Guthaben ist aufgebraucht!", Toast.LENGTH_LONG);
T.show();
}
}
}
});
registerForContextMenu(StartListe);
}
I think the way to change the background color in response to a click is to apply the change to the incoming View given to you in your onClickListener implementation. You seem to be messing about with setContentViews, etc. which isn't the way to go. SetContentView sets your overall layout, and there's rarely a reason to call it more than once in an Activity.

Categories

Resources