0

I have a class that builds a HttpResponse initializer. in one of the methods that should return the BasicNameValuePair I have to check if there is a entry in the list with key or name specified by String "name".

public List<BasicNameValuePair> getPostPairs() {
    if(mPostPairs == null || mPostPairs.size() < 1) {
        throw new NullPointerException(TAG + ": PostPairs is null or has no items in it!");
    }

    //there is no hasName() or hasKey() method :(
    if(!mPostPairs.hasName("action")) {
        throw new IllegalArgumentException(TAG + ": There is no 'action' defined in the collections");
    }

    return mPostPairs;
}

How to do this? if it is not possible with BasicNameValuePair, what would be the alternative? subclassing and adding the method?

I need to use this for a HttpPost, which its setEntity only accepts this type:

public UrlEncodedFormEntity (List<? extends NameValuePair> parameters)
Dumbo
  • 13,555
  • 54
  • 184
  • 288
  • 1
    Offtopic: you can use `isEmpty()` for check if the array is empty, is better than `size()` (size need to go through the entire list). – Arturo Volpe Aug 13 '14 at 00:12
  • @AVolpe Thanks for the note! never though of that lol possibly lots of performance issures in my entire appliation is because of that! – Dumbo Aug 13 '14 at 00:14
  • Shouldn't you be using a hashtable for this? – Robert Harvey Aug 13 '14 at 00:14
  • @RobertHarvey since this is going to be used for HttpPost it is required by this: public UrlEncodedFormEntity (List extends NameValuePair> parameters) – Dumbo Aug 13 '14 at 00:16
  • or maybe hashtable is base of NameValuePair...I dont know really – Dumbo Aug 13 '14 at 00:25

1 Answers1

2

It seems that mPostPairs is a List<BasicNameValuePair>, and a list dont know what kind of objects are stored, you can iterate over it and check

boolean finded = false;
for (BasicNameValuePair pair : mPostPairs) {
    if (pair.getName().equals("action")) {
        finded = true;
        break;
    }
}
if (finded)
    return mPostPairs;
else
    throw new IllegalArgumentException(TAG + ": There is no 'action' defined in the collections");

Or shorter:

for (BasicNameValuePair pair : mPostPairs) 
    if (pair.getName().equals("action")) 
        return mPostPairs;
throw new IllegalArgumentException(TAG + ": There is no 'action' defined in the collections");
Arturo Volpe
  • 3,442
  • 3
  • 25
  • 40