Created
August 11, 2015 08:53
-
-
Save osipovaleks/d89a53a88d18717ccc85 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.appsmakerstore.appmakerstorenative.gadgets.forecast; | |
import android.app.AlertDialog; | |
import android.app.LoaderManager; | |
import android.app.Service; | |
import android.content.Context; | |
import android.content.CursorLoader; | |
import android.content.DialogInterface; | |
import android.content.Intent; | |
import android.content.Loader; | |
import android.database.Cursor; | |
import android.location.Location; | |
import android.location.LocationListener; | |
import android.location.LocationManager; | |
import android.os.Bundle; | |
import android.provider.Settings; | |
import android.view.LayoutInflater; | |
import android.view.View; | |
import android.view.ViewGroup; | |
import android.view.inputmethod.InputMethodManager; | |
import android.widget.AdapterView; | |
import android.widget.ArrayAdapter; | |
import android.widget.AutoCompleteTextView; | |
import android.widget.BaseAdapter; | |
import android.widget.Button; | |
import android.widget.Filter; | |
import android.widget.RadioButton; | |
import android.widget.RadioGroup; | |
import android.widget.Spinner; | |
import android.widget.TextView; | |
import com.appsmakerstore.appmakerstorenative.BaseAppFragment; | |
import com.appsmakerstore.appmakerstorenative.R; | |
import com.appsmakerstore.appmakerstorenative.data.AppProvider; | |
import com.appsmakerstore.appmakerstorenative.data.DataStore; | |
import com.appsmakerstore.appmakerstorenative.data.entity.GoogleMapApiResponse; | |
import com.appsmakerstore.appmakerstorenative.data.network.GoogleMapApi; | |
import com.appsmakerstore.appmakerstorenative.gadgets.forecast.ForecastItem.ForecastCity; | |
import com.appsmakerstore.appmakerstorenative.utils.CheckInternetConnection; | |
import com.appsmakerstore.appmakerstorenative.utils.GadgetParamBundle; | |
import com.appsmakerstore.appmakerstorenative.utils.TagLog; | |
import com.google.gson.Gson; | |
import org.apache.http.HttpEntity; | |
import org.apache.http.HttpResponse; | |
import org.apache.http.StatusLine; | |
import org.apache.http.client.HttpClient; | |
import org.apache.http.client.methods.HttpGet; | |
import org.apache.http.impl.client.DefaultHttpClient; | |
import java.io.BufferedReader; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.InputStreamReader; | |
import java.util.ArrayList; | |
import java.util.Locale; | |
import retrofit.Callback; | |
import retrofit.RestAdapter; | |
import retrofit.RetrofitError; | |
import retrofit.client.Response; | |
public class ForecastSettingsFragment extends BaseAppFragment implements LoaderManager.LoaderCallbacks<Cursor> { | |
public static final int LOADER = 1; | |
public static final int REQUEST_CODE_GPS_SETTINGS = 100; | |
public static final String HTTP_MAPS_GOOGLEAPIS_COM = "http://maps.googleapis.com"; | |
public static final String EN = "en"; | |
public static final String LOCALITY = "locality"; | |
public static final String ADMINISTRATIVE_AREA_LEVEL_1 = "administrative_area_level_1"; | |
public static final String COUNTRY = "country"; | |
public static final String ESTABLISHMENT = "establishment"; | |
public static final String OK = "OK"; | |
private Spinner spinner; | |
private int count; | |
private AutoCompleteTextView editTextFind; | |
private LocationManager locationManager; | |
private String language; | |
@Override | |
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) { | |
View rootView = inflater.inflate(R.layout.fragment_gadget_forecast_settings, container, false); | |
final RadioGroup radioGroup = (RadioGroup) rootView.findViewById(R.id.radio_group); | |
RadioButton radioButtonCelsius = (RadioButton) rootView.findViewById(R.id.radio_button_celsius); | |
RadioButton radioButtonFahrenheit = (RadioButton) rootView.findViewById(R.id.radio_button_fahrenheit); | |
Button buttonApply = (Button) rootView.findViewById(R.id.button_apply); | |
Button buttonUseMyLocation = (Button) rootView.findViewById(R.id.button_use_my_location); | |
spinner = (Spinner) rootView.findViewById(R.id.spinner); | |
editTextFind = (AutoCompleteTextView) rootView.findViewById(R.id.edit_text_find); | |
CheckInternetConnection.isConnect(getActivity()); | |
language = Locale.getDefault().getLanguage(); | |
if (language.equals("")) { | |
language = EN; | |
} | |
if (ForecastMainFragment.forecastItem.isCelsius()) { | |
radioButtonCelsius.setChecked(true); | |
} else { | |
radioButtonFahrenheit.setChecked(true); | |
} | |
getActivity().getActionBar().hide(); | |
buttonApply.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View v) { | |
Intent intent = new Intent(); | |
switch (radioGroup.getCheckedRadioButtonId()) { | |
case R.id.radio_button_celsius: | |
ForecastMainFragment.forecastItem.setCelsius(true); | |
break; | |
case R.id.radio_button_fahrenheit: | |
ForecastMainFragment.forecastItem.setCelsius(false); | |
break; | |
} | |
getTargetFragment().onActivityResult(getTargetRequestCode(), ForecastMainFragment.RESULT_CODE_TEMPERATURE_SCALE, intent); | |
getActivity().onBackPressed(); | |
} | |
}); | |
buttonUseMyLocation.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View v) { | |
if (CheckInternetConnection.isConnect(getActivity())) { | |
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE); | |
getCoordinates(); | |
} | |
} | |
}); | |
final AutoCompleteAdapter adapter = new AutoCompleteAdapter(getActivity(), android.R.layout.simple_dropdown_item_1line); | |
editTextFind.setAdapter(adapter); | |
editTextFind.setOnItemClickListener(new AdapterView.OnItemClickListener() { | |
@Override | |
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { | |
sendNewCity(adapter.getData().get(position)); | |
InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Service.INPUT_METHOD_SERVICE); | |
inputMethodManager.hideSoftInputFromWindow(editTextFind.getWindowToken(), 0); | |
getActivity().onBackPressed(); | |
} | |
}); | |
getLoaderManager().initLoader(LOADER, Bundle.EMPTY, this); | |
return rootView; | |
} | |
private void getCoordinates() { | |
if (locationManager != null) { | |
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { | |
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); | |
builder.setTitle(getString(R.string.setting)) | |
.setMessage(getString(R.string.now_gps_off_enable_it)) | |
.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { | |
locationManager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, locationListener, null); | |
} | |
dialog.dismiss(); | |
} | |
}) | |
.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
Intent gpsOptionsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); | |
startActivityForResult(gpsOptionsIntent, REQUEST_CODE_GPS_SETTINGS); | |
} | |
}) | |
.show(); | |
} else { | |
locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, locationListener, null); | |
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { | |
locationManager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, locationListener, null); | |
} | |
} | |
} | |
} | |
@Override | |
public void onActivityResult(int requestCode, int resultCode, Intent data) { | |
super.onActivityResult(requestCode, resultCode, data); | |
switch (requestCode) { | |
case REQUEST_CODE_GPS_SETTINGS: | |
getCoordinates(); | |
break; | |
} | |
} | |
@Override | |
public Loader<Cursor> onCreateLoader(int id, Bundle args) { | |
CursorLoader cursorLoader = null; | |
switch (id) { | |
case LOADER: | |
long parentId = GadgetParamBundle.getParentId(getArguments()); | |
cursorLoader = new CursorLoader(getActivity(), | |
AppProvider.contentUri(DataStore.ForecastGadgetItem.CONTENT_URI), | |
null, | |
DataStore.ForecastGadgetItem.PARENT_ID + " = ?", | |
new String[]{String.valueOf(parentId)}, | |
null); | |
break; | |
} | |
return cursorLoader; | |
} | |
@Override | |
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { | |
switch (loader.getId()) { | |
case LOADER: | |
if (cursor.moveToFirst()) { | |
final ArrayList<ForecastCity> forecastCities = new ArrayList<>(cursor.getCount()); | |
if (ForecastMainFragment.forecastItem.isUnknownCity()) { | |
forecastCities.add(ForecastMainFragment.forecastItem.getForecastCity()); | |
} | |
int columnIndexCity = cursor.getColumnIndex(DataStore.ForecastGadgetItem.CITY); | |
int columnIndexTitle = cursor.getColumnIndex(DataStore.ForecastGadgetItem.TITLE); | |
int columnIndexLatitude = cursor.getColumnIndex(DataStore.ForecastGadgetItem.LATITUDE); | |
int columnIndexLongitude = cursor.getColumnIndex(DataStore.ForecastGadgetItem.LONGITUDE); | |
count = 0; | |
do { | |
forecastCities.add(new ForecastCity(cursor.getString(columnIndexCity), | |
cursor.getString(columnIndexTitle), | |
cursor.getString(columnIndexLatitude), | |
cursor.getString(columnIndexLongitude), | |
count++)); | |
} while (cursor.moveToNext()); | |
ForecastSpinnerAdapter adapter = new ForecastSpinnerAdapter(getActivity(), forecastCities); | |
spinner.setAdapter(adapter); | |
final int currentPosition = ForecastMainFragment.forecastItem.getForecastCity().getPosition(); | |
if (!ForecastMainFragment.forecastItem.isUnknownCity()) { | |
spinner.setSelection(currentPosition); | |
} | |
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { | |
@Override | |
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { | |
if (currentPosition == -1) { | |
if (position != (currentPosition + 1)) { | |
sendIntent(position); | |
} | |
} else { | |
if (position != currentPosition) { | |
sendIntent(position); | |
} | |
} | |
} | |
private void sendIntent(int position) { | |
Intent intent = new Intent(); | |
intent.putExtra(ForecastMainFragment.FORECAST_CITY, forecastCities.get(position)); | |
intent.putExtra(ForecastMainFragment.UNKNOWN_CITY, false); | |
getTargetFragment().onActivityResult(getTargetRequestCode(), ForecastMainFragment.RESULT_CODE_CITY, intent); | |
getActivity().onBackPressed(); | |
} | |
@Override | |
public void onNothingSelected(AdapterView<?> parent) { | |
} | |
}); | |
} | |
break; | |
} | |
} | |
@Override | |
public void onLoaderReset(Loader<Cursor> loader) { | |
} | |
private LocationListener locationListener = new LocationListener() { | |
private double latitude = -1; | |
private double longitude = -1; | |
@Override | |
public void onLocationChanged(Location location) { | |
if ((latitude == -1) || (longitude == -1)) { | |
latitude = location.getLatitude(); | |
longitude = location.getLongitude(); | |
GoogleMapApi googleMapApi = new RestAdapter.Builder() | |
.setEndpoint(HTTP_MAPS_GOOGLEAPIS_COM) | |
.build().create(GoogleMapApi.class); | |
googleMapApi.getNameByCoordinates(latitude + "," + longitude, language, new Callback<GoogleMapApiResponse>() { | |
@Override | |
public void success(GoogleMapApiResponse googleMapApiResponse, Response response) { | |
if (OK.equals(googleMapApiResponse.getStatus())) { | |
String locality = ""; | |
String adminArea = ""; | |
String countryName = ""; | |
for (GoogleMapApiResponse.Results.Address address : googleMapApiResponse.getResults().get(0).getAddressList()) { | |
switch (address.getTypes().get(0)) { | |
case LOCALITY: | |
locality = address.getLongName(); | |
break; | |
case ADMINISTRATIVE_AREA_LEVEL_1: | |
adminArea = address.getLongName(); | |
break; | |
case COUNTRY: | |
countryName = address.getLongName(); | |
break; | |
} | |
} | |
sendNewCity(locality, adminArea, countryName, latitude, longitude); | |
if (getActivity() != null) { | |
getActivity().onBackPressed(); | |
} | |
} | |
} | |
@Override | |
public void failure(RetrofitError error) { | |
} | |
}); | |
} | |
} | |
@Override | |
public void onStatusChanged(String provider, int status, Bundle extras) { | |
} | |
@Override | |
public void onProviderEnabled(String provider) { | |
} | |
@Override | |
public void onProviderDisabled(String provider) { | |
} | |
}; | |
private void sendNewCity(ForecastCity forecastCity) { | |
Intent intent = new Intent(); | |
intent.putExtra(ForecastMainFragment.FORECAST_CITY, forecastCity); | |
intent.putExtra(ForecastMainFragment.UNKNOWN_CITY, true); | |
getTargetFragment().onActivityResult(getTargetRequestCode(), ForecastMainFragment.RESULT_CODE_CITY, intent); | |
} | |
private void sendNewCity(String locality, String adminArea, String countryName, double latitude, double longitude) { | |
sendNewCity(new ForecastCity(adminArea + ", " + countryName, locality, String.valueOf(latitude), String.valueOf(longitude), -1)); | |
} | |
private static class ForecastSpinnerAdapter extends BaseAdapter { | |
private Context context; | |
private ArrayList<ForecastCity> list; | |
private LayoutInflater layoutInflater; | |
public ForecastSpinnerAdapter(Context context, ArrayList<ForecastCity> data) { | |
this.context = context; | |
list = data; | |
layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); | |
} | |
class ViewHolder { | |
TextView textView; | |
} | |
@Override | |
public int getCount() { | |
return list.size(); | |
} | |
@Override | |
public Object getItem(int position) { | |
return list.get(position); | |
} | |
@Override | |
public long getItemId(int position) { | |
return position; | |
} | |
@Override | |
public View getView(int position, View convertView, ViewGroup parent) { | |
View view = convertView; | |
ViewHolder holder; | |
if (view == null) { | |
view = layoutInflater.inflate(android.R.layout.simple_list_item_1, parent, false); | |
holder = new ViewHolder(); | |
holder.textView = (TextView) view.findViewById(android.R.id.text1); | |
view.setTag(holder); | |
} else { | |
holder = (ViewHolder) view.getTag(); | |
} | |
ForecastCity forecastCity = (ForecastCity) getItem(position); | |
holder.textView.setText(forecastCity.getTitle()); | |
return view; | |
} | |
} | |
private class AutoCompleteAdapter extends ArrayAdapter<ForecastCity> { | |
public static final String HTTP_MAPS_GOOGLEAPIS_COM_MAPS_API_GEOCODE_JSON_ADDRESS = "http://maps.googleapis.com/maps/api/geocode/json?address="; | |
public static final String LANGUAGE = "&language="; | |
public static final int RESPONSE_STATUS_SUCCESSFUL = 200; | |
private ArrayList<ForecastCity> data; | |
private Context context; | |
private int resource; | |
public AutoCompleteAdapter(Context context, int resource) { | |
super(context, resource); | |
data = new ArrayList<>(); | |
this.context = context; | |
this.resource = resource; | |
} | |
@Override | |
public int getCount() { | |
return data.size(); | |
} | |
@Override | |
public ForecastCity getItem(int position) { | |
return data.get(position); | |
} | |
@Override | |
public Filter getFilter() { | |
return new Filter() { | |
@Override | |
protected FilterResults performFiltering(CharSequence constraint) { | |
final FilterResults filterResults = new FilterResults(); | |
if (constraint != null) { | |
data = getArrayListForecastCity(constraint.toString()); | |
filterResults.values = data; | |
filterResults.count = data.size(); | |
} | |
return filterResults; | |
} | |
@Override | |
protected void publishResults(CharSequence constraint, FilterResults results) { | |
if (results != null && results.count > 0) { | |
notifyDataSetChanged(); | |
} else { | |
notifyDataSetInvalidated(); | |
} | |
} | |
}; | |
} | |
@Override | |
public View getView(int position, View convertView, ViewGroup parent) { | |
TextView textView; | |
if (convertView == null) { | |
textView = (TextView) LayoutInflater.from(context).inflate(resource, parent, false); | |
} else { | |
textView = (TextView) convertView; | |
} | |
textView.setText(data.get(position).toString()); | |
return textView; | |
} | |
public ArrayList<ForecastCity> getData() { | |
return data; | |
} | |
private ArrayList<ForecastCity> getArrayListForecastCity(String string) { | |
ArrayList<ForecastCity> arrayList = new ArrayList<>(); | |
String url = HTTP_MAPS_GOOGLEAPIS_COM_MAPS_API_GEOCODE_JSON_ADDRESS + string + LANGUAGE + language; | |
StringBuilder builder = new StringBuilder(); | |
HttpClient client = new DefaultHttpClient(); | |
HttpGet httpGet = new HttpGet(url); | |
try { | |
HttpResponse response = client.execute(httpGet); | |
StatusLine statusLine = response.getStatusLine(); | |
int statusCode = statusLine.getStatusCode(); | |
if (statusCode == RESPONSE_STATUS_SUCCESSFUL) { | |
HttpEntity entity = response.getEntity(); | |
InputStream content = entity.getContent(); | |
BufferedReader reader = new BufferedReader(new InputStreamReader(content)); | |
String line; | |
while ((line = reader.readLine()) != null) { | |
builder.append(line); | |
} | |
} else { | |
TagLog.e(this, context.getString(R.string.failed_to_download_data)); | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
GoogleMapApiResponse response = new Gson().fromJson(builder.toString(), GoogleMapApiResponse.class); | |
for (GoogleMapApiResponse.Results results : response.getResults()) { | |
String locality = ""; | |
String adminArea = ""; | |
String countryName = ""; | |
String establishment = ""; | |
for (GoogleMapApiResponse.Results.Address address : results.getAddressList()) { | |
switch (address.getTypes().get(0)) { | |
case LOCALITY: | |
locality = address.getLongName(); | |
break; | |
case ADMINISTRATIVE_AREA_LEVEL_1: | |
adminArea = address.getLongName(); | |
break; | |
case COUNTRY: | |
countryName = address.getLongName(); | |
break; | |
case ESTABLISHMENT: | |
establishment = address.getLongName(); | |
break; | |
} | |
} | |
if (!establishment.equals("")) { | |
locality = establishment; | |
} | |
String latitude = results.getGeometry().getLocation().getLat(); | |
String longitude = results.getGeometry().getLocation().getLng(); | |
arrayList.add(new ForecastCity(adminArea + ", " + countryName, locality, latitude, longitude, -1)); | |
} | |
return arrayList; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment