繁体   English   中英

使用 Foursquare 通过 Android Studio 获取附近的地方?

[英]Using Foursquare to get Nearby places with Android Studio?

我试图使用 foursquare api 获取附近的地方,但在启动我的应用程序时我崩溃了!

我制作了我的 GPSTracker、Googlemap 部分并使用了 foursquare api 但我没有工作? 任何的想法 ?

主要活动

package com.company.nearbyplaces_2;


import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.google.android.gms.maps.*;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends Activity {

ArrayList<FoursquareModel> venuesList;

final String CLIENT_ID = "**********************************************";
final String CLIENT_SECRET = "*******************************************************";

// we will need to take the latitude and the logntitude from a certain point

protected LocationManager locationManager;
protected LocationListener locationListener;
protected double latitude, longitude;
ArrayAdapter<String> myAdapter;

// GPSTracker class
GPSTracker gps;

// Near BY ListView
ListView lv;

// Google Map
private GoogleMap googleMap;

// ArrayList & array list adapter to set listview
ArrayList<FoursquareModel> _commentList = new ArrayList<FoursquareModel>();
NearbyListAdapter _nearByListAdapter;

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

    lv = (ListView) findViewById(R.id.listview);
    gps = new GPSTracker(this);

    // check if GPS enabled
    if (gps.canGetLocation()) {

        latitude = gps.getLatitude();
        longitude = gps.getLongitude();

    } else {

        gps.showSettingsAlert();
    }

    try {
        // Loading map
        initilizeMap();



        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                new LatLng(latitude, longitude), 13));

        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(new LatLng(latitude, longitude)) // Sets the center
                                                            // of the map to
                                                            // location user
                .zoom(17) // Sets the zoom
                .build(); // Creates a CameraPosition from the builder
        googleMap.animateCamera(CameraUpdateFactory
                .newCameraPosition(cameraPosition));

        // googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
        googleMap.setMyLocationEnabled(true);
        googleMap.getUiSettings().setCompassEnabled(true);

    } catch (Exception e) {
        e.printStackTrace();
    }


    // start the AsyncTask that makes the call for the venus search.

    new fourquare().execute();

}



private void initilizeMap() {
    if (googleMap == null) {
        googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                R.id.map)).getMap();

        // check if map is created successfully or not
        if (googleMap == null) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                    .show();
        }
    }
}

private class fourquare extends AsyncTask<View, Void, String> {

    String temp;

    @Override
    protected String doInBackground(View... urls) {
        // make Call to the url
        temp = makeCall("https://api.foursquare.com/v2/venues/search?client_id="
                + CLIENT_ID
                + "&client_secret="
                + CLIENT_SECRET
                + "&v=20130815&ll="
                + String.valueOf(latitude)
                + ","
                + String.valueOf(longitude));
        Log.e("Link ---- > ", temp);
        return "";
    }

    @Override
    protected void onPreExecute() {
        // we can start a progress bar here
    }

    @Override
    protected void onPostExecute(String result) {
        if (temp == null) {
            // we have an error to the call
            // we can also stop the progress bar
        } else {
            // all things went right

            // parseFoursquare venues search result
            venuesList = (ArrayList<FoursquareModel>) parseFoursquare(temp);

            // set the results to the list
            // and show them in the xml
            _nearByListAdapter = new NearbyListAdapter(getBaseContext(), 0,
                    venuesList);

            lv.setAdapter(_nearByListAdapter);

            for (FoursquareModel model : venuesList) {

                // create marker
                MarkerOptions marker = new MarkerOptions().position(
                        new LatLng(model.getLatitude(), model
                                .getLongtitude())).title(model.getName());

                // Changing marker icon
                marker.icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_GREEN));

                // adding marker
                googleMap.addMarker(marker);
            }

        }
    }
}

public static String makeCall(String url) {

    // string buffers the url
    StringBuffer buffer_string = new StringBuffer(url);
    String replyString = "";

    // instanciate an HttpClient
    HttpClient httpclient = new DefaultHttpClient();
    // instanciate an HttpGet
    HttpGet httpget = new HttpGet(buffer_string.toString());

    try {
        // get the responce of the httpclient execution of the url
        HttpResponse response = httpclient.execute(httpget);
        InputStream is = response.getEntity().getContent();

        // buffer input stream the result
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(20);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }
        // the result as a string is ready for parsing
        replyString = new String(baf.toByteArray());
    } catch (Exception e) {
        e.printStackTrace();
    }
    // trim the whitespaces
    return replyString.trim();
}

private static ArrayList<FoursquareModel> parseFoursquare(
        final String response) {

    ArrayList<FoursquareModel> temp = new ArrayList<FoursquareModel>();
    try {

        // make an jsonObject in order to parse the response
        JSONObject jsonObject = new JSONObject(response);

        // make an jsonObject in order to parse the response
        if (jsonObject.has("response")) {
            if (jsonObject.getJSONObject("response").has("venues")) {
                JSONArray jsonArray = jsonObject.getJSONObject("response")
                        .getJSONArray("venues");

                for (int i = 0; i < jsonArray.length(); i++) {
                    FoursquareModel poi = new FoursquareModel();

                    try {
                        if (jsonArray.getJSONObject(i).has("name")) {
                            poi.setName(jsonArray.getJSONObject(i)
                                    .getString("name"));

                            // We will get only those locations which has
                            // address
                            if (jsonArray.getJSONObject(i).has("location")) {
                                if (jsonArray.getJSONObject(i)
                                        .getJSONObject("location")
                                        .has("address")) {
                                    poi.setAddress(jsonArray
                                            .getJSONObject(i)
                                            .getJSONObject("location")
                                            .getString("address"));

                                    if (jsonArray.getJSONObject(i)
                                            .getJSONObject("location")
                                            .has("lat")) {
                                        poi.setLatitude(jsonArray
                                                .getJSONObject(i)
                                                .getJSONObject("location")
                                                .getString("lat"));
                                    }
                                    if (jsonArray.getJSONObject(i)
                                            .getJSONObject("location")
                                            .has("lng")) {
                                        poi.setLongtitude(jsonArray
                                                .getJSONObject(i)
                                                .getJSONObject("location")
                                                .getString("lng"));
                                    }

                                    if (jsonArray.getJSONObject(i)
                                            .getJSONObject("location")
                                            .has("city")) {
                                        poi.setCity(jsonArray
                                                .getJSONObject(i)
                                                .getJSONObject("location")
                                                .getString("city"));
                                    }
                                    if (jsonArray.getJSONObject(i)
                                            .getJSONObject("location")
                                            .has("country")) {
                                        poi.setCountry(jsonArray
                                                .getJSONObject(i)
                                                .getJSONObject("location")
                                                .getString("country"));
                                    }
                                    if (jsonArray.getJSONObject(i).has(
                                            "categories")) {
                                        if (jsonArray.getJSONObject(i)
                                                .getJSONArray("categories")
                                                .length() > 0) {
                                            if (jsonArray
                                                    .getJSONObject(i)
                                                    .getJSONArray(
                                                            "categories")
                                                    .getJSONObject(0)
                                                    .has("name")) {
                                                poi.setCategory(jsonArray
                                                        .getJSONObject(i)
                                                        .getJSONArray(
                                                                "categories")
                                                        .getJSONObject(0)
                                                        .getString("name"));
                                            }
                                            if (jsonArray
                                                    .getJSONObject(i)
                                                    .getJSONArray(
                                                            "categories")
                                                    .getJSONObject(0)
                                                    .has("id")) {
                                                poi.setCategoryID(jsonArray
                                                        .getJSONObject(i)
                                                        .getJSONArray(
                                                                "categories")
                                                        .getJSONObject(0)
                                                        .getString("id"));
                                            }
                                            if (jsonArray
                                                    .getJSONObject(i)
                                                    .getJSONArray(
                                                            "categories")
                                                    .getJSONObject(0)
                                                    .has("icon")) {

                                                poi.setCategoryIcon(jsonArray
                                                        .getJSONObject(i)
                                                        .getJSONArray(
                                                                "categories")
                                                        .getJSONObject(0)
                                                        .getJSONObject(
                                                                "icon")
                                                        .getString("prefix")
                                                        + "bg_32.png");
                                            }
                                        }
                                    }
                                    temp.add(poi);

                                }
                            }

                        }
                    } catch (Exception e) {

                    }

                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return temp;

}
}

GPS追踪器

package com.company.nearbyplaces_2;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.content.ContextCompat;
import android.util.Log;

public class GPSTracker extends Service implements LocationListener {

private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

public GPSTracker(Context context) {
    this.mContext = context;
    getLocation();
}

public Location getLocation() {
    try {

        if ( Build.VERSION.SDK_INT >= 23 &&
                ContextCompat.checkSelfPermission(this,            android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {  }

        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            // First get location from Network Provider
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}

/**
 * Stop using GPS listener Calling this function will stop using GPS in your
 * app
 * */
public void stopUsingGPS() {
    if ( Build.VERSION.SDK_INT >= 23 &&
            ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
            ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
    {  }
    if (locationManager != null) {
        locationManager.removeUpdates(GPSTracker.this);
    }
}

/**
 * Function to get latitude
 * */
public double getLatitude() {
    if (location != null) {
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude() {
    if (location != null) {
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 * 
 * @return boolean
 * */
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog On pressing Settings button will
 * lauch Settings Options
 * */
public void showSettingsAlert() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // 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);
                    mContext.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();
}

@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

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

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

四方模型

package com.company.nearbyplaces_2;

public class FoursquareModel {
private String name;
private String city;
private String longtitude,latitude,address,country;

private String icon;
private String category,category_id;


public FoursquareModel(String name,String city,String longtitude,String latitude,String address,String country,String category) {
    this.name = name;
    this.city = city;
    this.longtitude = longtitude;
    this.latitude = latitude;
    this.address= address;
    this.country  =  country;
    this.setCategory(category);

}

public FoursquareModel() {
    this.name = "";
    this.city = "";
    this.longtitude = "";
    this.latitude = "";
    this.address= "";
    this.country  =  "";
    this.setCategory("");

}

public String getCity() {
    if (city.length() > 0) {
        return city;
    }
    return city;
}

public void setCity(String city) {
    if (city != null) {
        this.city = city.replaceAll("\\(", "").replaceAll("\\)", "");
        ;
    }
}


public void setCategoryIcon(String icon)
{
    this.icon = icon;
}
public String getCategoryIcon()
{
    return this.icon;
}
public void setCategoryID(String category_id)
{
    this.category_id = category_id;
}
public String getCategoryID()
{
    return this.category_id;
}
public void setAddress(String address)
{
    this.address = address;
}

public String getAddress()
{
    return this.address;
}
public void setCountry(String country)
{
    this.country = country;
}
public String getCountry()
{
    return this.country;

}


public void setLongtitude(String longtitude)
{
     this.longtitude = longtitude;
}

public double getLongtitude( )
{
    return Double.parseDouble(this.longtitude)  ;
}


public void setLatitude(String latitude)
{
     this.latitude = latitude;
}

public double getLatitude( )
{
    return  Double.parseDouble(this.latitude)  ;
}

public void setName(String name) {
    this.name = name;
}

public String getName() {
    return name;
}

public String getCategory() {
    return category;
}

public void setCategory(String category) {
    this.category = category;
}
}

附近列表适配器

package com.company.nearbyplaces_2;

import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;



// List Adapter for NearBy ListView

public class NearbyListAdapter extends ArrayAdapter<FoursquareModel> {




ArrayList<FoursquareModel> mNearByList ;
public NearbyListAdapter(Context context, int textViewResourceId,
        ArrayList<FoursquareModel> objects) {
    super(context, textViewResourceId, objects);
    this.mNearByList = objects;
    // TODO Auto-generated constructor stub
}


 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
 // TODO Auto-generated method stub
 LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 View single_row = inflater.inflate(R.layout.row_layout, null,true);
 TextView tv_name = (TextView) single_row.findViewById(R.id.tv_name);
 TextView tv_address = (TextView) single_row.findViewById(R.id.tv_address);

 tv_name.setText(mNearByList.get(position).getName());
 tv_address.setText(mNearByList.get(position).getAddress());
 return single_row; 
 }
}

显现

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

<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"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

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

<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>
</application>

摇篮

apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion "23.0.1"

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

android {
useLibrary 'org.apache.http.legacy'
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.foursquare:foursquare-android-oauth:1.0.3'
compile 'com.google.android.gms:play-services:8.1.0'
compile 'com.android.support:design:23.0.1'
}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical" >

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
    <fragment
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.MapFragment"
    android:layout_width="match_parent"
    android:layout_height="168dp" />

</FrameLayout>

  <TextView
    android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="OR SELECT FROM NEARBY PLACES"
    android:textColor="#29a3c7" 
    android:paddingTop="5dp"
    android:textSize="18dp"

    android:paddingBottom="5dp"/>
<View android:layout_width="match_parent"
    android:layout_height="2dp"
    android:background="#29a3c7"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"/>

<ListView
    android:id="@+id/listview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:headerDividersEnabled="true" >"
</ListView>

行布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" 
android:background="#cccccc"
>
<LinearLayout android:layout_width="match_parent"
android:layout_height="60dp"
android:orientation="horizontal"
android:background="#ffffff">

<ImageView
    android:layout_marginLeft="10dp"
    android:layout_width="32dp"
    android:layout_height="32dp"
    android:layout_gravity="center"
    android:src="@android:drawable/alert_dark_frame" />

<LinearLayout android:layout_width="match_parent"
android:layout_marginLeft="10dp"
android:layout_height="60dp"
android:gravity="center_vertical"
android:orientation="vertical"
android:background="#ffffff">
 <TextView
    android:id="@+id/tv_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView"
    android:paddingLeft="2dp"
    android:textSize="18dp" 
    android:maxLines="1" 
android:ellipsize="end"/>
    <TextView
    android:id="@+id/tv_address"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView" 
    android:paddingLeft="4dp"
    android:textColor="#676666"
    android:maxLines="1" 
android:ellipsize="end"/>

 java.lang.RuntimeException: API key not found. Check that <meta-data android:name="com.google.android.geo.API_KEY" android:value="your API key"/> is in the <application> element of AndroidManifest.xml

移动

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

AndroidManifest.xml 中<application>元素内的根<manifest>元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM