How to check if numeric textbox is empty? - java

I'm Starting to learn Android Studio java, i'm on basics yet.
Im doing an simple exercice i found on youtube "adding two numbers simple calculator".
I finished it and im trying to improve it by myself but im having trouble, if i let one of the EditTextBox empty the app crash, so i'm trying to check if the EdidTextbox is empty.
I Searched here and tried all thing and none works, or the code give error, or the one it works simple keep crashing. tried using some String to get de value and then check but wont work. (the one it's commented)
Just want a simple check in the editText if its empty just tell me error.
help please. thanks!
Code:
public void OnButtonClick(View ver) {
EditText et1 = findViewById(R.id.et1);
EditText et2 = findViewById(R.id.et2);
TextView tv1 = findViewById(R.id.tv1);
float num1 = Float.parseFloat(et1.getText().toString());
float num2 = Float.parseFloat(et2.getText().toString());
//String input = et1.getText().toString();
//String input2 = et2.getText().toString();
if ( TextUtils.isEmpty(et1.getText().toString()) ) {
et1.setError("Error");
}
else {
et1.setError("Ok");
}
float sum = num1 + num2;
tv1.setText(String.valueOf(sum));
}
}

First implement TextWatcher in your class.
Then use this to check if your textfield is empty or not.
if(et1.getText().toString().lenghth()==0){
et1.setError("This Field cannot be empty");
}

Solution:The below statement will return true
if EditText remains empty
if(TextUtils.isEmpty(et1.getText()){
//enter code here
}

You can use a try catch clause instead of if like this
public void OnButtonClick(View ver) {
EditText et1 = findViewById(R.id.et1);
EditText et2 = findViewById(R.id.et2);
TextView tv1 = findViewById(R.id.tv1);
float num1;
float num2;
try
{
num1 = Float.parseFloat(et1.getText().toString());
num2 = Float.parseFloat(et2.getText().toString());
float sum = num1 + num2;
tv1.setText(String.valueOf(sum));
et1.setError("Ok");
}catch(NullPointerException e){
et1.setError("Error");
}
}
But is just a approach you cant try another different. This catch clause it is only for null point exceptions, but imagine if its something different like division by 0, you can try another clause. Please read this article

So you want to check the editText field is empty or not,you have to check that when user press "add" button.
you do it this way:
if (!etEmail.getText().toString().equals("")) {
//the editbox is not empty
//do what ever you want
} else
etEmail.setError("the edit box is empty");
Update full code:
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!etText.getText().toString().equals("")) {
//do what ever you want
Integer sum = text1 + text2;
} else
etBox.setError(getText(R.string.noEmail));
}
});
}

Thank you for your help, like exe said i used a try catch and it worked, im gonna read the article for some try catch info since im more familiar with if's.
the if didnt work in any way, if there is a if way for this resolution please tell me, i want to try and learn all possible ways to do it.
Thank you.
Working code with try:
public void OnButtonClick(View ver) {
//Atribuir as caixas de texto a varariavel
EditText et1 = findViewById(R.id.et1);
EditText et2 = findViewById(R.id.et2);
TextView tv1 = findViewById(R.id.tv1);
float input1;
float input2;
//Atribui o conteudo das ET para as variaveis e faz/apresenta a soma
try {
input1 = Float.parseFloat(et1.getText().toString());
input2 = Float.parseFloat(et2.getText().toString());
float sum = input1 + input2;
tv1.setText(String.valueOf(sum));
}
catch(NumberFormatException ex) {
//Se estiver vazio msg de erro
Toast.makeText(getApplicationContext(), "Vazio", Toast.LENGTH_SHORT).show();
}
}
}

Related

Edit Text to long variable issue?

