Android Studio E/RecyclerView:未连接适配器;跳过布局错误
嗨,我知道以前有人问过这个问题,但我似乎找不到任何帮助。我的应用程序曾经工作过,但突然停止了,唯一改变的是我的手机(我一直在运行应用程序的手机已经更新) 这是我的回收器视图适配器类: 公共类RecycleServiceAdapter扩展了RecyclerView.Adapter{Android Studio E/RecyclerView:未连接适配器;跳过布局错误,android,Android,嗨,我知道以前有人问过这个问题,但我似乎找不到任何帮助。我的应用程序曾经工作过,但突然停止了,唯一改变的是我的手机(我一直在运行应用程序的手机已经更新) 这是我的回收器视图适配器类: 公共类RecycleServiceAdapter扩展了RecyclerView.Adapter{ private List<WeatherObject> dailyWeather; protected Context context; public RecyclerViewAdapter(Conte
private List<WeatherObject> dailyWeather;
protected Context context;
public RecyclerViewAdapter(Context context, List<WeatherObject> dailyWeather) {
this.dailyWeather = dailyWeather;
this.context = context;
}
@Override
public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerViewHolders viewHolder = null;
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.weather_daily_list, parent, false);
viewHolder = new RecyclerViewHolders(layoutView);
return viewHolder;
}
@Override
public void onBindViewHolder(RecyclerViewHolders holder, int position) {
holder.dayOfWeek.setText(dailyWeather.get(position).getDayOfWeek());
holder.weatherIcon.setImageResource(dailyWeather.get(position).getWeatherIcon());
double mTemp = Double.parseDouble(dailyWeather.get(position).getWeatherResult());
holder.weatherResult.setText(String.valueOf(Math.round(mTemp)) + "°");
holder.weatherResultSmall.setText(dailyWeather.get(position).getWeatherResultSmall());
holder.weatherResultSmall.setVisibility(View.GONE);
}
@Override
public int getItemCount() {
return dailyWeather.size();
}
}
这是天气活动类,用于设置值:
公共类WeatherActivity扩展AppCompatActivity实现LocationListener{
private static final String TAG = WeatherActivity.class.getSimpleName();
private RecyclerView recyclerView;
private RecyclerViewAdapter recyclerViewAdapter;
private TextView cityCountry;
private TextView currentDate;
private ImageView weatherImage;
private String cardinalDirection;
private CircleView circleTitle;
private TextView windResult;
private TextView Direction;
//私人文本视图日出
private TextView humidityResult;
private RequestQueue queue;
private LocationMapObject locationMapObject;
private LocationManager locationManager;
private Location location;
private final int REQUEST_LOCATION = 200;
private CustomSharedPreference sharedPreference;
private String isLocationSaved;
private DatabaseQuery query;
private String apiUrl;
private FiveDaysForecast fiveDaysForecast;
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather);
ActionBar actionBar = getSupportActionBar();
if(actionBar != null){
actionBar.hide();
}
queue = Volley.newRequestQueue(this);
query = new DatabaseQuery(WeatherActivity.this);
sharedPreference = new CustomSharedPreference(WeatherActivity.this);
isLocationSaved = sharedPreference.getLocationInPreference();
cityCountry = (TextView)findViewById(R.id.city_country);
currentDate = (TextView)findViewById(R.id.current_date);
weatherImage = (ImageView)findViewById(R.id.weather_icon);
circleTitle = (CircleView)findViewById(R.id.weather_result);
windResult = (TextView)findViewById(R.id.wind_result);
Direction = (TextView)findViewById(R.id.wind_direction);
humidityResult = (TextView)findViewById(R.id.humidity_result);
// sunRise =(TextView)findViewById(R.id.sunrise_result);
locationManager = (LocationManager) getSystemService(Service.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(WeatherActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
} else {
if(isLocationSaved.equals("")){
// make API call with longitude and latitude
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 2, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
apiUrl = "http://api.openweathermap.org/data/2.5/weather?lat="+location.getLatitude()+"&lon="+location.getLongitude()+"&APPID="+Helper.API_KEY+"&units=metric";
makeJsonObject(apiUrl);
}
}else{
// make API call with city name
String storedCityName = sharedPreference.getLocationInPreference();
System.out.println("Stored city " + storedCityName);
String[] city = storedCityName.split(",");
if(!TextUtils.isEmpty(city[0])){
System.out.println("Stored city " + city[0]);
String url ="http://api.openweathermap.org/data/2.5/weather?q="+city[0]+"&APPID="+Helper.API_KEY+"&units=metric";
makeJsonObject(url);
}
}
}
ImageButton addLocation = (ImageButton) findViewById(R.id.add_location);
addLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent addLocationIntent = new Intent(WeatherActivity.this, AddLocationActivity.class);
startActivity(addLocationIntent);
}
});
GridLayoutManager gridLayoutManager = new GridLayoutManager(WeatherActivity.this, 4);
recyclerView = (RecyclerView)findViewById(R.id.weather_daily_list);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView.setHasFixedSize(true);
}
private void makeJsonObject(final String apiUrl){
StringRequest stringRequest = new StringRequest(Request.Method.GET, apiUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Response " + response);
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
locationMapObject = gson.fromJson(response, LocationMapObject.class);
if (null == locationMapObject) {
Toast.makeText(getApplicationContext(), "Nothing was returned", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Response Good", Toast.LENGTH_LONG).show();
String city = locationMapObject.getName() + ", " + locationMapObject.getSys().getCountry();
String todayDate = getTodayDateInStringFormat();
Long tempVal = Math.round(Math.floor(Double.parseDouble(locationMapObject.getMain().getTemp())));
String weatherTemp = String.valueOf(tempVal) + "°";
String weatherDescription = Helper.capitalizeFirstLetter(locationMapObject.getWeather().get(0).getDescription());
String windSpeed = locationMapObject.getWind().getSpeed();
convertDegreeToCardinalDirection();
String windDirection = cardinalDirection;
String humidityValue = locationMapObject.getMain().getHumudity();
// String riseTime = locationMapObject.getSys().getSunrise();
//save location in database
if(apiUrl.contains("lat")){
query.insertNewLocation(locationMapObject.getName());
}
// populate View data
cityCountry.setText(String.valueOf(city));
currentDate.setText(Html.fromHtml(todayDate));
circleTitle.setTitleText(Html.fromHtml(weatherTemp).toString());
circleTitle.setSubtitleText(Html.fromHtml(weatherDescription).toString());
windResult.setText(Html.fromHtml(windSpeed) + " km/h");
Direction.setText(Html.fromHtml(windDirection) + " direction");
humidityResult.setText(Html.fromHtml(humidityValue) + " %");
// sunRise.setText(Html.fromHtml(riseTime));
fiveDaysApiJsonObjectCall(locationMapObject.getName());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error " + error.getMessage());
}
});
queue.add(stringRequest);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_LOCATION) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
//make api call
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 2, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
apiUrl = "http://api.openweathermap.org/data/2.5/weather?lat="+location.getLatitude()+"&lon="+location.getLongitude()+"&APPID="+Helper.API_KEY+"&units=metric";
makeJsonObject(apiUrl);
}else{
apiUrl = "http://api.openweathermap.org/data/2.5/weather?lat=51.5074&lon=0.1278&APPID="+Helper.API_KEY+"&units=metric";
makeJsonObject(apiUrl);
}
}
}else{
Toast.makeText(WeatherActivity.this, getString(R.string.permission_notice), Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onLocationChanged(Location location) {
this.location = location;
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String provider) {
if (provider.equals(LocationManager.GPS_PROVIDER)) {
showGPSDisabledAlertToUser();
}
}
private void showGPSDisabledAlertToUser() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Goto Settings Page To Enable GPS", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
private String getTodayDateInStringFormat(){
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("E, d MMMM", Locale.getDefault());
return df.format(c.getTime());
}
private void fiveDaysApiJsonObjectCall(String city){
String apiUrl = "http://api.openweathermap.org/data/2.5/forecast?q="+city+ "&APPID="+Helper.API_KEY+"&units=metric";
final List<WeatherObject> daysOfTheWeek = new ArrayList<WeatherObject>();
StringRequest stringRequest = new StringRequest(Request.Method.GET, apiUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Response 5 days" + response);
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
Forecast forecast = gson.fromJson(response, Forecast.class);
if (null == forecast) {
Toast.makeText(getApplicationContext(), "Nothing was returned", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Response Good", Toast.LENGTH_LONG).show();
int[] everyday = new int[]{0,0,0,0,0,0,0};
List<FiveWeathers> weatherInfo = forecast.getList();
if(null != weatherInfo){
for(int i = 0; i < weatherInfo.size(); i++){
String time = weatherInfo.get(i).getDt_txt();
String shortDay = convertTimeToDay(time);
String temp = weatherInfo.get(i).getMain().getTemp();
String tempMin = weatherInfo.get(i).getMain().getTemp_min();
if(convertTimeToDay(time).equals("Mon") && everyday[0] < 1){
daysOfTheWeek.add(new WeatherObject(shortDay, R.drawable.small_weather_icon, temp, tempMin));
everyday[0] = 1;
}
if(convertTimeToDay(time).equals("Tue") && everyday[1] < 1){
daysOfTheWeek.add(new WeatherObject(shortDay, R.drawable.small_weather_icon, temp, tempMin));
everyday[1] = 1;
}
if(convertTimeToDay(time).equals("Wed") && everyday[2] < 1){
daysOfTheWeek.add(new WeatherObject(shortDay, R.drawable.small_weather_icon, temp, tempMin));
everyday[2] = 1;
}
if(convertTimeToDay(time).equals("Thu") && everyday[3] < 1){
daysOfTheWeek.add(new WeatherObject(shortDay, R.drawable.small_weather_icon, temp, tempMin));
everyday[3] = 1;
}
if(convertTimeToDay(time).equals("Fri") && everyday[4] < 1){
daysOfTheWeek.add(new WeatherObject(shortDay, R.drawable.small_weather_icon, temp, tempMin));
everyday[4] = 1;
}
if(convertTimeToDay(time).equals("Sat") && everyday[5] < 1){
daysOfTheWeek.add(new WeatherObject(shortDay, R.drawable.small_weather_icon, temp, tempMin));
everyday[5] = 1;
}
if(convertTimeToDay(time).equals("Sun") && everyday[6] < 1){
daysOfTheWeek.add(new WeatherObject(shortDay, R.drawable.small_weather_icon, temp, tempMin));
everyday[6] = 1;
}
recyclerViewAdapter = new RecyclerViewAdapter(WeatherActivity.this, daysOfTheWeek);
recyclerView.setAdapter(recyclerViewAdapter);
}
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error " + error.getMessage());
}
});
queue.add(stringRequest);
}
private String convertTimeToDay(String time){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:SSSS", Locale.getDefault());
String days = "";
try {
Date date = format.parse(time);
System.out.println("Our time " + date);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
days = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault());
System.out.println("Our time " + days);
} catch (ParseException e) {
e.printStackTrace();
}
return days;
}
public void convertDegreeToCardinalDirection() {
if ((locationMapObject.getWind().getDeg() >= 348.75) && (locationMapObject.getWind().getDeg() <= 360) ||
(locationMapObject.getWind().getDeg() >= 0) && (locationMapObject.getWind().getDeg() <= 11.25)) {
cardinalDirection = "N";
} else if ((locationMapObject.getWind().getDeg() >= 11.25) && (locationMapObject.getWind().getDeg() <= 33.75)) {
cardinalDirection = "NNE";
} else if ((locationMapObject.getWind().getDeg() >= 33.75) && (locationMapObject.getWind().getDeg() <= 56.25)) {
cardinalDirection = "NE";
} else if ((locationMapObject.getWind().getDeg() >= 56.25) && (locationMapObject.getWind().getDeg() <= 78.75)) {
cardinalDirection = "ENE";
} else if ((locationMapObject.getWind().getDeg()>= 78.75) && (locationMapObject.getWind().getDeg() <= 101.25)) {
cardinalDirection = "E";
} else if ((locationMapObject.getWind().getDeg() >= 101.25) && (locationMapObject.getWind().getDeg()<= 123.75)) {
cardinalDirection = "ESE";
} else if ((locationMapObject.getWind().getDeg() >= 123.75) && (locationMapObject.getWind().getDeg() <= 146.25)) {
cardinalDirection = "SE";
} else if ((locationMapObject.getWind().getDeg()>= 146.25) && (locationMapObject.getWind().getDeg()<= 168.75)) {
cardinalDirection = "SSE";
} else if ((locationMapObject.getWind().getDeg() >= 168.75) && (locationMapObject.getWind().getDeg() <= 191.25)) {
cardinalDirection = "S";
} else if ((locationMapObject.getWind().getDeg() >= 191.25) && (locationMapObject.getWind().getDeg() <= 213.75)) {
cardinalDirection = "SSW";
} else if ((locationMapObject.getWind().getDeg() >= 213.75) && (locationMapObject.getWind().getDeg() <= 236.25)) {
cardinalDirection = "SW";
} else if ((locationMapObject.getWind().getDeg() >= 236.25) && (locationMapObject.getWind().getDeg() <= 258.75)) {
cardinalDirection = "WSW";
} else if ((locationMapObject.getWind().getDeg() >= 258.75) && (locationMapObject.getWind().getDeg() <= 281.25)) {
cardinalDirection = "W";
} else if ((locationMapObject.getWind().getDeg() >= 281.25) && (locationMapObject.getWind().getDeg() <= 303.75)) {
cardinalDirection = "WNW";
} else if ((locationMapObject.getWind().getDeg() >= 303.75) && (locationMapObject.getWind().getDeg() <= 326.25)) {
cardinalDirection = "NW";
} else if ((locationMapObject.getWind().getDeg() >= 326.25) && (locationMapObject.getWind().getDeg() <= 348.75)) {
cardinalDirection = "NNW";
} else {
cardinalDirection = "?";
}
}
}
}如果其他人有这个问题,结果是我在logcat的详细部分发现了一个单独的错误,错误是不允许明文HTTP通信。为了解决这个问题,我在我的android清单文件中添加了android:usesCleartextTraffic=“true”这只是一个警告。附加一个空适配器以删除它-或者忽略它。但是现在没有数据通过?很明显,您以后会获取它…因此您可以先添加一个空适配器,然后用填充的适配器替换它。这并不重要,因此这不是一个错误。。。这仅仅是一种装饰,将logcat输出减少1行。好的,我应该在哪里添加空适配器?或者这有关系吗?在获得
RecyclerView
的句柄之后。
private TextView humidityResult;
private RequestQueue queue;
private LocationMapObject locationMapObject;
private LocationManager locationManager;
private Location location;
private final int REQUEST_LOCATION = 200;
private CustomSharedPreference sharedPreference;
private String isLocationSaved;
private DatabaseQuery query;
private String apiUrl;
private FiveDaysForecast fiveDaysForecast;
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather);
ActionBar actionBar = getSupportActionBar();
if(actionBar != null){
actionBar.hide();
}
queue = Volley.newRequestQueue(this);
query = new DatabaseQuery(WeatherActivity.this);
sharedPreference = new CustomSharedPreference(WeatherActivity.this);
isLocationSaved = sharedPreference.getLocationInPreference();
cityCountry = (TextView)findViewById(R.id.city_country);
currentDate = (TextView)findViewById(R.id.current_date);
weatherImage = (ImageView)findViewById(R.id.weather_icon);
circleTitle = (CircleView)findViewById(R.id.weather_result);
windResult = (TextView)findViewById(R.id.wind_result);
Direction = (TextView)findViewById(R.id.wind_direction);
humidityResult = (TextView)findViewById(R.id.humidity_result);
// sunRise =(TextView)findViewById(R.id.sunrise_result);
locationManager = (LocationManager) getSystemService(Service.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(WeatherActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
} else {
if(isLocationSaved.equals("")){
// make API call with longitude and latitude
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 2, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
apiUrl = "http://api.openweathermap.org/data/2.5/weather?lat="+location.getLatitude()+"&lon="+location.getLongitude()+"&APPID="+Helper.API_KEY+"&units=metric";
makeJsonObject(apiUrl);
}
}else{
// make API call with city name
String storedCityName = sharedPreference.getLocationInPreference();
System.out.println("Stored city " + storedCityName);
String[] city = storedCityName.split(",");
if(!TextUtils.isEmpty(city[0])){
System.out.println("Stored city " + city[0]);
String url ="http://api.openweathermap.org/data/2.5/weather?q="+city[0]+"&APPID="+Helper.API_KEY+"&units=metric";
makeJsonObject(url);
}
}
}
ImageButton addLocation = (ImageButton) findViewById(R.id.add_location);
addLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent addLocationIntent = new Intent(WeatherActivity.this, AddLocationActivity.class);
startActivity(addLocationIntent);
}
});
GridLayoutManager gridLayoutManager = new GridLayoutManager(WeatherActivity.this, 4);
recyclerView = (RecyclerView)findViewById(R.id.weather_daily_list);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView.setHasFixedSize(true);
}
private void makeJsonObject(final String apiUrl){
StringRequest stringRequest = new StringRequest(Request.Method.GET, apiUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Response " + response);
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
locationMapObject = gson.fromJson(response, LocationMapObject.class);
if (null == locationMapObject) {
Toast.makeText(getApplicationContext(), "Nothing was returned", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Response Good", Toast.LENGTH_LONG).show();
String city = locationMapObject.getName() + ", " + locationMapObject.getSys().getCountry();
String todayDate = getTodayDateInStringFormat();
Long tempVal = Math.round(Math.floor(Double.parseDouble(locationMapObject.getMain().getTemp())));
String weatherTemp = String.valueOf(tempVal) + "°";
String weatherDescription = Helper.capitalizeFirstLetter(locationMapObject.getWeather().get(0).getDescription());
String windSpeed = locationMapObject.getWind().getSpeed();
convertDegreeToCardinalDirection();
String windDirection = cardinalDirection;
String humidityValue = locationMapObject.getMain().getHumudity();
// String riseTime = locationMapObject.getSys().getSunrise();
//save location in database
if(apiUrl.contains("lat")){
query.insertNewLocation(locationMapObject.getName());
}
// populate View data
cityCountry.setText(String.valueOf(city));
currentDate.setText(Html.fromHtml(todayDate));
circleTitle.setTitleText(Html.fromHtml(weatherTemp).toString());
circleTitle.setSubtitleText(Html.fromHtml(weatherDescription).toString());
windResult.setText(Html.fromHtml(windSpeed) + " km/h");
Direction.setText(Html.fromHtml(windDirection) + " direction");
humidityResult.setText(Html.fromHtml(humidityValue) + " %");
// sunRise.setText(Html.fromHtml(riseTime));
fiveDaysApiJsonObjectCall(locationMapObject.getName());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error " + error.getMessage());
}
});
queue.add(stringRequest);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_LOCATION) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
//make api call
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 2, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
apiUrl = "http://api.openweathermap.org/data/2.5/weather?lat="+location.getLatitude()+"&lon="+location.getLongitude()+"&APPID="+Helper.API_KEY+"&units=metric";
makeJsonObject(apiUrl);
}else{
apiUrl = "http://api.openweathermap.org/data/2.5/weather?lat=51.5074&lon=0.1278&APPID="+Helper.API_KEY+"&units=metric";
makeJsonObject(apiUrl);
}
}
}else{
Toast.makeText(WeatherActivity.this, getString(R.string.permission_notice), Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onLocationChanged(Location location) {
this.location = location;
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String provider) {
if (provider.equals(LocationManager.GPS_PROVIDER)) {
showGPSDisabledAlertToUser();
}
}
private void showGPSDisabledAlertToUser() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Goto Settings Page To Enable GPS", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
private String getTodayDateInStringFormat(){
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("E, d MMMM", Locale.getDefault());
return df.format(c.getTime());
}
private void fiveDaysApiJsonObjectCall(String city){
String apiUrl = "http://api.openweathermap.org/data/2.5/forecast?q="+city+ "&APPID="+Helper.API_KEY+"&units=metric";
final List<WeatherObject> daysOfTheWeek = new ArrayList<WeatherObject>();
StringRequest stringRequest = new StringRequest(Request.Method.GET, apiUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Response 5 days" + response);
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
Forecast forecast = gson.fromJson(response, Forecast.class);
if (null == forecast) {
Toast.makeText(getApplicationContext(), "Nothing was returned", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Response Good", Toast.LENGTH_LONG).show();
int[] everyday = new int[]{0,0,0,0,0,0,0};
List<FiveWeathers> weatherInfo = forecast.getList();
if(null != weatherInfo){
for(int i = 0; i < weatherInfo.size(); i++){
String time = weatherInfo.get(i).getDt_txt();
String shortDay = convertTimeToDay(time);
String temp = weatherInfo.get(i).getMain().getTemp();
String tempMin = weatherInfo.get(i).getMain().getTemp_min();
if(convertTimeToDay(time).equals("Mon") && everyday[0] < 1){
daysOfTheWeek.add(new WeatherObject(shortDay, R.drawable.small_weather_icon, temp, tempMin));
everyday[0] = 1;
}
if(convertTimeToDay(time).equals("Tue") && everyday[1] < 1){
daysOfTheWeek.add(new WeatherObject(shortDay, R.drawable.small_weather_icon, temp, tempMin));
everyday[1] = 1;
}
if(convertTimeToDay(time).equals("Wed") && everyday[2] < 1){
daysOfTheWeek.add(new WeatherObject(shortDay, R.drawable.small_weather_icon, temp, tempMin));
everyday[2] = 1;
}
if(convertTimeToDay(time).equals("Thu") && everyday[3] < 1){
daysOfTheWeek.add(new WeatherObject(shortDay, R.drawable.small_weather_icon, temp, tempMin));
everyday[3] = 1;
}
if(convertTimeToDay(time).equals("Fri") && everyday[4] < 1){
daysOfTheWeek.add(new WeatherObject(shortDay, R.drawable.small_weather_icon, temp, tempMin));
everyday[4] = 1;
}
if(convertTimeToDay(time).equals("Sat") && everyday[5] < 1){
daysOfTheWeek.add(new WeatherObject(shortDay, R.drawable.small_weather_icon, temp, tempMin));
everyday[5] = 1;
}
if(convertTimeToDay(time).equals("Sun") && everyday[6] < 1){
daysOfTheWeek.add(new WeatherObject(shortDay, R.drawable.small_weather_icon, temp, tempMin));
everyday[6] = 1;
}
recyclerViewAdapter = new RecyclerViewAdapter(WeatherActivity.this, daysOfTheWeek);
recyclerView.setAdapter(recyclerViewAdapter);
}
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error " + error.getMessage());
}
});
queue.add(stringRequest);
}
private String convertTimeToDay(String time){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:SSSS", Locale.getDefault());
String days = "";
try {
Date date = format.parse(time);
System.out.println("Our time " + date);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
days = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault());
System.out.println("Our time " + days);
} catch (ParseException e) {
e.printStackTrace();
}
return days;
}
public void convertDegreeToCardinalDirection() {
if ((locationMapObject.getWind().getDeg() >= 348.75) && (locationMapObject.getWind().getDeg() <= 360) ||
(locationMapObject.getWind().getDeg() >= 0) && (locationMapObject.getWind().getDeg() <= 11.25)) {
cardinalDirection = "N";
} else if ((locationMapObject.getWind().getDeg() >= 11.25) && (locationMapObject.getWind().getDeg() <= 33.75)) {
cardinalDirection = "NNE";
} else if ((locationMapObject.getWind().getDeg() >= 33.75) && (locationMapObject.getWind().getDeg() <= 56.25)) {
cardinalDirection = "NE";
} else if ((locationMapObject.getWind().getDeg() >= 56.25) && (locationMapObject.getWind().getDeg() <= 78.75)) {
cardinalDirection = "ENE";
} else if ((locationMapObject.getWind().getDeg()>= 78.75) && (locationMapObject.getWind().getDeg() <= 101.25)) {
cardinalDirection = "E";
} else if ((locationMapObject.getWind().getDeg() >= 101.25) && (locationMapObject.getWind().getDeg()<= 123.75)) {
cardinalDirection = "ESE";
} else if ((locationMapObject.getWind().getDeg() >= 123.75) && (locationMapObject.getWind().getDeg() <= 146.25)) {
cardinalDirection = "SE";
} else if ((locationMapObject.getWind().getDeg()>= 146.25) && (locationMapObject.getWind().getDeg()<= 168.75)) {
cardinalDirection = "SSE";
} else if ((locationMapObject.getWind().getDeg() >= 168.75) && (locationMapObject.getWind().getDeg() <= 191.25)) {
cardinalDirection = "S";
} else if ((locationMapObject.getWind().getDeg() >= 191.25) && (locationMapObject.getWind().getDeg() <= 213.75)) {
cardinalDirection = "SSW";
} else if ((locationMapObject.getWind().getDeg() >= 213.75) && (locationMapObject.getWind().getDeg() <= 236.25)) {
cardinalDirection = "SW";
} else if ((locationMapObject.getWind().getDeg() >= 236.25) && (locationMapObject.getWind().getDeg() <= 258.75)) {
cardinalDirection = "WSW";
} else if ((locationMapObject.getWind().getDeg() >= 258.75) && (locationMapObject.getWind().getDeg() <= 281.25)) {
cardinalDirection = "W";
} else if ((locationMapObject.getWind().getDeg() >= 281.25) && (locationMapObject.getWind().getDeg() <= 303.75)) {
cardinalDirection = "WNW";
} else if ((locationMapObject.getWind().getDeg() >= 303.75) && (locationMapObject.getWind().getDeg() <= 326.25)) {
cardinalDirection = "NW";
} else if ((locationMapObject.getWind().getDeg() >= 326.25) && (locationMapObject.getWind().getDeg() <= 348.75)) {
cardinalDirection = "NNW";
} else {
cardinalDirection = "?";
}
}
}
private String dayOfWeek;
private int weatherIcon;
private String weatherResult;
private String weatherResultSmall;
public WeatherObject(String dayOfWeek, int weatherIcon, String weatherResult, String weatherResultSmall) {
this.dayOfWeek = dayOfWeek;
this.weatherIcon = weatherIcon;
this.weatherResult = weatherResult;
this.weatherResultSmall = weatherResultSmall;
}
public String getDayOfWeek() {
return dayOfWeek;
}
public int getWeatherIcon() {
return weatherIcon;
}
public String getWeatherResult() {
return weatherResult;
}
public String getWeatherResultSmall() {
return weatherResultSmall;
}