i have an adapter from which i am creating edittext for user to input data dynamically.
Now, i have to store the same in JSONObject in a key-value pair? how can i do it?
i am storing all the created edit text in a list
ArrayList<EditText> list = new ArrayList<>();
EDIT PART
i am adding edittext to list like this:
list.add(holder.editText);
EDIT PART -ENDS
this is my button click listener code:
addnewAcnt.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Toast.makeText(context, "INIT", Toast.LENGTH_SHORT).show();
JSONObject jsonObject2 = null;
for (int i = 0; i < count; i++)
{
jsonObject2 = new JSONObject();
try
{
jsonObject2.put(String.valueOf(list.get(i).getHint()), String.valueOf(list.get(i).getText()));
}
catch (Exception e)
{
e.printStackTrace();
Log.e("JsonToSendError: ", String.valueOf(e));
}
Log.e("JsonToSend: ", String.valueOf(jsonObject2));
}
}
});
I am getting data in Log as:
2020-10-05 15:19:21.476 16462-16462/com.packagename E/JsonToSend:: {"Title":"StackOverFlow"}
2020-10-05 15:19:21.476 16462-16462/com.packagename E/JsonToSend:: {"URL":"www.stackoverflow.com"}
2020-10-05 15:19:21.476 16462-16462/com.packagename E/JsonToSend:: {"Username":"test"}
2020-10-05 15:19:21.476 16462-16462/com.packagename E/JsonToSend:: {"Password":"testtesttest"}
But, i need it to be in a single object like:
{"Title":"StackOverFlow", "URL":"www.stackoverflow.com", "Username":"test", "Password":"testtesttest"}
any help will be useful. Please
Because you creating new object in loop, try moving your jsonObject2 = new JSONObject();
before the loop.
About the last object, i'm not sure how do variable count
value is changed. But if you are getting value from list, you should use that list count in your loop.
The code should be like this.
addnewAcnt.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Toast.makeText(context, "INIT", Toast.LENGTH_SHORT).show();
JSONObject jsonObject2 = new JSONObject();
for (int i = 0; i < list.size(); i++) // variable count to be your list (edit text) size.
{
try
{
jsonObject2.put(String.valueOf(list.get(i).getHint()), list.get(i).getText().toString().trim());
}
catch (Exception e)
{
e.printStackTrace();
Log.e("JsonToSendError: ", String.valueOf(e));
}
Log.e("JsonToSend: ", String.valueOf(jsonObject2));
}
}
});