Volley connection 使用(Where)条件句一次性获取所有数据 [英] Volley connection get all data in one time with use (Where) Conditional Sentence

查看:36
本文介绍了Volley connection 使用(Where)条件句一次性获取所有数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Google 地图来显示特定位置.位置数据从我的数据库中获取,并且已经在数据库中可用.我的数据库中的每个字段都有自己的位置,如纬度和经度.

I use Google Maps to display specific location. The data of location get from my database and it's already available into database. Every field in my database has own location as Latitude and Longitude.

例如

学生 1 - 座位号 - 学期 - 纬度 - 经度

Student 1 - Seating Number - Semester - Latitude - Longitude

学生 1 - 3 - 2 - 33.8523341 - 151.2106085

Student 1 - 3 - 2 - 33.8523341 - 151.2106085

就这样..

问题是 Volley 连接一次从数据库中获取所有学生的位置数据.这是错误,我应该只获取所选学生的数据(我使用条件句(Where)进入 Volley 的 url 和 php 文件以获取特定的数据.但我不知道为什么它仍然不起作用).

The problem is Volley connection get all students location data from databases at once time .This is error, I should only get the data of chosen student (I use Conditional Sentence (Where) into url of Volley and php file to get specific data.But I don't Know Why still it's not work ).

如下图所示,我在数据库中有两名学生,当我订购一名学生时,他们的位置点同时出现.

As you can see picture below that I have two students in the database and their location points appear at same time when I order one student.

这张图片来自数据库,你可以看到我现在必须学习:

And this picture from database as you can see I have to student now :

如果有人知道解决方案请帮我我需要根据每个学生的数据库中的数据显示不同的位置.

If any one know the solution please help me I need to display different locations according to the data in the database for each student.

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);

?>


推荐答案

好的,你应该在你的 Activity 顶部声明:

Ok, you should declare this at the top of your activity :

private String st_id = "";

然后在 onCreate() 中,像您一样从意图中获取字符串.

Then in onCreate(), get your string from the intent like you did.

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

并且在调用方法 getMarkers() 时,请确保您的 st_id 字符串不为空,因为 php 会向您发送整个数据库.这里:

And when calling method getMarkers(), make sure your st_id String is not empty, because php will send you the entire data base. here :

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

告诉我这是否解决了你的问题;

tell me if that solved your pb;

这篇关于Volley connection 使用(Where)条件句一次性获取所有数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