pass arraylist bean from android to webservice php
try this code
JSONParser.java
public class JSONParser
{
static InputStream is ;
static JSONObject jObj = null;
static String json = "";
String Dataurl = "";
// constructor
public JSONParser(String url)
{
Dataurl = url;
}
// function get json from url by making HTTP POST or GET method
public JSONObject makeHttpRequestResponse(String method,List<NameValuePair> Data_Request_Response)
{
try {
// check for request method
if(method == "POST_Request_Response")
{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(Dataurl);
httpPost.setEntity(new UrlEncodedFormEntity(Data_Request_Response));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
else if(method == "GET_Request_Response")
{
HttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(Data_Request_Response, "utf-8");
Dataurl += "?" + paramString;
HttpGet httpGet = new HttpGet(Dataurl);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
json = sb.toString();
}
catch (Exception e)
{
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try
{
jObj = new JSONObject(json);
}
catch (JSONException e)
{
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}// End Http Request Response
}
Yourfilename.java
// Object of the Json Parser Class
JSONParser mJsonParser = new JSONParser(DataUrl);
JSONObject mJsonObject_Request = new JSONObject();
List<NameValuePair> Send_Request = new ArrayList<NameValuePair>();
Send_Request.add(new BasicNameValuePair("Token", "Data"));
Send_Request.add(new BasicNameValuePair("Token1","Data"));
try {
mJsonObject_Request = mJsonParser.makeHttpRequestResponse("POST_Request_Response",Request);
Log.d("No Of Tables", "" + mJsonObject_Request.names().length());
Log.d("Name Of Tables", "" + mJsonObject_Request.names());
Log.d("DATA", "" + mJsonObject_Request);
}
catch (Exception e) {
}
here data URL is your web service link.
POST array list from android application to php page
Try like this.
Map<String,Object> productimages = new HashMap<String, Object>();
List<String> datas = new ArrayList<String>();
datas.add("image");
datas.add("small_image");
datas.add("thumbnail");
productimages.put("types",datas);
If your using nemevalue pair use like this.
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("colors[]","red"));
nameValuePairs.add(new BasicNameValuePair("colors[]","white"));
nameValuePairs.add(new BasicNameValuePair("colors[]","black"));
nameValuePairs.add(new BasicNameValuePair("colors[]","green"));
How to send Arraylist of class in POST method of WCF webservice from android
use jackson library to create json string from array list of class object and after that send it. I have done successfully with this.
public String sendArrayListOfuserclass() {
String request_string = null;
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
HttpResponse response;
try {
HttpPost post = new HttpPost(
ServiceConstant.ALL_PERSON_UPDATE_DETAIL_URL);
post.setHeader("Content-type", "application/x-www-form-urlencoded");
DatabaseHelper mDatabaseHelper = DatabaseHelper
.getInstance(sContext);
List<PersonInformationBean> allPersonDetailList = mDatabaseHelper
.getAllPersonDetail();
List<ActivationBean2> PersonRequest = new ArrayList<ActivationBean2>();
int size = allPersonDetailList.size();
if (size > 0) {
for (PersonInformationBean personInformationBean : allPersonDetailList) {
ActivationBean2 personactivationdata = new ActivationBean2();
try {
personactivationdata.setPersonID(personInformationBean
.getPersonId());
personactivationdata
.setActivationKey(personInformationBean
.getActivationKey());
} catch (Exception e) {
}
PersonRequest.add(personactivationdata);
}
}
RefreshPersonBean personwithdeviceid = new RefreshPersonBean();
personwithdeviceid.setPersonRequest(PersonRequest);
personwithdeviceid.setDeviceID(MyPreferences.getInstance(sContext)
.getDeviceId());
request_string = convertBeanToJson(personwithdeviceid);
request_string = request_string.replace("\\", "")
.replace("\"[", "[").replace("]\"", "]");
request_string = request_string.replace("\n", "").replace("\r", "");
Log.e("referesh person request", request_string);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair(
ServiceConstant.RequestData, request_string));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
// post.setEntity(new ByteArrayEntity(json.toString().getBytes()));
response = client.execute(post);
/* Checking response */
if (response != null) {
InputStream inputStream = response.getEntity().getContent(); // Get
request_string = convertStreamToString(inputStream);
Log.e("response",
"response of post = " + request_string.toString());
return request_string;
}
} catch (IOException e) {
request_string = "timeout";
e.printStackTrace();
} catch (Exception e) {
// Toast.makeText(sContext, "Server Error",
// Toast.LENGTH_LONG).show();
e.printStackTrace();
}
return request_string;
}
this is jackson library function:
private String convertBeanToJson(RefreshPersonBean bean) {
String reqQuery = null;
try {
reqQuery = mapperObj.writeValueAsString(bean);
Log.d("convertBeanToJson(): request query is:", reqQuery);
} catch (JsonGenerationException e) {
Log.e("convertBeanToJson():", " caught JsonGenerationException");
} catch (JsonMappingException e) {
// mELogger.error("convertBeanToJson(): caught JsonMappingException");
} catch (IOException e) {
Log.e("convertBeanToJson():", " caught IOException");
}
return reqQuery;
}//
library name jackson-all-1.6.2
Getting MultiDimensional Array from JSONArray(PHP to ANDROID)
String s = "[{\"index\":1,\"questions\":\"If the number of berths in a train are 900 more than one-fifth of it, find the total berths in the train?\",\"options\":[\"1145\",\"1130\",\"1135\",\"1125\",\"1120\"],\"answers\":\"1125\",\"useranswers\":\"1145\"}]";
try {
JSONArray a;
a = new JSONArray(s);
JSONObject o = (JSONObject) a.get(0);
JSONArray options = o.getJSONArray("options");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
How to populate ArrayList after getting it from the webservice in Android
Your method should be declared as private ArrayList<?> callWebService()
and you should return your arrayList from that method when you are done.
Also as mentioned above you should check if your result object is returned as Vector
. If it is returned as Vector modify it to ArrayList.
Finally, in the doInBackround
of your AsyncTask you should change your return null
code to return callWebService();
since your callWebService()
method will return the result ArrayList with the above modification. Then in your onPostExecute(ArrayList<?> result)
the result variable will not be null but will have the result ArrayList from your webservice.
So with the bove modifications you will have something like this:
private ArrayList<?> callWebService() {
...
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);
envelope.dotNet = false;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION,envelope);
result = envelope.getResponse();
if (result instanceof ArrayList<?>) {
ArrayList<?> weatherList = (ArrayList<?>)result;
for (int i=0; i<weatherList.size(); i++)
Object weekDay = weatherList.get(i);
System.out.println();
}
} else {
}
return result;
} catch (SocketTimeoutException e) {
Toast.makeText(mainActivity, "Service is not connected, Please make sure your server is running", Toast.LENGTH_LONG).show();
} catch(Exception e) {
e.printStackTrace();
}
} //end of callWebService()
The AsyncTask:
public class MyTask extends AsyncTask<Void, Void, ArrayList<?>> {
ProgressDialog dialog = null;
Object result = null;
MainActivity mainActivity;
public MyTask(MainActivity mainActivity) {
this.mainActivity = mainActivity ;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if (dialog == null) {
dialog = new ProgressDialog(mainActivity);
}
dialog.setMessage("Please Wait. Your authentication is in progress");
dialog.show();
} //end of onPreExecute()
@Override
protected ArrayList<?> doInBackground(Void... params) {
return callWebService();
} //end of doInBackground()
@Override
protected void onPostExecute(ArrayList<?> result) {
super.onPostExecute(result);
dialog.dismiss();
} //end of onPostExecute()
} //end of class MyTask
You can change your Vector to Array list with something like this:
ArrayList<WeekDays> arraylist = new ArrayList<WeekDays>();
Collectios.copy(arraylist, vector_containing_the_data);
Edit(Basit)
---------------------------------------------------------------
@Override
protected void onPostExecute(Vector<?> result) {
super.onPostExecute(result);
if (result != null) {
for (int i=0; i<result.size(); i++) {
Object weekDay = result.get(i);
if (weekDay instanceof SoapObject) {
SoapObject weekDayObject = (SoapObject)weekDay;
String objectName = weekDayObject.getName(); //WeekDays
String dayName = weekDayObject.getProperty("name").toString();
String weather = weekDayObject.getProperty("weather").toString();
String temp = weekDayObject.getProperty("temperature").toString();
} //end of if (weekDay instanceof SoapObject)
} //end of for (int i=0; i<result.size();...)
} //end of if (result != null)
dialog.dismiss();
} //end of onPostExecute()
But i think this should be done in the doBackGround() method and after populating the values in the bean. Then i should use that bean in my onPostExecute() method, to update the UIThread. But this code is working fine for me.
Related Topics
Using PHP to Execute Multiple MySQL Queries
Prevent Nginx 504 Gateway Timeout Using PHP Set_Time_Limit()
PHP - Get Numeric Index of Associative Array
Is It Recommended to Store PHP Sessions in Memcache
How to Set Up Entity (Doctrine) for Database View in Symfony 2
How to Test If a User Has Selected a File to Upload
Http_Build_Query with Same Name Parameters
How to Create a Subquery Using Laravel Eloquent
"PHP Fatal Error: Class 'Httprequest' Not Found"
Which Is the Best Way to Generate Excel Output in PHP
How to Get All Combinations from Multiple Arrays
What Is an Abstract Class in PHP
Proper Url Forming with a Query String and an Anchor Hashtag
Save PHP Variables to a Text File
Download CSV File Using "Ajax"
Is HTMLentities() Sufficient for Creating Xml-Safe Values