响应监听器没有工作

时间:2016-06-29 01:38:19

标签: android google-maps android-volley android-json

我是Android界的新手。

我在使用Volley Response.Listener时遇到了一些麻烦。 我不是没有为什么json没有抓住结果,而当我手动执行json URL时,它进展顺利。 请给我一些帮助,找出问题所在。 这是我的代码:

MAIN ACTIVITY.java:

package com.mitrainfotek.locationlistener;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.Marker;

import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity implements
    OnMapReadyCallback,
    GoogleApiClient.OnConnectionFailedListener,
    GoogleApiClient.ConnectionCallbacks,
    LocationListener {

private GoogleMap mMap;
private Marker mMarker;
private GoogleApiClient mLocationClient;
private LocationListener mListener;
private LocationRequest request;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    mLocationClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

    request = new LocationRequest();
    //request = LocationRequest.create();
    request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    request.setInterval(3000);
    request.setFastestInterval(1000);

    mLocationClient.connect();
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    mMap.setMyLocationEnabled(false);
}


@Override
public void onConnected(Bundle bundle) {
    Toast.makeText(this, "Ready To Map!", Toast.LENGTH_SHORT).show();


    mListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            UpdateLoc(location.getLatitude(), location.getLongitude());
        }
    };
    LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, request, mListener);
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Log.w("LatLng", connectionResult.getErrorMessage());
}

@Override
public void onLocationChanged(Location location) {

}

@Override
protected void onPause() {
    super.onPause();
    LocationServices.FusedLocationApi.removeLocationUpdates(mLocationClient, mListener);
}

public void UpdateLoc(double Lat, double Lng) {
    Log.w("LatLng","Start UpdateLoc");

    // Login
    Response.Listener<String> responseListener = new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.w("LatLng", "WUANJEEEEENGG");
            try {
                JSONObject jsonResponse = new JSONObject(response);
                boolean success = jsonResponse.getBoolean("success");

                Log.w("LatLng", String.valueOf(success));

                // Sukses
                if (success == true) {
                    Log.w("LatLng","Success");
                    // Failed
                } else {
                    Log.w("LatLng","Failed");
                }


            } catch (JSONException e) {
                e.printStackTrace();
                Log.w("LatLng", "Failed : " + e.getMessage());
            }

        }
    };

    // temporary Force Parameters
    UpdateLoc updateLoc = new UpdateLoc("mloc_insert", "46", "-6.23434", "106.823423", responseListener);
    RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
    queue.add(updateLoc);
    }
}

UPDATELOC.java:

package com.mitrainfotek.locationlistener;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by MAULANA on 6/28/2016.
 */
public class UpdateLoc extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://10.0.2.2/pangkut.com/pang_function.php";
private Map<String, String> params;

public UpdateLoc (String funcName, String user_no, String lat, String lng, Response.Listener<String> listener) {
    super(Request.Method.POST, REGISTER_REQUEST_URL, listener, null);

    params = new HashMap<>();
    params.put("funcName", funcName);
    params.put("user_no", user_no);
    params.put("lat", lat);
    params.put("lng", lng);
}

@Override
public Map<String, String> getParams() {
    return params;
    }
}

ACTIVITY_MAIN.XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">


<fragment
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mitrainfotek.tespeta.MapsActivity" />
</LinearLayout>

ANDROIDMANIFEST.XML:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mitrainfotek.locationlistener">

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>


<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="*****MY_KEY****" />
</application>

</manifest>

BUILD.GRADLE:

apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion "23.0.3"

defaultConfig {
    applicationId "com.mitrainfotek.locationlistener"
    minSdkVersion 17
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
    }
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.google.android.gms:play-services:9.0.0'
compile 'com.android.volley:volley:1.0.0'
}
非常感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

您可以在实例化(对象)updateloc时添加参数。除了传入四个参数和一个responseListener之外,添加另一个接收你的url的参数。还将此参数添加到updateLoc构造函数