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.
Related
I need to delete an item from a list view on android when clicked. The thing is, my table is not on the phone(SQLite), but on the server. So I'm using a PHP code for this.
I have set up an onClickListener.
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v,int position, long id) {
Show_Alert_box(v.getContext(),
"Please select action.", position);
}
});
public void Show_Alert_box(Context context, String message, int position) {
final int pos = position;
final AlertDialog alertDialog = new AlertDialog.Builder(context)
.create();
//alertDialog.setTitle(getString(R.string.app_name_for_alert_Dialog));
alertDialog.setButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
DBHandlerComments dbhelper = new DBHandlerComments(Comments.this);
SQLiteDatabase db = dbhelper.getWritableDatabase();
try{
JSONObject json2 = JSONParser.makeHttpRequest(urlDelete, "POST", params);
try {
int success = json2.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully updated
Intent i = getIntent();
// send result code 100 to notify about product update
setResult(100, i);
finish();
} else {
// failed to update product
}
} catch (JSONException e) {
e.printStackTrace();
}
//adapter.notifyDataSetChanged();
db.close();
}catch(Exception e){
}
}
});
alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog.setMessage(message);
alertDialog.show();
}
This is my JSONParser's makehttprequest code:
public static JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
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;
//from here
while ((line = reader.readLine()) != null) {
if(!line.startsWith("<", 0)){
if(!line.startsWith("(", 0)){
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;
}
`
And this is my PHP code:
$response = array();
if (isset($_POST['id'])) {
$id = $_POST['id'];
// include db connect class
$db = mysql_connect("localhost","tbl","password");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("shareity",$db);
// mysql update row with matched id
$result = mysql_query("DELETE FROM comments_activities WHERE id = $id");
// check if row deleted or not
if (mysql_affected_rows() > 0) {
// successfully updated
$response["success"] = 1;
$response["message"] = "Product successfully deleted";
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
I'm adding the params like this:
params.add(new BasicNameValuePair(KEY_ID, id));
params.add(new BasicNameValuePair(KEY_AID, aid));
params.add(new BasicNameValuePair(KEY_ANAME, an));
params.add(new BasicNameValuePair(KEY_EVENT, ev));
params.add(new BasicNameValuePair(KEY_COMMENT, cb));
params.add(new BasicNameValuePair(KEY_USER, cby));
params.add(new BasicNameValuePair(KEY_TIME, cd));
I don't get any result. Can I know why?
I have noticed that you add unneeded parameters although you just need the id.
This is a simple code for deleting the given id, you can try it. If it worked, the error would be in your android code.
<?php
$servername = "your servername";
$username = "your username";
$password = "your password";
$dbname = "your dbname";
$link = mysql_connect($servername, $username, $password);
mysql_select_db($dbname, $link);
$id=$_POST['id'];
$result = mysql_query("DELETE FROM table_name WHERE id=$id", $link);
$response["success"] = 1;
$response["message"] = "Deleted successfully!";
echo json_encode($response);
?>
Change the servername to your database url and so on the other information.
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?
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).
im trying to find a way to post username and password using json rather than normal http post that im currently using. i have being going through most of the tutorials and examples to undestand but yet i was unable to get an idea. i have json phasers available to get the data from my sql but not the post json.
thank you for the help
following is the currently used json post
EditText uname = (EditText) findViewById(R.id.log_Eu_name);
String username = uname.getText().toString();
EditText pword = (EditText) findViewById(R.id.log_Epass);
String password = pword.getText().toString();
String result = new String();
result = "";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs
.add(new BasicNameValuePair("username", username));
nameValuePairs
.add(new BasicNameValuePair("password", password));
InputStream is = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.loshwickphotography.com/log.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.w("SENCIDE", "Execute HTTP Post Request");
String str = inputStreamToString(
response.getEntity().getContent()).toString();
Log.w("SENCIDE", str);
if (str.toString().equalsIgnoreCase("true")) {
Log.w("SENCIDE", "TRUE");
Toast.makeText(getApplicationContext(),
"FUking hell yeh!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"Sorry it failed", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
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();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
if (result != null) {
JSONArray jArray = new JSONArray(result);
Log.i("log_tag", Integer.toString(jArray.length()));
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
}
} else {
Toast.makeText(getApplicationContext(), "NULL",
Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
private Object inputStreamToString(InputStream is) {
// TODO Auto-generated method stub
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(
new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
});
Is this correct which i have written?
how to write the Php for this?
use this
JSONObject myjson=new JSONObject();
myjson.put("userName", "someOne");
myjson.put("password", "123");
and StringEntity se = new StringEntity(myjson.toString());
and httpPost.setEntity(se);
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");