android - 如何使用 Volley Library 发送数据?

标签 android android-volley google-distancematrix-api

我尝试过某种方式,但响应始终为空, 但是数据将被发送我用 toast 检查并按预期发送

我也用过postman来检查,什么时候数据按照key值发送,结果是否合适。

这是我发送数据的代码

public class FragmentPetaniTerdekat extends Fragment {

    Context context;
    View view;
    Dialog dialog;
    RecyclerView recyclerView;

    ArrayList<String> jenis = new ArrayList<>();
    ArrayList<String> jarak = new ArrayList<>();
    ArrayList<String> durasi = new ArrayList<>();

    String my_location;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getContext();
        dialog = new Dialog(context);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_fragment_petani, container, false);
        location();
        return view;
    }

//    get adddres name current location
    private void location() {
        dialog.showDialog("Pesan","memuat data...");
        LocationListener mLocationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                // get lat and lng
                if (location != null) {
                    double lat = location.getLatitude();
                    double lng = location.getLongitude();

                    my_location = String.valueOf(lat+","+lng);
                    getApi(my_location);
                    Toast.makeText(context,String.valueOf(lat+","+lng),Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(context,"lokasi tidak ditemukan",Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }

            @Override
            public void onProviderEnabled(String provider) {
            }

            @Override
            public void onProviderDisabled(String provider) {
            }
        };

        LocationManager mLocationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE);

        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return ;
        }

        // check alternative get location
        boolean GPS_ENABLE, NETWORK_ENABLE;
        GPS_ENABLE = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        NETWORK_ENABLE = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (GPS_ENABLE){
            Toast.makeText(getActivity(),"GPS state",Toast.LENGTH_LONG).show();
            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000 * 60 * 1 , 1, mLocationListener);
        }else if(NETWORK_ENABLE){
            Toast.makeText(getActivity(),"network state",Toast.LENGTH_LONG).show();
            mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 1,mLocationListener);
        }else{
            Toast.makeText(getActivity(),"ganok seng kepilih cak",Toast.LENGTH_LONG).show();
            showSettingsAlert();
        }

    }

//    show alert setting if gps non aktif
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                getActivity().startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    public void initRecylerView(View v){
        recyclerView = (RecyclerView)v.findViewById(R.id.recylerview_petani_terdekat);

        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context);
        recyclerView.setLayoutManager(layoutManager);

        RecyclerView.Adapter adapter = new AdapterPetaniTerdekat(context,jenis,jarak,durasi);
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

    }

    public void getApi(final String my_location){
        Log.e("my_location", my_location);
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL_PETANI_TERDEKAT, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                dialog.message(response.toString());
                if (response != null) {
                    try {
                        JSONArray get_respone = response.getJSONArray("result_petani_terdekat");

                        for (int i=0; i<get_respone.length(); i++){

                            JSONObject result = get_respone.getJSONObject(i);

                            ModelPetaniTerdekat petaniTerdekat = new ModelPetaniTerdekat();
                            petaniTerdekat.setJenis(result.getString("jenis"));

                            JSONObject kriteria = result.getJSONObject("jarak");
                            for (int z=0; z<kriteria.length(); z++){
                                petaniTerdekat.setJarak(kriteria.getString("distance"));
                                petaniTerdekat.setDurasi(kriteria.getString("duration"));
                            }

                            jenis.add(petaniTerdekat.getJenis());
                            jarak.add(petaniTerdekat.getJarak());
                            durasi.add(petaniTerdekat.getDurasi());

                            dialog.closeDialog();
                        }

                        initRecylerView(view);

                    } catch (JSONException e) {
                        dialog.message("Error : "+e.toString());
                        e.printStackTrace();
                    }
                }else{
                    dialog.message("Error : Tidak ada data !");
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                    dialog.message("Error : TimeoutError");
                } else if (error instanceof AuthFailureError) {
                    dialog.message("Error : AuthFailureError");
                } else if (error instanceof ServerError) {
                    dialog.message("Error : ServerError");
                } else if (error instanceof NetworkError) {
                    dialog.message("Error : NetworkError");
                } else if (error instanceof ParseError) {
                    error.printStackTrace();
                    dialog.message("Error : ParseError");
                }
                dialog.closeDialog();
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> stringMap = new HashMap<>();
                stringMap.put("lokasi_saya",my_location);
                return stringMap;

            }
        };

        AppSingleton.getInstance(context).addToRequestQueue(request);
        request.setRetryPolicy(new DefaultRetryPolicy(
                60000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }


}

这是我的网络服务

header('Content-Type: application/json');

include_once 'helper_api.php';
include_once '../crud.php';

if ($_SERVER['REQUEST_METHOD']=='POST') {

    $origins = isset($_POST['lokasi_saya'])?$_POST['lokasi_saya']:"";

    $crud    = new Crud();

    $sql     = "SELECT tb_petani.id_petani, tb_petani.nama, tb_petani.no_telp, tb_petani.alamat, tb_jenis.nama_jenis
                FROM tb_petani, tb_master_cabe, tb_jenis
                WHERE tb_jenis.id_jenis = tb_master_cabe.id_jenis
                AND tb_petani.id_petani = tb_master_cabe.id_petani
                AND tb_petani.status ='2'";
    $result  = $crud->fetchData($sql);

    $helper  = new Helper_api();

    $data_petani = array();
    foreach ($result as $value) {
        $destinatios = $value['alamat'];

        $distance_duration = $helper->getDistanceDuration($origins, $destinatios);

        $data_petani[] = array(
            "nama"=>$value['nama'],
            "no_telp"=>$value['no_telp'],
            "alamat"=>$value['alamat'],
            "jenis"=>$value['nama_jenis'],
            "jarak"=>$distance_duration
        );
    }

    // sort ascending array multidimensi (distance)
    usort($data_petani, function($a, $b) {
        return $a['jarak']['distance'] - $b['jarak']['distance'];
    });

    echo json_encode(array("result_petani_terdekat"=>$data_petani));
}

最佳答案

尝试在键值对中发送数据,试试这个代码:

       HashMap<String, String> inputs = new HashMap<String, String>();
       inputs.put("your key1", "value");
       inputs.put("your key2", "value2");

        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
            URL_PETANI_TERDEKAT, new JSONObject(inputs),
            new com.android.volley.Response.Listener<JSONObject>() {
                ......
            }

关于android - 如何使用 Volley Library 发送数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43906422/

相关文章:

google-maps - 使用地点 ID 查找距离

javascript - 无法访问从谷歌距离矩阵函数派生的变量值

javascript - Google 距离矩阵 API 特定出发时间

java - Twitter4j:在某个推文/时间点后下载推文

Android:将自定义复选框动态添加到 tableLayout

android - 错误版本发布APK

android - 如何检查 Volley Request Queue 是否为空?Request 已完成?

java - 使用volley在Android Studio中调用API(JAVA)

java - 单击后如何禁用 ListView 项目?

javascript - Android studio Volley 响应不好