-1

So, in my app, I am retrieving JSON data and parsing it. RIght now, it is displaying every record on a textView like this

Name: Eric Email: Eric.com

Name: Greg Email: Greg@Greg.com

.................. etc

Code:

  //parse json data
 try {
   String s = "";
   JSONArray jArray = new JSONArray(result);

   for(int i=0; i<jArray.length();i++){
       JSONObject json = jArray.getJSONObject(i);

       s = s + 
               "Name : "+json.getString("Name")+"\n"+
               "Email : "+json.getString("Email")+"\n\n";
   }

   resultView.setText(s);

I want to be able to search and display only a single record, e.g. Eric's record. How could I do this? I tried this adding if (json.getString("Name") == "Eric") { } like this:

//parse json data
 try {
   String s = "";
   JSONArray jArray = new JSONArray(result);

   for(int i=0; i<jArray.length();i++){
       JSONObject json = jArray.getJSONObject(i);
           if (json.getString("Name") == "Eric) { //added if statement
       s = s + 
               "Name : "+json.getString("Name")+"\n"+
               "Email : "+json.getString("Email")+"\n\n";
               }
   }

   resultView.setText(s);

but it doesn't display anything, then. Any ideas on how I can search for a single person's record in JSON? Thanks!

user2976670
  • 29
  • 3
  • 9

2 Answers2

1

Change

json.getString("Name") == "Eric"

to

json.getString("Name").equals("Eric")

When comparing String you should use equals not ==

Apoorv
  • 13,470
  • 4
  • 27
  • 33
1

Use

json.getString("Name").equals("Eric")

do not use ==,as basically it is used to compare int value and you are comparing string.

Community
  • 1
  • 1
Pankaj Arora
  • 10,224
  • 2
  • 37
  • 59