0

I am trying to remove duplicates from json string using the answer from Remove duplicates from a Json String in Java? question,but it is not working.Here is my code

inquire.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //location = loc.getText().toString();
            StringRequest request = new StringRequest(Request.Method.POST, urlRec, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        String responseString = response.toString();
                        JSONObject obj = new JSONObjectIgnoreDuplicates(responseString);
                        JSONArray recJsonArray = obj.getJSONArray("search");
                        // JSONArray recJsonArray = new JSONArray(responseString);
                        List<Recipient> recList = new ArrayList<>();
                        for (int i = 0; i < recJsonArray.length(); i++) {
                            JSONObject recJsonObj = (JSONObject) recJsonArray.get(i);
                            Recipient rec = new Recipient();
                            rec.setname(recJsonObj.getString("name"));
                            rec.setLocation(recJsonObj.getString("location"));
                            rec.setcontact(recJsonObj.getString("contact"));
                            recList.add(rec);
                        }
                        Intent myintent = new Intent(Search_inq.this, Reclist.class);
                        myintent.putExtra("recList", (Serializable) recList);
                        startActivity(myintent);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("Error", error.getMessage());
                    Toast.makeText(getApplication(), "Error occurred", Toast.LENGTH_LONG).show();
                }
            }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> parameters = new HashMap<>();
                    parameters.put("location", location);
                    return parameters;
                }
            };
            queue.add(request);
        }
    });

Here,the table on which i conducted query is called SEARCH.Please help if you can.

edit

here is the code for the class JSONObjectIgnoreDuplicates

public class JSONObjectIgnoreDuplicates extends JSONObject {


    public JSONObjectIgnoreDuplicates(String json) throws JSONException {
        super(json);
    }

    public JSONObject putOnce(String key, Object value) throws JSONException {
        Object storedValue;
        if (key != null && value != null) {
            if ((storedValue = this.opt(key)) != null ) {
                if(!storedValue.equals(value))                          //Only through Exception for different values with same key

                   Log.d("not accepted","n");


                else
                    return this;
            }
            this.put(key, value);
        }
        return this;
    }

}

edit-

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_reclist);

    Intent i = getIntent();
   // List<Recipient> recList = (List<Recipient>) i.getParcelableArrayListExtra("recList");
    ArrayList<Recipient> recList = getIntent().getParcelableArrayListExtra("recList");
    list = (ListView) findViewById(R.id.list1);


    onLoaded(recList);


}

public void onLoaded(List<Recipient> recList) {

    for (Recipient rec : recList) {

        HashMap<String, String> map = new HashMap<>();

        map.put("name", rec.getUserName());
        map.put("location", rec.getLocation());
        map.put("contact", rec.getContact());

        recplist.add(map);
    }

    loadListView();
}

private void loadListView() {

    ListAdapter adapter = new SimpleAdapter(Reclist.this, recplist, R.layout.list_item,
            new String[]{"name", "location", "contact"},
            new int[]{R.id.textView3, R.id.textView4, R.id.textView6});

    list.setAdapter(adapter);
}
2
  • 1
    What do you mean by "it is not working" ? Commented Feb 17, 2017 at 17:13
  • Whenever i press the button,there is no resultant json array which could be shown as a list. Commented Feb 17, 2017 at 17:15

1 Answer 1

0

Create an equals and hashcode overide for your Recipient class and while yer at it make it implement Parcelable since its faster than serializable. Example:

public class Recipient implements Parcelable {
    private String name, location, contact;

    public Recipient(String name, String location, String contact) {
        this.name = name;
        this.location = location;
        this.contact = contact;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getContact() {
        return contact;
    }

    public void setContact(String contact) {
        this.contact = contact;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Recipient recipient = (Recipient) o;

        if (name != null ? !name.equals(recipient.name) : recipient.name != null) return false;
        if (location != null ? !location.equals(recipient.location) : recipient.location != null)
            return false;
        return contact != null ? contact.equals(recipient.contact) : recipient.contact == null;

    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + (location != null ? location.hashCode() : 0);
        result = 31 * result + (contact != null ? contact.hashCode() : 0);
        return result;
    }


    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.name);
        dest.writeString(this.location);
        dest.writeString(this.contact);
    }

    protected Recipient(Parcel in) {
        this.name = in.readString();
        this.location = in.readString();
        this.contact = in.readString();
    }

    public static final Parcelable.Creator<Recipient> CREATOR = new Parcelable.Creator<Recipient>() {
        @Override
        public Recipient createFromParcel(Parcel source) {
            return new Recipient(source);
        }

        @Override
        public Recipient[] newArray(int size) {
            return new Recipient[size];
        }
    };
}

Then your implementation can be as follows since the Recipient class can be compared via the ArrayList#contains method:

try {
    String responseString = response.toString();
    JSONObject object = new JSONObject(responseString);
    JSONArray recJsonArray = object.getJSONArray("search");

    ArrayList<Recipient> recList = new ArrayList<>();
    for (int i = 0; i < recJsonArray.length(); i++) {
        JSONObject recJsonObj = (JSONObject) recJsonArray.get(i);
        Recipient rec = new Recipient(recJsonObj.getString("name"),
                                      recJsonObj.getString("location"),
                                      recJsonObj.getString("contact"));
        if (!recList.contains(rec)) {
            // if it isn't already there, add it
            recList.add(rec);
        }
    }
    Intent myintent = new Intent(Search_inq.this, Reclist.class);
    //use putParcelableArrayListExtra since its faster than serializable
    myintent.putParcelableArrayListExtra("recList", recList);
    startActivity(myintent);
} catch (JSONException e) {
    Log.e("some tag", e.getMessage(), e);
}

To get the data out of the intent just use in your new activity:

ArrayList<Recipient> recList = getIntent().getParcelableArrayListExtra("recList");
Sign up to request clarification or add additional context in comments.

2 Comments

perhaps your response string is empty/null? Also, added a way to get the list from the intent.
I think there may be a problem in the class which i am using to show the list.Now,I have added that in my question.Please check if there is an error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.