I am working on a timer app, I have an EditText for taking an input number and based on my radio button selected, multiply the input to be equal to long millisInFuture for the CountDownTimer class. but apparently there is something wrong with parsing my EditText as a long. here is the part for RadioGroup:
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == rdSeconds.getId()) {
et_num.setHint("Seconds");
String value = et_num.getText().toString();
//selectedOption is a long variable
selectedOption = Long.parseLong(value) * 1000;
} else {
et_num.setHint("Minutes");
String value = et_num.getText().toString();
selectedOption = Long.parseLong(value) * 60000; //line 102
}
}
});
Here is part of the error it gaves me?
java.lang.NumberFormatException: For input string: ""
at java.lang.Long.parseLong(Long.java:455)
at java.lang.Long.parseLong(Long.java:485)
at com.example.timemachine.MainActivity$2.onCheckedChanged(MainActivity.java:102)
check your editText have proper value before parse long
String value = et_num.getText().toString();
if(value != null && !value.isEmpty())
{
selectedOption = Long.parseLong(value) * 1000;
}
The error is very clear that you parse empty String to type Number. There some way to handle this
You can check the value on your Edit Text as #sasikumar answer like :
if (!yourEditText.getText().toString().equals("")) {
/* Then parse your value from Edit Text to Number */
}
You can use NumberFormatException :
try {
/* Then parse your value from Edit Text to Number */
} catch(NumberFormatException e) {
/* Any error about formating will catch here */
}

How to properly append text to TextView from SharedPreferences file instead of overwriting it?

I have two classes, one class is saving weight, then in the other class/ activity I want a log that appends the weight along with the date and time, then makes a new line and displays the next weight. This way the user can keep track of their daily weight changes.
Problem is I'm brand new to Java and clearly am getting stuck on a silly problem. Each time I try append it instead just overwrites. I probably need to save it and then add it? maybe? I've tried a few different things and nothing is working all that well.
This is day 3 of Java. Apologies.
Tried making a list that is saved with sharedpreferences. Either did it wrong or it didnt work. Also tried just calling for the weight and appending it, but it overwrites it all.
My Logging activity:
public class LogActivity extends AppCompatActivity {
TextView logger;
//TextView more;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Button back = findViewById(R.id.btnBack);
logger = findViewById(R.id.txtLog);
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
SharedPreferences log = getSharedPreferences("MyPrefsFile", 0);
//Float value = log.getFloat("floatingLog",0);
Float value = log.getFloat("weight", 0);
//more.append(logger + "Weight: " + value.toString() + " at: " + dateFormat.format(date) + "\n");
logger.append("Weight: " + value.toString() + " at: " + dateFormat.format(date) + "\n");
// Adding back button
back.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v){
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
}
});
// SharedPreferences settings7 = getSharedPreferences("PREFS",0);
// String wordsString = settings7.getString("words","");
// String[] itemWords = wordsString.split(",");
// List<String> items = new ArrayList<String>();
// for (int i = 0; i < itemWords.length; i++){
// items.add(itemWords[i]);
// }
// for (int i = 0; i < items.size(); i++){
// Log.d("list", items.get(i));
// }
}
}
This is getting the sharedpreferences from here, in my ProfileActivity:
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((TextView) findViewById(R.id.txtWeight)).setText(findViewById(R.id.txtNewWeight).toString());
floatingLog = weight.toString();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
floatingWeight = Float.valueOf(newWeight.getText().toString());
editor.putString("floatingLog", floatingLog);
editor.putFloat("weight", floatingWeight);
editor.apply();
editor.commit();
weight.setText(String.valueOf(floatingWeight));
Hello and welcome to SO!
actually in TextView, you can access to current value via TextView#getText() and after that you can update the text value similarly using TextView#setText(String text)
so you need to write something like this:
String currentText = logger.getText();
String updatedText = currentText + "Weight: " + value.toString() + " at: " + dateFormat.format(date) + "\n";
logger.setText(updatedText)
tada !
UPDATE
I think your problem is with how you save your records in your sharedPrefs
in this line
editor.putFloat("weight", floatingWeight); in this part you are overwriting the existing value,
simplest approach that comes to my mind is that instead of saving weight like this, you create an array of weights and append to end of it every day and store the array.
how ever it will be far more better if you use data base for this which gives you far more flexibility.
to use database take a look at Android official orm Android Room it is very simple and straightforward

Number Format Exception in service

