按纬度和经度Android获取动态内容

时间:2016-06-01 08:15:50

标签: java android api gps

我正在使用Yelp API,现在我正在使用静态方法根据位置和术语进行API调用。我想让这个动态,点击按钮我应该点击API并根据我当前的位置获取餐馆列表,即纬度和经度。我在下面的代码中尝试了这个但是不起作用。

MainActivity.java     package com ........ projectmaw;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    double latitude; // Latitude
    double longitude; // Longitude


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        /*
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });*/

        Log.v("TAG", "MainOnCreate");
        Button searchButton = (Button) findViewById(R.id.restCall);
        Log.v("TAG", "Button Created");
        searchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // instantiate the location manager, note you will need to request permissions in your manifest
                LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                // get the last know location from your location manager.
                if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), 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;
                }
                Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                // now get the lat/lon from the location and do something with it.
                latitude = location.getLatitude();
                longitude = location.getLongitude();
                Log.d("Lat and Lon", "lat " + latitude + " " + "Lon " + longitude);
                search();
            }
        });



}

    public void search() {
        Log.v("TAG", "search");
        Intent intent = new Intent("android.intent.action.YELPSEARCH");
        startActivity(intent);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }



}/* End of MainActivity Activity */

Yelp.java

import android.content.Context;
import android.util.Log;

import org.scribe.builder.ServiceBuilder;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.oauth.OAuthService;


public class Yelp {

    OAuthService service;
    Token accessToken;


    static String YELP_CONSUMER_KEY ="xxxxxxxxxxxxxxxxxxxx";
    static String YELP_CONSUMER_SECRET = "xxxxxxxxxxxxxxxxxxxx";
    static String YELP_TOKEN = "xxxxxxxxxxxxxxxxxxxx";
    static String YELP_TOKEN_SECRET = "xxxxxxxxxxxxxxxxxxxx";

    public static Yelp getYelp(Context context) {
        return new Yelp(YELP_CONSUMER_KEY, YELP_CONSUMER_SECRET,
                YELP_TOKEN, YELP_TOKEN_SECRET);
    }

    public Yelp(String consumerKey, String consumerSecret, String token, String tokenSecret) {
        this.service = new ServiceBuilder().provider(TwoStepOAuth.class).apiKey(consumerKey).apiSecret(consumerSecret).build();
        this.accessToken = new Token(token, tokenSecret);
    }

    public String search(String term, String location) {
        Log.v("TAG","YelpSearch");
        OAuthRequest request = new OAuthRequest(Verb.GET, "http://api.yelp.com/v2/search");
        request.addQuerystringParameter("term", term);
        request.addQuerystringParameter("location", location);
        this.service.signRequest(this.accessToken, request);
        Log.v("TAG","Before Response");
        Response response = request.send();
        Log.v("TAG","response :"+response.getBody());
        return response.getBody();
    }

}

YelpHelper.java

import android.app.ListActivity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ListView;

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

import java.io.Serializable;
import java.util.ArrayList;

import java.util.Collections;

import java.util.List;


public class YelpSearch extends ListActivity implements Serializable {

    @SuppressWarnings("serial")
    class Business implements Serializable {
        final String name;
        final String url;
        final String id;
        final String rating;


        public Business(String name, String url, String id, String rating) {
            this.name = name;
            this.url = url;
            this.id = id;
            this.rating = rating;
        }


        @Override
        public String toString() {
            return "name :"+name+""+"ID : "+id;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        super.onCreate(savedInstanceState);
        setTitle("Finding Tacos...");
        setProgressBarIndeterminateVisibility(true);
        Log.v("TAG","YelpSearchOnCreate");

        new AsyncTask<Void, Void, List<Business>>() {
            @Override
            protected List<Business> doInBackground(Void... params) {
                Log.v("TAG","Async List");

                String businesses = Yelp.getYelp(YelpSearch.this).search("food", "91754");
                Log.v("TAG","String businsesses"+businesses);
                try {
                    Log.v("TAG","try");
                    return processJson(businesses);
                } catch (JSONException e) {
                    return Collections.<Business>emptyList();
                }
            }

            @Override
            protected void onPostExecute(List<Business> businesses) {
                Log.v("TAG","onPostExecute");
                Log.v("BusinessesList","Businesses "+ businesses);
                //setTitle("Tacos Found");
                setProgressBarIndeterminateVisibility(false);
                getListView().setAdapter(new ArrayAdapter<Business>(YelpSearch.this, android.R.layout.simple_list_item_1, businesses));

            }
        }.execute();
    }

    @Override
    protected void onListItemClick(ListView listView, View view, int position, long id) {
        Business biz = (Business) listView.getItemAtPosition(position);
        Log.v("Sending data to Detail","hi "+biz);
        startActivity(new Intent(getApplicationContext(), YelpBizDetail.class).putExtra("Detailclass",biz));
    }

    List<Business> processJson(String jsonStuff) throws JSONException {
        JSONObject json = new JSONObject(jsonStuff);
        JSONArray businesses = json.getJSONArray("businesses");

        ArrayList<Business> businessObjs = new ArrayList<Business>(businesses.length());
        for (int i = 0; i < businesses.length(); i++) {
            JSONObject business = businesses.getJSONObject(i);
            businessObjs.add(new Business(business.optString("name"), business.optString("mobile_url"),business.optString("id"),business.optString("rating")));
        }
        return businessObjs;
    }
}

如何使这项工作。

0 个答案:

没有答案