How to pass Array as parameters with okhttp Library - android

I am using OKHttp dependency.I am not able to pass array to server in NamvaluePair paramenters.
This my function to send parameter in POST and Getting jSON in response.
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) throws IOException, JSONException {
OkHttpClient client = new OkHttpClient();
Log.i("PARAMETERS", "PARAMETERS ::" + params);
FormEncodingBuilder builder = new FormEncodingBuilder();
for (NameValuePair valuePair : params) {
builder.add(valuePair.name, URLEncoder.encode(valuePair.value, "UTF-8"));
}
Request request = new Request.Builder().url(url).post(builder.build()).build();
Log.i("Registration Request::", request.toString());
Response response = client.newCall(request).execute();
Log.i("REGISTRATION RESPONSE::", response.toString());
JSONObject jObj= new JSONObject(response.body().string()) ;
return jObj;
}
This is my Funtion to Call Action.
public JSONObject getShopCategory(String jsonArray) throws IOException {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new NameValuePair("tag", categoryShopTag));
params.add(new NameValuePair(categoryShopTag, jsonArray));
// params.add(new BasicNameValuePair("buyer_id", buyer_id));
// params.add(new BasicNameValuePair("last_sync_date", last_sync_date));
Log.i("CATEGORY REQUEST::", params.toString());
// getting JSON Object
JSONObject json = null;
try {
json = jsonParser.getJSONFromUrl(UrlMap.urlPath, params);
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
This is from where i am calling the funtion.
for (int i = 0; i < sellerId.size(); i++) {
lastdateCat = "2011-02-11 18:57:25";
buyerCategoryFunction = new BuyerCategoryFunction();
JSONObject jsonObjectCategory = new JSONObject();
try {
jsonObjectCategory.put("shop_id", sellerId.get(i));
jsonObjectCategory.put("last_sync_date", lastdateCat);
jsonObjectCategory.put("buyer_id", CommonUtilities
.getSellerId(getApplicationContext()));
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
jsonCategoryArray.put(jsonObjectCategory);
}
JSONObject jsonCategory = buyerCategoryFunction
.getShopCategory(jsonCategoryArray.toString();
Issue is not from web service because its working fine with HttpClient.
Please help me to go thought.

Related

Use a “animated circle” while complete asynctask process

I'm trying to get data by calling a web service, and for that I'm using an Async task class.
I want to use an “animated circle” while loading stuff (complete async task process). It will be really helpful if anyone can give me some idea how to do it.
I was looking at this answer by DBragion in Animated loading image in picasso, but doesn't explain exactly where to use those in the project.
Activity.java
new AddressAsyncTask(getBaseContext(), new OnTaskCompletedObject() {
#Override
public void onTaskCompletedObject(JSONObject responseJson) {
Constants.dataAddress = responseJson.toString();
loaddata();
}
}).execute(email);
OnTaskCompletedObject.java
public interface OnTaskCompletedObject {
void onTaskCompletedObject(JSONObject responseJson);
}
AddressAsyncTask.java
public class AddressAsyncTask extends AsyncTask<String, Integer, JSONObject> {
private OnTaskCompletedObject listener;
private JSONObject responseJson = null;
private Context contxt;
private Activity activity;
String email;
public AddressAsyncTask(Context context, OnTaskCompletedObject onTaskCompletedObject) {
this.contxt = context;
this.listener=onTaskCompletedObject;
}
// async task to accept string array from context array
#Override
protected JSONObject doInBackground(String... params) {
String path = null;
String response = null;
HashMap<String, String> request = null;
JSONObject requestJson = null;
DefaultHttpClient httpClient = null;
HttpPost httpPost = null;
StringEntity requestString = null;
ResponseHandler<String> responseHandler = null;
// get the email and password
Log.i("Email", params[0]);
try {
path = "http://xxxxxxxxxxxxxxxxx/MemberDetails";
new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
// set the API request
request = new HashMap<String, String>();
request.put(new String("Email"), params[0]);
request.entrySet().iterator();
// Store locations in JSON
requestJson = new JSONObject(request);
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(path);
requestString = new StringEntity(requestJson.toString());
// sets the post request as the resulting string
httpPost.setEntity(requestString);
httpPost.setHeader("Content-type", "application/json");
// Handles the response
responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
responseJson = new JSONObject(response);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
responseJson = new JSONObject(response);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return responseJson;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
listener.onTaskCompletedObject(responseJson);
}
}
Show Progress Dialog in the onpreExecute method of AsyncTask and dismiss the dialog in Post Execute.I hope that gets your problem solved

What is best way to pass JSON data one Fragment to another Fragment

I have two fragments in site my first fragment call AsyncTask and get some json values.and then i want to pass my JSON values to my second Fragment's TextViews.What is the best way pass json value between fragments?
this is my AsyncTask in Fragment 1
class LoadingAccountEntry extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... args) {
String response;
Map<String, Object> data = new LinkedHashMap<String, Object>();
data.put(SESSION, sessionId);
data.put(MODULE_NAME, module_name);
data.put(ID, entry_id != null ? entry_id : "");
data.put(
SELECT_FIELDS,
(selectFields != null && selectFields.length != 0) ? new JSONArray(
Arrays.asList(selectFields)) : "");
try {
JSONArray nameValueArray = new JSONArray();
if (linkNameToFieldsArray != null
&& linkNameToFieldsArray.size() != 0) {
for (Entry<String, List<String>> entry : linkNameToFieldsArray
.entrySet()) {
JSONObject nameValue = new JSONObject();
nameValue.put("name", entry.getKey());
nameValue.put("value", new JSONArray(entry.getValue()));
nameValueArray.put(nameValue);
}
}
data.put(LINK_NAME_TO_FIELDS_ARRAY, nameValueArray);
String restData = org.json.simple.JSONValue.toJSONString(data);
HttpClient httpClient = new DefaultHttpClient();
HttpPost req = new HttpPost(restURL);
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair(METHOD, GET_ENTRY));
nameValuePairs.add(new BasicNameValuePair(INPUT_TYPE, JSON));
nameValuePairs.add(new BasicNameValuePair(RESPONSE_TYPE, JSON));
nameValuePairs.add(new BasicNameValuePair(REST_DATA, restData));
req.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Send POST request
httpClient.getParams().setBooleanParameter(
CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
HttpResponse res = httpClient.execute(req);
response = EntityUtils.toString(res.getEntity());
// Log.d("Responce", response.toString());
if (response == null) {
Log.e("Error !", "faild to connect !");
}
JSONObject responseObj = new JSONObject(response);
JSONArray jArray = responseObj.getJSONArray(ENTRY_LIST);
for (int i = 0; i < jArray.length(); i++) {
JSONObject obj = jArray.getJSONObject(i);
// Log.d("obj", obj.toString());
// JSONObject objName = new JSONObject("name");
id = obj.getString("id");
Log.d("id", id);
JSONObject name_value_list = obj
.getJSONObject("name_value_list");
JSONObject assignedUserName = name_value_list
.getJSONObject("assigned_user_name");
assigned_user_name = assignedUserName.getString("value");
Log.d("assigned_user_name", assigned_user_name);
JSONObject modifiedByName = name_value_list
.getJSONObject("modified_by_name");
modified_by_name = modifiedByName.getString("value");
Log.d("modified_by_name", modified_by_name);
}
} catch (JSONException e) {
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
}
This Fragment 2
public class Fragment_account_details extends Fragment {
TextView name, officePhone,fax;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_account_details, container,false);
name = (TextView) rootView.findViewById(R.id.text_name);
fax = (TextView) rootView.findViewById(R.id.text_fax);
return rootView;
}
You can use bundle to pass data to Fragment_account_details like this :
Fragment fragment = new Fragment_account_details();
Bundle bundle = new Bundle();
bundle.putString("name", name);
fragment.setArguments(bundle);
now in your Fragment_account_details onCreateView do like :
String name= getArguments().getString("name");
like this you can pass values.hope this helps.

How to send JSON string to ASP.NET C#-based web server from Android?

I cannot post or send my JSON string t ASP.NET C# based web server from android.
Here is my code, I have retrieve data from SQLite database using cursor and which I have converted these data into JSONobject and then JSONstring.
Code are given below:
protected Boolean doInBackground(final String... args) {
try {
JSONObject parrent = new JSONObject();
// JSONObject jMainObject = new JSONObject();
JSONArray jArray = new JSONArray();
Cursor Online = MainActivity.mydb.rawQuery("select * from myTable", null);
while (Online.moveToNext()) {
JSONObject jObject = new JSONObject();
jObject.put("CategoryType", Online.getString(0));
jObject.put("CategoryID", Online.getString(1));
jObject.put("CategoryName", Online.getString(2));
jObject.put("CustomerId", Online.getString(3));
jObject.put("CustomerName", Online.getString(4));
jObject.put("Accountno", Online.getString(5));
jObject.put("Balance", Online.getString(6));
jObject.put("Installment", Online.getString(7));
jObject.put("Amount", Online.getString(8));
jObject.put("Collected", Online.getString(9));
jObject.put("Dueinstnum", Online.getString(10));
jObject.put("customer_id", Online.getString(11));
jObject.put("dueInstNum", Online.getString(12));
jObject.put("account_id", Online.getString(13));
jObject.put("branch_id", Online.getString(14));
jObject.put("customer_id", Online.getString(15));
jObject.put("id", Online.getString(16));
jArray.put(jObject);
// String JSONString = jObject.toString();
}
parrent.put("FildCollections", jArray);
parrent.put("ProgramOrganizerId","70cff4d5-cc0f-4bf8-80de-23dd82d90719");
parrent.put("BranchId", "bde14105-4617-4d07-9ab8-a95e98f8c5a5");
parrent.put("Password", "Pass#123");
parrent.put("UserId", "5103");
But now after that very next line I want to send this JSONstring to C# web Server
Code:
HttpPost httppost = new HttpPost("Posting url");
StringEntity entity = new StringEntity(parrent.toString(),
"UTF-8");
entity.setContentType("application/json;charset=UTF-8");// text/plain;charset=UTF-8
entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json;charset=UTF-8"));
httppost.addHeader("language", "en");
httppost.addHeader("Content-Type", "application/json");
httppost.addHeader("user_Id", "5103");
httppost.addHeader("user_Pass", "Pass#123");
httppost.setEntity(entity);
// Send request to WCF service
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(httppost);
return true;
}
I have call my function from sub menu like this:
calling Function code:
case R.id.submenu1_1:
if (item.isChecked())
item.setChecked(false);
else {
item.setChecked(true);
// Export Online
try {
new ExportDatabaseOnline().execute();
} catch (Exception ex) {
Log.e("Error in ActivityB", ex.toString());
}
}
// Toast.makeText(this, "Clicked: Menu No. 2 - SubMenu No .1",
// Toast.LENGTH_SHORT).show();
return true;
Now the full function code which I have told you earlier in partial. So my full function code is:
public class ExportDatabaseOnline extends AsyncTask<String, Void, Boolean> {
private final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
// private HttpResponse response;
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please wait...");
this.dialog.setTitle("Exporting Database To Online");
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
try {
JSONObject parrent = new JSONObject();
// JSONObject jMainObject = new JSONObject();
JSONArray jArray = new JSONArray();
Cursor Online = MainActivity.mydb.rawQuery("select * from myTable", null);
while (Online.moveToNext()) {
JSONObject jObject = new JSONObject();
jObject.put("CategoryType", Online.getString(0));
jObject.put("CategoryID", Online.getString(1));
jObject.put("CategoryName", Online.getString(2));
jObject.put("CustomerId", Online.getString(3));
jObject.put("CustomerName", Online.getString(4));
jObject.put("Accountno", Online.getString(5));
jObject.put("Balance", Online.getString(6));
jObject.put("Installment", Online.getString(7));
jObject.put("Amount", Online.getString(8));
jObject.put("Collected", Online.getString(9));
jObject.put("Dueinstnum", Online.getString(10));
jObject.put("customer_id", Online.getString(11));
jObject.put("dueInstNum", Online.getString(12));
jObject.put("account_id", Online.getString(13));
jObject.put("branch_id", Online.getString(14));
jObject.put("customer_id", Online.getString(15));
jObject.put("id", Online.getString(16));
jArray.put(jObject);
// String JSONString = jObject.toString();
}
parrent.put("FildCollections", jArray);
parrent.put("ProgramOrganizerId","70cff4d5-cc0f-4bf8-80de-23dd82d90719");
parrent.put("BranchId", "bde14105-4617-4d07-9ab8-a95e98f8c5a5");
parrent.put("Password", "Pass#123");
parrent.put("UserId", "5103");
HttpPost httppost = new HttpPost("Posting url");
StringEntity entity = new StringEntity(parrent.toString(),"UTF-8");
entity.setContentType("application/json;charset=UTF-8");//text/plain;charset=UTF-8
entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
httppost.addHeader("language", "en");
httppost.addHeader("Content-Type", "application/json");
httppost.addHeader("user_Id", "5103");
httppost.addHeader("user_Pass", "Pass#123");
httppost.setEntity(entity);
// Send request to WCF service
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(httppost);
return true;
} catch (Exception e) {
Log.e("ActivityB", e.getMessage(), e);
return false;
}
}
protected void onPostExecute(final Boolean success) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
if (success) {
Toast.makeText(MainActivity.this, "Export successful!",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Export failed",
Toast.LENGTH_SHORT).show();
}
}
}
This code is not working, it shows successful message but doesn't post any JSON string to the website.

send JSON to server via HTTP put request in android

How to wrap given json to string and send it to server via Http put request in android?
This is how my json look like.
{
"version": "1.0.0",
"datastreams": [
{
"id": "example",
"current_value": "333"
},
{
"id": "key",
"current_value": "value"
},
{
"id": "datastream",
"current_value": "1337"
}
]
}
above is my json array.
below is how I wrote the code but, its not working
protected String doInBackground(Void... params) {
String text = null;
try {
JSONObject child1 = new JSONObject();
try{
child1.put("id", "LED");
child1.put("current_value", "0");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray();
jsonArray.put(child1);
JSONObject datastreams = new JSONObject();
datastreams.put("datastreams", jsonArray);
JSONObject version = new JSONObject();
version.put("version", "1.0.0");
version.put("version", datastreams);
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPut put = new HttpPut("url");
put.addHeader("X-Apikey","");
StringEntity se = new StringEntity( version.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
put.addHeader("Accept", "application/json");
put.addHeader("Content-type", "application/json");
put.setEntity(se);
try{
HttpResponse response = httpClient.execute(put, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
}
catch (Exception e) {
return e.getLocalizedMessage();
}
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return text;
}
please help on this
this is one sample.
JSONObject Parent = new JSONObject();
JSONArray array = new JSONArray();
for (int i = 0 ; i < datastreamList.size() ; i++)
{
JSONObject jsonObj = new JSONObject();
jsonObj.put("id", datastreamList.get(i).GetId());
jsonObj.put("current_value", datastreamList.get(i).GetCurrentValue());
array.put(jsonObj);
}
Parent.put("datastreams", array);
Parent.put("version", version);
and for sending that:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
StringEntity se = new StringEntity( Parent.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
post.setEntity(se);
client.execute(post);
EDIT
in this sample datastreamList that used in for statement is a list that you must have for all value that want send to server ( one list of one class that have 2 property , id and value ), actually i think you have two class like bellow:
class A {
List<Datastreams> datastreamList
String version;
//get
//set
}
class Datastreams {
String id;
String current_value; // or int
//get
//set
}
and in your code you must have one object of A class that want send to server, so you can use first part to map your object to json.
If you prefer to use a library then I'll prefer you to use Ion Library by Kaush.
Form this library you can simply post your JSON like this :
JsonObject json = new JsonObject();
json.addProperty("foo", "bar");
Ion.with(context, "http://example.com/post")
.setJsonObjectBody(json)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception e, JsonObject result) {
// do stuff with the result or error
}
});
Just you have to send as a String so store following JSON data in String
{
"version": "1.0.0",
"datastreams": [
{
"id": "example",
"current_value": "333"
},
{
"id": "key",
"current_value": "value"
},
{
"id": "datastream",
"current_value": "1337"
}
]
}
then you have to send like:
pairs.add(new BasicNameValuePair("data", finalJsonObject.toString()));
The '{' bracket represent a object and '[' represent an array or list. In your case create a bean
YourObj{
private String version;
private List<DataStream> datastreams;
//getters
//setters
}
DataStream{
private String id;
private String current_value;
//getters
//setters
}
use org.codehaus.jackson:jackson-xc jar for json parssing
use ObjectMapper
String to Object
YourObj obj = new ObjectMapper().readValue(stringyouwanttopass,new TypeReference<YourObj>(){});
now you can use the parsed value.
or you can set the values to the YourObj
YourObj obj =new YourObj();
obj.setVersion(1.0.0);
List<Datastream> datastreams=new ArrayList<Datastream>();
Datastream datestr=new Datastream();
datestr.setId("example");
datestr.setCurrent_value("333");
datastreams.add(datestr);
datestr.setId("key");
datestr.setCurrent_value("value");
datastreams.add(datestr);
datestr.setId("datastream");
datestr.setCurrent_value("1337");
datastreams.add(datestr);
JSONObject jsonget = new JSONObject(appObject);
jsonget.toString();
Connecting server using Jersey
Client client = Client.create();
WebResource webResource = client.resource("serverURl");
ClientResponse response = webResource.path("somePath")
.type("application/json").accept("application/json")
.post(ClientResponse.class, jsonget.toString());
in the server side get it as string and parse it.
here is a android Client library can help you:
Httpzoid - Android REST (JSON) Client,it has some examples and you can do put post,get request easily.
https://github.com/kodart/Httpzoid

jsonexception of type org.json.JSONObject cannot be converted to JSONArray

I'm trying to read a JSON string from a webpage but get the error jsonexception of type org.json.JSONObject cannot be converted to JSONArray.
final static String URL = "http://www2.park.se/~ts5124/";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = (TextView)findViewById(R.id.text1);
client = new DefaultHttpClient();
new Read().execute("JSON");
if (logged=="yes") {
setContentView(R.layout.main);
} else {
setContentView(R.layout.login);
b1 = (Button)findViewById(R.id.btn);
name = (EditText)findViewById(R.id.name);
pass = (EditText)findViewById(R.id.password);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
JSONObject json = new JSONObject();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www2.park.se/~ts5124/login.php");
json.put("userName", name.getText().toString());
json.put("password", pass.getText().toString());
StringEntity se;
se = new StringEntity(json.toString(), "UTF-8");
// Add your data
httppost.setEntity(se);
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
Log.i(TAG, json.toString());
// Execute HTTP Post Request
httpclient.execute(httppost);
} catch (JSONException je) {
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
});
}
}
public JSONObject getData(String page) throws ClientProtocolException, IOException, JSONException {
StringBuilder url = new StringBuilder(URL);
url.append(page);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
} else {
Log.i("JSON","Ain't workin'");
return null;
}
}
public class Read extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
try {
json = getData("send.php");
return json.getString(params[0]);
} catch (ClientProtocolException e) {
return e.toString();
} catch (IOException e) {
return e.toString();
} catch (JSONException e) {
return e.toString();
}
}
#Override
protected void onPostExecute(String result) {
tv.setText(result);
}
}
http://pastebin.com/dUnmsEd6 I get this in the logcat and when i debug it says: jsonexception of type org.json.JSONObject cannot be converted to JSONArray
try doing:
JSONArray timeline = new JSONArray(data);
String s = timeline.get(0).toString();
JSONObject last = new JSONObject(s);
pay attention also if the JSON String has only one element in the array. If you want post the JSON String response from the server to analyse.
try using the onProgressUpdate:
protected void onProgressUpdate(String... result){
tv.setText(result[0]);
}
and int the doInBackground call in the end:
publishProgress(json.getString("JSON"));
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(uri.toString());
try {
//Obter objeto JSON
clientesJSONArray = json.optJSONArray(Clientes.TABELA);
//Se for 1 objeto não virá em JSONArray - Os objetos em JSON são separados
//por colchetes [] - No caso de um objeto, não será array e sim um simples
//objeto em JSON
if(clientesJSONArray==null){
// means item is JSONObject instead of JSONArray
//json = obj.optJSONObject("offerRideResult");
JSONObject obj = json.getJSONObject(Clientes.TABELA);
Clientes oCliente = new Clientes();
oCliente.setCliente(obj.getString(Clientes.CLIENTE));
oCliente.setCod_cliente(obj.getInt(Clientes.COD_CLIENTE));
oCliente.setE_mail(obj.getString(Clientes.E_MAIL));
oCliente.setUsuario(obj.getString(Clientes.USUARIO));
oCliente.setUsuario(obj.getString(Clientes.SENHA));
clientesList.add(oCliente);
}else{
// Mais de um objeto JSON separado por colchetes [] - JSONArray ao invés JSONObject
for (int i = 0; i < clientesJSONArray.length(); i++) {
JSONObject obj = clientesJSONArray.getJSONObject(i);
Clientes oCliente = new Clientes();
oCliente.setCliente(obj.getString(Clientes.CLIENTE));
oCliente.setCod_cliente(obj.getInt(Clientes.COD_CLIENTE));
oCliente.setE_mail(obj.getString(Clientes.E_MAIL));
oCliente.setUsuario(obj.getString(Clientes.USUARIO));
oCliente.setUsuario(obj.getString(Clientes.SENHA));
clientesList.add(oCliente);
}
}

Categories

Resources