Code
final EditText wid = (EditText) myview.findViewById(R.id.width);
final EditText hie = (EditText) myview.findViewById(R.id.height);
Button mSave = (Button) myview.findViewById(R.id.save);
Button mCancel = (Button) myview.findViewById(R.id.cancel);
final String mWidth = wid.getText().toString();
final String mHeight = hie.getText().toString();
mSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Integer.parseInt(mWidth)>= 500 && Integer.parseInt(mWidth) <= 1000 &&
Integer.parseInt(mHeight) >= 500 && Integer.parseInt(mHeight) <= 1500) {
Intent intent = new Intent(ResizeService.this, UsersService.class);
intent.putExtra("Width", mWidth);
intent.putExtra("Height", mHeight);
startService(intent);
} else {
Toast.makeText(getApplicationContext(), "Check whether the data you entered matches the requirements", Toast.LENGTH_LONG).show();
}
}
});
The entered numbers are integers without a decimal. But still getting error
java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:334)
at
com.appmaster.akash.messageplus.Services.ResizeService$1.onClick(ResizeService.java:57)
at android.view.View.performClick(View.java:5215)
at android.view.View$PerformClick.run(View.java:21193)
at android.os.Handler.handleCallback(Handler.java:742)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5571)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:745)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:635)
The editTexts aren't empty either... im typing numbers but still getting error
Also this is in a service by the way...
The error is on the line of the if statement
try to move
final String mWidth = wid.getText().toString();
final String mHeight = hie.getText().toString();
inside the onclick. that way you get the values when you click instead of when it starts.
Instead of doing
final String mWidth = wid.getText().toString();
final String mHeight = hie.getText().toString();
I would do
final int mWidth = wid.getText();
final int mHeight = hie.getText();
And in the xml I would set the inputType of the EditText to just numbers.
And then remove the Integer.parseInt and you just place it inside your onClick since you are pressing a button to get the values inside an EditText, if you try to get the values before, your variables mWidth and mHeight will return null since there is nothing inside them before you click your button.

CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0 - Database Android

