我已经尝试过某种方式,但响应总是为空, 但是我会用吐司和预期的方式发送数据
我也用邮递员检查数据按照键值发送的时间,然后结果是合适的。
这是我发送数据的代码
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));
}
答案 0 :(得分:1)
尝试在键值对中发送数据,请尝试以下代码:
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>() {
......
}
答案 1 :(得分:0)
尝试使用getparams()
添加此代码 @Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
答案 2 :(得分:0)
问题已解决
我将objectRequest替换为成功发送的stringRequest参数
非常感谢你们