2016-04-20 72 views
1

我有兩個RadioButton命名爲已婚,未婚,我必須做的是當用戶檢查已婚單選按鈕時,我必須發送radioButton「已婚」的值給服務器,使用jsons和未婚時一樣。我該怎麼做。如何發送單選按鈕值到android中的服務器?

這裏是JSON代碼的字段: -

jsonObject.put("maritalstatus", ""); 

回答

1

嘗試以下代碼:

RadioGroup radioGroup = (RadioGroup)findViewById(R.id.yourid); 
String selectedText = ((RadioButton)findViewById(radioGroup.getCheckedRadioButtonId())).getText().toString(); 

jsonObject.put("maritalstatus", selectedText); 

要設置的單選按鈕選中:

String status = jsonObject.getString("maritalstatus"); 
if(status.equals("married")){ 
    radioGroup.check(radioGroup.getChildAt(0).getId()); 
}else{ 
    radioGroup.check(radioGroup.getChildAt(1).getId()); 
} 
+0

多數民衆贊成在工作,但在作出迴應後,我得到了軍事地位後,我已檢查答覆可能已婚或未婚 – niraj

+0

對不起,我沒有得到你的評論。你得到什麼迴應以及你需要什麼迴應? –

+0

我gettig從服務器結婚時,我得到maaried然後我必須設置已婚radioButoon檢查,如果未婚,那麼我必須設置未婚RdaioButton檢查 – niraj

0

首先,對於每個單選按鈕元件你需要設置一個標籤以供稍後檢索:

marriedRadioButton.setTag("married"); 
unmarriedRadioButton.setTag("unmarried") 


RadioGroup rdGroup = (RadioGroup) findViewById(R.id.rdbGp1); 
rdGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { 

@Override 
public void onCheckedChanged(RadioGroup group, int checkedId) { 
    RadioButton selectedRadioButton = (RadioButton) group.findViewById(checkedId); 
    String text = radioButton.getTag(); 
    JSONObject jsonObject = new JSONObject(); 
    jsonObject.put("maritalstatus", text); 
    // Now you need to send the json to the server through an AsyncTask 
    SendJsonTask sendJsonTask = new SendJsonTask(); 
    sendJsonTask.execute(jsonObject.toString()); 
}}); 

private class SendJsonTask extends AsyncTask<String, Void, Void> { 
protected String doInBackground(String... params) { 
    URL url = new URL("http://domaintoreceive.com/pagetoreceive"); 

    HttpClient httpClient = new DefaultHttpClient(); 
    HttpPost httpPost = new HttpPost(url.toURI()); 

    httpPost.setEntity(new StringEntity(params[0], "UTF-8")); 

    // Set up the header types needed to properly transfer JSON 
    httpPost.setHeader("Content-Type", "application/json"); 
    httpPost.setHeader("Accept-Encoding", "application/json"); 
    httpPost.setHeader("Accept-Language", "en-US"); 

    // Execute POST 
    response = httpClient.execute(httpPost); 
}} 

不要忘記捕捉所有必需的例外。

問候。

相關問題