Соединение залпа получает все данные за один раз с использованием (где) условного предложения - PullRequest
0 голосов
/ 26 апреля 2020

Я использую Google Maps для отображения указанного c местоположения. Данные о местоположении получают из моей базы данных, и она уже доступна в базе данных. Каждое поле в моей базе данных имеет свое местоположение в виде Широты и Долготы.

Например

Студент 1 - Номер места - Семестр - Широта - Долгота

Студент 1 - 3 - 2 - 33.8523341 - 151.2106085

вот так ..

Проблема заключается в том, что подключение Volley получает данные о местоположении всех учащихся одновременно из баз данных. Это ошибка, я должен получать данные только выбранного ученика ( Я использую условное предложение (где) в URL-адрес Volley и файл php, чтобы получить конкретные c данные. Но я не знаю, почему это все еще не работает).

Как вы можете видеть на картинке ниже, У меня есть два студента в базе данных, и их точки местоположения появляются одновременно, когда я заказываю одного студента.

enter image description here

И это изображение из базы данных, как вы можете видите, я должен учиться сейчас:

enter image description here

Если кто-нибудь знает решение, пожалуйста, помогите мне, мне нужно отобразить различные местоположения в соответствии с данными в базе данных за каждого студента нт.

public class GetMapLaction extends AppCompatActivity implements OnMapReadyCallback {

    GoogleMap gMap;
    MarkerOptions markerOptions = new MarkerOptions();
    private final LatLng mDefaultLocation = new LatLng(-33.8523341, 151.2106085);
     FusedLocationProviderClient mFusedLocationProviderClient;
    private static final int DEFAULT_ZOOM = 6;
    private CameraPosition mCameraPosition;
    private Location mLastKnownLocation;
    LatLng latLng;
    String title;
    private boolean mLocationPermissionGranted;
    private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
    private static final String KEY_CAMERA_POSITION = "camera_position";
    public static final String st_ids= "st_id";
    public static final String TITLE = "nama";
    public static final String LAT = "Latitude";
    public static final String LNG = "Longitude";
    private static final String TAG = GetMapLaction.class.getSimpleName();
    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
            mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
        }

        setContentView(R.layout.get_map_lcation);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
        Intent i = getIntent();
        final String st_id= i.getStringExtra("st_id");
        textView=(TextView)findViewById(R.id.textView) ;
        textView.setText(textView.getText() + st_id);


    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        if (gMap != null) {
            outState.putParcelable(KEY_CAMERA_POSITION, gMap.getCameraPosition());
            outState.putParcelable(KEY_LOCATION, mLastKnownLocation);
            super.onSaveInstanceState(outState);
        }
    }
    @Override
    public void onMapReady(GoogleMap map) {
        gMap = map;

        if (ContextCompat.checkSelfPermission(GetMapLaction.this,
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
  permission!",Toast.LENGTH_SHORT).show();
            mLocationPermissionGranted = true;
            getMarkers();

        } else {
            requestStoragePermissionn();
        }
    }


    private void requestStoragePermissionn() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {

            new AlertDialog.Builder(this)
                    .setTitle("Permission needed")
                    .setMessage("This permission is needed because of this and that")
                    .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(GetMapLaction.this,
                                    new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
                        }
                    })
                    .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                          dialog.dismiss();
                        }
                    })
                    .create().show();

        } else {
            ActivityCompat.requestPermissions(this,
                    new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION)  {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getMarkers();
                gMap.setMyLocationEnabled(true);
                gMap.getUiSettings().setZoomControlsEnabled(true);
                gMap.setMinZoomPreference(7);
                Toast.makeText(this, "Permission GRANTED", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Permission DENIED", Toast.LENGTH_SHORT).show();

            }
        }
    }

    private void addMarker(LatLng latlng, final String title) {
        markerOptions.position(latlng);
      markerOptions.title(title);
        gMap.addMarker(markerOptions);
        gMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {

            @Override
            public void onInfoWindowClick(Marker marker) {
                Toast.makeText(getApplicationContext(), marker.getTitle(), Toast.LENGTH_SHORT).show();
            }
        });
    }


    private void getMarkers() {
        final String url ="http://000000000/stedant/map.php?st_id=" + st_id;
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                    Log.e("Response: ", response.toString());
                    try {
                        JSONObject jObj = new JSONObject(response);
                        String getObject = jObj.getString("data");
                        JSONArray jsonArray = new JSONArray(getObject);
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            //  title = jsonObject.getString(TITLE);
                            latLng = new LatLng(Double.parseDouble(jsonObject.getString(LAT)), Double.parseDouble(jsonObject.getString(LNG)));
                            addMarker(latLng, title);
                         gMap.animateCamera(zoomingLocation(latLng));
                        }
                    } catch (JSONException e) {
                        Toast.makeText(GetMapLaction.this, "This is my Toast message!", Toast.LENGTH_LONG).show();
                    }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("Error: ", error.getMessage());
                Toast.makeText(GetMapLaction.this, error.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        requestQueue.add(stringRequest);

    }
    private CameraUpdate zoomingLocation(LatLng latLng) {
       return CameraUpdateFactory.newLatLngZoom(latLng, 7);
    }


    private void getDeviceLocation() {

        try {
            if (mLocationPermissionGranted) {
                Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
                locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {
                    @Override
                    public void onComplete(@NonNull Task<Location> task) {
                        if (task.isSuccessful()) {
                            // Set the map's camera position to the current location of the device.
                            mLastKnownLocation = task.getResult();
                            if (mLastKnownLocation != null) {
                                gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                                        new LatLng(mLastKnownLocation.getLatitude(),
                                                mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
                            }
                        } else {
                            Log.d(TAG, "Current location is null. Using defaults.");
                            Log.e(TAG, "Exception: %s", task.getException());
                            gMap.moveCamera(CameraUpdateFactory
                                    .newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
                            gMap.getUiSettings().setMyLocationButtonEnabled(false);
                        }
                    }
                });
            }
        } catch (SecurityException e)  {
            Log.e("Exception: %s", e.getMessage());
        }
    }
    private void updateLocationUI() {
        if (gMap == null) {
            return;
        }
        try {
            if (mLocationPermissionGranted) {
                gMap.setMyLocationEnabled(true);
                gMap.getUiSettings().setMyLocationButtonEnabled(true);
            } else {
                gMap.setMyLocationEnabled(false);
                gMap.getUiSettings().setMyLocationButtonEnabled(false);
                mLastKnownLocation = null;
             //  getLocationPermission();
            }
        } catch (SecurityException e)  {
            Log.e("Exception: %s", e.getMessage());
        }
    }

}


<?php
$con=mysqli_connect("localhost","test","","student");

$st_id= strip_tags(trim($_GET["st_id"]));
$sql="SELECT * FROM Student where st_id= $st_id";
$result=mysqli_query($con,$sql);

$data=array();
while($row=mysqli_fetch_assoc($result)){
$data["data"][]=$row;

}
    //header('Content-Type:Application/json');

    echo json_encode($data);

?>


1 Ответ

1 голос
/ 27 апреля 2020

Хорошо, вы должны объявить это в начале своей деятельности:

private String st_id = "";

Затем в onCreate() получите свою строку из намерения, как вы сделали.

st_id = getIntent().getStringExtra("st_id");

И при вызове метода getMarkers () убедитесь, что ваша строка st_id не пуста, потому что php отправит вам всю базу данных. здесь:

final String url ="......../stedant/map.php?st_id=" + st_id;

скажите мне, если это решило ваш пб;

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...