2016-12-15 27 views
0

我试图找到Stack Overflow问题上的很多帖子,然后我发现有关on here的帖子。是否有可能从Android插入数据到MySQL通过PHP但是在按钮onClick中定义namevaluepair?

但是,链接,我发现这样的内部类新的一些代码:

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); 

其实我想定义里面button OnClick数据,因为我通过循环for所有的字符串。

对于例如:

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); 
} 

所以,每次我环,我需要调用定义按钮,在字符串的insert class

有没有什么方法可以像我需要的那样去做?

+0

可以修改PostDataTOServe类,书写方法您可以定义值对 – MikeKeepsOnShine

+0

@MikeKeepsOnShine但如何?我已经阅读过很多次关于谷歌的教程,但直到现在我还没有找到方法 – dondo

回答

0

在你的类PostDataTOServer中,你可以创建一个方法,在其中填充NameValuePair列表,例如,

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())); 
     } 
    } 

    .... 

} 

,并在您的循环必须调用

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

然后在doInBackground,你可以直接使用valuePair创建

httppost.setEntity(new UrlEncodedFormEntity(this.values)); 
+1

感谢代码,虐待它,:) – dondo

相关问题