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.
Related
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 */
}
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();
}
}
}
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();
}
is it possible to set a value into a editable edittext like this?
LayoutInflater layoutInflater = LayoutInflater.from(getBaseContext());
View promptView = layoutInflater.inflate(R.layout.prompt_dialog, null);
final EditText input = (EditText) promptView.findViewById(R.id.input_prompt);
TextView txt_prompt_mensaje = (TextView) promptView.findViewById(R.id.txt_prompt_mensaje);
Editable value = input.getText();
int suma_valor = Integer.parseInt(value.toString());
suma_valor = suma_valor + Integer.parseInt(value.toString());
Log.d("#### suma valor", Integer.toString(suma_valor));
input.setText(Integer.toString(suma_valor));
Using input.setText("Testing"); will give the editText the string of "Testing" in it's field. However you question seems vague when you say 'set a value'.
Another thing to add is that the editText will only take the values for when it is first instantiated.
I have created a tablelayout with dynamically created rows with 3 edittexts on every row. Say there are 5 rows with 3 edittexts on each, how can i get the the entered values from every first edittext from each row into an arraylits and calculating them.
Here is my code so far:
Public void addRow (View v) {
TableRow row = new TableRow(this);
EditText et1 = new EditText(this);
EditText et2 = new EditText(this);
EditText et3 = new EditText(this);
idCount++;
mRowCount++;
et1.setTag(a + idCount);
et1.setText(a + idCount);
et2.setTag(b + idCount);
et2.setText(b + idCount);
et3.setTag(c + idCount);
et3.setText(c + idCount);
mLayout.addView(row);
row.setId(mRowCount);
row.addView(et1);
row.addView(et2);
row.addView(et3);
Thanx in advance
ArrayList<String> stringList = new ArrayList<String>(); //Generic ArrayList to Store your Strings
stringList.add(et1.getText()) ;//do this for your 3 textviews
stringList.add(et2.getText()) ;
stringList.add(et3.getText()) ;
int count=0;
Iterator<String> iterator = stringList.iterator();
while (iterator.hasNext()) {
count=count+Integer.parseInt(iterator.next());
}
1) If you have the reference, you can access it with getText().
2) If you haven't the reference, you have to set an ID to every EditText and the you could reach them with findViewById()
by the getText() method
edt1.gettext();
If you are entering string data then use toString() method as
String res=edt1.getText().toString();
Depending how many rows you are likely to end up creating I would store a reference to the EditText objects when you create them. This may mean defining a row object for holding the three EditText objects, but just as east to create a Map:
Map<String, List<EditText>> mRows = new HashMap<String, List<<EditText>>();
When creating the new row you can modify your code so as to store the references:
Public void addRow (View v) {
TableRow row = new TableRow(this);
EditText et1 = new EditText(this);
EditText et2 = new EditText(this);
EditText et3 = new EditText(this);
List<EditText> row = new ArrayList<EditText>();
row.add(et1);
row.add(et2);
row.add(et3);
mRows.add("" + idCount, row);
I would also move that code into a separate function.
On submission you can now iterate over the map and pull the first entry out from each entry.
First of all you have to take EditText(View) from your table layout and
TableRow tr = (TableRow) v.getParent();
// Index of column of table layout it should be an Integer value.
EditText et = (EditText) tr.getChildAt(Your_Index);
EditText et1 = (EditText) tr.getChildAt(Your_Index);
EditText et2 = (EditText) tr.getChildAt(Your_Index);
Then you will get value of that edittext with following code
String a = et.getText().toString();
String b = et1.getText().toString();
String c = et2.getText().toString();
Hope it will help you.