I'm trying to read a php script URL through QR code and then retrieve MAC of device, after that, I want to send the MAC to php script but android app is crashing if I try it.
I'm also opening the url in a browser using intent. What should I write at php side to retrieve the MAC address and any changes in android activity?
Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_decoder);
mydecoderview = (QRCodeReaderView) findViewById(R.id.qrdecoderview);
mydecoderview.setOnQRCodeReadListener(this);
myTextView = (TextView) findViewById(R.id.exampleTextView);
line_image = (ImageView) findViewById(R.id.red_line_image);
TranslateAnimation mAnimation = new TranslateAnimation(
TranslateAnimation.ABSOLUTE, 0f,
TranslateAnimation.ABSOLUTE, 0f,
TranslateAnimation.RELATIVE_TO_PARENT, 0f,
TranslateAnimation.RELATIVE_TO_PARENT, 0.5f);
mAnimation.setDuration(1000);
mAnimation.setRepeatCount(-1);
mAnimation.setRepeatMode(Animation.REVERSE);
mAnimation.setInterpolator(new LinearInterpolator());
line_image.setAnimation(mAnimation);
Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
/*String ur="http://192.168.0.105/project/rec.html";
Intent intent1=new Intent("android.intent.action.VIEW");
if (!ur.contains("http://"))
ur = "http://" + ur;
intent1.setData(Uri.parse(ur));
startActivity(intent1);// Perform action on click*/
}
});
}
// Called when a QR is decoded
// "text" : the text encoded in QR
// "points" : points where QR control points are placed
#Override
public void onQRCodeRead(String text, PointF[] points) {
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
action = wInfo.getMacAddress();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(addr);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair(1);
nameValuePairs.add(new BasicNameValuePair("action",action));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = newBasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
String reverseString = response;
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
Intent localIntent = new Intent("android.intent.action.VIEW");
if (!text.contains("http://"))
text = "http://" + text;
addr=text;
localIntent.setData(Uri.parse(text));
startActivity(localIntent);
}
error_reporting(0);
include("db_config.php");
$response = array();
if (isset($_GET['id'])) {
$id = $_GET['id'];
$item = $_GET['item'];
$r = mysql_query("select Department_id from student where st_id = '$id'");
$row = mysql_fetch_array($r);
$Department_id = $row[0];
$r = mysql_query("select Subject_name from subject where Subject_code ='$item'");
$row = mysql_fetch_array($r);
$Subject_name = $row[0];
$result = mysql_query("INSERT INTO `sis_fyp`.`student-subject` (`st_id`, `Subject_code`, `Status`, `grade`, `Department_id`, `Subject_name`) VALUES ('$id', '$item', 'Repeat', 'W', '$Department_id', '$Subject_name');");
if ($result>0) {
$response["success"] = 1;
} else {
$response["success"] = 0;
}
// echoing JSON response
echo json_encode($response);
}
Just make a php script like above
and pass your url in and android like:
wwww.yoururl.com?id=$id&item=$item
Related
I am inserting some values from my android login page to mysql database using php .
login.php
<?php
$con = mysql_connect("localhost","abc","xyz") or die(mysql_error());
mysql_select_db("sync",$con) or die(mysql_error());
$user_name = $_POST['user_name'];
$user_mobile_no = $_POST['user_mobile_no'];
$user_email_id = $_POST['user_email_id'];
$imei_no = $_POST['imei_no'];
$login_date = $_POST['login_date'];
$time = $_POST['time'];
$user_name = 'Navdeep';
$user_mobile_no = '12345678990';
$user_email_id = 'nav#gmail.com';
$imei_no = '1234567890';
$login_date = '24-12-2012';
$time = '01:01:01';
$result = mysql_query("INSERT INTO
login_details(user_name,user_mobile_no,user_email_id,
imei_no,login_date,time)
VALUES('$user_name','$user_mobile_no','$user_email_id',' $imei_no','$login_date','$time')");
if($result)
{
$response["success"] = 1;
$response["message"] = "User Details inserted successfully";
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "There was an error inserting user details";
echo json_encode($response);
}
mysql_close($con);
?>
When i use $_POST[''] values are getting inserted as blank , but when i hardcode the values it is getting inserted , need some help
Android code :
try{
JSONObject jsonObject = new JSONObject();
jsonObject.put("user_name",userName);
jsonObject.put("user_mobile_no",mobNo);
jsonObject.put("user_email_id",email);
jsonObject.put("imei_no",imeino);
jsonObject.put("login_date",date);
jsonObject.put("time",time);
JSONArray jsonArray = new JSONArray();
jsonArray.put(jsonObject);
String basicAuth = "Device " + new
String(Base64.encode((imeino).getBytes(), Base64.NO_WRAP));
RequestBody body =
RequestBody.create(JSON,String.valueOf(jsonArray));
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().header("Authorization",
basicAuth).url(url).post(body).build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
Login.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getBaseContext(), "Request to the
server failed", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onResponse(Call call, Response response) throws
IOException {
Log.i("response ", "onResponse(): " + response );
StatusLine statusLine = null;
String result = response.body().string();
if(result.equals("") || result.equals(null)){
Log.i("No response", "No response");
}else{
Log.i("Response","Response "+result);
statusLine = StatusLine.get(response);
final int responseCode = statusLine.code;
Log.d("Code:", String.valueOf(responseCode));
}
}
});
}catch (Exception e){
e.printStackTrace();
}
You should send form data request from android.
Replace this
JSONObject jsonObject = new JSONObject();
jsonObject.put("user_name",userName);
jsonObject.put("user_mobile_no",mobNo);
jsonObject.put("user_email_id",email);
jsonObject.put("imei_no",imeino);
jsonObject.put("login_date",date);
jsonObject.put("time",time);
JSONArray jsonArray = new JSONArray();
jsonArray.put(jsonObject);
String basicAuth = "Device " + new
String(Base64.encode((imeino).getBytes(), Base64.NO_WRAP));
RequestBody body =
RequestBody.create(JSON,String.valueOf(jsonArray));
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().header("Authorization",
basicAuth).url(url).post(body).build();
With
RequestBody formBody = new FormBody.Builder()
.add("user_name",userName)
.add("user_mobile_no",mobNo)
.add("user_email_id",email)
.add("imei_no",imeino)
.add("login_date",date)
.add("time",time)
.build();
String basicAuth = "Device " + new
String(Base64.encode((imeino).getBytes(), Base64.NO_WRAP));
Request request = new Request.Builder().header("Authorization",
basicAuth).url(url).post(formBody).build();
i want to send all contacts with contact name and number in one row in one array in my android application like
john => "+92312xxxxxxx" ,
Right now i'm using namevaluepairs to post two arrays but it's not working like :
public class ContactList extends Activity {
public TextView outputText;
String phoneNumber = null;
String names = null;
String[] keyValue;
String[] kes;
int Count;
String s = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_list);
outputText = (TextView) findViewById(R.id.textView1);
fetchContacts();
//Http connection
InputStream is=null;
List<NameValuePair> nameValuePairs =new ArrayList<NameValuePair>(1);
for (int i = 0; i < Count ; i++)
{
nameValuePairs.add(new BasicNameValuePair("CN[]", keyValue[i]));
nameValuePairs.add(new BasicNameValuePair("names[]",kes[i]));
Log.i("Response", "you sent :" +kes[i]+" :"+ keyValue[i] + "\n ");
}
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.107/older/ContactList.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(ClientProtocolException e)
{
Log.e("ClientProtocol","Log_tag");
e.printStackTrace();
System.out.println("Excep: "+e);
}
catch(IOException e)
{
Log.e("Log_tag","IOException");
e.printStackTrace();
}
String result = "";
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");
}
reader.close();
is.close();
result=sb.toString();
Log.i("Response", "result "+ result);
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
//result = "[{\"0\":\"Muhaimin\",\"1\":\"3\",\"2\":\"o+\"}]";
try
{
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++)
{
s= s +";"+ jArray.getString(i) + "\n";
}
}
catch (Exception e)
{
Log.e("Response", "error fetching indexes" + e);
}
String[] friends= s.split(";");
StringBuffer output = new StringBuffer();
for (int i = 0; i < friends.length; i++)
{
Log.i("List","Your friends namee"+friends[i]);
output.append("\n Your friend's number"+ friends[i]);
}
}
//Fetch Contacts
public void fetchContacts() {
// String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
// Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
//String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
// String DATA = ContactsContract.CommonDataKinds.Email.DATA;
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null,null, null, null);
// Loop for every contact in the phone
Count = cursor.getCount();
if (cursor.getCount() > 0) {
keyValue= new String[Count];
kes= new String[Count];
while (cursor.moveToNext()) {
String contact_id = cursor.getString(cursor.getColumnIndex( _ID ));
String name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME ));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex( HAS_PHONE_NUMBER )));
if (hasPhoneNumber > 0) {
// Query and loop for every phone number of the contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);
while (phoneCursor.moveToNext())
{
int i=0;
String stu = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
phoneNumber +=":"+ stu;
names +=":" + name;
Log.i("List",stu + name +"\n" );
}
phoneCursor.close();
}
}
}
keyValue = phoneNumber.split(":");
kes = names.split(":");
Log.i("List","24th"+keyValue[23]);
Toast.makeText(getApplicationContext(), "99th "+keyValue[909] ,Toast.LENGTH_LONG).show();
}
PHP after receiving contacts will match them and return only those which have a match with database contacts. And then it returns contacts with names
i'm stuck with sending and receving part
Here is php code
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'verification');
define('DB_USER','root');
define('DB_PASSWORD','');
// 1. Create a database connection
$connection = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD);
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
$PhoneNum= $_POST["CN"];
$i=0;
$j=0;
$friends = array();
$Invite = array();
unset ($PhoneNum[0]);
foreach ($PhoneNum as $i=> $element){
//or do whatever you need to do to that variable
$query="SELECT Number FROM `user` WHERE Number=$element";
$query_exec = mysqli_query($connection ,$query);
if (!$query_exec)
{ echo mysql_error(); }
ELSE {
if(mysqli_num_rows($query_exec)>0)
{
$friends["$j"]= $PhoneNum[$i];
$j++;
}
else
{
;
}}
}
echo (json_encode($friends));
?>
You'll get a URL now that would look like:
www.example.com/yourscript?CN[]=keyValue1&names[]=key1&CN[]=keyValue2&names[]=key2 etc.. going on untill your whole list has looped.
I doubt that is what your PHP script wants to receive, you probably want to send the POST for each time you increment the loop. But thats just conjecture untill you post more information/code.
Instead send a JSON array as the value of the nameValuePair and convert it to a PHP array using json_decode function in the server side.
I have My databases on an xampp server and my activity and php file is given below. The problem in this page is that when I run application it always throws an exception. It always shows my last message that there is "Some problem is there." My submission date is due soon.
This is my Activity file
public class AdminLoginActivity extends Activity {
TextView username, password, message;
Button SignIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_login);
StrictMode.enableDefaults();
username = (TextView) findViewById(R.id.adminusername);
password = (TextView) findViewById(R.id.adminpassword);
message = (TextView) findViewById(R.id.textView5);
SignIn = (Button) findViewById(R.id.adminloginbtn);
SignIn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
checkAdminData();
}
});
}
public void checkAdminData()
{
InputStream isr = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:1234/adminlogin.php");
try
{
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair> (2);
nameValuePairs.add(new BasicNameValuePair("username", username.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("password", password.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch (ClientProtocolException e)
{
Log.e("log_tag", "Error in Http connection " + e.toString());
message.setText("couldn't connect to database");
}
catch (IOException e)
{
}
String responseText = null;
try
{
String res = isr.toString();
// res = res.replaceAll("\\s+", "");
if (res.equals("1")) {
Intent i = new Intent(this, AdminMainPage.class);
startActivity(i);
}
else{
message.setText("Username or Password incorrect");
}
}
catch (Exception e)
{
Log.e("log_tag", "Sorry!! Incorrect Username or Password " + e.toString());
message.setText("Some problem is there");
}
}
}
PHP file:
<?php
$hostname_localhost ="localhost";
$database_localhost ="sibuilder";
$username_localhost ="root";
$password_localhost ="";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
$username = $_POST['username'];
$password = $_POST['password'];
$query_search = "select * from login l, admin a where a.username = '".$username."' AND l.password = '".$password. "'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
if($rows == 0) {
echo 0;
}
else {
echo 1;
}
?>
If you want to use your php script instead json format, can refer these questions
Android: AsyncTask to make an HTTP GET Request? Make an HTTP request with android to handle the response. Using AsyncTask is recommended.
I am in a problem can any one help me please.
I have a php file which i am calling from my java class file's Asynctask.
In the Asynctask i am sending three variables email,password and pin.
What is happening, is that when i run my php with hardcoded values it gives me proper result.
RESULT IS:
Inside 1st if
Inside 2nd if
Verified
main if
But wen i try running my php through the code it gives me wrong result
RESULT IS:
Inside 1st if
Invalid
main if
I'am not able to understand why is this happening please Guide me.
My PHP File
<?php
require 'DbConnect.php';
$i=1;
$Password = $_POST["password"];
$Email = $_POST["email"];
$Pin = $_POST["pin"];
//$KeyCode = $_REQUEST["key"];
if((isset($_POST["password"])) && (isset($_POST["email"])) && (isset($_POST["pin"])))
{
$query4 = ("SELECT seller_id, name, email, password, verification_Pin, verification_Code, created_Date FROM `seller` WHERE email = '$Email'");
$query_run = mysql_query($query4);
$row=mysql_fetch_row($query_run);
$int=$row[0];
$strName=$row[1];
$strEmail=$row[2];
$strPwd=$row[3];
$strPin=$row[4];
echo $Pin;
echo $Password;
echo $Email;
echo $int;
echo $strEmail;
echo $strPwd;
echo $strPin;
if(($Email==$strEmail) && ($Password==$strPwd) && ($Pin==$strPin))
{
global $i;
$i=2;
$id=updateValidation($int);
echo $id;
if($id==1)
{
echo "Verified";
}
else
{
echo "Not Verified";
}
}
else
{
echo "Invaild";
}
}
else
{
echo "Values not set";
}
function updateValidation($sid)
{
global $i;
if($i==2)
{
echo "Inside Update vAlidation";
$queryUpdate = ("UPDATE `seller` SET verification_Pin = 0, verification_Code = 'Verified', created_Date = CURDATE() where seller_id='$sid'");
if(mysql_query($queryUpdate))
{
return 1;
}
else
{
return 2;
}
}
else
{
echo "i not 2";
}
}
?>
My Class file:
Button ok = (Button) myDialog
.findViewById(R.id.button1);
et_pin = (EditText) myDialog
.findViewById(R.id.editText1);
ok.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
"CLICKED OK", Toast.LENGTH_LONG).show();
pin = et_pin.getText().toString();
Toast.makeText(
getApplicationContext(),
"email,pass,pin= " + str1 + "," + str2
+ "," + pin, Toast.LENGTH_LONG)
.show();
new App_pin_Task().execute(FILENAME_pin);
// Intent intent = new
// Intent(Dealer_details.this,
// Login.class);
// startActivity(intent);
}
});
public class App_pin_Task extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#SuppressLint("NewApi")
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(),
"Inside App_pin_Task post Execute(Result)=" + result,
Toast.LENGTH_LONG).show();
if (result.contains("Invalid")) {
et_pin.setText("");
} else {
Intent myIntent = new Intent(Login.this, UserActivity.class);
startActivity(myIntent);
}
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected String doInBackground(String... params) {
// String is = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://animsinc.com/verifyEmail.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
4);
nameValuePairs.add(new BasicNameValuePair("email", str1));
nameValuePairs.add(new BasicNameValuePair("password", str2));
nameValuePairs.add(new BasicNameValuePair("pin", pin));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
}
return is;
}
}
What is being returned with
$Password = $_REQUEST["password"];
$Email = $_REQUEST["email"];
$Pin = $_REQUEST["pin"];
$KeyCode = $_REQUEST["key"];
Your server configuration may have this option disabled and not returning anything.
You shouldn't use $_REQUEST anyway because you can never be sure where the data is actually coming from: $_POST, $_GET or $_cookie.
try this!
Change this
$Password = $_REQUEST["password"];
$Email = $_REQUEST["email"];
$Pin = $_REQUEST["pin"];
$KeyCode = $_REQUEST["key"];
to for Get Request
$Password = $_GET["password"];
$Email = $_GET["email"];
$Pin = $_GET["pin"];
$KeyCode = $_GET["key"];
or for Post Request
$Password = $_POST["password"];
$Email = $_POST["email"];
$Pin = $_POST["pin"];
$KeyCode = $_POST["key"];
or
"SELECT seller_id, name, email, password, verification_Pin,
verification_Code, created_Date FROM seller WHERE email = '".$Email."'"
Complementing the answer from fayeq-ali-khan I would also do the following;
First use post and add html special character for security.
htmlspecialchars => Convert special characters to HTML entities
$Password = htmlspecialchars($_POST['password'],ENT_QUOTES);
$Email = htmlspecialchars($_POST['email'],ENT_QUOTES);
$Pin = htmlspecialchars($_POST['pin'],ENT_QUOTES);
$KeyCode = htmlspecialchars($_POST['key'],ENT_QUOTES);
Also on your android activity and before you send the string it would be a good idea to trim the value to make sure that you are not transmitting empty character that can also mess up with the PHP
nameValuePairs.add(new BasicNameValuePair("email", str1.trim()));
nameValuePairs.add(new BasicNameValuePair("password", str2.trim()));
nameValuePairs.add(new BasicNameValuePair("pin", pin.trim()));
I hope it help you with something
What I am trying is I get my current location (the coordinates) and i want to post those coordinates on a server. I have made a server using WAMP. I have written php code and the code in java but its showing me error in the POST word. Please tell me if its correct or if i can modify it!!
PHP CODE
<?php
echo 'Hello, world!';
$json = $_GET['jsonpost'];//get the post you sent...
$data = json_decode($json); //decode the json formatted string...
print_r($data);
$id = $data->id;
$devid = $data->devid;
$latitude = $data->latitude;
$longitude = $data->longitude;
$service = $data->service;
$con = mysql_connect("","","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("a5234826_ul", $con);
$devid = $_POST['devid'];
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
echo "devid" +$devid;
echo "latitude" + $latitude;
echo "longitude" + $longitude;
$sql = "INSERT INTO `a5234826_ul`.`locations` (
`id` ,
`devid` ,
`latitude` ,
`longitude` ,
`service`
)
VALUES (
NULL , '$devid', '$latitude', '$longitude', '$service'
)";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con);
echo json_encode($variable);
?>
EDITED
LocationService.java
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "lock");
wl.acquire();
context = this;
final String who = intent.getStringExtra("who");
final LocationManager locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
final LocationListener listener = new LocationListener(){
// start location changed
public void onLocationChanged(Location loc) {
double latitude = loc.getLatitude();
double longitude = loc.getLongitude();
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://.../serverFile.php");
JSONObject json = new JSONObject();
TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
String devid = telephonyManager.getDeviceId();
String postData = "{\"request\":{\"type\":\"locationinfo\"},\"userinfo\":{\"latitude\":\""+latitude+"\",\"longitude\":\""+longitude+"\",\"devid\":\""+devid+"\"}}";
try {
json.put("longitude", longitude);//place each of the strings as you did in postData method
json.put("latitude", latitude);
json.put("devid", devid);
JSONArray postjson=new JSONArray();
postjson.put(json);
httppost.setHeader("json",json.toString());
httppost.getParams().setParameter("jsonpost",postjson);
HttpResponse response = httpclient.execute(httppost);
// for JSON retrieval:
if(response != null)
{
InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String jsonStr = sb.toString(); //take the string you built place in a string
JSONObject rec = new JSONObject(jsonStr);
String longitudecord = rec.getString("lon");
String latitudecord = rec.getString("lat");
// ...
}
}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (who.equals("me")){
Intent i = new Intent(context.getPackageName()+".LocationReceived");
i.putExtra("lat", String.valueOf(latitude));
i.putExtra("longitude", String.valueOf(longitude));
i.putExtra("accuracy", String.valueOf(loc.getAccuracy()));
context.sendBroadcast(i);
Notification notif = new Notification();
NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notif.tickerText = "Location Found!";
notif.icon = R.drawable.ic_launcher;
notif.flags = Notification.FLAG_AUTO_CANCEL;
notif.when = System.currentTimeMillis();
Intent notificationIntent = new Intent(context, TestLocatorActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
notificationIntent.putExtra("lat", String.valueOf(latitude));
notificationIntent.putExtra("longitude", String.valueOf(longitude));
notificationIntent.putExtra("accuracy", String.valueOf(loc.getAccuracy()));
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notif.setLatestEventInfo(context, "Location Found!", "Click to open.", contentIntent);
nm.notify(0, notif);
} else {
SmsManager smsMan = SmsManager.getDefault();
smsMan.sendTextMessage(who, null, "http://maps.google.com/maps?q=loc:"+latitude+","+longitude, null, null);
smsMan.sendTextMessage(who, null, "Latitude: "+latitude+"\nLongitude: "+longitude, null, null);
}
locMan.removeUpdates(this);
try {
wl.release();
} catch (Exception e){
e.printStackTrace();
}
stopSelf();
}
public void onProviderDisabled(String provider){
}
public void onProviderEnabled(String provider) {
//Log.i(tag, "GPS IS ON");
}
public void onStatusChanged(String provider, int status, Bundle extras){
switch(status) {
case LocationProvider.OUT_OF_SERVICE:
case LocationProvider.TEMPORARILY_UNAVAILABLE:
case LocationProvider.AVAILABLE:
break;
}
} };
locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
return 2;
}
}
The main problem I can see here is that You are talking about POST but in Your android LocationService You are creating an HttpGet object:
HttpGet httppost = new HttpGet("http://.../serverFile.php");
and then from nowhere a httpost variable is used as post:
post.setHeader("json",json.toString());
post.getParams().setParameter("jsonpost",postjson);
In PHP I'm not sure what are You trying to achieve by this:
$_SERVER['HTTP_JSON'];
cos I'm sure there is no such index. Instead call
$_POST['jsonpost']; // <-- that is the parameter name from Your JAVA code...
or
$_GET['jsonpost']; // <-- that is the parameter name from Your JAVA code...
It almost looks like You COPY + PASTE the code from similar question here (which this one should be a duplicate of!): Sending Data From Android To Server with JSON data .
EDIT : OK, let's assume that Your android JAVA code is OK and You are sending data through GET. Then You will have to repair Your PHP - try this:
<?php
echo 'Hello, world!';
$json = $_GET['jsonpost']; // get the json you sent through GET...
$data = json_decode($json); // decode the json formatted string...
print_r($data); // print out the $data variable to see whether everything is OK...
$devid = $data->devid;
$longitude = $data->longitude;
$latitude = $data->latitude;
$con = mysql_connect("","","") or die('Could not connect: ' . mysql_error());
mysql_select_db("a5234826_ul", $con);
echo "devid" +$devid;
echo "latitude" + $latitude;
echo "longitude" + $longitude;
$sql = "INSERT INTO `a5234826_ul`.`locations` (
`devid`,
`latitude`,
`longitude`
) VALUES (
'$Devid',
'$latitude',
'$longitude'
);";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
mysql_close($con);
echo json_encode($variable);
You should proceed with the print_r($data); and see whether the data arrived and whether the JSON was decoded and also to see what properties it contains.
EDIT 2 Due to posted logcat: Did You read the error from the logcat? It is so clear!!! Programmer should of course understand what an error message is saying and should thing about what he is doing, not just copy+pasting pieces of code from somewhere without thinking of it... In Your manifest.xml You need to add a permision READ_PHONE_STATE - read about permissions here: http://developer.android.com/reference/android/Manifest.permission.html and about adding permissions to manifest.xml here: http://developer.android.com/guide/topics/security/security.html#permissions.