Reputation: 149
I am new android developer in my company. I maintain a project.. In my project, 3 checkboxes are there and when we click on those checkboxes, it can be selectable mutiple and if we click button those values are stored into json in android. How can i write code? anybody give me advice.. I will send my layout design just for idea purpose you..
Upvotes: 0
Views: 1451
Reputation: 1670
Checkout the code below,
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private CheckBox cbDineIn;
private CheckBox cbTakeOut;
private CheckBox cbDelivery;
private Button btnDone;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
}
private void initUI(){
cbDineIn =(CheckBox)findViewById(R.id.cbDineInActivityMain);
cbTakeOut =(CheckBox)findViewById(R.id.cbtakeOutActivityMain);
cbDelivery =(CheckBox)findViewById(R.id.cbDeliveryActivityMain);
btnDone=(Button)findViewById(R.id.btnDoneActivityMain);
btnDone.setOnClickListener(this);
}
private JSONObject generateJSON(){
JSONObject jsonObjectChoices = new JSONObject();
try {
if(cbDineIn.isChecked()){
jsonObjectChoices.put("Dine-In","YES");
}else {
jsonObjectChoices.put("Dine-In","NO");
}
if(cbTakeOut.isChecked()){
jsonObjectChoices.put("Take-Out","YES");
}else {
jsonObjectChoices.put("Take-Out","NO");
}
if(cbDelivery.isChecked()){
jsonObjectChoices.put("Delivery","YES");
}else {
jsonObjectChoices.put("Delivery","NO");
}
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObjectChoices;
}
@Override
public void onClick(View v) {
generateJSON();
}
}
Upvotes: 1
Reputation: 668
Better you can set unique tag or id to your each CheckBoxes and then you can get the id or tag when you click the button.
Set those values in JSON and send.
To understand about JSON, you have lot of opportunities.
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
http://www.tutorialspoint.com/android/android_json_parser.htm
http://www.javatpoint.com/android-json-parsing-tutorial
Upvotes: 0
Reputation: 2455
Your question is not clear enough
In android, if you need to generate JSON
try this one
CheckBox checkBox;
checkBox = (CheckBox) findViewById(R.id.checkbox);
checkBox.setOnClickListener(new View.OnClickListener(){
@override
public void onClick(){
String jsonObject = generateJSONData();
Log.i("Json Data", jsonObject);
}
}
public String generateJSONData(){
JSONObject jsonObj = new JSONObject();
jsonObj.put("name","ajay");
jsonObj.put("address","fairfield");
return jsonObj.toString();
}
}
This code will generate JSON on CheckBox click.
The output will be
{ name:"ajay", address:"fairfield" }
I just write this code. I didn't test it. Hope it helps you :)
Upvotes: 0