Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.foodhygiene;
- import android.Manifest;
- 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.support.v4.app.ActivityCompat;
- import android.support.v4.content.ContextCompat;
- import android.support.v7.app.AlertDialog;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.AdapterView;
- import android.widget.ArrayAdapter;
- import android.widget.CheckBox;
- import android.widget.ListView;
- import android.widget.ProgressBar;
- import android.widget.Spinner;
- import android.widget.TextView;
- import com.android.volley.AuthFailureError;
- import com.android.volley.Request;
- import com.android.volley.RequestQueue;
- import com.android.volley.Response;
- import com.android.volley.VolleyError;
- import com.android.volley.toolbox.JsonArrayRequest;
- import com.android.volley.toolbox.JsonObjectRequest;
- import com.android.volley.toolbox.StringRequest;
- import com.android.volley.toolbox.Volley;
- import org.json.JSONArray;
- import org.json.JSONException;
- import org.json.JSONObject;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.Map;
- public class MainActivity extends AppCompatActivity {
- private ListView listView;
- private ArrayList names;
- private ArrayList names1;
- private ArrayAdapter namesAdapter;
- private ArrayAdapter namesAdapter1;
- private String searchParam;
- private LocationManager locationManager;
- private LocationListener locationListener;
- private final int FINE_LOCATION_PERMISSION = 1;
- final String url = "http://api.ratings.food.gov.uk/Establishments/?pageNumber=1&pageSize=10&";
- private String nameExtra = "";
- private String locationExtra = "";
- ProgressBar pb;
- private Location currentLocation;
- private TextView textView;
- ArrayList<String> RegionName;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- pb = (ProgressBar) findViewById(R.id.progressBarSearch);
- pb.setMax(100);
- names1 = new ArrayList<Region>();
- regionSpinner();
- namesAdapter1 = new ArrayAdapter(this, android.R.layout.simple_selectable_list_item, names1);
- names = new ArrayList<Establishment>();
- namesAdapter = new ArrayAdapter(this, android.R.layout.simple_selectable_list_item, names);
- listView = findViewById(R.id.display_list);
- listView.setAdapter(namesAdapter);
- Spinner spinner = findViewById(R.id.regionSpinner1);
- spinner.setAdapter(namesAdapter1);
- final AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
- Establishment clickedItem = (Establishment) namesAdapter.getItem(position);
- Intent intent = new Intent(MainActivity.this, RestaurantDetailsActivity.class);
- intent.putExtra("apiID", clickedItem.getApiID());
- startActivity(intent);
- }
- };
- locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
- locationListener = new LocationListener() {
- @Override
- public void onLocationChanged(Location location) {
- currentLocation = location;
- }
- @Override
- public void onStatusChanged(String provider, int status, Bundle extras) {
- }
- @Override
- public void onProviderEnabled(String provider) {
- }
- @Override
- public void onProviderDisabled(String provider) {
- }
- };
- if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED) {
- if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
- new AlertDialog.Builder(this)
- .setMessage("The application is about to request access to your location.")
- .setPositiveButton("OK", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialogInterface, int i) {
- requestLocPerms();
- }
- })
- .create()
- .show();
- } else {
- requestLocPerms();
- }
- } else {
- attachLocManager();
- }
- listView.setOnItemClickListener(itemClickListener);
- currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
- locationListener.onLocationChanged(currentLocation);
- }
- @Override
- public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
- switch (requestCode) {
- case FINE_LOCATION_PERMISSION: {
- if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
- attachLocManager();
- } else {
- }
- return;
- }
- }
- }
- public void attachLocManager() {
- try {
- locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
- } catch (SecurityException err) {
- }
- }
- public void requestLocPerms() {
- ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, FINE_LOCATION_PERMISSION);
- }
- public void queryAPI(View view) {
- RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
- textView = findViewById(R.id.search_text);
- searchParam = textView.getText().toString().toLowerCase().trim();
- if (searchParam == null) {
- //print a dialogue
- }
- String urlExtra = url;
- String filterChoice = checkSpinner();
- nameExtra = filterChoice + searchParam;
- urlExtra += nameExtra;
- urlExtra += locationExtra;
- // Request a string response from the provided URL.
- JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, urlExtra, null,
- new Response.Listener<JSONObject>() {
- @Override
- public void onResponse(JSONObject response) {
- try {
- pb.setVisibility(View.VISIBLE);
- pb.setProgress(0);
- JSONArray data = response.getJSONArray("establishments");
- if (data != null) {
- populateList(data);
- System.out.println(response.toString());
- }
- } catch (JSONException e) {
- e.printStackTrace();
- } finally {
- // pb.setProgress(100);
- }
- }
- }, new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- textView.setText("That didn't work!");
- System.err.println(error.toString());
- }
- }) {
- @Override
- public Map<String, String> getHeaders() {
- Map<String, String> params = new HashMap<String, String>();
- params.put("x-api-version", "2");
- params.put("Accept-Language", "cy-GB");
- params.put("Content-Type", "application/json");
- return params;
- }
- };
- // Add the request to the RequestQueue.
- requestQueue.add(objectRequest);
- }
- public void populateList(JSONArray data) throws JSONException {
- for (int i = 0; i < data.length(); i++) {
- JSONObject jo = data.getJSONObject(i);
- names.add(new Establishment(jo.getInt("FHRSID"), jo.getString("BusinessName"), jo.getString("FHRSID"), jo.getString("AddressLine1"), jo.getString("RatingValue")));
- }
- namesAdapter.notifyDataSetChanged();
- }
- public void populateList2(JSONArray data) throws JSONException {
- for (int i = 0; i < data.length(); i++) {
- JSONObject jo = data.getJSONObject(i);
- Region region = new Region(jo.getInt("id"), jo.getString("name"), jo.getString("nameKey"), jo.getString("code"));
- names1.add(region);
- }
- namesAdapter1.notifyDataSetChanged();
- }
- public void useLocation(View view) {
- CheckBox checkBox = findViewById(R.id.location_checkbox);
- if (checkBox.isChecked()) {
- String longitude = String.format("%.2f", currentLocation.getLongitude());
- String latitude = String.format("%.2f", currentLocation.getLatitude());
- locationExtra = "&longitude=" + longitude + "&latitude=" + latitude + "&maxDistanceLimit=2";
- } else {
- locationExtra = "";
- }
- }
- public String checkSpinner() {
- String choice = "name=";
- Spinner spinner = findViewById(R.id.filterSpinner);
- switch (spinner.getSelectedItem().toString()) {
- case "name":
- choice = "name=";
- break;
- case "type of business":
- choice = "BusinessType=";
- break;
- case "rating":
- choice = "ratingKey=";
- break;
- case "region and local authority":
- choice = "LocalAuthorityName=";
- break;
- }
- return choice;
- }
- public void regionSpinner() {
- RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
- String urlExtra1 = "http://api.ratings.food.gov.uk/Regions/?";
- // Request a string response from the provided URL.
- JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, urlExtra1, null,
- new Response.Listener<JSONObject>() {
- @Override
- public void onResponse(JSONObject response) {
- try {
- // pb.setVisibility(View.VISIBLE);
- // pb.setProgress(0);
- JSONArray data = response.getJSONArray("regions");
- if (data != null) {
- populateList2(data);
- System.out.println(response.toString());
- }
- } catch (JSONException e) {
- e.printStackTrace();
- } finally {
- // pb.setProgress(100);
- }
- }
- }, new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- // textView.setText("That didn't work!");
- System.err.println(error.toString());
- }
- }){
- @Override
- public Map<String, String> getHeaders() {
- Map<String, String> params = new HashMap<String, String>();
- params.put("x-api-version", "2");
- params.put("Accept-Language", "cy-GB");
- params.put("Content-Type", "application/json");
- return params;
- }
- };
- requestQueue.add(objectRequest);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement