check empty value in edit text - java

i get error when i want to check empty value in edittext that I create. It become error to my source code
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = etCode.getText().toString();
String name = etName.getText().toString();
float price = Float.parseFloat(etPrice.getText().toString());
int qty = Integer.parseInt(etQty.getText().toString());
if(code.length() != 0 && name.length() != 0 && price.length() != 0 && qty.length() != 0){
myDB.addData(code, name, price, qty);
etCode.setText("");
etName.setText("");
etPrice.setText("");
etQty.setText("");
}else{
Toast.makeText(MainActivity.this,"You must put something in the text field!",Toast.LENGTH_LONG).show();
}
}
});
How to solve my problem ?

try using
TextUtils.isEmpty(editText.getText().toString());
normally you can never have a null come out of a text field but you check if its empty with the above line. so both "" and null will give you back a true

I believe your error java.lang.NumberFormatException: Invalid float: ""
that is because you are trying to convert empty value to float.
you can do as follow.
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = etCode.getText().toString();
String name = etName.getText().toString();
String price = etPrice.getText().toString();
String qty = etQty.getText().toString();
if(code.isEmpty() && name.isEmpty() && price.isEmpty() && qty.isEmpty(){
float price1 = Float.parseFloat(etPrice.getText().toString());
int qty1 = Integer.parseInt(etQty.getText().toString());
myDB.addData(code, name, price1, qty1);
etCode.setText("");
etName.setText("");
etPrice.setText("");
etQty.setText("");
}else{
Toast.makeText(MainActivity.this,"You must put something in the text field!",Toast.LENGTH_LONG).show();
}
}
});

Use the
if (TextUtils.isEmpty(edittext.getText().toString()) {
Log.d("ERROR","Edittext is empty");
}

You can check that way
if(etCode.getText().toString().trim().equalsIgnoreCase(""))
{
// etCode edittext is empty
}

Try this
/*
* for checking String valid or not
*/
public boolean validateString(String data) {
return (data != null && !data.isEmpty() && data.length() > 0 && !data.equals("null"));
}
if(validateString(edittext.getText().toString()){
//Valid String
}

Try this:
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = etCode.getText().toString();
String name = etName.getText().toString();
float price = Float.parseFloat(etPrice.getText().toString());
int qty = Integer.parseInt(etQty.getText().toString());
if(code.length() != 0 && name.length() != 0 && price != 0 && qty != 0){
myDB.addData(code, name, price, qty);
etCode.setText("");
etName.setText("");
etPrice.setText("");
etQty.setText("");
}else{
Toast.makeText(MainActivity.this,"You must put something in the text field!",Toast.LENGTH_LONG).show();
}
}
});

You can try like this:
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = etCode.getText().toString();
String name = etName.getText().toString();
String priceStr = etPrice.getText().toString();
String qtyStr = etQty.getText().toString();
float price;
int qty;
if(code.length()==0) {
Toast.makeText(MainActivity.this,"Your code is empty!",Toast.LENGTH_LONG).show();
}
if(name.length()==0) {
Toast.makeText(MainActivity.this,"Your name is empty!",Toast.LENGTH_LONG).show();
}
if(priceStr.length()==0) {
Toast.makeText(MainActivity.this,"Your price is empty!",Toast.LENGTH_LONG).show();
}else {
try {
price = Float.parseFloat(priceStr);
}catch (Exception e) {
Toast.makeText(MainActivity.this,"Your price is not valid!",Toast.LENGTH_LONG).show();
}
}
if(qtyStr.length()==0) {
Toast.makeText(MainActivity.this,"Your qty is empty!",Toast.LENGTH_LONG).show();
}else {
try {
qty = Integer.parseInt(qtyStr);
}catch (Exception e) {
Toast.makeText(MainActivity.this,"Your qty is not valid!",Toast.LENGTH_LONG).show();
}
}
myDB.addData(code, name, price, qty);
etCode.setText("");
etName.setText("");
etPrice.setText("");
etQty.setText("");
}
});

Related

Why my android app is going back to previous activity while I fill up a simple question form to database?

