Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Dear All
I am getting problem in PHP code but I don't know also Android code is correct or not. Anyone help me to find out the problem.

As below I am showing my written code.

MainActivity.Java Code
Java
public class MainActivity extends Activity {
	
    private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
    private static final long MINIMUM_TIME_BETWEEN_UPDATES = 2000; // in Milliseconds
     
    protected LocationManager locationManager;
    protected Button retrieveLocationButton;
    TextView txtLatLng;
    UserClass user;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    	 
    retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);
    txtLatLng = (TextView) findViewById(R.id.textview1);
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    
    locationManager.requestLocationUpdates(
    		LocationManager.NETWORK_PROVIDER, 
    		MINIMUM_TIME_BETWEEN_UPDATES, 
    		MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
    		new MyLocationListener()
    );
       
    retrieveLocationButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCurrentLocation();
                new HttpAsyncTask().execute("http://localhost:8080/Monitoring/index.php");
                /*Toast.makeText(MainActivity.this,"Data Sent Successfully !!!", Toast.LENGTH_LONG).show();*/
	            }
    		});        
    	}
    
    protected void showCurrentLocation() {
    	Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);  	
    	if (location != null) {
    		String message = String.format("Current Location \n Longitude: %1$s \n Latitude: %2$s",location.getLongitude(), location.getLatitude());
    		Toast.makeText(MainActivity.this, message,Toast.LENGTH_LONG).show();
    	}
    }
    
    private class MyLocationListener implements LocationListener {
    	
    	public void onLocationChanged(Location location) {
    		String message = String.format("New Location \n Longitude: %1$s \n Latitude: %2$s",location.getLongitude(), location.getLatitude());
    		Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
    	}

    	public void onStatusChanged(String s, int i, Bundle b) {
    		Toast.makeText(MainActivity.this, "Provider status changed",Toast.LENGTH_LONG).show();
    	}
    	
    	public void onProviderDisabled(String s) {
    		Toast.makeText(MainActivity.this,"GPS turned off disabled by the user. ",Toast.LENGTH_LONG).show();
    	}

    	public void onProviderEnabled(String s) {
    		Toast.makeText(MainActivity.this,"GPS turned on enabled by the user. ",Toast.LENGTH_LONG).show();
    	}
    }
    
    public static String POST(String url, UserClass user){
        InputStream inputStream = null;
        String result = "";
        try {
 
            // 1. create HttpClient
            HttpClient httpclient = new DefaultHttpClient();
 
            // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost(url);
 
            String json = "";
 
            // 3. build jsonObject
            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("Lat", user.getLat());
            jsonObject.accumulate("Lon", user.getLon());
            /*jsonObject.accumulate("TABID", user.getTABID());*/
 
            // 4. convert JSONObject to JSON to String
            json = jsonObject.toString();
 
            // ** Alternative way to convert Person object to JSON string using Jackson Lib
            // ObjectMapper mapper = new ObjectMapper();
            // json = mapper.writeValueAsString(person);
 
            // 5. set json to StringEntity
            StringEntity se = new StringEntity(json);
 
            // 6. set httpPost Entity
            httpPost.setEntity(se);
 
            // 7. Set some headers to inform server about the type of the content   
            httpPost.setHeader("Accept", "application/json");
            /*httpPost.setHeader("Content-type", "application/json")*/;
            httpPost.getParams().setParameter("jsonpost",json);
 
            // 8. Execute POST request to the given URL
            HttpResponse httpResponse = httpclient.execute(httpPost);
 
            // 9. receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();
 
            // 10. convert inputstream to string
            if(inputStream != null)
                result = convertInputStreamToString(inputStream);
            else
                result = "Did not work!";
 
        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }
 
        // 11. return result
        return result;
    }
    
    private static String convertInputStreamToString(InputStream inputStream) throws IOException{
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine()) != null)
            result += line;
        inputStream.close();
        return result; 
    }  
    
    private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
        	Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            user = new UserClass();
            user.setLat(location.getLatitude());
            user.setLon(location.getLongitude());
            /*user.setTABID(txtTABID.getText().toString());*/
            return POST(urls[0],user);
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(MainActivity.this,"Data Sent Successfully !!!", Toast.LENGTH_LONG).show();
       }
    } 
}


PHP Code
PHP
<?php

echo 'Hello, world!';

$json = $_GET['json']; // 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...

$tabid = $data->tabid;
$lon = $data->lon;
$lat = $data->lat;

$con = mysql_connect("localhost","root","") or die('Could not connect: ' . mysql_error());    
mysql_select_db("dssmonitoring", $con);

echo "tabid" +$tabid;
echo "lat" + $lat;
echo "lon" + $lon; 

$sql = "INSERT INTO  `dssmonitoring`.`monitor` (
    `tabid`,
    `lat`,
    `lon` 
) VALUES (
    '$tabid',
    '$lat',  
    '$lon'
);";
if (!mysql_query($sql,$con)) {
    die('Error: ' . mysql_error());
}

mysql_close($con);
?>
Posted
Comments
Dave Kreskowiak 8-Jan-24 9:53am    
"Correct or not" isn't a valid question. We have no idea what the code is supposed to do, what problem you're having, or anything else you're trying to do.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900