1

I am writing an app that takes two user inputs and matches them to data stored in a database and displays the corresponding data(row) from the user inputs in a TextView.

The if statement works perfectly alone if the condition is true. It is however not executed even if the condition is true if I add the else statement.

The else statement is always executed if the statement is true or false

protected void onPostExecute(Void v) { // ambil data dari Json database try { JSONArray Jarray = new JSONArray(result); for (int i = 0; i < Jarray.length(); i++) { JSONObject Jasonobject = null; //text_1 = (TextView)findViewById(R.id.txt1); Jasonobject = Jarray.getJSONObject(i); //get an output on the screen //String id = Jasonobject.getString("id"); String name = Jasonobject.getString("name"); String db_detail=""; if (et.getText().toString().equalsIgnoreCase(name)) { db_detail = Jasonobject.getString("detail"); text.setText(db_detail); break; } else { Toast.makeText(MainActivity.this, "Not available", Toast.LENGTH_LONG).show(); break; } } this.progressDialog.dismiss(); 

3 Answers 3

2

you never loop entirely on Jarray. If a the first iteration et.getText().toString().equalsIgnoreCase(name) is false, and the else branch is executed, you break immediately.

try { JSONArray Jarray = new JSONArray(result); for(int i=0;i< Jarray.length(); i++) { // other code if(et.getText().toString().equalsIgnoreCase(name)) { db_detail = Jasonobject.getString("detail"); text.setText(db_detail); break; } } if (TextUtils.isEmpty(db_detail)) { // show toast } } 
Sign up to request clarification or add additional context in comments.

Comments

1

Use flag variable to check whether user is available or not, and print your message after for loop.

boolean available=false; JSONArray Jarray = new JSONArray(result); for(int i=0;i<Jarray.length();i++) { JSONObject Jasonobject = null; //text_1 = (TextView)findViewById(R.id.txt1); Jasonobject = Jarray.getJSONObject(i); //get an output on the screen //String id = Jasonobject.getString("id"); String name = Jasonobject.getString("name"); String db_detail=""; if(et.getText().toString().equalsIgnoreCase(name)) { db_detail = Jasonobject.getString("detail"); text.setText(db_detail); available=true; break; } } if(!available) Toast.makeText(MainActivity.this, "Not available", Toast.LENGTH_LONG).show(); 

Comments

0

Have you tried using:

else if(!et.getText().toString().equalsIgnoreCase(name)) 

1 Comment

While the code may answer the question, it would be better to explain how it works and why to use it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.