我是此Android编程的新手。 这次我想从MySQL数据库获取数据的纬度和经度。 我已经完成了从Arduino向我的MySQL数据库发送GPS数据的操作,然后我想使用Google Map API在我的android应用程序中动态显示它。
这是我的MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private final static String TAG = "EasyBle";
private Handler handler;
private RecyclerView rv;
private BleManager manager;
private List<BleDevice> deviceList = new ArrayList<>();
private ScanDeviceAdapter adapter;
private Handler mhandler = new Handler();
String nilaiLat;
String nilaiLong;
double lat, lng, backupLat, backupLng;
ProgressDialog loading; //========= EDITED ==============
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initBleManager();
showDevicesByRv();
handler = new Handler();
new Connection().execute();
}
case R.id.btn_disconnect:
manager.disconnectAll();
onPause();
//========== EDITED ================
loading = new ProgressDialog(MainActivity.this);
loading.setTitle("Mendapatkan Lokasi Terkini");
loading.setMessage("Tunggu Sebentar ..");
loading.setCancelable(false);
loading.show();
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
loading.dismiss();
}catch (Exception e){
e.printStackTrace();
}
}
}).start();
//========== EDITED ================
Intent intent = new Intent(MainActivity.this, MapsActivity.class);
//========== EDITED ================
intent.putExtra("Latitude", nilaiLat);
intent.putExtra("Longitude", nilaiLong);
//========== EDITED ================
startActivity(intent);
class Connection extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
String result = "";
String host = "https://gpslocation123.000webhostapp.com/ambil_data_gps.php";
try{
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI (new URI(host));
HttpResponse response = client.execute(request);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer stringBuffer = new StringBuffer("");
String line = ""; //Data kendaraan akan di simpan disini
while ((line = reader.readLine()) != null){
stringBuffer.append(line);
//break;
}
reader.close();
result = stringBuffer.toString();
}
catch (Exception e){
return new String("Exception : " + e.getMessage());
}
return result;
}
@Override
protected void onPostExecute(String result){
//Parsing json data disini
try{
JSONObject jsonResult = new JSONObject(result);
int success = jsonResult.getInt("success");
if(success == 1){
JSONArray data = jsonResult.getJSONArray("data");
for(int i=0; i < data.length(); i++){
JSONObject dtkendaraan = data.getJSONObject(i);
String longitude = dtkendaraan.getString("longitude");
String latitude = dtkendaraan.getString("latitude");
nilaiLat = latitude;
nilaiLong = longitude;
}
我的MapsActivity
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
public GoogleMap mMap;
String nilaiLat;
String nilaiLong;
double lat, lng, backupLat, backupLng;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Intent intent = getIntent();
//============== EDITED ====================
String data1 = intent.getStringExtra("latitude");
String data2 = intent.getStringExtra("longitude");
lat = Double.parseDouble(data1);
lng = Double.parseDouble(data2);
//============== EDITED ====================
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-lat, lng);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
public void getData(View view)
{
new Connection().execute();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
LatLng lokasi = new LatLng(lat,lng);
mMap.clear();
mMap.addMarker(new MarkerOptions().position(lokasi).title("Posisi Kendaraan"));
mMap.moveCamera(
CameraUpdateFactory.newLatLngZoom(
lokasi,
16f
)
);
Toast.makeText(getBaseContext(), lat + ", " + lng, Toast.LENGTH_SHORT).show();
}
}, 3000);
}
class Connection extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
String result = "";
String host = "https://gpslocation123.000webhostapp.com/ambil_data_gps.php";
try{
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI (new URI(host));
HttpResponse response = client.execute(request);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer stringBuffer = new StringBuffer("");
String line = ""; //Data kendaraan akan di simpan disini
while ((line = reader.readLine()) != null){
stringBuffer.append(line);
//break;
}
reader.close();
result = stringBuffer.toString();
}
catch (Exception e){
return new String("Exception : " + e.getMessage());
}
return result;
}
@Override
protected void onPostExecute(String result){
//Parsing json data disini
try{
JSONObject jsonResult = new JSONObject(result);
int success = jsonResult.getInt("success");
if(success == 1){
JSONArray data = jsonResult.getJSONArray("data");
for(int i=0; i < data.length(); i++){
JSONObject dtkendaraan = data.getJSONObject(i);
String longitude = dtkendaraan.getString("longitude");
String latitude = dtkendaraan.getString("latitude");
nilaiLat = latitude;
nilaiLong = longitude;
}
if(nilaiLat.equals("") && nilaiLat.equals("")){
lat = backupLat;
lng = backupLng;
}
else{
lat = Double.parseDouble(nilaiLat);
lng = Double.parseDouble(nilaiLong);
backupLat = lat;
backupLng = lng;
}
}
}
catch(JSONException e){
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
}
我的Connection.java与我的虚拟主机连接
package com.ficat.sample;
import android.app.Activity;
import android.os.AsyncTask;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
class Connection extends AsyncTask<String, String, String> {
String nilaiLat;
String nilaiLong;
double lat, lng, backupLat, backupLng;
@Override
protected String doInBackground(String... params) {
String result = "";
String host = "https://gpslocation123.000webhostapp.com/ambil_data_gps.php";
try{
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI (new URI(host));
HttpResponse response = client.execute(request);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer stringBuffer = new StringBuffer("");
String line = ""; //Data kendaraan akan di simpan disini
while ((line = reader.readLine()) != null){
stringBuffer.append(line);
//break;
}
reader.close();
result = stringBuffer.toString();
}
catch (Exception e){
return new String("Exception : " + e.getMessage());
}
return result;
}
@Override
protected void onPostExecute(String result){
//Parsing json data disini
try{
JSONObject jsonResult = new JSONObject(result);
int success = jsonResult.getInt("success");
if(success == 1){
JSONArray data = jsonResult.getJSONArray("data");
for(int i=0; i < data.length(); i++){
JSONObject lokasi = data.getJSONObject(i);
String latitude = lokasi.getString("latitude");
String longitude = lokasi.getString("longitude");
nilaiLat = latitude;
nilaiLong = longitude;
}
if(nilaiLat.equals("") && nilaiLat.equals("")){
lat = backupLat;
lng = backupLng;
}
else{
lat = Double.parseDouble(nilaiLat);
lng = Double.parseDouble(nilaiLong);
backupLat = lat;
backupLng = lng;
}
}
}
catch(JSONException e){
// Toast.makeText(context.getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
} 这是我的PHP代码
<?php
$servername = "localhost";
$username = "id10329518_yudaihza";
$password = " ";
$dbname = "id10329518_db_gps";
error_reporting(E_ALL ^ E_DEPRECATED);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
echo "Tidak Ada Koneksi";
}
$response = array();
$sql_query = "SELECT * FROM location ORDER BY no DESC LIMIT 1";
$result = mysqli_query($conn, $sql_query);
if(mysqli_num_rows($result) > 0){
$response['success'] = 1;
$data = array();
while ($row = mysqli_fetch_assoc($result)){
array_push($data, $row);
}
$response['data'] = $data;
}
else{
$response['success'] = 0;
$response['message'] = 'No Data';
}
echo json_encode($response);
mysqli_close($conn);
?>
但是每当我打开应用程序时,敬酒“价值