I'm not a very expert programmer but for an exam text I have to do an android app that interact with a php server. I read lots of tutorial and examples, but the code I write doesn't work. Could you tell me why?
PHP code
<?php
$conn = mysqli_connect("localhost","root","","my_onceuponatimestories");
if (mysqli_connect_error()) {
echo("connessione fallita!!".mysqli_connect_error());
exit;
} else {
$sql= "SELECT * ";
$sql.="FROM stories";
//$sql.="WHERE ";
// echo $sql;
//echo "<br>";
$result=mysqli_query($conn,$sql);
if ($result){
if (mysqli_num_rows($result)>0){
//echo mysqli_num_rows($result);
//echo "<br>";
while($e=mysqli_fetch_assoc($result)){
$output = array(htmlspecialchars($e['title']), htmlspecialchars($e['author']));
//$output = array(htmlspecialchars($e['title']), htmlspecialchars($e['author']));
//echo json_encode($output);
}
//echo(json_encode($ris));
}
}
mysqli_close($conn);
}
?
And my java code:
public void getData (View v){
HttpGet httpGet = new HttpGet("http://www.onceuponatimestories.altervista.org/viewAnd.php");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity= null;
String response = "NADA";
try {
HttpResponse httpReponse =httpClient.execute(httpGet);
httpEntity = httpReponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//} catch (UnsupportedEncodingException e) {
//e.printStackTrace();
}
TextView result = (TextView) findViewById(R.id.textView1);
result.setText(response);;
}
You commented out your echo statement so PHP isn't going to give you any text back. Also, you don't assign a value to the $ris variable in your PHP. What do you see when you just navigate to the PHP file in a browser?
Related
I need help.
Have seen similar questions but I cant still do it. So I post mine.
php codes runs well so far. Ijust dont know how to get the array.
How can I get the array from php and list it in my alertdialog like this:
soy sauce - $1
onion - $1
total= $2
Or is this possible or not? Or maybe please tell me what to add in here.
Thanks for your time in advance. Any form of help would be appreciated.
This are my codes:
public class updateData2 extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
ArrayList<NameValuePair> postVars = new ArrayList<>();
postVars.add(new BasicNameValuePair("JSON", String.valueOf(EverythingJSON)));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://abcabc.com/buy_now.php");
try {
httppost.setEntity(new UrlEncodedFormEntity(postVars));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
HttpResponse response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.v("MAD", "Error sending... ");
} catch (IOException e) {
e.printStackTrace();
Log.v("MAD", "Error sending... ");
}
return null;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(Cart.this,EverythingJSON.toString(), Toast.LENGTH_LONG).show();
AlertDialog.Builder builder = new AlertDialog.Builder(Cart.this);
builder.setTitle("ORDER:");
builder.setMessage(EverythingJSON.toString());
builder.setPositiveButton("Confirm",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
}
});
builder.show();
}
}
php
<?php
require "conn.php";
$total = 0;
// $ing = array("ampalaya", "soy sauce");
$JSON_Received = $_POST["JSON"];
$obj = json_decode($JSON_Received, true);
$products_name_array = array();
$products_price_array = array();
// foreach($ing as $value){
foreach($obj['ques'] as $value){
$sql="select MIN(product_price) , product_id , store_id , product_name,product_unit_of_measure , product_price ,product_stock from products where product_name like '%$value%'";
$result2 = mysqli_query($conn, $sql);
if(mysqli_num_rows($result2) > 0){
while($row = mysqli_fetch_assoc($result2)){
$product_id=$row['product_id'];
$store_id=$row['store_id'];
$product_name=$row['product_name']; $products_name_array[] = $product_name;
$product_unit_of_measure=$row['product_unit_of_measure'];
$product_price=$row['product_price']; $products_price_array[] = $product_price;
$total = $total+$product_price;
}}
}
foreach($products_name_array as $key => $value) {
echo $products_name_array[$key] . " - " . "$" . $products_price_array[$key] . ".00" ."<br>";
}
echo "</br>";
echo "</br>";
echo "TOTAL IS: ".$total. ".00";
?>
example:
getArray.php
<? echo json_encode($your_array);?>
and in android use for example retrofit library(http client)
interface phpApi{
#GET("url/getArray.php")
Call<YourObject> getArray();
}
I trying to send this json data form android to php server.
this my json data{email:"user111#gmail.com",password:"00000"},
any one help how the decode this json data in php server
this my php server code
<?php
$response = array();`
require_once __DIR__ . '/db_connect.php';`
if(!isset($_POST['params'])){
$decoded=json_decode($_POST['params'],true)
$email=json_decode['email'];
$pass=json_decode['password'];
// connecting to db
$db = new DB_CONNECT();`
$result = mysql_query("SELECT *FROM user WHERE email = $email");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {`
$result = mysql_fetch_array($result);
$this->mylog("email".$email.",password".$pass);
if($pass==$result[password]){
echo " password is correct";
$response["code"]=0;
$response["message"]="sucess";
$response["user_id"]=$result["userid"];
$response["firstname"]=$result["fname"];
$response["lastname"]=$result["lname"];
echo json_encode($response);
}else{
$response["code"]=3;
$response["message"]="invalid password and email";
echo json_encode($response);
}
}else {
// required field is missing
$response["code"] = 1 ;
$response["message"] = "no data found";
// echoing JSON response
echo json_encode($response);
}
}
}else {
// required field is missing
$response["code"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response); }?>
**this my android code json praser **
public JSONObject loginUser(String email, String password) {
Uri.Builder loginURL2 = Uri.parse(web).buildUpon();
loginURL2.appendPath("ws_login.php");
JSONObject loginJSON = new JSONObject();
try {
loginJSON.put("email", email);
loginJSON.put("password", password);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject json = jsonParser.getJSONFromUrl(loginURL2.toString(),
loginJSON);
return json;
}
this my android json data send function
public JSONObject getJSONFromUrl(String url, JSONObject params) {
// Making HTTP request
try {
// defaultHttpClient
// boolean status=isNetworkAvailable();
HttpParams param = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(param, 10000);
HttpConnectionParams.setSoTimeout(param, 10000);
DefaultHttpClient httpClient = new DefaultHttpClient(param);
HttpPost httpPost = new HttpPost(url);
StringEntity se = new StringEntity(params.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
CONTENT_TYPE_JSON));
httpPost.setEntity(se);
Log.d("URL Request: ", url.toString());
Log.d("JSON Params: ", params.toString());
HttpResponse httpResponse = httpClient.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
if (code != 200) {
Log.d("HTTP response code is:", Integer.toString(code));
return null;
} else {
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (ConnectTimeoutException e) {
// TODO: handle exception
Log.e("Timeout Exception", e.toString());
return null;
} catch (SocketTimeoutException e) {
// TODO: handle exception
Log.e("Socket Time out", e.toString());
return null;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
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();
jsonResp = sb.toString();
Log.d("Content: ", sb.toString());
} catch (Exception e) {
Log.e("Buffer Error", "Error converting Response " + e.toString());
return null;
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(jsonResp);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}
public boolean isNetworkAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
If $_POST['params'] is a JSON encoded string, you only have to call json_decode once, not the multiple times that you have shown.
$decoded = json_decode($_POST['params'], true);
// Decoded is now an array of the JSON data
$email = $decoded['email'];
$pass = $decoded['password'];
It should be noted that the string in your question is not valid JSON, as email and password need to be quoted, as well.
You can do live testing of the json_decode function here:
http://php.fnlist.com/php/json_decode
You can validate your JSON here:
http://jsonlint.com
I am facing a problem, a valid JSON string cannot become a JSON object.
I have tested the response coming from the server, it is a valid JSON.
I have checked on the internet, it is about the problem of UTF-8 with DOM. But even I changed the charset in Notepad++ into UTF-8 with no DOM, the same error still coming out.
My codes:
<?php
require_once("Connection/conn.php");
//parse JSON and get input
$json_string = $_POST['json'];
$json_associative_array = json_decode($json_string,true);
$userId = $json_associative_array["userId"];
$password = $json_associative_array["password"];
$userType = $json_associative_array["userType"];
//get the resources
$json_output_array = array();
$sql = "SELECT * FROM account WHERE userId = '$userId' AND password = '$password' AND userType = '$userType'";
$result = mysql_query($sql);
//access success?
if (!$result) {
die('Invalid query: ' . mysql_error());
$json_output_array["status"] = "query failed";
}
else{
$json_output_array["status"] = "query success";
}
//find the particular user?
if (mysql_num_rows($result) > 0){
$json_output_array["valid"] = "yes";
}
else{
$json_output_array["valid"] = "no";
}
//output JSON
echo json_encode($json_output_array);
?>
Android codes:
public boolean login() {
// instantiates httpclient to make request
DefaultHttpClient httpClient = new DefaultHttpClient();
// url with the post data
String url = SERVER_IP + "/gc/login.php";
JSONObject holder = new JSONObject();
try {
holder.put("userId", "S1");
holder.put("password", "s12345");
holder.put("userType", "supervisor");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d("JSON", holder.toString());
// HttpPost
HttpPost httpPost = new HttpPost(url);
//FormEntity
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("json", holder.toString()));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// execution and response
boolean valid = false;
try {
HttpResponse response = httpClient.execute(httpPost);
Log.d("post request", "finished execueted");
String responseString = getHttpResponseContent(response);
Log.d("post result", responseString);
//parse JSON
JSONObject jsonComeBack = new JSONObject(responseString);
String validString = jsonComeBack.getString("valid");
valid = (validString.equals("yes"))?true:false;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return valid;
}
private String getHttpResponseContent(HttpResponse response) {
String responseString = "";
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
responseString += line ;
}
rd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return responseString;
}
JSON come from server:
{
"status": "query success",
"valid": "yes"
}
unformat JSON:
{"status":"query success","valid":"yes"}
When I copy this into notepad++, it becomes ?{"status":"query success","valid":"yes"}
It seems that there is a invisible character .
I fixed it with the solution provided by MuhammedPasha, which substring the JSON string to remove invisible character. And I substring the JSON String from 1 to fix my problem.
There is a way to detect those invisible characters, copy the log result into notepad++.(copy! no typing!) If there are any ?(question mark), they indicates that there are some invisible character.
I had a same problem. Maybe you need to save without unicode signature (BOM).
I have created a gps application which works fine. Now what i am trying is to connect it to a php server with mysql database where all the locations of the people are updated automatically.. I am a new user for this part. I have tried some of it but I dont think its write.. Can someone help me and guide me to the process about how should i do it.. Your help will be really appreciated. Below is the code i wrote from a frieds help and the php script.
public class Post extends LocService {{
TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
String deviceid = telephonyManager.getDeviceId();
//this is JSON part to put your information inside it
String postData = "{\"request\":{\"type\":\"locationinfo\"},\"userinfo\":{\"latitude\":\""+latitude+"\",\"longitude\":\""+longitude+"\",\"deviceid\":\""+deviceid+"\"}}";
HttpClient httpClient = new DefaultHttpClient();
// Post method to send data to server
HttpPost post = new HttpPost("http://location.net/storeg.php");
SQLiteDatabase db = databasehelper.getWritableDatabase();
Cursor cursor = db.query(TABLE, null, null, null, null);
cursor.moveToFirst();
while(cursor.isAfterLast() == false) {
if(cursor.getString(cursor.getColumnIndex("Sync")).equals("yes") ) {
String mob = cursor.getString(cursor.getColumnIndex("MobileID"));
String latitude = cursor.getString(cursor.getColumnIndex("Latitude"));
String longitude = cursor.getString(cursor.getColumnIndex("Longitude"));
String service = cursor.getString(cursor.getColumnIndex("Service"));
JSONObject json = new JSONObject();
try {
json.put("MobileID", mob);
json.put("Latitude", latitude);
json.put("Longitude", longitude);
json.put("Service", service);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
receive = HttpPostExample.SendJsonUpdate(json, Sync_URL);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(context, receive,Toast.LENGTH_SHORT).show();
}
cursor.moveToNext();
}
cursor.close();
try {
post.setURI(new URI("http://location.net/storeg.php"));
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// set your post data inside post method
try {
post.setEntity(new StringEntity(postData));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// execute post request here
try {
HttpResponse response = httpClient.execute(post);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
PHP Script
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mel_db", $con);
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
$service = $_POST['service'];
$devid = $_POST['devid'];
$sql = "INSERT INTO `mehul_db`.`locations` (
`id` ,
`devid` ,
`latitude` ,
`longitude` ,
`service`
)
VALUES (
NULL , '$devid', '$latitude', '$longitude', '$service'
);";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con);
?>
Please help me with the process... Or suggest me about how should i do it..
*EDITED:*Got this code can i use it for getting the latitude and longitude after changing the variables..?
String result;
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getInt("id")+
", name: "+json_data.getString("name")+
", sex: "+json_data.getInt("sex")+
", birthyear: "+json_data.getInt("birthyear")
);
}
finally }
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
String url="http://location.net/storeg.php";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("latitude", latitude));
nameValuePairs.add(new BasicNameValuePair("longitude", longitude));
nameValuePairs.add(new BasicNameValuePair("service", service));
nameValuePairs.add(new BasicNameValuePair("devid", devid));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream httpEntity = httpResponse.getEntity().getContent();
you can use this code to send parametrs to php through post and in response you will get inputstream.
I am currently trying to develop an app that among other things can send and receive data from a mysql server.
The app calls a php script which makes the connection to the mysql server. I have successfully developed the sending part and now I want to retrieve data from mysql and display it on an android phone.
The mysql table consists of 5 columns:
bssid
building
floor
lon
lat
The php file getdata.php contains:
<?php
$con = mysql_connect("localhost","root","xxx");
if(!$con)
{
echo 'Not connected';
echo ' - ';
}else
{
echo 'Connection Established';
echo ' - ';
}
$db = mysql_select_db("android");
if(!$db)
{
echo 'No database selected';
}else
{
echo 'Database selected';
}
$sql = mysql_query("SELECT building,floor,lon,lat FROM ap_location WHERE bssid='00:19:07:8e:f7:b0'");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close(); ?>
This part is working fine, when tested in a browser.
The java code for connecting to php:
public class Database {
public static Object[] getData(){
String db_url = "http://xx.xx.xx.xx/getdata.php";
InputStream is = null;
String line = null;
ArrayList<NameValuePair> request = new ArrayList<NameValuePair>();
request.add(new BasicNameValuePair("bssid",bssid));
Object returnValue[] = new Object[4];
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httppost = new HttpPost(db_url);
httppost.setEntity(new UrlEncodedFormEntity(request));
HttpResponse response = httpclient.execute(httppost, localContext);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection" +e.toString());
}
String result = "";
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error in http connection" +e.toString());
}
try
{
JSONArray jArray = new JSONArray(result);
JSONObject json_data = jArray.getJSONObject(0);
returnValue[0] = (json_data.getString("building"));
returnValue[1] = (json_data.getString("floor"));
returnValue[2] = (json_data.getString("lon"));
returnValue[3] = (json_data.getString("lat"));
}catch(JSONException e){
Log.e("log_tag", "Error parsing data" +e.toString());
}
return returnValue;
}
}
This is a modified code used to send data to the mysql server, but something is wrong.
I've tried to test it by setting different returnValues in the code and this shows me that the part with the httpclient connection does not run.
Can you guys help me?
I hope this is not too confussing, and if you want I can try to explain it futher.
Use HttpGet instead of HttpPost and parse your url.
Here is a class I always use to GET
public JSONObject get(String urlString){
URL currentUrl;
try {
currentUrl = new URL(currentUrlString);
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
HttpURLConnection urlConnection = null;
InputStream in;
BufferedReader streamReader = null;
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
try {
urlConnection = (HttpURLConnection) currentUrl.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream());
streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
while ((inputStr = streamReader.readLine()) != null) {
responseStrBuilder.append(inputStr);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
if(null != streamReader){
try {
streamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
return new JSONObject(responseStrBuilder.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Try to test with get("http://echo.jsontest.com/key/value");