【问题标题】:Response Listener didn't work响应侦听器不起作用
【发布时间】:2016-06-29 01:38:19
【问题描述】:

我是 Android 世界的新手。

我在使用 Volley Response.Listener 时遇到了一些问题。 我不知道为什么 json 没有捕捉到结果,而当我手动执行 json URL 时,它运行良好。 请帮我找出问题所在。 这是我的代码:

主要活动.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'
}

非常感谢您的帮助。

【问题讨论】:

  • 您还应该创建 Volley 错误侦听器。看看是什么错误
  • 您是否收到任何特定错误?
  • 感谢马克提供线索。
  • @intj 创建凌空错误侦听器后,是的,问题已解决。谢谢你

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


【解决方案1】:

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

【讨论】:

猜你喜欢
  • 2017-09-27
  • 1970-01-01
  • 1970-01-01
  • 2013-04-30
  • 1970-01-01
  • 2018-11-26
  • 1970-01-01
  • 2012-05-20
  • 2011-11-24
相关资源
最近更新 更多