I am trying to build a quiz app, where admin will create questions in admin activity and these questions will be shown as quiz exam in another activity. While I try to fill up the form by clicking CREATE QUESTION button from admin activity my app is going back to previous activity(adminlogin activity)
Here is the code of AdminActivity:
public class AdminActivity extends AppCompatActivity {
Button btnCreateQuestion, btnReadQuestion, btnDeleteQuestion;
EditText editTextQuestion, editTextOption1, editTextOption2, editTextOption3, editTextOption4,
editTextAnswerNo,editTextChapterNo;
QuizDbHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
btnCreateQuestion = findViewById(R.id.btnCreateQuestion);
btnReadQuestion = findViewById(R.id.btnReadQuestions);
btnDeleteQuestion = findViewById(R.id.btnDeleteQuestions);
editTextQuestion = findViewById(R.id.editTextQuestion);
editTextOption1 = findViewById(R.id.editTextOption1);
editTextOption2 = findViewById(R.id.editTextOption2);
editTextOption3 = findViewById(R.id.editTextOption3);
editTextOption4 = findViewById(R.id.editTextOption4);
editTextAnswerNo = findViewById(R.id.editTextAnswerNo);
editTextChapterNo = findViewById(R.id.editTextChapterNo);
db = new QuizDbHelper(this);
btnCreateQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String question = editTextQuestion.getText().toString();
String option1 = editTextOption1.getText().toString();
String option2 = editTextOption2.getText().toString();
String option3 = editTextOption3.getText().toString();
String option4 = editTextOption4.getText().toString();
Integer answerNo = Integer.parseInt(editTextAnswerNo.getText().toString());
String chapterName = editTextAnswerNo.getText().toString();
if( question != "" && option1 != "" && option2 != "" && option3 != "" && option4 != "" && answerNo!= null && chapterName != ""){
Question q = new Question(question,option1,option2,option3,option4,answerNo,chapterName);
db.addQuestion(q);
Toast.makeText(AdminActivity.this,"Question Added", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(AdminActivity.this,"Please fill up", Toast.LENGTH_SHORT).show();
}
}
});
btnReadQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<Question> allQuestions = db.getAllQuestions();
if(allQuestions.size()< 1){
Toast.makeText(AdminActivity.this,"No questions in the Database", Toast.LENGTH_SHORT).show();
}else {
StringBuffer buffer = new StringBuffer();
for (Question q: allQuestions) {
buffer.append("Question : " + q.getQuestion() + "\n" );
buffer.append("Option1: " + q.getOption1() + "\n");
buffer.append("Option2: " + q.getOption2() + "\n");
buffer.append("Option3: " + q.getOption3() + "\n");
buffer.append("Option4: " + q.getOption4() + "\n");
buffer.append("Answer No: " + q.getAnswerNo() + "\n");
buffer.append("Option4: " + q.getChapterName() + "\n\n");
}
AlertDialog.Builder builder = new AlertDialog.Builder(AdminActivity.this);
builder.setCancelable(true);
builder.setTitle("Questions");
builder.setMessage(buffer.toString());
builder.show();
}
}
});
btnDeleteQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}}
Any clue? Thank You in Advance.
Check in onCreate function of your Activity class, did you have initialize your EditText and Button.
Also, You have to make change in your condition as below:
if(!question.equalsIgnoreCase("") && !option1.equalsIgnoreCase("") && !option2.equalsIgnoreCase("") && !option3.equalsIgnoreCase("") && !option4.equalsIgnoreCase("") && answerNo != 0 && !chapterName.equalsIgnoreCase("")
Because, == tests for reference equality (whether they are the same object).
Whereas, equalsIgnoreCase() ignores the case while comparing two strings.

How to change data in firebase and check id auto increment

Hye, my problem is to rewrite if the user put the same nameItem that will change the price and the quantityItem, if not the item will add new id. i also do auto increment on id.
My Database :
This is how i try but when the name == nameItem can't read and run on else in on DataChange.
if(i != 0){
for(id1 = 1; id1<=i; id1++){
if(id1 != 0){
final DatabaseReference reff1 = FirebaseDatabase.getInstance().getReference().child("CartList").child(userID).child(String.valueOf(id1));
reff1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String carinama = dataSnapshot.child("nameItem").getValue().toString();
String changequantity = dataSnapshot.child("quantityItem").getValue().toString();
if(nameItem == carinama) {
int calcQuantity = Integer.parseInt(cdtb.getQuantityItem());
newpositionItem = newpositionItem + calcQuantity;
String x = String.valueOf(newpositionItem);
cdtb.setQuantityItem(x);
int price1Item = Integer.parseInt(priceItem);
newpositionItem = newpositionItem * price1Item;
cdtb.setPriceItem(d2f.format(newpositionItem));
reff1.setValue(cdtb);
id1 = i;
}else {
int calcQuantity = Integer.parseInt(changequantity);
newpositionItem = newpositionItem + calcQuantity;
String x = String.valueOf(newpositionItem);
cdtb.setQuantityItem(x);
double price1Item = Double.parseDouble(priceItem);
newpositionItem = newpositionItem * price1Item;
cdtb.setPriceItem(d2f.format(newpositionItem));
reff1.setValue(cdtb);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getContext(), ""+databaseError, Toast.LENGTH_SHORT).show();
}
});
}else {
}
}
}else{
cdtb.setImageItem(imageUrl);
cdtb.setNameItem(nameItem);
cdtb.setPriceItem(d2f.format(calcPrice));
cdtb.setSpecification(specItem);
cdtb.setQuantityItem(positionItem);
reff.child(String.valueOf(++maxid)).setValue(cdtb);
}
Thank you...
nameItem and carinama is String
in java to compare two string you must use equals method not "=="
because == will compare object location in memory and not the content string
so you code condition will be
if(nameItem.equals(carinama)){
//your code here
}

