I'm doing an app that interacts with a mysql database with some php scripts. I would like to know if it is possible to send and array in a php POST from an android activity ?
This is th code I'm using for the moment :
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("userID", String.valueOf(userID)));
but I think sending and array would be much better than sending one ID at a time.
I would generate a JSON/XML document. You can easily generate especially JSON objects in Android platform.
There are many examples about generating JSON in Android and reading/parsing JSON in PHP.
Hope this helps.
I saw a part of the solution in here :
enter link description here
In his example he simply does a for loop like this :
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//friendID is an array of friends ID
for (int i=0;i<friendID.length;i++){
nameValuePairs.add(new BasicNameValuePair("userAsked[]", String.valueOf(friendID[i])));
}
The thing is : how do I use it in my php file ? Is it as simple as that :
$asked[] = $_POST['userAsked[]'];
Seems a little bit too easy :s
Related
I need to post data to webservice where I need to send a parameter along with JSON object in android . Is it possible to send both parameter and JSON object while posting data ?
My code is as folows:
nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("token", "abc.org"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpPost.setEntity(JSON.toString);
Thanks in Advance
You can't call setEntity() twice like this. If your server is expecting POST content that is form-encoded, then you'll need to add your JSON object as one of the POST parameters. If your server is expecting the JSON object as the POST body, then it can't also be expecting any other parameters (this wouldn't be possible). It may be possible that it expects additional parameters in the query string part of the URL though. Check the API documentation of your server.
I am new t ajax, but quite familiar with android. I am converting a ajax program to android app. As a part of it, i need to post data to the server. Below is the given post command in ajax.
var postTo = 'xyz.php';
$.post(postTo,{employee_name: $('[name=employee_name]').val() , phone: $('[name=phone]').val(), employee_type: 'guest' } ,
function(data) {
if(data.success){
window.localStorage["sa_id"] = data.mid;
window.location="getempdb.html";
}
if(data.message) {
$('#output').html(data.message);
} else {
$('#output').html('Could not connect');
}
},'json');
I want to implement this in android but under very little from the above statements. Could anyone who is good at ajax help me out with this thing. As of now, i get the user name and telephone number as a edit text input. I need to send this to php using http client. I know how to send data using php, but do not know what format to send and whether its a string to send or as a json object to send. Please help in interpreting the above code and oblige.
Apparently, this uses UrlEncodedFormEntity if you are using HttpClient in android.
This is created by using a List of NameValuePair.
from the parameters to the $.post:
{employee_name: $('[name=employee_name]').val() , phone: $('[name=phone]').val(), employee_type: 'guest' }
You have to create a NameValuePair for employee_name, one for phone ... each of which is fetched from a HTML element name employee_name, phone ... This is where you put the values from your EditTexts.
It returns a JSON formatted String, which you have to parse (typically using JSONObject obj = new JSONObject(result); once you have fetched the result from the server)
In this JSON object, you have a key named success, which format is not specified, except you can assume things went well if it is present ; a key mid, and a key message.
Hello i am new to android , i am trying to send array of string ( contain episode Titles) to server with just 1 key ( which will be called items ) ,i tried to use
nameValuePairs.add(new BasicNameValuePair("items", "EpTitle1"));
but it takes just 1 key for 1 value string not array of string , i want that value to be array ,i found sending php array with POST android ,but in his example b.toString(); only send className not my array . any hint will be appreciated .Thanks
Just a wild guess: Does this work (assuming arrayOfValues is a String array containing your items)?
for(String value: arrayOfValues){
nameValuePairs.add(new BasicNameValuePair("items[]",value));
}
This is the way you would send an array of data in HTML to a PHP-server.
Seemingly simple question, but no obvious answer found online.
At this link, there is a tutorial on posting simple name value pairs to a file from within an android app. http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient
What I want to do is post 'something' which on the receiving end (a php script) can be accessed as an array.
In PHP I want to receive:
$_POST['array']=array("key"=>"value","key2"=>"value2");
Being relatively new to android development, perhaps someone could elaborate on creating a similar thing in Java, and then how one cant send it - setEntity seems to only take namevaluepairs...
Many Thanks
You should use a JSON Wrapper both in Android App and your PHP server.
In PHP you should use json_decode(), like: $thingFromPost = json_decode($data).
In Java, there are many ways to create a JSONArray. A basic example would be:
List<String> list = new ArrayList<String>();
list.add("foo");
list.add("bar");
JSONArray jsonArray = new JSONArray(list);
And after that, you just send your array with a HttpPost to your server.
StringEntity stringEntity = new StringEntity(jsonArray.toString());
stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING, "UTF-8"));
stringEntity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
HttpPost post = new HttpPost(url);
post.setEntity(stringEntity);
post.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
If you need a detailed tutorial how to make requests using JSON in Android, follow this link.
Hope it helps!
If you want the entire, raw body of your POST to be the stringified array (and nothing else), I believe you should use a StringEntity instead of a UrlEncodedFormEntity.
So this:
String s = "asdf"; // replace this with your JSON string
StringEntity stringEntity = new StringEntity(s);
httpPost.setEntity(stringEntity);
I am not familiar with PHP, but conceptually on the receiving end you'll then do something like json.parse(request.full_body). Note that this (request.full_body or the equivalent) is very different from the common pattern of fetching a single value of the POST form like request['input_field1'].
However, reading your question I'm not entirely sure that this full_body approach is what you want. It looks to me like you want to access the data via the form variable 'array', as you indicate here:
$_POST['array']=array("key"=>"value","key2"=>"value2");
Note that you are not working with the entire POST body here, rather instead you are fetching the value of a single form variable called 'array' (I think, I don't really know PHP). If this is the case, then you should use NameValuePairs like something below:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("array", yourJSONArrayAsString));
This will post the array as a value associated with the form variable 'array' I believe.
I am implementing an android app in which I want to use some methods from a server (which was not implemented by me). Now when I try to make an http-post where I have to pass only String parameters everything works fine with a code like:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user[email]", email));
nameValuePairs.add(new BasicNameValuePair("user[password]", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler=new BasicResponseHandler();
String responseBody = httpclient.execute(httppost, responseHandler);
JSONObject response=new JSONObject(responseBody);
System.out.println("RESPONSE " + response.toString());
I get the response as a json object which I can easily use to take the attributes I wish.
Now there are methods that require non String values (integer, or boolean) as parameters. I cannot pass these arguments in a list such as List<NameValuePair> since this takes only Strings. I tried to pass it as a json object too but no success.
So my first question is if it is possible to have non String parameters in http post? And if yes, how should it be done? Eg if in the code above email was an integer and password a Boolean (in shake of the example), how should I handle them?
Thank you all in advance!
Sure, consider a file upload.
The file is binary (ok, consider uploading a picture if someone consider a text not to be binary enough)
the technique is a http-post
All http request parameters will come in as strings, but the server side code can convert them. The server could for example grab a JSON string from a request parameter and turn it into an object that contains any amount of serialized data. This could include integers, lists etc.
The implementation though will be dependent on that server side code. Both the client and server for example could use GSON to send objects and lists back and forth.
public void doPost(...)
{
String param = request.getParameter("someParam");
MyCustomObject myCustomObject = (MyCustomObject)gson.fromJson(param, MyCustomObject.class);
}