I've experienced some error in my program.
I'm trying to make quiz app using radiobutton. The question and answer option is obtained from database.
This is some part of my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* Get Intent Parameter */
/* Open Database File */
db_helper.openDataBase();
db = db_helper.getReadableDatabase();
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setContentView(R.layout.activity_exercise_question);
Qcontent = (TextView) findViewById(R.id.txtQuestion);
Qnum = (TextView) findViewById(R.id.txtNumb);
a = (RadioButton) findViewById(R.id.rbA);
b = (RadioButton) findViewById(R.id.rbB);
c = (RadioButton) findViewById(R.id.rbC);
d = (RadioButton) findViewById(R.id.rbD);
g = (RadioGroup) findViewById(R.id.rgOption);
next = (Button) findViewById(R.id.btnNextQuestion);
next.setBackgroundColor(Color.GREEN);
//To handle event when button Next is clicked
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int radioButtonID = g.getCheckedRadioButtonId();
View radioButton = g.findViewById(radioButtonID);
int idx = g.indexOfChild(radioButton);
if (opsys.getString(idx + 1).equals(opsys.getString(5))) {
nilai = nilai + 1;
}
quiz();
}
});
quiz();
}
public void finish() {
next.setText("Finish");
next.setBackgroundColor(Color.RED);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
int radioButtonID = g.getCheckedRadioButtonId();
View radioButton = g.findViewById(radioButtonID);
int idx = g.indexOfChild(radioButton);
if (opsys.getString(idx + 1).equals(opsys.getString(5))) {
score = score + 1;
}
ExerciseQuestion.this.finish();
Intent showScore = new Intent(ExerciseQuestion.this, ExerciseScore.class);
String achieveScore = String.valueOf(score);
Bundle bundle = new Bundle();
bundle.putString("AchieveScore", achieveScore);
tampilNilai.putExtras(bundle);
startActivity(showScore);
}
});
}
private void quiz() {
question_numb = question_numb + 1;
if (question_numb < 10) {
Qnum.setText(" " + Integer.toString(question_numb) + '.');
} else Qnum.setText(Integer.toString(question_numb) + '.');
checkResult();
Qcontent.setText(opsys.getString(0)); //this is to set the question I've taken from db to TextView
a.setText(opsys.getString(1)); //this is to set the option A I've taken from db to radiobutton
b.setText(opsys.getString(2)); //this is to set the option B I've taken from db to radiobutton
c.setText(opsys.getString(3)); //this is to set the option C I've taken from db to radiobutton
d.setText(opsys.getString(4)); //this is to set the option D I've taken from db to radiobutton
//To handle when question number is 10
if (question_numb == 10) {
finish();
}
}
private boolean checkResult() {
// TODO Auto-generated method stub
int random10 = generateRandomNumber(10); //I've a method to generate Random number using Math.random() without repetition
int random18 = generateRandomNumber(18);
String query;
Bundle bundle = getIntent().getExtras();
int chooseContent = bundle.getInt("chooseContent");
if (chooseContent == 0) {
query = "SELECT question, a, b, c, d, answer FROM tbl_Exercise WHERE (id_topic=" + random18 + " and id_question=" + random10 + ")";
} else {
query = "SELECT question, a, b, c, d, answer FROM tbl_Exercise WHERE (id_topic=" + chooseContent + " and id_question=" + random10 + ")";
}
opsys = db.rawQuery(query, null);
if (opsys != null && opsys.moveToFirst()) {
return true;
}
opsys.close();
return false;
}
Sometimes when I touch the Next button, the app crashes (but sometimes it doesn't, and it works like charm). The logcat is as follows:
06-04 19:14:16.884 10062-10062/com.coder.learningmodule E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.coder.learningmodule, PID: 10062
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:426)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at com.coder.learningmodule.ExerciseQuestion.quiz(ExerciseQuestion.java:106)
at com.coder.learningmodule.ExerciseQuestion.access$300(ExerciseQuestion.java:19)
at com.coder.learningmodule.ExerciseQuestion$1.onClick(ExerciseQuestion.java:68)
at android.view.View.performClick(View.java:4443)
at android.view.View$PerformClick.run(View.java:18442)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5021)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)
at dalvik.system.NativeStart.main(Native Method)
The error refers to Qcontent.setText(opsys.getString(0)); in quiz() method
After I read some related question in Stackoverflow, I have tried the following code, but it does not solve the problem
opsys = db.rawQuery(query, null);
if (opsys != null && opsys.moveToFirst()) {
return true;
}
opsys.close();
return false;
I would really appreciate help and/or suggestion from anyone to solve this problem. Thank you very much.
You are on the right path by checking opsys for null and the return value of moveToFirst(). Your method checkResult() returns true if these checks are successful, or false otherwise.
Your issue is that you don't actually check this return value before working with the query result:
checkResult();
Qcontent.setText(opsys.getString(0)); //this is to set the question I've taken from db to TextView
a.setText(opsys.getString(1)); //this is to set the option A I've taken from db to radiobutton
b.setText(opsys.getString(2)); //this is to set the option B I've taken from db to radiobutton
c.setText(opsys.getString(3)); //this is to set the option C I've taken from db to radiobutton
d.setText(opsys.getString(4)); //this is to set the option D I've taken from db to radiobutton
Instead, check against the returned value first before accessing the values:
if(checkResult()) {
Qcontent.setText(opsys.getString(0)); //this is to set the question I've taken from db to TextView
a.setText(opsys.getString(1)); //this is to set the option A I've taken from db to radiobutton
b.setText(opsys.getString(2)); //this is to set the option B I've taken from db to radiobutton
c.setText(opsys.getString(3)); //this is to set the option C I've taken from db to radiobutton
d.setText(opsys.getString(4)); //this is to set the option D I've taken from db to radiobutton
}
This way, you are only accessing the query result if there are actually any return values. Your exception is caused by trying to access a result that has no lines.
You are trying to get the first result from the Cursor without checking if the query returned any results. You can try something like this:
if(checkResult()){
Qcontent.setText(opsys.getString(0));
...
opsys.close();
}

Datatypes and application has stopped

I've this part of code:
public void onClickHandler(View a) {
String pressed = null;
String actual_text = null;
String new_text = null;
char last_char; //or char last_char = (Character) null; - the same problem
int bla;
pressed=((Button)a).getText().toString();
EditText lifeView = (EditText) findViewById(R.id.edittext);
actual_text = lifeView.getText().toString();
bla=actual_text.length()-1;
last_char = actual_text.charAt(bla);
}
And I'm solving the problem, that after pressed button I will get the error "The application has stopped unexpectedly. Please try it again."
The problem is on the line "char last_char" -- but I don't know why, Eclipse does not report a fault too...
You need to initialize the char last_char;
Ex:
char last_char=' ';
or similar but not null.
Try initilizing local variable char last_char;

Categories