I am new to android and got entangle in problem. what i want is to pass an array object or say an arraylist to a php page so that the same can be inserted into the mysql database.To be more precise i would like to develop an app to sync my contacts with phone numbers to my own server.
thanks in advance.
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"));
You should be using an API for ex.Rest API. This API will grant the information from your app by an POST action (from you're android app). (transfer data-objects like an array with JSON) Php can decode the JSON and you analyze you're array in php. You can now send specific data into your tables using MYSQL, PDO,..
If the data you transfer needs to be protected, you should use SSL encryption on you're api acces url
Try this
ArrayList <NameValuePair> postparametersSend = new ArrayList <NameValuePair> ();
//This is your file php
String URL = "www.yourserver.com/file.php";
postparameters2send.add (new BasicNameValuePair ("param1", nameParam1));
postparameters2send.add (new BasicNameValuePair ("param2", nameParam2));
postparameters2send.add (new BasicNameValuePair ("param3", nameParam3));
// perform a request and response obtenes JSON array
JSONArray jdata = con.getserverdata (postparametersSend, URL);
//since we are working locally on return will almost immediately
//To give a little realism we say that the process is stopped for a few seconds to
//Observe progressdialog
// We can remove if we
// if what we got is not null
if (jdata! = null && jdata.length ()> 0) {
JSONObject json_data; // create a JSON object
try {
jdata.getJSONObject json_data = (0); // read the first segment in our case the only
System.out.println (json_data);
logstatus = json_data.getInt ("logstatus"); // access the value
Log.e ("LoginStatus", "logstatus =" + logstatus) // show by log we obtained
} Catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace ();
}
// validate the value obtained
if (logstatus == 0) {// [{"logstatus": "0"}]
Log.e ("logStatus", "invalid");
return false;
}
else {// [{"logstatus": "1"}]
Log.e ("logStatus", "valid");
return true;
}
//} else {invalid json obtained WEB verify part.
Log.e ("JSON", "ERROR");
return false;
}
To make the variables you should put this in the php file
<? php
$nameParam1 = $_POST ["nameParam1"];
$nameParam2 = $_POST ["nameParam2"];
$nameParam3 = $_POST ["nameParam3"];
<- Put your code here ->
?>
Related
I have existing PHP that accepts arrays as parameters. This is currently being invoked from javascript and the javascript array is being set directly as part of the data object sent through AJAX call to the php.
Now, I want to send an array from an Android app and I don't want to change the existing php and javascript. I have looked for an answer, but don't see anything, other than the suggestion to encode the array as JSON and decode it in the php, but that will require lots of changes everywhere, including the javascript. It appears the javascript and the php are made to just work. Maybe something is done automatically to the array?
The PHP looks like this:
foreach($_POST as $key => $value) {
if (is_array($_POST[$key])){
for ($index = 0; $index < count($_POST[$key]); $index++){
if(ini_get('magic_quotes_gpc'))
$_POST[$key][$index] = stripslashes($_POST[$key][$index]);
$_POST[$key][$index] = htmlspecialchars(strip_tags($_POST[$key][$index]));
}
}
else {
if(ini_get('magic_quotes_gpc'))
$_POST[$key] = stripslashes($_POST[$key]);
$_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}
}
So, it is definitely expecting some parameters to be arrays.
The javascript currently does this:
$.ajax({
type: "POST",
url: 'php/getLibraryPatterns.php',
dataType: 'json',
data: data,
and data is a javascript object with arrays contained in it. For example:
var data = {};
if (sortBy.length > 0){
data.sortBy = sortBy;
}
and sortBy is an array in the javascript.
How do I pass an array from the Android app to this php? Currently, all of the parameters for my other calls to php have just been simple strings, so I use the following function to put all the parameters together in a string and then write that to the OutputStream of my HttpURLConnection. I have that all working, just not sure what to do with the arrays?
private String buildParameterString() throws UnsupportedEncodingException
{
if (m_parameterMap == null) return "";
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<Map.Entry<String, String>> itr = m_parameterMap.entrySet().iterator();
while(itr.hasNext())
{
Map.Entry<String, String> param = itr.next();
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(param.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(param.getValue(), "UTF-8"));
}
return result.toString();
}
I tried creating a JSONArray with the data, then convert to string and set it just like I would set the other strings I am sending. But, this does not appear to work, at least not automagically.
So, I am sending something like "[29]" or "['sortAsc']" as strings in the parameters.
I got back an empty list. I will continue to debug in the php to see what those look like there, but I expect they will be just strings and the php won't know what to do with that.
So, how can I send an array to the php? I don't want to have to change the php, as that means that the javascript then also has to change. Is there any way to do this from a java Android app?
Solution Found!
I found an answer in the JQuery documentation for ajax method. It says there that arrays are encoded like this:
%5B is '['
and %5D is ']'
For example, { a: [1,2] } becomes the string "a%5B%5D=1&a%5B%5D=2" with the default traditional: false setting.
I have encoded my arrays like that in the string that I write to the output stream. From https://api.jquery.com/jQuery.ajax/
Here is the code I am using to create my output stream:
private String buildParameterString() throws UnsupportedEncodingException
{
if (m_parameterMap == null || m_parameterMap.size() == 0) return "";
StringBuilder result = new StringBuilder();
for (int iPair = 0; iPair < m_parameterMap.size(); iPair++)
{
Pair<String, Object> param = m_parameterMap.get(iPair);
if (iPair > 0) result.append("&");
Object value = param.second;
if (value instanceof ArrayList){
for (int i = 0; i < ((ArrayList)value).size(); i++){
Object nextValue = ((ArrayList)value).get(i);
String nextValueStr = "";
if (nextValue instanceof String){
nextValueStr = (String)nextValue;
}
else {
nextValueStr = Integer.toString((Integer)nextValue);
}
if (i > 0) result.append("&");
result.append(URLEncoder.encode(param.first, "UTF-8"));
result.append("%5B%5D=");
result.append(URLEncoder.encode(nextValueStr, "UTF-8"));
}
}
else {
result.append(URLEncoder.encode(param.first, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode((String)value, "UTF-8"));
}
}
return result.toString();
}
m_parameters is an ArrayList of Pair's where Pair is in android.util.
It works, this is the answer. You don't have to encode and decode in JSON string to do this. All the othere answers I have seen for this are just that. There is a way to encode the array into the string output.
Try this:
Outside of while loop:
JSONArray data = new JSONArray();
And put this in while loop:
JSONObject jsonObjSend = new JSONObject();
jsonObjSend.put(param.getKey(), param.getValue());
data.put(jsonObjSend);
From Android, send it as json data
public String convertMapToJson() {
Map<String, String> elements = new HashMap<>();
elements.put("Key1", "Value1");
elements.put("Key2", "Value2");
elements.put("Key3", "Value3");
JSONObject json = new JSONObject(elements);
return json.toString();
}
In server side PHP,
$json = file_get_contents('php://input');
// Converts it into a PHP object
$params = json_decode($json, true);
echo $params["Key1"];
I am trying to communicate to a php server from my gwt project.
I already got a GET request to work, however, my POST request doesn't work so far.
Here's my code:
Button synchronize = new Button("synchronize ",
new ClickHandler() {
public void onClick(ClickEvent event) {
String myurl = URL
.encode("php/test.php");
RequestBuilder builder = new RequestBuilder(
RequestBuilder.POST, myurl);
JSONObject jsonValue = new JSONObject();
jsonValue.put("name", new JSONString("Abc"));
builder.setHeader("Content-Type", "application/json");
try {
Request request = builder.sendRequest(jsonValue.toString(),
new RequestCallback() {
public void onError(Request request,
Throwable exception) {
processResponse("ERROR");
}
public void onResponseReceived(
Request request,
Response response) {
if (200 == response.getStatusCode()) {
processResponse(response
.getText());
} else {
processResponse("ERROR");
}
}
});
} catch (RequestException e) {
processResponse("ERROR");
}
}
});
public void processResponse(String responseString) {
Window.alert(responseString);
}
I can see that the post request goes out and the request payload is a json-object. However, when I try to access the data in the php script, I get the error that the index name is undefined.
Here's the PHP:
<?php
echo $_POST["name"];
?>
Is there something wrong with my PHP?
Does anyone have a working example for this?
While I haven't checked the PHP documentation so far, I tend to remember, that $POST contains the post request's variables, especially useful in a x-www-form-urlencoded request. .. Checked it, yes. I am right :-)
What you actually want is to read the body of the post request and parse it's JSON content to a PHP array or hash.
To read the body see here: How to get body of a POST in php?
$entityBody = file_get_contents('php://input');
Parsing json is described here: Parsing JSON file with PHP
I will not quote the code from there, as it maybe does not exactly fit your needs, but you look for json_decode($json, TRUE).
I have a url site.com/test.php which has the following code
<?php
$num1 = $_REQUEST['num1'] ;
$num2 = $_REQUEST['num2'] ;
$tot = $num1 + $num2 ;
?>
From an android application using POST/GET num1 and num2 parameters are passed to www.site.com/test.php
How can I make the response in such a way that the android application will be able to get the response from this request.
I tried this
header('Content-Type: application/json');
echo json_encode($response);
but all it does is echo it in the web view and im not able to get the response.Is there someway I can get the response as standard json response,which is not displayed but get it as soon as I hit the url as a response ?
** UPDATE **
#Override
public boolean shouldOverrideUrlLoading (WebView view, String url) {
if(flag) {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
// read inputstream to get the json..
...
...
return true;
}
return false
}
#override
public void onPageFinished (WebView view, String url) {
if (url contains "form.html") {
flag = true;
}
}
this is the java code I got from SO , which Im planning to use in the android appication
Seems to be a problem in the handling of the response, not the generation of the JSON. Are you clicking a link to the JSON on a page that is has "form.html" in it? Because that is what seems to be assumed in the code you posted.
It seems to be better to just overload the shouldOverrideUrlLoading and check if the url matches your json page. Something like this:
#Override
public boolean shouldOverrideUrlLoading (WebView view, String url) {
if(url.toLowerCase().contains("www.site.com/test.php")) {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
// read inputstream to get the json..
...
...
return true;
}
return false;
}
It might be a good idea to start an activity and load the JSON in that activity using, for example, an AsyncTask (network operations aren't allowed on the UI thread in the latest android APIs), instead of doing URL.openConnection immediately.
I am writing a Native Android App in which i am using PHP MYSQL to get data from server
In this [Appointment List] i am allowing user to Reschedule an Appointment, but whenever i do tap on item getting blank form, in short not getting data for that particular appointment which i have clicked in a List.
Question
How to show data in a form using AppointmentID ?
Below i am showing all required code written by me [Client & Server Side both]
UpcomingActivity.java:
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
int menuItemIndex = item.getItemId();
String[] menuItems = Cmd;
String CmdName = menuItems[menuItemIndex];
// Check Event Command
if ("Cancel".equals(CmdName))
{
Toast.makeText(UpcomingActivity.this,"Selected Cancel",Toast.LENGTH_LONG).show();
}
else if ("Reschedule".equals(CmdName))
{
Toast.makeText(UpcomingActivity.this,"Selected Update",Toast.LENGTH_LONG).show();
String sAppointmentID = MyArrList.get(info.position).get("UserID").toString();
Log.d(tag, "sAppointmentID :: " + sAppointmentID);
Intent newActivity = new Intent(UpcomingActivity.this, UpdateActivity.class);
newActivity.putExtra("UserID", sAppointmentID);
startActivity(newActivity);
}
return true;
}
UpdateActivity.java:
public void showInfo()
{
final TextView tAppointmentID = (TextView)findViewById(R.id.txtUsername);
final TextView tType = (TextView)findViewById(R.id.txtName);
final TextView tDate = (TextView)findViewById(R.id.txtEmail);
final TextView tTime = (TextView)findViewById(R.id.txtTel);
Button btnSave = (Button) findViewById(R.id.btnSave);
Button btnCancel = (Button) findViewById(R.id.btnCancel);
String url = "http://10.0.2.2/appointments/getByMemberID.php";
Intent intent= getIntent();
final String AppointmentID = intent.getStringExtra("AppointmentID");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sAppointmentID", AppointmentID));
String resultServer = getHttpPost(url,params);
String strAppointmentID = "";
String strType = "";
String strDate = "";
String strTime = "";
JSONObject c;
try {
c = new JSONObject(resultServer);
strAppointmentID = c.getString("UserID");
Log.d(TAG, "String strAppointmentID" + strAppointmentID);
strType = c.getString("Type");
Log.d(TAG, "String strType" + strType);
strDate = c.getString("Date");
Log.d(TAG, "String strDate" + strDate);
strTime = c.getString("Time");
Log.d(TAG, "String strTime" + strTime);
if(!strAppointmentID.equals(""))
{
tAppointmentID.setText(strAppointmentID);
tType.setText(strType);
tDate.setText(strDate);
tTime.setText(strTime);
}
else
{
tAppointmentID.setText("-");
tType.setText("-");
tDate.setText("-");
tTime.setText("-");
btnSave.setEnabled(false);
btnCancel.requestFocus();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
first of all make sure that you have valid AppointmentID and UserIdand
in UpcomingActivity.java at method onContextItemSelected you are not providing AppointmentID instead you are only providing UserID to the Intend
List but in Updateactivity at method showData you are requesting intent.getStringExtra("AppointmentID") which is invaild.
so your update your UpcomingActivity.java should look like this
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
int menuItemIndex = item.getItemId();
String[] menuItems = Cmd;
String CmdName = menuItems[menuItemIndex];
// Check Event Command
if ("Cancel".equals(CmdName))
{
Toast.makeText(UpcomingActivity.this,"Selected Cancel",Toast.LENGTH_LONG).show();
}
else if ("Reschedule".equals(CmdName))
{
Toast.makeText(UpcomingActivity.this,"Selected Update",Toast.LENGTH_LONG).show();
String sAppointmentID = MyArrList.get(info.position).get("UserID").toString();
Log.d(tag, "sAppointmentID :: " + sAppointmentID);
Intent newActivity = new Intent(UpcomingActivity.this, UpdateActivity.class);
newActivity.putExtra("UserID", sAppointmentID);
newActivity.putExtra("AppointmentID", MyArrList.get(info.position).get("AppointmentID").toString());// <== here
startActivity(newActivity);
}
return true;
}
I noticed a couple of issues (might be typos, but I prefer to ask anyway):
You are calling a getByMemberID.php, but you have not included its source code in the question - you do have such service, right? :)
In the onContextItemSelected you are starting the UpdateActivity and pass UserID as extra. But in the showInfo method of that activity you are trying to get AppointmentID from the intent's extras, so it is not processing any data.
1) Try weather your PHP code is working fine or not...
You can do that by running directly on server and passing UserId and appoinmentId as a parameter by ?
For eg.... www.abc.com?sUserId=123?sAppointmentID=456
See weather it's showing you proper output.
2) you are calling getByMemberID.php but you have specified code of it but you are not passing "AppointmentID" for that also check with php code weather you are retriving it ??
3) On call of updateData.php in UpdateActivity.java: you are not providing "AppointmentID" but you are retriving it in php code it will get null value by default which will be an error ofcourse
I’m working on a GWT web application that needs to communicate with a common web server. Unfortunately, the server only supports PHP, so I can’t use GWT RPC. That’s why I want to use a simple PHP script on server side, which returns all the necessary data in JSON format. Because I’m fairly new to GWT, my code is based on this example:
http://code.google.com/p/google-web-toolkit-doc-1-5/wiki/GettingStartedJSON
The PHP script seems to work fine. Firebug shows me the returned JSON data and the port 200:
Response:
[{"key1":"k1","value1":"v1"},{"key2":"k2","value2":"v2"},{"key2":"k3","value3":"v3]
However, the response is never processed further. Here is my code:
private static final String JSON_URL = "http://www.myUrl/myScript.php";
public HashMap<String, Integer> loadCalendarTable(String p1, String p2) {
table = new HashMap<String, Integer>();
String url = JSON_URL+"?p1="+p1+"&p2="+p2;
url = URL.encode(url);
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
try {
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
Window.alert("Couldn't retrieve JSON");
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
try {
// parse the response text into JSON
JSONValue jsonValue = JSONParser.parse(response.getText());
JSONArray jsonArray = jsonValue.isArray();
if (jsonArray != null) {
HashMap<String, Integer> hm = updateTable(jsonArray);
}
else
throw new JSONException();
}
catch (JSONException e) {
Window.alert("Could not parse JSON");
}
}
else
Window.alert("Couldn't retrieve JSON (" + response.getStatusText() + ")");
}
});
//(*)
}
catch (RequestException e) {
Window.alert("Couldn't retrieve JSON");
}
return table;
}
private HashMap<String, Integer> updateTable(JSONArray array) {
//do something
return table;}
By executing the application on the web server, there occurs no exception and no alert pops up. By using some alerts (which I omitted in the code above for readability), I noticed that the try-statement in new RequestBuilder() is executed. Another alert at (*) shows, that the try-statement is passed. (No exception occurs, as mentioned before). Obviously, the method onResponseReceived() is never executed. I never called this method, so this could be the reason for my problem. But then, I don’t understand where I should call onResponseReceived().
Remark:
I omitted my PHP script, because that’s actually the same as showed in the online example (http://code.google.com/p/google-web-toolkit-doc-1-5/wiki/GettingStartedJSON). Besides, the script seems to work properly.
How do you know that onResponseRecieved is not being executed? This should be called when your script.php returns JSON data. Assuming your server sends back a 200 status code, the response might be parsed, but no nothing is done with the data
try {
// parse the response text into JSON
JSONValue jsonValue = JSONParser.parse(response.getText());
JSONArray jsonArray = jsonValue.isArray();
if (jsonArray != null) {
HashMap<String, Integer> hm = updateTable(jsonArray);
// Now what? hm isn't actually used for anything...
} else {
throw new JSONException();
}
From the value returned at the end of the method, table is apparently important, but it will be returned, empty before the onResponseRecieved callback is ever invoked. This is because all GWT Ajax calls are asynchronous - the script won't stop running while waiting for the server to resume. Create an alert with response.getTest() in the if (jsonArray != null) block, and you may find that this code is getting called after all. If so, you've fallen victim to That's not async - it is considered generally good JavaScript practice (and all but mandatory in GWT) to wait for results to arrive when ready, and to keep executing as normal in the meantime.