Firebase Android Java - Can't get value of a child

So I have been trying to implement a way to check if the user had already sent a friend a request to the profile visited, or if the user has received a friend request from the profile visited. Based on the results, the buttons will be set to sent request, accept request ,add friend or friends
However, in my Firebase function, the first 3 if statements aren't met, even if one of them was supposed to be met. The first else if statement should have worked because I already sent a friend request to the profile visited.
When I ran a debug, it shows something like value = {sentFriendRequests={jmarston=2}}. So Firebase knows that I added John Marston as a friend, but for some reason the else if statement wasn't working. Its the else statement that works instead
My code is down below:
checkFriendRequestStatus function
private void checkFriendRequestStatus(final ButtonStatus buttonsCallback, final String strSignedInUID, final String visitedUsername, final String strVisitedUID) {
final DatabaseReference checkFriendRequestsRef = database.getReference("friend_requests/test/" + strSignedInUID);
checkFriendRequestsRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// choice is 1 to show buttons, then select which buttons to show with second params
if (dataSnapshot.child("friends/" + visitedUsername).getValue(String.class) == strVisitedUID) {
buttonsCallback.setButtonStatus(1, 1);
}
else if (dataSnapshot.child("sentFriendRequest/" + visitedUsername).getValue(String.class) == strVisitedUID) {
buttonsCallback.setButtonStatus(1, 2);
}
else if (dataSnapshot.child("receivedFriendRequests/" + visitedUsername).getValue(String.class) == strVisitedUID) {
buttonsCallback.setButtonStatus(1, 3);
}
else {
buttonsCallback.setButtonStatus(1, 4);;
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
onViewCreated function
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
sRFullName = (TextView) view.findViewById(R.id.sRUFullNameET);
addFriendBtn = (Button) view.findViewById(R.id.sRUAddFriendBtn);
sentRequestBtn = (Button) view.findViewById(R.id.sRUFriendReqSentBtn);
acceptRequestBtn = (Button) view.findViewById(R.id.sRUAcceptRequestBtn);
wereFriendsBtn = (Button) view.findViewById(R.id.sRUWeFriendsBtn);
final String strVisitedUserID = getArguments().getString("sRUserID");
final String visitedUsername = getArguments().getString("sRUsername");
ShPreference = getActivity().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
// converts Stringed userID back to Int
final String strSignedInUID = ShPreference.getInt(currentUserID, 0) + "";
final String signedInUsername = ShPreference.getString(currentUsername, "");
// converts the userSignedIn id to string
//final String strSignedInUID = userSignedInID + "";
// checks if the current User visited has been sent a friend Request
checkFriendRequestStatus(new ButtonStatus() {
#Override
public void setButtonStatus(int choice, int button) {
/**
* The choice params is for the choose if to show or hide buttons.
* The buttons params selects which buttons are to show or hide
*/
addFriendBtn.setVisibility(View.GONE);
sentRequestBtn.setVisibility(View.GONE);
acceptRequestBtn.setVisibility(View.GONE);
wereFriendsBtn.setVisibility(View.GONE);
// if choosed to show buttons
if (choice == 1) {
// show buttons depending on the friendRequest status
if (button == 1) {
wereFriendsBtn.setVisibility(View.VISIBLE);
}
else if (button == 2) {
sentRequestBtn.setVisibility(View.VISIBLE);
}
else if (button == 3) {
acceptRequestBtn.setVisibility(View.VISIBLE);
}
else {
addFriendBtn.setVisibility(View.VISIBLE);
}
}
}
}, strSignedInUID, visitedUsername, strVisitedUserID);
// sets the name with the Full Name; called from SearchResultsAdapter
sRFullName.setText(getArguments().getString("sRFullName"));
}
To compare String object use equals instead of == (double equals). Double equals will compare reference not their values.
Update your code of comparison like below:
private void checkFriendRequestStatus(final ButtonStatus buttonsCallback, final String strSignedInUID, final String visitedUsername, final String strVisitedUID) {
final DatabaseReference checkFriendRequestsRef = database.getReference("friend_requests/test/" + strSignedInUID);
checkFriendRequestsRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// choice is 1 to show buttons, then select which buttons to show with second params
if (dataSnapshot.child("friends/" + visitedUsername).getValue(String.class).equals(strVisitedUID)) {
buttonsCallback.setButtonStatus(1, 1);
}
else if (dataSnapshot.child("sentFriendRequest/" + visitedUsername).getValue(String.class).equals(strVisitedUID)) {
buttonsCallback.setButtonStatus(1, 2);
}
else if (dataSnapshot.child("receivedFriendRequests/" + visitedUsername).getValue(String.class).equals(strVisitedUID)) {
buttonsCallback.setButtonStatus(1, 3);
}
else {
buttonsCallback.setButtonStatus(1, 4);;
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}

How add various editText in one TextView

I'm new in programming and I need your help, I have a error when insert number in editText txt50, app crashes please help me, I don't know what is the error:
code:
public class Main2Activity extends AppCompatActivity {
private EditText cinco, cien, doscientos, quinientos, mil, dosmil, cincomil, diezmil, veintemil, cincuentamil, cienmil;
private TextView diezmob;
public static final String nombres = "names";
TextView txtBienvenido;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
txtBienvenido = (TextView) findViewById(R.id.txtbienvenido);
String usuario = getIntent().getStringExtra("names");
txtBienvenido.setText("¡Bienvenido(a) Hermano(a) " + usuario + "!");
diezmob = (TextView) findViewById(R.id.txtdiezmob);
cinco = (EditText) findViewById(R.id.txt50);
cien = (EditText) findViewById(R.id.txt100);
doscientos = (EditText) findViewById(R.id.txt200);
quinientos = (EditText) findViewById(R.id.txt500);
mil = (EditText) findViewById(R.id.txt1000);
dosmil = (EditText) findViewById(R.id.txt2000);
cincomil = (EditText) findViewById(R.id.txt5000);
diezmil = (EditText) findViewById(R.id.txt10000);
veintemil = (EditText) findViewById(R.id.txt20000);
cincuentamil = (EditText) findViewById(R.id.txt50000);
cienmil = (EditText) findViewById(R.id.txt100000);
cinco.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if ((cinco.toString().equals("")) && (!cinco.toString().equals(null)) && (cinco.toString().isEmpty() || (cinco.toString().length() >= 0))) {
double valor1 = Double.parseDouble((cinco.getText().toString()));
double valor2 = Double.parseDouble((cien.getText().toString()));
double valor3 = Double.parseDouble((doscientos.getText().toString()));
double valor4 = Double.parseDouble((quinientos.getText().toString()));
double valor5 = Double.parseDouble((mil.getText().toString()));
double valor6 = Double.parseDouble((dosmil.getText().toString()));
double valor7 = Double.parseDouble((cincomil.getText().toString()));
double valor8 = Double.parseDouble((diezmil.getText().toString()));
double valor9 = Double.parseDouble((veintemil.getText().toString()));
double valor10 = Double.parseDouble((cincuentamil.getText().toString()));
double valor11 = Double.parseDouble((cienmil.getText().toString()));
double suma = (valor1 * 50) + (valor2 * 100) + (valor3 * 200) + (valor4 * 500) + (valor5 * 1000) + (valor6 * 2000) + (valor7 * 5000) + (valor8 * 10000) + (valor9 * 20000) + (valor10 * 50000) + (valor11 * 100000);
String resultado = String.valueOf((int) suma);
diezmob.setText(String.valueOf(resultado));
} else {
diezmob.setText("0");
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
} }
LogCat: Error when insert number in editText txt50, the app crashes:
java.lang.NumberFormatException: Invalid double: ""
I resolve this error with this code, any error please say it.
package com.example.josue.login;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Calendar;
public class Main2Activity extends AppCompatActivity implements View.OnClickListener {
private TextView diezmob;
public static final String nombres = "names";
TextView txtBienvenido;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
txtBienvenido = (TextView) findViewById(R.id.txtbienvenido);
String usuario = getIntent().getStringExtra("names");
txtBienvenido.setText("¡Bienvenido(a) Hermano(a) " + usuario + "!");
diezmob = (TextView) findViewById(R.id.txtdiezmob);
findViewById(R.id.btncalcular).setOnClickListener(this);
findViewById(R.id.btncalcular5).setOnClickListener(this);
findViewById(R.id.btncalcular10).setOnClickListener(this);
findViewById(R.id.btncalcular15).setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btncalcular:
double cinco, cien, doscientos, quinientos, mil, dosmil, cincomil, diezmil, veintemil, cincuentamil, cienmil;
String Cinco = ((EditText) findViewById(R.id.txt50)).getText().toString();
String Cien = ((EditText) findViewById(R.id.txt100)).getText().toString();
String Doscientos = ((EditText) findViewById(R.id.txt200)).getText().toString();
String Quinientos = ((EditText) findViewById(R.id.txt500)).getText().toString();
String Mil = ((EditText) findViewById(R.id.txt1000)).getText().toString();
String Dosmil = ((EditText) findViewById(R.id.txt2000)).getText().toString();
String Cincomil = ((EditText) findViewById(R.id.txt5000)).getText().toString();
String Diezmil = ((EditText) findViewById(R.id.txt10000)).getText().toString();
String Veintemil = ((EditText) findViewById(R.id.txt20000)).getText().toString();
String Cincuentamil = ((EditText) findViewById(R.id.txt50000)).getText().toString();
String Cienmil = ((EditText) findViewById(R.id.txt100000)).getText().toString();
if (Cinco != null && !Cinco.equals("")) {
cinco = Double.valueOf(Cinco);
}else{
cinco = 0;
}
if (Cien != null && !Cien.equals("")){
cien = Double.valueOf(Cien);
}else{
cien=0;
}
if (Doscientos != null && !Doscientos.equals("")) {
doscientos = Double.valueOf(Doscientos);
}else{
doscientos=0;
}
if (Quinientos != null && !Quinientos.equals("")) {
quinientos = Double.valueOf(Quinientos);
}else{
quinientos = 0;
}
if (Mil != null && !Mil.equals("")){
mil = Double.valueOf(Mil);
}else{
mil = 0;
}
if (Dosmil != null && !Dosmil.equals("")) {
dosmil = Double.valueOf(Dosmil);
}else {
dosmil = 0;
}
if (Cincomil != null && !Cincomil.equals("")) {
cincomil = Double.parseDouble(Cincomil);
}else {
cincomil = 0;
}
if (Diezmil !=null && !Diezmil.equals("")) {
diezmil = Double.valueOf(Diezmil);
}else {
diezmil = 0;
}
if (Veintemil != null && !Veintemil.equals("")) {
veintemil = Double.valueOf(Veintemil);
}else {
veintemil = 0;
}
if (Cincuentamil != null && !Cincuentamil.equals("") ) {
cincuentamil = Double.valueOf(Cincuentamil);
}else {
cincuentamil = 0;
}
if (Cienmil != null && !Cienmil.equals("") ) {
cienmil = Double.valueOf(Cienmil);
}else {
cienmil = 0;
}
double suma = (cinco * 50) + (cien * 100) + (doscientos * 200) + (quinientos * 500) + (mil * 1000) +
(dosmil * 2000) + (cincomil * 5000) + (diezmil * 10000) + (veintemil * 20000) + (cincuentamil * 50000) +
(cienmil * 100000);
String resultado = String.valueOf((int)(suma));
diezmob.setText(String.valueOf(resultado));
break;
case R.id.btncalcular5:
Intent i = new Intent(this, Main5Activity.class);
i.putExtra("dato",diezmob.getText().toString());
startActivity(i);
break;
case R.id.btncalcular10:
Intent ii = new Intent(this, Main5Activity.class);
startActivity(ii);
break;
case
R.id.btncalcular15:
Intent iii = new Intent(this, Main5Activity.class);
startActivity(iii);
break;
default:
break;
}
}
}
Let's evaluate this:
if ((cinco.toString().equals("")) && (!cinco.toString().equals(null)) && (cinco.toString().isEmpty() || (cinco.toString().length() >= 0))) {
double valor1 = Double.parseDouble((cinco.getText().toString()));
You are saying if ("cinco is an empty string") and (not null) and ((isEmpty(same as empty string)) or is a length >= 0) then parse double
I am pretty sure the only time this evaluates to true is if cinco is empty which will result in a NumberFormatException because you are trying to parse cinco for a double while it is empty. You will have to handle exceptions with a try-catch block:
try {
double valor1 = Double.parseDouble((cinco.getText().toString()));
} catch (NumberFormatException e) {
e.printStackTrace();
}
or construct if statements that don't allow cinco to be evaluated if it is empty:
if(cinco.toString() != null && !(cinco.toString().isEmpty() {
double valor1 = Double.parseDouble((cinco.getText().toString()));
}
edit: All of the Double.parseDouble in your code will throw NumberFormatExceptions not just cinco by the way. That one is just first so this answer applies to all of the parses.

Android toast message (identify the correct answer using radio button)

I'm developing a quiz. I got an error while showing my toast message. The error is, if the user taps the correct answer, toast says it is the wrong answer even if I tap the correct choice. Help is really appreciated! Here is the code:
public class Question2 extends Activity {
/** Called when the activity is first created. */
TextView question, items = null;
RadioButton answer1 = null;
RadioButton answer2 = null;
RadioButton answer3 = null;
RadioGroup answers = null;
int selectedAnswer = -1;
int quesIndex = 0;
int numEvents = 0;
int selected[] = null;
int correctAns[] = null;
boolean review = false;
Button next = null;
int score = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.startquiz);
try {
score = getIntent().getIntExtra("score",0);
items = (TextView)findViewById(R.id.displayitems);
question = (TextView) findViewById(R.id.displayquestion);
answer1 = (RadioButton) findViewById(R.id.option1);
answer2 = (RadioButton) findViewById(R.id.option2);
answer3 = (RadioButton) findViewById(R.id.option3);
answers = (RadioGroup) findViewById(R.id.QueGroup1);
next = (Button) findViewById(R.id.selected);
next.setOnClickListener(nextListener);
selected = new int[Question1.getQuesList().length()];
java.util.Arrays.fill(selected, -1);
correctAns = new int[Question1.getQuesList().length()];
java.util.Arrays.fill(correctAns, -1);
this.showQuestion(0, review);
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
private void showQuestion(int qIndex, boolean review) {
try {
JSONObject aQues = Question1.getQuesList().getJSONObject(
qIndex);
String quesValue = aQues.getString("Question");
if (correctAns[qIndex] == -1) {
String correctAnsStr = aQues.getString("CorrectAnswer");
correctAns[qIndex] = Integer.parseInt(correctAnsStr);
}
question.setText(quesValue.toCharArray(), 0, quesValue.length());
answers.check(-1);
answer1.setTextColor(Color.BLACK);
answer2.setTextColor(Color.BLACK);
answer3.setTextColor(Color.BLACK);
JSONArray ansList = aQues.getJSONArray("Answers");
String aAns = ansList.getJSONObject(0).getString("Answer");
answer1.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(1).getString("Answer");
answer2.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(2).getString("Answer");
answer3.setText(aAns.toCharArray(), 0, aAns.length());
Log.d("", selected[qIndex] + "");
if (selected[qIndex] == 0)
answers.check(R.id.option1);
if (selected[qIndex] == 1)
answers.check(R.id.option2);
if (selected[qIndex] == 2)
answers.check(R.id.option3);
setText();
if (quesIndex == (Question1.getQuesList().length() - 1))
next.setEnabled(false);
if (quesIndex < (Question1.getQuesList().length() - 1))
next.setEnabled(true);
if (review) {
Log.d("review", selected[qIndex] + "" + correctAns[qIndex]);
;
if (selected[qIndex] != correctAns[qIndex]) {
if (selected[qIndex] == 0)
answer1.setTextColor(Color.RED);
if (selected[qIndex] == 1)
answer2.setTextColor(Color.RED);
if (selected[qIndex] == 2)
answer3.setTextColor(Color.RED);
}
if (correctAns[qIndex] == 0)
answer1.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 1)
answer2.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 2)
answer3.setTextColor(Color.GREEN);
}
} catch (Exception e) {
Log.e(this.getClass().toString(), e.getMessage(), e.getCause());
}
}
private void setAnswer() {
if (answer1.isChecked())
selected[quesIndex] = 0;
if (answer2.isChecked())
selected[quesIndex] = 1;
if (answer3.isChecked())
selected[quesIndex] = 2;
Log.d("", Arrays.toString(selected));
Log.d("", Arrays.toString(correctAns));
}
private OnClickListener nextListener = new OnClickListener() {
public void onClick(View v) {
for(int i=0; i<correctAns.length; i++){
if ((correctAns[i] != -1) && (correctAns[i] == selected[i]))
{
score++;
Toast.makeText(getApplicationContext(), "Your answer is correct!", Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(getApplicationContext(), "Your answer is wrong...", Toast.LENGTH_SHORT).show();
}
}
quesIndex++;
try {
if (quesIndex >= Question1.getQuesList().length())
quesIndex = Question1.getQuesList().length() - 1;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
showQuestion(quesIndex, review);
}
};
private void setText() throws JSONException {
this.setTitle("Question " + (quesIndex + 1) + " out of "
+ Question1.getQuesList().length());
items.setGravity(250);
}
public void reload() {
setAnswer();
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
Your If() condition should be like this:-
if ((correctAns[i] != -1) && (correctAns[i].equalsIgnoreCase(selected[i]))) {
score++;
Toast.makeText(getApplicationContext(), "Your answer is correct!", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Your answer is wrong...", Toast.LENGTH_SHORT).show();
}
It seems like you can change your condition. Are users be able to select multiple answers?
And try that thin with condition like
for(int i=0; i<correctAns.length; i++){
if ((correctAns[i].euqalsIgnoreCase(selected[i]))){
score++;
Toast.makeText(getApplicationContext(), "Your answer is correct!", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Your answer is wrong...", Toast.LENGTH_SHORT).show();
}
}
Try this and let me know that it works or not.

Categories