Как отправить php запрос в Android?

Я здесь новый парень и сейчас изучаю приложение для Android.
Я пытаюсь получить местоположение GPS и отправить его обратно в базу данных, но он просто продолжает сбой.

Я пытался исправить это в течение нескольких дней и пробовал много других решений.
До сих пор я все еще не могу найти способ работы в этом случае. Может кто-нибудь, пожалуйста, помогите мне?

С наилучшими пожеланиями.

Это мой код

public class MainActivity extends AppCompatActivity {
private Button start, stop;
private TextView textView;

private BroadcastReceiver broadcastreceiver;

RequestQueue requestQueue;
String insertUrl = "http://140.123.107.170/st2017a/RT2.php";
String latitude = "0";
String longitude = "0";
String age;

@Override
protected void onResume() {
super.onResume();
//If receiver doesn't exist create a new one
if (broadcastreceiver == null) {
broadcastreceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {

//textView.append("\n" +intent.getExtras().get("coordinates"));//"coordinates" is defined in GPS_Service
////////I guess it crash here///////////////////////
POST__(intent.getExtras().get("coordinates"), System.currentTimeMillis());
}
};
}
//receiver  from above
//filter    "location_update" in GPS_Service
registerReceiver(broadcastreceiver, new IntentFilter("location_update"));
}

private void POST__(Object input, long time) {
//textView.append("\n" +input);
String[] cutten = input.toString().split(" ");//cut input Object into String
//check
textView.append("\n----" +cutten[0] + "-----\n");
textView.append("\n----" +cutten[1] + "-----\n");
textView.append("\n-----"+ time + "-----\n");
latitude = cutten[0];
longitude = cutten[1];

//build the request
StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("latitude", latitude);
parameters.put("longitude", longitude);
parameters.put("age", age);
return parameters;
}
};
requestQueue.add(request);
}

@Override
protected void onDestroy() {
super.onDestroy();
if (broadcastreceiver != null) {
unregisterReceiver(broadcastreceiver);
}
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

start = (Button) findViewById(R.id.button);
stop = (Button) findViewById(R.id.button2);
textView = (TextView) findViewById(R.id.textView);

if (!check_permissions()) {
enable_buttons();
}
}

private void enable_buttons() {
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), GPS_Service.class);
startService(i);
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), GPS_Service.class);
stopService(i);
}
});
}

private Boolean check_permissions() {
if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, Manifest.permission
.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission
.ACCESS_COARSE_LOCATION}, 100);

return true;
}
return false;
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
grantResult) {
super.onRequestPermissionsResult(requestCode, permissions, grantResult);
if (requestCode == 100) {
enable_buttons();
} else {
check_permissions();
}
}

}

Сервис для определения местоположения по GPS

public class GPS_Service extends Service{

@Nullable
@Override
public IBinder onBind(Intent intent){
return null;
}

private LocationListener listener;
private LocationManager locationManager;

@Override
public void onCreate(){
listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {

Intent i = new Intent("location_update");

i.putExtra("coordinates",location.getLatitude() + " " +location.getLongitude());

sendBroadcast(i);
}

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

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

startActivity(i);
}
};

locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);

//noinspection MissingPermission
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER , 3000,0,listener);
/*GPS Location        : LocationManager.GPS_PROVIDER;
NETWORK Location    : LocationManager.NETWORK_PROVIDER;*/
//check by check_permissions() in MainActivity
}

//To prevent memory leak when service is destroy
@Override
public  void onDestroy(){
super.onDestroy();
if(locationManager != null){
locationManager.removeUpdates(listener);
}
}

}

Logcat

05-20 15:43:17.674 2638-2638/net.jack.learn E/AndroidRuntime: FATAL EXCEPTION: main
Process: net.jack.learn, PID: 2638
java.lang.RuntimeException: Error receiving broadcast Intent { act=location_update flg=0x10 (has extras) } in net.jack.learn.MainActivity$1@5e6e6a0
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:1132)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.android.volley.Request com.android.volley.RequestQueue.add(com.android.volley.Request)' on a null object reference
at net.jack.learn.MainActivity.POST__(MainActivity.java:111)
at net.jack.learn.MainActivity.access$000(MainActivity.java:34)
at net.jack.learn.MainActivity$1.onReceive(MainActivity.java:70)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:1122)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

0

Решение

После нескольких дней поиска я нахожу решение от http://www.c-sharpcorner.com/article/binding-services-to-activity-part-2/

0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector