0

I've tried to find many post on Stack Overflow question, then I found a useful post about that on here.

But on that link, I found some code like that inside new class :

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);

Actually I want to define the data inside button OnClick, Because I got all string through loop for.

For the example :

int size = adapter3.getCount();
for (int i=0;i<size;i++){
    id = adapter3.getItem(i).getId();
    nilai = String.valueOf(adapter3.getItem(i).getRatingStar());
    PostDataTOServer p = new PostDataTOServer(); // call the class insert
    p.execute(id, nilai);
}

So, everytime I loop, I need to call the insert class that define the String in button.

Is there any method how to do like I need?

Community
  • 1
  • 1
dondo
  • 99
  • 12

1 Answers1

0

In your class PostDataTOServer you can create a method in which you fill the NameValuePair list, e.g.

public class PostDataTOServer{

    private List<NameValuePair> values;
    // here I use an HashMap because I need a <K,V> object
    public void setDataToSend(HashMap<String,String> datas){
        //TODO: make a check on the size of HashMap
        values = new ArrayList<NameValuePair>(datas.size());

        //iterate the HashMap and fill the valuePair
        for(Map.Entry<String, String> entry : datas.entrySet()){
            values.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
    }

    ....

}

and in your for loop you must call

p.setDataToSend(hashMap) // p = new PostDataTOServer();

Then in doInBackground, you can use directly the valuePair created

httppost.setEntity(new UrlEncodedFormEntity(this.values));
MikeKeepsOnShine
  • 1,730
  • 4
  • 23
  • 35