packagenasa.spaceapps.dsos.activities; | |
importandroid.content.SharedPreferences; | |
importandroid.graphics.Color; | |
importandroid.graphics.DashPathEffect; | |
importandroid.graphics.Paint; | |
importandroid.os.Bundle; | |
importandroid.preference.PreferenceManager; | |
importandroid.support.design.widget.Snackbar; | |
importandroid.support.v7.app.AppCompatActivity; | |
importandroid.support.v7.widget.Toolbar; | |
importandroid.util.Log; | |
importcom.db.chart.Tools; | |
importcom.db.chart.model.LineSet; | |
importcom.db.chart.view.ChartView; | |
importcom.db.chart.view.LineChartView; | |
importorg.json.JSONArray; | |
importorg.json.JSONException; | |
importorg.json.JSONObject; | |
importjava.text.SimpleDateFormat; | |
importjava.util.ArrayList; | |
importjava.util.TimeZone; | |
importnasa.spaceapps.dsos.R; | |
importnasa.spaceapps.dsos.models.Weather; | |
importnasa.spaceapps.dsos.tasks.ParseResult; | |
importnasa.spaceapps.dsos.utils.UnitConvertor; | |
publicclassGraphActivityextendsAppCompatActivity { | |
SharedPreferences sp; | |
int theme; | |
ArrayList<Weather> weatherList =newArrayList<>(); | |
float minTemp =100000; | |
float maxTemp =0; | |
float minRain =100000; | |
float maxRain =0; | |
float minPressure =100000; | |
float maxPressure =0; | |
@Override | |
protectedvoidonCreate(BundlesavedInstanceState) { | |
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this); | |
setTheme(theme = getTheme(prefs.getString("theme", "fresh"))); | |
boolean darkTheme = theme ==R.style.AppTheme_NoActionBar_Dark|| | |
theme ==R.style.AppTheme_NoActionBar_Classic_Dark; | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_graph); | |
Toolbar toolbar = (Toolbar) findViewById(R.id.graph_toolbar); | |
setSupportActionBar(toolbar); | |
getSupportActionBar().setDisplayHomeAsUpEnabled(true); | |
if (darkTheme) { | |
toolbar.setPopupTheme(R.style.AppTheme_PopupOverlay_Dark); | |
} | |
sp =PreferenceManager.getDefaultSharedPreferences(GraphActivity.this); | |
String lastLongterm = sp.getString("lastLongterm", ""); | |
if (parseLongTermJson(lastLongterm) ==ParseResult.OK) { | |
temperatureGraph(); | |
rainGraph(); | |
pressureGraph(); | |
} else { | |
Snackbar.make(findViewById(android.R.id.content), R.string.msg_err_parsing_json, Snackbar.LENGTH_LONG).show(); | |
} | |
} | |
privatevoidtemperatureGraph() { | |
LineChartView lineChartView = (LineChartView) findViewById(R.id.graph_temperature); | |
// Data | |
LineSet dataset =newLineSet(); | |
for (int i =0; i < weatherList.size(); i++) { | |
float temperature =UnitConvertor.convertTemperature(Float.parseFloat(weatherList.get(i).getTemperature()), sp); | |
if (temperature < minTemp) { | |
minTemp = temperature; | |
} | |
if (temperature > maxTemp) { | |
maxTemp = temperature; | |
} | |
dataset.addPoint(getDateLabel(weatherList.get(i), i), (float) temperature); | |
} | |
dataset.setSmooth(false); | |
dataset.setColor(Color.parseColor("#FF5722")); | |
dataset.setThickness(4); | |
lineChartView.addData(dataset); | |
// Grid | |
Paint paint =newPaint(); | |
paint.setStyle(Paint.Style.STROKE); | |
paint.setAntiAlias(true); | |
paint.setColor(Color.parseColor("#333333")); | |
paint.setPathEffect(newDashPathEffect(newfloat[]{10, 10}, 0)); | |
paint.setStrokeWidth(1); | |
lineChartView.setGrid(ChartView.GridType.HORIZONTAL, paint); | |
lineChartView.setBorderSpacing(Tools.fromDpToPx(10)); | |
lineChartView.setAxisBorderValues((int) (Math.round(minTemp)) -1, (int) (Math.round(maxTemp)) +1); | |
lineChartView.setStep(2); | |
lineChartView.setXAxis(false); | |
lineChartView.setYAxis(false); | |
lineChartView.show(); | |
} | |
privatevoidrainGraph() { | |
LineChartView lineChartView = (LineChartView) findViewById(R.id.graph_rain); | |
// Data | |
LineSet dataset =newLineSet(); | |
for (int i =0; i < weatherList.size(); i++) { | |
float rain =Float.parseFloat(weatherList.get(i).getRain()); | |
if (rain < minRain) { | |
minRain = rain; | |
} | |
if (rain > maxRain) { | |
maxRain = rain; | |
} | |
dataset.addPoint(getDateLabel(weatherList.get(i), i), rain); | |
} | |
dataset.setSmooth(false); | |
dataset.setColor(Color.parseColor("#2196F3")); | |
dataset.setThickness(4); | |
lineChartView.addData(dataset); | |
// Grid | |
Paint paint =newPaint(); | |
paint.setStyle(Paint.Style.STROKE); | |
paint.setAntiAlias(true); | |
paint.setColor(Color.parseColor("#333333")); | |
paint.setPathEffect(newDashPathEffect(newfloat[]{10, 10}, 0)); | |
paint.setStrokeWidth(1); | |
lineChartView.setGrid(ChartView.GridType.HORIZONTAL, paint); | |
lineChartView.setBorderSpacing(Tools.fromDpToPx(10)); | |
lineChartView.setAxisBorderValues(0, (int) (Math.round(maxRain)) +1); | |
lineChartView.setStep(1); | |
lineChartView.setXAxis(false); | |
lineChartView.setYAxis(false); | |
lineChartView.show(); | |
} | |
privatevoidpressureGraph() { | |
LineChartView lineChartView = (LineChartView) findViewById(R.id.graph_pressure); | |
// Data | |
LineSet dataset =newLineSet(); | |
for (int i =0; i < weatherList.size(); i++) { | |
float pressure =UnitConvertor.convertPressure(Float.parseFloat(weatherList.get(i).getPressure()), sp); | |
if (pressure < minPressure) { | |
minPressure = pressure; | |
} | |
if (pressure > maxPressure) { | |
maxPressure = pressure; | |
} | |
dataset.addPoint(getDateLabel(weatherList.get(i), i), pressure); | |
} | |
dataset.setSmooth(true); | |
dataset.setColor(Color.parseColor("#4CAF50")); | |
dataset.setThickness(4); | |
lineChartView.addData(dataset); | |
// Grid | |
Paint paint =newPaint(); | |
paint.setStyle(Paint.Style.STROKE); | |
paint.setAntiAlias(true); | |
paint.setColor(Color.parseColor("#333333")); | |
paint.setPathEffect(newDashPathEffect(newfloat[]{10, 10}, 0)); | |
paint.setStrokeWidth(1); | |
lineChartView.setGrid(ChartView.GridType.HORIZONTAL, paint); | |
lineChartView.setBorderSpacing(Tools.fromDpToPx(10)); | |
lineChartView.setAxisBorderValues((int) minPressure -1, (int) maxPressure +1); | |
lineChartView.setStep(2); | |
lineChartView.setXAxis(false); | |
lineChartView.setYAxis(false); | |
lineChartView.show(); | |
} | |
publicParseResultparseLongTermJson(Stringresult) { | |
int i; | |
try { | |
JSONObject reader =newJSONObject(result); | |
finalString code = reader.optString("cod"); | |
if ("404".equals(code)) { | |
returnParseResult.CITY_NOT_FOUND; | |
} | |
JSONArray list = reader.getJSONArray("list"); | |
for (i =0; i < list.length(); i++) { | |
Weather weather =newWeather(); | |
JSONObject listItem = list.getJSONObject(i); | |
JSONObject main = listItem.getJSONObject("main"); | |
JSONObject windObj = listItem.optJSONObject("wind"); | |
weather.setWind(windObj.getString("speed")); | |
weather.setPressure(main.getString("pressure")); | |
weather.setHumidity(main.getString("humidity")); | |
JSONObject rainObj = listItem.optJSONObject("rain"); | |
JSONObject snowObj = listItem.optJSONObject("snow"); | |
if (rainObj !=null) { | |
weather.setRain(MainActivity.getRainString(rainObj)); | |
} else { | |
weather.setRain(MainActivity.getRainString(snowObj)); | |
} | |
weather.setDate(listItem.getString("dt")); | |
weather.setTemperature(main.getString("temp")); | |
weatherList.add(weather); | |
} | |
} catch (JSONException e) { | |
Log.e("JSONException Data", result); | |
e.printStackTrace(); | |
returnParseResult.JSON_EXCEPTION; | |
} | |
returnParseResult.OK; | |
} | |
String previous =""; | |
publicStringgetDateLabel(Weatherweather, inti) { | |
if ((i +4) %4==0) { | |
SimpleDateFormat resultFormat =newSimpleDateFormat("E"); | |
resultFormat.setTimeZone(TimeZone.getDefault()); | |
String output = resultFormat.format(weather.getDate()); | |
if (!output.equals(previous)) { | |
previous = output; | |
return output; | |
} else { | |
return""; | |
} | |
} else { | |
return""; | |
} | |
} | |
privateintgetTheme(StringthemePref) { | |
switch (themePref) { | |
case"dark": | |
returnR.style.AppTheme_NoActionBar_Dark; | |
case"black": | |
returnR.style.AppTheme_NoActionBar_Black; | |
case"classic": | |
returnR.style.AppTheme_NoActionBar_Classic; | |
case"classicdark": | |
returnR.style.AppTheme_NoActionBar_Classic_Dark; | |
case"classicblack": | |
returnR.style.AppTheme_NoActionBar_Classic_Black; | |
default: | |
returnR.style.AppTheme_NoActionBar; | |
} | |
} | |
} |
packagenasa.spaceapps.dsos.activities; | |
importandroid.app.ProgressDialog; | |
importandroid.graphics.Typeface; | |
importandroid.location.LocationManager; | |
importandroid.support.design.widget.TabLayout; | |
importandroid.support.v4.view.ViewPager; | |
importandroid.view.View; | |
importandroid.widget.TextView; | |
importjava.util.ArrayList; | |
importjava.util.HashMap; | |
importjava.util.List; | |
importjava.util.Map; | |
importnasa.spaceapps.dsos.models.Weather; | |
publicclassMain { | |
protectedstaticfinalintMY_PERMISSIONS_ACCESS_FINE_LOCATION=1; | |
// Time in milliseconds; only reload weather if last update is longer ago than this value | |
privatestaticfinalintNO_UPDATE_REQUIRED_THRESHOLD=300000; | |
privatestaticMap<String, Integer> speedUnits =newHashMap<>(3); | |
privatestaticMap<String, Integer> pressUnits =newHashMap<>(3); | |
privatestaticboolean mappingsInitialised =false; | |
Typeface weatherFont; | |
Weather todayWeather =newWeather(); | |
TextView todayTemperature; | |
TextView todayDescription; | |
TextView todayWind; | |
TextView todayPressure; | |
TextView todayHumidity; | |
TextView todaySunrise; | |
TextView todaySunset; | |
TextView lastUpdate; | |
TextView todayIcon; | |
ViewPager viewPager; | |
TabLayout tabLayout; | |
View appView; | |
LocationManager locationManager; | |
ProgressDialog progressDialog; | |
int theme; | |
boolean destroyed =false; | |
privateList<Weather> longTermWeather =newArrayList<>(); | |
privateList<Weather> longTermTodayWeather =newArrayList<>(); | |
privateList<Weather> longTermTomorrowWeather =newArrayList<>(); | |
publicString recentCity =""; | |
} |
packagenasa.spaceapps.dsos.activities; | |
importandroid.Manifest; | |
importandroid.app.ProgressDialog; | |
importandroid.content.Context; | |
importandroid.content.DialogInterface; | |
importandroid.content.Intent; | |
importandroid.content.SharedPreferences; | |
importandroid.content.pm.PackageManager; | |
importandroid.content.res.TypedArray; | |
importandroid.graphics.Color; | |
importandroid.graphics.Typeface; | |
importandroid.location.Location; | |
importandroid.location.LocationListener; | |
importandroid.location.LocationManager; | |
importandroid.net.ConnectivityManager; | |
importandroid.net.NetworkInfo; | |
importandroid.os.AsyncTask; | |
importandroid.os.Bundle; | |
importandroid.preference.PreferenceManager; | |
importandroid.provider.Settings; | |
importandroid.support.design.widget.Snackbar; | |
importandroid.support.design.widget.TabLayout; | |
importandroid.support.v4.app.ActivityCompat; | |
importandroid.support.v4.content.ContextCompat; | |
importandroid.support.v4.view.ViewPager; | |
importandroid.support.v7.app.AlertDialog; | |
importandroid.support.v7.app.AppCompatActivity; | |
importandroid.support.v7.widget.Toolbar; | |
importandroid.text.InputType; | |
importandroid.util.Log; | |
importandroid.view.Menu; | |
importandroid.view.MenuItem; | |
importandroid.view.View; | |
importandroid.webkit.WebView; | |
importandroid.widget.EditText; | |
importandroid.widget.TextView; | |
importorg.json.JSONArray; | |
importorg.json.JSONException; | |
importorg.json.JSONObject; | |
importjava.text.DateFormat; | |
importjava.text.DecimalFormat; | |
importjava.util.ArrayList; | |
importjava.util.Calendar; | |
importjava.util.Date; | |
importjava.util.GregorianCalendar; | |
importjava.util.HashMap; | |
importjava.util.List; | |
importjava.util.Map; | |
importnasa.spaceapps.dsos.AlarmReceiver; | |
importnasa.spaceapps.dsos.Constants; | |
importnasa.spaceapps.dsos.R; | |
importnasa.spaceapps.dsos.adapters.ViewPagerAdapter; | |
importnasa.spaceapps.dsos.adapters.WeatherRecyclerAdapter; | |
importnasa.spaceapps.dsos.fragments.RecyclerViewFragment; | |
importnasa.spaceapps.dsos.models.Weather; | |
importnasa.spaceapps.dsos.tasks.GenericRequestTask; | |
importnasa.spaceapps.dsos.tasks.ParseResult; | |
importnasa.spaceapps.dsos.tasks.TaskOutput; | |
importnasa.spaceapps.dsos.utils.UnitConvertor; | |
importnasa.spaceapps.dsos.widgets.AbstractWidgetProvider; | |
importnasa.spaceapps.dsos.widgets.DashClockWeatherExtension; | |
publicclassMainActivityextendsAppCompatActivityimplementsLocationListener { | |
protectedstaticfinalintMY_PERMISSIONS_ACCESS_FINE_LOCATION=1; | |
// Time in milliseconds; only reload weather if last update is longer ago than this value | |
privatestaticfinalintNO_UPDATE_REQUIRED_THRESHOLD=300000; | |
privatestaticMap<String, Integer> speedUnits =newHashMap<>(3); | |
privatestaticMap<String, Integer> pressUnits =newHashMap<>(3); | |
privatestaticboolean mappingsInitialised =false; | |
Typeface weatherFont; | |
Weather todayWeather =newWeather(); | |
TextView todayTemperature; | |
TextView todayDescription; | |
TextView todayWind; | |
TextView todayPressure; | |
TextView todayHumidity; | |
TextView todaySunrise; | |
TextView todaySunset; | |
TextView lastUpdate; | |
TextView todayIcon; | |
ViewPager viewPager; | |
TabLayout tabLayout; | |
TextView soslable; | |
TextView sosstat; | |
View appView; | |
LocationManager locationManager; | |
ProgressDialog progressDialog; | |
int theme; | |
boolean destroyed =false; | |
privateList<Weather> longTermWeather =newArrayList<>(); | |
privateList<Weather> longTermTodayWeather =newArrayList<>(); | |
privateList<Weather> longTermTomorrowWeather =newArrayList<>(); | |
publicString recentCity =""; | |
@Override | |
protectedvoidonCreate(BundlesavedInstanceState) { | |
// Initialize the associated SharedPreferences file with default values | |
PreferenceManager.setDefaultValues(this, R.xml.prefs, false); | |
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this); | |
setTheme(theme = getTheme(prefs.getString("theme", "fresh"))); | |
boolean darkTheme = theme ==R.style.AppTheme_NoActionBar_Dark|| | |
theme ==R.style.AppTheme_NoActionBar_Classic_Dark; | |
boolean blackTheme = theme ==R.style.AppTheme_NoActionBar_Black|| | |
theme ==R.style.AppTheme_NoActionBar_Classic_Black; | |
// Initiate activity | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_scrolling); | |
appView = findViewById(R.id.viewApp); | |
progressDialog =newProgressDialog(MainActivity.this); | |
// Load toolbar | |
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); | |
setSupportActionBar(toolbar); | |
if (darkTheme) { | |
toolbar.setPopupTheme(R.style.AppTheme_PopupOverlay_Dark); | |
} elseif (blackTheme) { | |
toolbar.setPopupTheme(R.style.AppTheme_PopupOverlay_Black); | |
} | |
// Initialize textboxes | |
todayTemperature = (TextView) findViewById(R.id.todayTemperature); | |
todayDescription = (TextView) findViewById(R.id.todayDescription); | |
todayWind = (TextView) findViewById(R.id.todayWind); | |
todayPressure = (TextView) findViewById(R.id.todayPressure); | |
todayHumidity = (TextView) findViewById(R.id.todayHumidity); | |
todaySunrise = (TextView) findViewById(R.id.todaySunrise); | |
todaySunset = (TextView) findViewById(R.id.todaySunset); | |
lastUpdate = (TextView) findViewById(R.id.lastUpdate); | |
todayIcon = (TextView) findViewById(R.id.todayIcon); | |
weatherFont =Typeface.createFromAsset(this.getAssets(), "fonts/weather.ttf"); | |
todayIcon.setTypeface(weatherFont); | |
soslable = (TextView) findViewById(R.id.soslbl); | |
sosstat = (TextView) findViewById(R.id.sos_statos); | |
// Initialize viewPager | |
viewPager = (ViewPager) findViewById(R.id.viewPager); | |
tabLayout = (TabLayout) findViewById(R.id.tabs); | |
destroyed =false; | |
initMappings(); | |
// Preload data from cache | |
preloadWeather(); | |
updateLastUpdateTime(); | |
// Set autoupdater | |
AlarmReceiver.setRecurringAlarm(this); | |
} | |
publicWeatherRecyclerAdaptergetAdapter(intid) { | |
WeatherRecyclerAdapter weatherRecyclerAdapter; | |
if (id ==0) { | |
weatherRecyclerAdapter =newWeatherRecyclerAdapter(this, longTermTodayWeather); | |
} elseif (id ==1) { | |
weatherRecyclerAdapter =newWeatherRecyclerAdapter(this, longTermTomorrowWeather); | |
} else { | |
weatherRecyclerAdapter =newWeatherRecyclerAdapter(this, longTermWeather); | |
} | |
return weatherRecyclerAdapter; | |
} | |
@Override | |
publicvoidonStart() { | |
super.onStart(); | |
updateTodayWeatherUI(); | |
updateLongTermWeatherUI(); | |
} | |
@Override | |
publicvoidonResume() { | |
super.onResume(); | |
if (getTheme(PreferenceManager.getDefaultSharedPreferences(this).getString("theme", "fresh")) != theme) { | |
// Restart activity to apply theme | |
overridePendingTransition(0, 0); | |
finish(); | |
overridePendingTransition(0, 0); | |
startActivity(getIntent()); | |
} elseif (shouldUpdate() && isNetworkAvailable()) { | |
getTodayWeather(); | |
getLongTermWeather(); | |
} | |
} | |
@Override | |
protectedvoidonDestroy() { | |
super.onDestroy(); | |
destroyed =true; | |
if (locationManager !=null) { | |
try { | |
locationManager.removeUpdates(MainActivity.this); | |
} catch (SecurityException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
privatevoidpreloadWeather() { | |
SharedPreferences sp =PreferenceManager.getDefaultSharedPreferences(MainActivity.this); | |
String lastToday = sp.getString("lastToday", ""); | |
if (!lastToday.isEmpty()) { | |
newTodayWeatherTask(this, this, progressDialog).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "cachedResponse", lastToday); | |
} | |
String lastLongterm = sp.getString("lastLongterm", ""); | |
if (!lastLongterm.isEmpty()) { | |
newLongTermWeatherTask(this, this, progressDialog).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "cachedResponse", lastLongterm); | |
} | |
} | |
privatevoidgetTodayWeather() { | |
newTodayWeatherTask(this, this, progressDialog).execute(); | |
} | |
privatevoidgetLongTermWeather() { | |
newLongTermWeatherTask(this, this, progressDialog).execute(); | |
} | |
privatevoidsearchCities() { | |
AlertDialog.Builder alert =newAlertDialog.Builder(this); | |
alert.setTitle(this.getString(R.string.search_title)); | |
finalEditText input =newEditText(this); | |
input.setInputType(InputType.TYPE_CLASS_TEXT); | |
input.setMaxLines(1); | |
input.setSingleLine(true); | |
alert.setView(input, 32, 0, 32, 0); | |
alert.setPositiveButton(R.string.dialog_ok, newDialogInterface.OnClickListener() { | |
publicvoidonClick(DialogInterfacedialog, intwhichButton) { | |
String result = input.getText().toString(); | |
if (!result.isEmpty()) { | |
saveLocation(result); | |
} | |
} | |
}); | |
alert.setNegativeButton(R.string.dialog_cancel, newDialogInterface.OnClickListener() { | |
publicvoidonClick(DialogInterfacedialog, intwhichButton) { | |
// Cancelled | |
} | |
}); | |
alert.show(); | |
} | |
privatevoidsaveLocation(Stringresult) { | |
SharedPreferences preferences =PreferenceManager.getDefaultSharedPreferences(MainActivity.this); | |
recentCity = preferences.getString("city", Constants.DEFAULT_CITY); | |
SharedPreferences.Editor editor = preferences.edit(); | |
editor.putString("city", result); | |
editor.commit(); | |
if (!recentCity.equals(result)) { | |
// New location, update weather | |
getTodayWeather(); | |
getLongTermWeather(); | |
} | |
} | |
privatevoidaboutDialog() { | |
AlertDialog.Builder alert =newAlertDialog.Builder(this); | |
alert.setTitle("Forecastie"); | |
finalWebView webView =newWebView(this); | |
String about ="<p>1.6.1</p>"+ | |
"<p>Developed for NASA Challange</p>"+ | |
"<p>By <a href='mailto:gunaid@ymail.com'>Gunaid Bawazir</a> & Abdulaziz Alqahtani</p>"+ | |
"<p>By using source of Tomas Martykan</p>"+ | |
"<p>Data provided by <a href='https://openweathermap.org/'>OpenWeatherMap</a>, under the <a href='http://creativecommons.org/licenses/by-sa/2.0/'>Creative Commons license</a>"+ | |
"<p>Icons are <a href='https://erikflowers.github.io/weather-icons/'>Weather Icons</a>, by <a href='http://www.twitter.com/artill'>Lukas Bischoff</a> and <a href='http://www.twitter.com/Erik_UX'>Erik Flowers</a>, under the <a href='http://scripts.sil.org/OFL'>SIL OFL 1.1</a> licence."; | |
TypedArray ta = obtainStyledAttributes(newint[]{android.R.attr.textColorPrimary, R.attr.colorAccent}); | |
String textColor =String.format("#%06X", (0xFFFFFF& ta.getColor(0, Color.BLACK))); | |
String accentColor =String.format("#%06X", (0xFFFFFF& ta.getColor(1, Color.BLUE))); | |
ta.recycle(); | |
about ="<style media=\"screen\" type=\"text/css\">"+ | |
"body {\n"+ | |
" color:"+ textColor +";\n"+ | |
"}\n"+ | |
"a:link {color:"+ accentColor +"}\n"+ | |
"</style>"+ | |
about; | |
webView.setBackgroundColor(Color.TRANSPARENT); | |
webView.loadData(about, "text/html", "UTF-8"); | |
alert.setView(webView, 32, 0, 32, 0); | |
alert.setPositiveButton(R.string.dialog_ok, newDialogInterface.OnClickListener() { | |
publicvoidonClick(DialogInterfacedialog, intwhichButton) { | |
} | |
}); | |
alert.show(); | |
} | |
privateStringsetWeatherIcon(intactualId, inthourOfDay) { | |
int id = actualId /100; | |
String icon =""; | |
if (actualId ==800) { | |
if (hourOfDay >=7&& hourOfDay <20) { | |
icon =this.getString(R.string.weather_sunny); | |
} else { | |
icon =this.getString(R.string.weather_clear_night); | |
} | |
} else { | |
switch (id) { | |
case2: | |
icon =this.getString(R.string.weather_thunder); | |
break; | |
case3: | |
icon =this.getString(R.string.weather_drizzle); | |
break; | |
case7: | |
icon =this.getString(R.string.weather_foggy); | |
break; | |
case8: | |
icon =this.getString(R.string.weather_cloudy); | |
break; | |
case6: | |
icon =this.getString(R.string.weather_snowy); | |
break; | |
case5: | |
icon =this.getString(R.string.weather_rainy); | |
break; | |
} | |
} | |
return icon; | |
} | |
publicstaticStringgetRainString(JSONObjectrainObj) { | |
String rain ="0"; | |
if (rainObj !=null) { | |
rain = rainObj.optString("3h", "fail"); | |
if ("fail".equals(rain)) { | |
rain = rainObj.optString("1h", "0"); | |
} | |
} | |
return rain; | |
} | |
privateParseResultparseTodayJson(Stringresult) { | |
try { | |
JSONObject reader =newJSONObject(result); | |
finalString code = reader.optString("cod"); | |
if ("404".equals(code)) { | |
returnParseResult.CITY_NOT_FOUND; | |
} | |
String city = reader.getString("name"); | |
String country =""; | |
JSONObject countryObj = reader.optJSONObject("sys"); | |
if (countryObj !=null) { | |
country = countryObj.getString("country"); | |
todayWeather.setSunrise(countryObj.getString("sunrise")); | |
todayWeather.setSunset(countryObj.getString("sunset")); | |
} | |
todayWeather.setCity(city); | |
todayWeather.setCountry(country); | |
JSONObject coordinates = reader.getJSONObject("coord"); | |
if (coordinates !=null) { | |
SharedPreferences sp =PreferenceManager.getDefaultSharedPreferences(this); | |
sp.edit().putFloat("latitude", (float) coordinates.getDouble("lon")).putFloat("longitude", (float) coordinates.getDouble("lat")).commit(); | |
} | |
JSONObject main = reader.getJSONObject("main"); | |
todayWeather.setTemperature(main.getString("temp")); | |
todayWeather.setDescription(reader.getJSONArray("weather").getJSONObject(0).getString("description")); | |
JSONObject windObj = reader.getJSONObject("wind"); | |
todayWeather.setWind(windObj.getString("speed")); | |
if (windObj.has("deg")) { | |
todayWeather.setWindDirectionDegree(windObj.getDouble("deg")); | |
} else { | |
Log.e("parseTodayJson", "No wind direction available"); | |
todayWeather.setWindDirectionDegree(null); | |
} | |
todayWeather.setPressure(main.getString("pressure")); | |
todayWeather.setHumidity(main.getString("humidity")); | |
JSONObject rainObj = reader.optJSONObject("rain"); | |
String rain; | |
if (rainObj !=null) { | |
rain = getRainString(rainObj); | |
} else { | |
JSONObject snowObj = reader.optJSONObject("snow"); | |
if (snowObj !=null) { | |
rain = getRainString(snowObj); | |
} else { | |
rain ="0"; | |
} | |
} | |
todayWeather.setRain(rain); | |
finalString idString = reader.getJSONArray("weather").getJSONObject(0).getString("id"); | |
todayWeather.setId(idString); | |
todayWeather.setIcon(setWeatherIcon(Integer.parseInt(idString), Calendar.getInstance().get(Calendar.HOUR_OF_DAY))); | |
SharedPreferences.Editor editor =PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit(); | |
editor.putString("lastToday", result); | |
editor.commit(); | |
} catch (JSONException e) { | |
Log.e("JSONException Data", result); | |
e.printStackTrace(); | |
returnParseResult.JSON_EXCEPTION; | |
} | |
returnParseResult.OK; | |
} | |
privatevoidupdateTodayWeatherUI() { | |
try { | |
if (todayWeather.getCountry().isEmpty()) { | |
preloadWeather(); | |
return; | |
} | |
} catch (Exception e) { | |
preloadWeather(); | |
return; | |
} | |
String city = todayWeather.getCity(); | |
String country = todayWeather.getCountry(); | |
DateFormat timeFormat =android.text.format.DateFormat.getTimeFormat(getApplicationContext()); | |
getSupportActionBar().setTitle(city + (country.isEmpty() ?"":", "+ country)); | |
SharedPreferences sp =PreferenceManager.getDefaultSharedPreferences(MainActivity.this); | |
// Temperature | |
float temperature =UnitConvertor.convertTemperature(Float.parseFloat(todayWeather.getTemperature()), sp); | |
if (sp.getBoolean("temperatureInteger", false)) { | |
temperature =Math.round(temperature); | |
} | |
// Rain | |
double rain =Double.parseDouble(todayWeather.getRain()); | |
String rainString =UnitConvertor.getRainString(rain, sp); | |
// Wind | |
double wind; | |
try { | |
wind =Double.parseDouble(todayWeather.getWind()); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
wind =0; | |
} | |
wind =UnitConvertor.convertWind(wind, sp); | |
// Pressure | |
double pressure =UnitConvertor.convertPressure((float) Double.parseDouble(todayWeather.getPressure()), sp); | |
todayTemperature.setText(newDecimalFormat("0.#").format(temperature) +""+ sp.getString("unit", "°C")); | |
todayDescription.setText(todayWeather.getDescription().substring(0, 1).toUpperCase() + | |
todayWeather.getDescription().substring(1) + rainString); | |
if (sp.getString("speedUnit", "m/s").equals("bft")) { | |
todayWind.setText(getString(R.string.wind) +": "+ | |
UnitConvertor.getBeaufortName((int) wind) + | |
(todayWeather.isWindDirectionAvailable() ?""+ getWindDirectionString(sp, this, todayWeather) :"")); | |
} else { | |
todayWind.setText(getString(R.string.wind) +": "+newDecimalFormat("0.0").format(wind) +""+ | |
localize(sp, "speedUnit", "m/s") + | |
(todayWeather.isWindDirectionAvailable() ?""+ getWindDirectionString(sp, this, todayWeather) :"")); | |
} | |
todayPressure.setText(getString(R.string.pressure) +": "+newDecimalFormat("0.0").format(pressure) +""+ | |
localize(sp, "pressureUnit", "hPa")); | |
todayHumidity.setText(getString(R.string.humidity) +": "+ todayWeather.getHumidity() +" %"); | |
todaySunrise.setText(getString(R.string.sunrise) +": "+ timeFormat.format(todayWeather.getSunrise())); | |
todaySunset.setText(getString(R.string.sunset) +": "+ timeFormat.format(todayWeather.getSunset())); | |
todayIcon.setText(todayWeather.getIcon()); | |
} | |
publicParseResultparseLongTermJson(Stringresult) { | |
int i; | |
try { | |
JSONObject reader =newJSONObject(result); | |
finalString code = reader.optString("cod"); | |
if ("404".equals(code)) { | |
if (longTermWeather ==null) { | |
longTermWeather =newArrayList<>(); | |
longTermTodayWeather =newArrayList<>(); | |
longTermTomorrowWeather =newArrayList<>(); | |
} | |
returnParseResult.CITY_NOT_FOUND; | |
} | |
longTermWeather =newArrayList<>(); | |
longTermTodayWeather =newArrayList<>(); | |
longTermTomorrowWeather =newArrayList<>(); | |
JSONArray list = reader.getJSONArray("list"); | |
for (i =0; i < list.length(); i++) { | |
Weather weather =newWeather(); | |
JSONObject listItem = list.getJSONObject(i); | |
JSONObject main = listItem.getJSONObject("main"); | |
weather.setDate(listItem.getString("dt")); | |
weather.setTemperature(main.getString("temp")); | |
weather.setDescription(listItem.optJSONArray("weather").getJSONObject(0).getString("description")); | |
JSONObject windObj = listItem.optJSONObject("wind"); | |
if (windObj !=null) { | |
weather.setWind(windObj.getString("speed")); | |
weather.setWindDirectionDegree(windObj.getDouble("deg")); | |
} | |
weather.setPressure(main.getString("pressure")); | |
weather.setHumidity(main.getString("humidity")); | |
JSONObject rainObj = listItem.optJSONObject("rain"); | |
String rain =""; | |
if (rainObj !=null) { | |
rain = getRainString(rainObj); | |
} else { | |
JSONObject snowObj = listItem.optJSONObject("snow"); | |
if (snowObj !=null) { | |
rain = getRainString(snowObj); | |
} else { | |
rain ="0"; | |
} | |
} | |
weather.setRain(rain); | |
finalString idString = listItem.optJSONArray("weather").getJSONObject(0).getString("id"); | |
weather.setId(idString); | |
finalString dateMsString = listItem.getString("dt") +"000"; | |
Calendar cal =Calendar.getInstance(); | |
cal.setTimeInMillis(Long.parseLong(dateMsString)); | |
weather.setIcon(setWeatherIcon(Integer.parseInt(idString), cal.get(Calendar.HOUR_OF_DAY))); | |
Calendar today =Calendar.getInstance(); | |
if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) { | |
longTermTodayWeather.add(weather); | |
} elseif (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR) +1) { | |
longTermTomorrowWeather.add(weather); | |
} else { | |
longTermWeather.add(weather); | |
} | |
} | |
SharedPreferences.Editor editor =PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit(); | |
editor.putString("lastLongterm", result); | |
editor.commit(); | |
} catch (JSONException e) { | |
Log.e("JSONException Data", result); | |
e.printStackTrace(); | |
returnParseResult.JSON_EXCEPTION; | |
} | |
returnParseResult.OK; | |
} | |
privatevoidupdateLongTermWeatherUI() { | |
if (destroyed) { | |
return; | |
} | |
ViewPagerAdapter viewPagerAdapter =newViewPagerAdapter(getSupportFragmentManager()); | |
Bundle bundleToday =newBundle(); | |
bundleToday.putInt("day", 0); | |
RecyclerViewFragment recyclerViewFragmentToday =newRecyclerViewFragment(); | |
recyclerViewFragmentToday.setArguments(bundleToday); | |
viewPagerAdapter.addFragment(recyclerViewFragmentToday, getString(R.string.today)); | |
Bundle bundleTomorrow =newBundle(); | |
bundleTomorrow.putInt("day", 1); | |
RecyclerViewFragment recyclerViewFragmentTomorrow =newRecyclerViewFragment(); | |
recyclerViewFragmentTomorrow.setArguments(bundleTomorrow); | |
viewPagerAdapter.addFragment(recyclerViewFragmentTomorrow, getString(R.string.tomorrow)); | |
Bundle bundle =newBundle(); | |
bundle.putInt("day", 2); | |
RecyclerViewFragment recyclerViewFragment =newRecyclerViewFragment(); | |
recyclerViewFragment.setArguments(bundle); | |
viewPagerAdapter.addFragment(recyclerViewFragment, getString(R.string.later)); | |
int currentPage = viewPager.getCurrentItem(); | |
viewPagerAdapter.notifyDataSetChanged(); | |
viewPager.setAdapter(viewPagerAdapter); | |
tabLayout.setupWithViewPager(viewPager); | |
if (currentPage ==0&& longTermTodayWeather.isEmpty()) { | |
currentPage =1; | |
} | |
viewPager.setCurrentItem(currentPage, false); | |
} | |
privatebooleanisNetworkAvailable() { | |
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); | |
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); | |
return activeNetworkInfo !=null&& activeNetworkInfo.isConnected(); | |
} | |
privatebooleanshouldUpdate() { | |
long lastUpdate =PreferenceManager.getDefaultSharedPreferences(this).getLong("lastUpdate", -1); | |
boolean cityChanged =PreferenceManager.getDefaultSharedPreferences(this).getBoolean("cityChanged", false); | |
// Update if never checked or last update is longer ago than specified threshold | |
return cityChanged || lastUpdate <0|| (Calendar.getInstance().getTimeInMillis() - lastUpdate) >NO_UPDATE_REQUIRED_THRESHOLD; | |
} | |
@Override | |
publicbooleanonCreateOptionsMenu(Menumenu) { | |
getMenuInflater().inflate(R.menu.menu_main, menu); | |
returntrue; | |
} | |
@Override | |
publicbooleanonOptionsItemSelected(MenuItemitem) { | |
int id = item.getItemId(); | |
if (id ==R.id.action_refresh) { | |
if (isNetworkAvailable()) { | |
getTodayWeather(); | |
getLongTermWeather(); | |
} else { | |
Snackbar.make(appView, getString(R.string.msg_connection_not_available), Snackbar.LENGTH_LONG).show(); | |
} | |
returntrue; | |
} | |
if (id ==R.id.action_map) { | |
Intent intent =newIntent(MainActivity.this, MapActivity.class); | |
startActivity(intent); | |
} | |
if (id ==R.id.NASA_map) { | |
Intent intent =newIntent(MainActivity.this, MapAcivityNWV.class); | |
startActivity(intent); | |
} | |
if (id ==R.id.WIND_map) { | |
Intent intent =newIntent(MainActivity.this, MapActivityWind.class); | |
startActivity(intent); | |
} | |
if (id ==R.id.Dis_map) { | |
Intent intent =newIntent(MainActivity.this, MapActivityDis.class); | |
startActivity(intent); | |
} | |
if (id ==R.id.EQH_map) { | |
Intent intent =newIntent(MainActivity.this, MapActivityQH.class); | |
startActivity(intent); | |
} | |
if (id ==R.id.action_graphs) { | |
Intent intent =newIntent(MainActivity.this, GraphActivity.class); | |
startActivity(intent); | |
} | |
if (id ==R.id.action_search) { | |
searchCities(); | |
returntrue; | |
} | |
if (id ==R.id.action_location) { | |
getCityByLocation(); | |
returntrue; | |
} | |
if (id ==R.id.action_settings) { | |
Intent intent =newIntent(MainActivity.this, SettingsActivity.class); | |
startActivity(intent); | |
} | |
if (id ==R.id.action_about) { | |
aboutDialog(); | |
returntrue; | |
} | |
returnsuper.onOptionsItemSelected(item); | |
} | |
publicstaticvoidinitMappings() { | |
if (mappingsInitialised) | |
return; | |
mappingsInitialised =true; | |
speedUnits.put("m/s", R.string.speed_unit_mps); | |
speedUnits.put("kph", R.string.speed_unit_kph); | |
speedUnits.put("mph", R.string.speed_unit_mph); | |
speedUnits.put("kn", R.string.speed_unit_kn); | |
pressUnits.put("hPa", R.string.pressure_unit_hpa); | |
pressUnits.put("kPa", R.string.pressure_unit_kpa); | |
pressUnits.put("mm Hg", R.string.pressure_unit_mmhg); | |
} | |
privateStringlocalize(SharedPreferencessp, StringpreferenceKey, StringdefaultValueKey) { | |
return localize(sp, this, preferenceKey, defaultValueKey); | |
} | |
publicstaticStringlocalize(SharedPreferencessp, Contextcontext, StringpreferenceKey, StringdefaultValueKey) { | |
String preferenceValue = sp.getString(preferenceKey, defaultValueKey); | |
String result = preferenceValue; | |
if ("speedUnit".equals(preferenceKey)) { | |
if (speedUnits.containsKey(preferenceValue)) { | |
result = context.getString(speedUnits.get(preferenceValue)); | |
} | |
} elseif ("pressureUnit".equals(preferenceKey)) { | |
if (pressUnits.containsKey(preferenceValue)) { | |
result = context.getString(pressUnits.get(preferenceValue)); | |
} | |
} | |
return result; | |
} | |
publicstaticStringgetWindDirectionString(SharedPreferencessp, Contextcontext, Weatherweather) { | |
try { | |
if (Double.parseDouble(weather.getWind()) !=0) { | |
String pref = sp.getString("windDirectionFormat", null); | |
if ("arrow".equals(pref)) { | |
return weather.getWindDirection(8).getArrow(context); | |
} elseif ("abbr".equals(pref)) { | |
return weather.getWindDirection().getLocalizedString(context); | |
} | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
return""; | |
} | |
voidgetCityByLocation() { | |
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); | |
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=PackageManager.PERMISSION_GRANTED) { | |
if (ActivityCompat.shouldShowRequestPermissionRationale(this, | |
Manifest.permission.ACCESS_FINE_LOCATION)) { | |
// Explanation not needed, since user requests this themmself | |
} else { | |
ActivityCompat.requestPermissions(this, | |
newString[]{Manifest.permission.ACCESS_FINE_LOCATION}, | |
MY_PERMISSIONS_ACCESS_FINE_LOCATION); | |
} | |
} elseif (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) || | |
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { | |
progressDialog =newProgressDialog(this); | |
progressDialog.setMessage(getString(R.string.getting_location)); | |
progressDialog.setCancelable(false); | |
progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.dialog_cancel), newDialogInterface.OnClickListener() { | |
@Override | |
publicvoidonClick(DialogInterfacedialogInterface, inti) { | |
try { | |
locationManager.removeUpdates(MainActivity.this); | |
} catch (SecurityException e) { | |
e.printStackTrace(); | |
} | |
} | |
}); | |
progressDialog.show(); | |
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { | |
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); | |
} | |
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { | |
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); | |
} | |
} else { | |
showLocationSettingsDialog(); | |
} | |
} | |
privatevoidshowLocationSettingsDialog() { | |
AlertDialog.Builder alertDialog =newAlertDialog.Builder(this); | |
alertDialog.setTitle(R.string.location_settings); | |
alertDialog.setMessage(R.string.location_settings_message); | |
alertDialog.setPositiveButton(R.string.location_settings_button, newDialogInterface.OnClickListener() { | |
publicvoidonClick(DialogInterfacedialog, intwhich) { | |
Intent intent =newIntent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); | |
startActivity(intent); | |
} | |
}); | |
alertDialog.setNegativeButton(R.string.dialog_cancel, newDialogInterface.OnClickListener() { | |
publicvoidonClick(DialogInterfacedialog, intwhich) { | |
dialog.cancel(); | |
} | |
}); | |
alertDialog.show(); | |
} | |
@Override | |
publicvoidonRequestPermissionsResult(intrequestCode, Stringpermissions[], int[] grantResults) { | |
switch (requestCode) { | |
caseMY_PERMISSIONS_ACCESS_FINE_LOCATION: { | |
// If request is cancelled, the result arrays are empty. | |
if (grantResults.length >0&& grantResults[0] ==PackageManager.PERMISSION_GRANTED) { | |
getCityByLocation(); | |
} | |
return; | |
} | |
} | |
} | |
@Override | |
publicvoidonLocationChanged(Locationlocation) { | |
progressDialog.hide(); | |
try { | |
locationManager.removeUpdates(this); | |
} catch (SecurityException e) { | |
Log.e("LocationManager", "Error while trying to stop listening for location updates. This is probably a permissions issue", e); | |
} | |
Log.i("LOCATION ("+ location.getProvider().toUpperCase() +")", location.getLatitude() +", "+ location.getLongitude()); | |
double latitude = location.getLatitude(); | |
double longitude = location.getLongitude(); | |
newProvideCityNameTask(this, this, progressDialog).execute("coords", Double.toString(latitude), Double.toString(longitude)); | |
} | |
@Override | |
publicvoidonStatusChanged(Stringprovider, intstatus, Bundleextras) { | |
} | |
@Override | |
publicvoidonProviderEnabled(Stringprovider) { | |
} | |
@Override | |
publicvoidonProviderDisabled(Stringprovider) { | |
} | |
classTodayWeatherTaskextendsGenericRequestTask { | |
publicTodayWeatherTask(Contextcontext, MainActivityactivity, ProgressDialogprogressDialog) { | |
super(context, activity, progressDialog); | |
} | |
@Override | |
protectedvoidonPreExecute() { | |
loading =0; | |
super.onPreExecute(); | |
} | |
@Override | |
protectedvoidonPostExecute(TaskOutputoutput) { | |
super.onPostExecute(output); | |
// Update widgets | |
AbstractWidgetProvider.updateWidgets(MainActivity.this); | |
DashClockWeatherExtension.updateDashClock(MainActivity.this); | |
} | |
@Override | |
protectedParseResultparseResponse(Stringresponse) { | |
return parseTodayJson(response); | |
} | |
@Override | |
protectedStringgetAPIName() { | |
return"weather"; | |
} | |
@Override | |
protectedvoidupdateMainUI() { | |
updateTodayWeatherUI(); | |
updateLastUpdateTime(); | |
} | |
} | |
classLongTermWeatherTaskextendsGenericRequestTask { | |
publicLongTermWeatherTask(Contextcontext, MainActivityactivity, ProgressDialogprogressDialog) { | |
super(context, activity, progressDialog); | |
} | |
@Override | |
protectedParseResultparseResponse(Stringresponse) { | |
return parseLongTermJson(response); | |
} | |
@Override | |
protectedStringgetAPIName() { | |
return"forecast"; | |
} | |
@Override | |
protectedvoidupdateMainUI() { | |
updateLongTermWeatherUI(); | |
} | |
} | |
classProvideCityNameTaskextendsGenericRequestTask { | |
publicProvideCityNameTask(Contextcontext, MainActivityactivity, ProgressDialogprogressDialog) { | |
super(context, activity, progressDialog); | |
} | |
@Override | |
protectedvoidonPreExecute() { /*Nothing*/ } | |
@Override | |
protectedStringgetAPIName() { | |
return"weather"; | |
} | |
@Override | |
protectedParseResultparseResponse(Stringresponse) { | |
Log.i("RESULT", response.toString()); | |
try { | |
JSONObject reader =newJSONObject(response); | |
finalString code = reader.optString("cod"); | |
if ("404".equals(code)) { | |
Log.e("Geolocation", "No city found"); | |
returnParseResult.CITY_NOT_FOUND; | |
} | |
String city = reader.getString("name"); | |
String country =""; | |
JSONObject countryObj = reader.optJSONObject("sys"); | |
if (countryObj !=null) { | |
country =", "+ countryObj.getString("country"); | |
} | |
saveLocation(city + country); | |
} catch (JSONException e) { | |
Log.e("JSONException Data", response); | |
e.printStackTrace(); | |
returnParseResult.JSON_EXCEPTION; | |
} | |
returnParseResult.OK; | |
} | |
@Override | |
protectedvoidonPostExecute(TaskOutputoutput) { | |
/* Handle possible errors only */ | |
handleTaskOutput(output); | |
} | |
} | |
publicstaticlongsaveLastUpdateTime(SharedPreferencessp) { | |
Calendar now =Calendar.getInstance(); | |
sp.edit().putLong("lastUpdate", now.getTimeInMillis()).apply(); | |
return now.getTimeInMillis(); | |
} | |
privatevoidupdateLastUpdateTime() { | |
updateLastUpdateTime( | |
PreferenceManager.getDefaultSharedPreferences(this).getLong("lastUpdate", -1) | |
); | |
} | |
privatevoidupdateLastUpdateTime(longtimeInMillis) { | |
if (timeInMillis <0) { | |
// No time | |
lastUpdate.setText(""); | |
} else { | |
lastUpdate.setText(getString(R.string.last_update, formatTimeWithDayIfNotToday(this, timeInMillis))); | |
} | |
} | |
publicstaticStringformatTimeWithDayIfNotToday(Contextcontext, longtimeInMillis) { | |
Calendar now =Calendar.getInstance(); | |
Calendar lastCheckedCal =newGregorianCalendar(); | |
lastCheckedCal.setTimeInMillis(timeInMillis); | |
Date lastCheckedDate =newDate(timeInMillis); | |
String timeFormat =android.text.format.DateFormat.getTimeFormat(context).format(lastCheckedDate); | |
if (now.get(Calendar.YEAR) == lastCheckedCal.get(Calendar.YEAR) && | |
now.get(Calendar.DAY_OF_YEAR) == lastCheckedCal.get(Calendar.DAY_OF_YEAR)) { | |
// Same day, only show time | |
return timeFormat; | |
} else { | |
returnandroid.text.format.DateFormat.getDateFormat(context).format(lastCheckedDate) +""+ timeFormat; | |
} | |
} | |
privateintgetTheme(StringthemePref) { | |
switch (themePref) { | |
case"dark": | |
returnR.style.AppTheme_NoActionBar_Dark; | |
case"black": | |
returnR.style.AppTheme_NoActionBar_Black; | |
case"classic": | |
returnR.style.AppTheme_NoActionBar_Classic; | |
case"classicdark": | |
returnR.style.AppTheme_NoActionBar_Classic_Dark; | |
case"classicblack": | |
returnR.style.AppTheme_NoActionBar_Classic_Black; | |
default: | |
returnR.style.AppTheme_NoActionBar; | |
} | |
} | |
} |
packagenasa.spaceapps.dsos.activities; | |
importandroid.content.SharedPreferences; | |
importandroid.os.Bundle; | |
importandroid.preference.PreferenceManager; | |
importandroid.support.annotation.IdRes; | |
importandroid.support.v7.app.AppCompatActivity; | |
importandroid.webkit.WebView; | |
importcom.roughike.bottombar.BottomBar; | |
importcom.roughike.bottombar.OnMenuTabClickListener; | |
importnasa.spaceapps.dsos.R; | |
publicclassMapAcivityNWVextendsAppCompatActivity { | |
privateBottomBar mBottomBar; | |
@Override | |
protectedvoidonCreate(BundlesavedInstanceState) { | |
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this); | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_map); | |
SharedPreferences sp =PreferenceManager.getDefaultSharedPreferences(this); | |
String apiKey = sp.getString("apiKey", getResources().getString(R.string.apiKey)); | |
finalWebView webView = (WebView) findViewById(R.id.webView); | |
webView.getSettings().setJavaScriptEnabled(true); | |
// webView.loadUrl("file:///android_asset/map.html?lat=" + prefs.getFloat("latitude", 0) + "&lon=" + prefs.getFloat("longitude", 0) + "&appid=" + apiKey); | |
webView.loadUrl("https://worldview.earthdata.nasa.gov/"); | |
mBottomBar =BottomBar.attach(this, savedInstanceState); | |
mBottomBar.setItems(R.menu.menu_map_bottom); | |
mBottomBar.setOnMenuTabClickListener(newOnMenuTabClickListener() { | |
@Override | |
publicvoidonMenuTabSelected(@IdResintmenuItemId) { | |
if (menuItemId ==R.id.map_rain) { | |
webView.loadUrl("javascript:map.removeLayer(windLayer);map.removeLayer(tempLayer);map.addLayer(rainLayer);"); | |
} elseif (menuItemId ==R.id.map_wind) { | |
webView.loadUrl("javascript:map.removeLayer(rainLayer);map.removeLayer(tempLayer);map.addLayer(windLayer);"); | |
} elseif (menuItemId ==R.id.map_temperature) { | |
webView.loadUrl("javascript:map.removeLayer(windLayer);map.removeLayer(rainLayer);map.addLayer(tempLayer);"); | |
} | |
} | |
@Override | |
publicvoidonMenuTabReSelected(@IdResintmenuItemId) { | |
} | |
}); | |
} | |
@Override | |
protectedvoidonSaveInstanceState(BundleoutState) { | |
super.onSaveInstanceState(outState); | |
mBottomBar.onSaveInstanceState(outState); | |
} | |
} |
packagenasa.spaceapps.dsos.activities; | |
importandroid.content.SharedPreferences; | |
importandroid.os.Bundle; | |
importandroid.preference.PreferenceManager; | |
importandroid.support.annotation.IdRes; | |
importandroid.support.v7.app.AppCompatActivity; | |
importandroid.webkit.WebView; | |
importcom.roughike.bottombar.BottomBar; | |
importcom.roughike.bottombar.OnMenuTabClickListener; | |
importnasa.spaceapps.dsos.R; | |
publicclassMapActivityextendsAppCompatActivity { | |
privateBottomBar mBottomBar; | |
@Override | |
protectedvoidonCreate(BundlesavedInstanceState) { | |
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this); | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_map); | |
SharedPreferences sp =PreferenceManager.getDefaultSharedPreferences(this); | |
String apiKey = sp.getString("apiKey", getResources().getString(R.string.apiKey)); | |
finalWebView webView = (WebView) findViewById(R.id.webView); | |
webView.getSettings().setJavaScriptEnabled(true); | |
webView.loadUrl("file:///android_asset/map.html?lat="+ prefs.getFloat("latitude", 0) +"&lon="+ prefs.getFloat("longitude", 0) +"&appid="+ apiKey); | |
mBottomBar =BottomBar.attach(this, savedInstanceState); | |
mBottomBar.setItems(R.menu.menu_map_bottom); | |
mBottomBar.setOnMenuTabClickListener(newOnMenuTabClickListener() { | |
@Override | |
publicvoidonMenuTabSelected(@IdResintmenuItemId) { | |
if (menuItemId ==R.id.map_rain) { | |
webView.loadUrl("javascript:map.removeLayer(windLayer);map.removeLayer(tempLayer);map.addLayer(rainLayer);"); | |
} elseif (menuItemId ==R.id.map_wind) { | |
webView.loadUrl("javascript:map.removeLayer(rainLayer);map.removeLayer(tempLayer);map.addLayer(windLayer);"); | |
} elseif (menuItemId ==R.id.map_temperature) { | |
webView.loadUrl("javascript:map.removeLayer(windLayer);map.removeLayer(rainLayer);map.addLayer(tempLayer);"); | |
} | |
} | |
@Override | |
publicvoidonMenuTabReSelected(@IdResintmenuItemId) { | |
} | |
}); | |
} | |
@Override | |
protectedvoidonSaveInstanceState(BundleoutState) { | |
super.onSaveInstanceState(outState); | |
mBottomBar.onSaveInstanceState(outState); | |
} | |
} |
packagenasa.spaceapps.dsos.activities; | |
importandroid.content.SharedPreferences; | |
importandroid.os.Bundle; | |
importandroid.preference.PreferenceManager; | |
importandroid.support.annotation.IdRes; | |
importandroid.support.v7.app.AppCompatActivity; | |
importandroid.webkit.WebView; | |
importcom.roughike.bottombar.BottomBar; | |
importcom.roughike.bottombar.OnMenuTabClickListener; | |
importnasa.spaceapps.dsos.R; | |
publicclassMapActivityDisextendsAppCompatActivity { | |
privateBottomBar mBottomBar; | |
@Override | |
protectedvoidonCreate(BundlesavedInstanceState) { | |
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this); | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_map); | |
SharedPreferences sp =PreferenceManager.getDefaultSharedPreferences(this); | |
String apiKey = sp.getString("apiKey", getResources().getString(R.string.apiKey)); | |
finalWebView webView = (WebView) findViewById(R.id.webView); | |
webView.getSettings().setJavaScriptEnabled(true); | |
webView.loadUrl("https://maps.disasters.nasa.gov/arcgis/apps/webappviewer/index.html?id=64c5bc2e969e4dfab9a0391fe49cce51"); | |
mBottomBar =BottomBar.attach(this, savedInstanceState); | |
mBottomBar.setItems(R.menu.menu_map_bottom); | |
mBottomBar.setOnMenuTabClickListener(newOnMenuTabClickListener() { | |
@Override | |
publicvoidonMenuTabSelected(@IdResintmenuItemId) { | |
if (menuItemId ==R.id.map_rain) { | |
webView.loadUrl("javascript:map.removeLayer(windLayer);map.removeLayer(tempLayer);map.addLayer(rainLayer);"); | |
} elseif (menuItemId ==R.id.map_wind) { | |
webView.loadUrl("javascript:map.removeLayer(rainLayer);map.removeLayer(tempLayer);map.addLayer(windLayer);"); | |
} elseif (menuItemId ==R.id.map_temperature) { | |
webView.loadUrl("javascript:map.removeLayer(windLayer);map.removeLayer(rainLayer);map.addLayer(tempLayer);"); | |
} | |
} | |
@Override | |
publicvoidonMenuTabReSelected(@IdResintmenuItemId) { | |
} | |
}); | |
} | |
@Override | |
protectedvoidonSaveInstanceState(BundleoutState) { | |
super.onSaveInstanceState(outState); | |
mBottomBar.onSaveInstanceState(outState); | |
} | |
} |
packagenasa.spaceapps.dsos.activities; | |
importandroid.content.SharedPreferences; | |
importandroid.os.Bundle; | |
importandroid.preference.PreferenceManager; | |
importandroid.support.annotation.IdRes; | |
importandroid.support.v7.app.AppCompatActivity; | |
importandroid.webkit.WebView; | |
importcom.roughike.bottombar.BottomBar; | |
importcom.roughike.bottombar.OnMenuTabClickListener; | |
importnasa.spaceapps.dsos.R; | |
publicclassMapActivityQHextendsAppCompatActivity { | |
privateBottomBar mBottomBar; | |
@Override | |
protectedvoidonCreate(BundlesavedInstanceState) { | |
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this); | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_map); | |
SharedPreferences sp =PreferenceManager.getDefaultSharedPreferences(this); | |
String apiKey = sp.getString("apiKey", getResources().getString(R.string.apiKey)); | |
finalWebView webView = (WebView) findViewById(R.id.webView); | |
webView.getSettings().setJavaScriptEnabled(true); | |
// webView.loadUrl("file:///android_asset/map.html?lat=" + prefs.getFloat("latitude", 0) + "&lon=" + prefs.getFloat("longitude", 0) + "&appid=" + apiKey); | |
webView.loadUrl("https://worldwind.arc.nasa.gov/quakehunter/"); | |
mBottomBar =BottomBar.attach(this, savedInstanceState); | |
mBottomBar.setItems(R.menu.menu_map_bottom); | |
mBottomBar.setOnMenuTabClickListener(newOnMenuTabClickListener() { | |
@Override | |
publicvoidonMenuTabSelected(@IdResintmenuItemId) { | |
if (menuItemId ==R.id.map_rain) { | |
webView.loadUrl("javascript:map.removeLayer(windLayer);map.removeLayer(tempLayer);map.addLayer(rainLayer);"); | |
} elseif (menuItemId ==R.id.map_wind) { | |
webView.loadUrl("javascript:map.removeLayer(rainLayer);map.removeLayer(tempLayer);map.addLayer(windLayer);"); | |
} elseif (menuItemId ==R.id.map_temperature) { | |
webView.loadUrl("javascript:map.removeLayer(windLayer);map.removeLayer(rainLayer);map.addLayer(tempLayer);"); | |
} | |
} | |
@Override | |
publicvoidonMenuTabReSelected(@IdResintmenuItemId) { | |
} | |
}); | |
} | |
@Override | |
protectedvoidonSaveInstanceState(BundleoutState) { | |
super.onSaveInstanceState(outState); | |
mBottomBar.onSaveInstanceState(outState); | |
} | |
} |
packagenasa.spaceapps.dsos.activities; | |
importandroid.content.SharedPreferences; | |
importandroid.os.Bundle; | |
importandroid.preference.PreferenceManager; | |
importandroid.support.annotation.IdRes; | |
importandroid.support.v7.app.AppCompatActivity; | |
importandroid.webkit.WebView; | |
importcom.roughike.bottombar.BottomBar; | |
importcom.roughike.bottombar.OnMenuTabClickListener; | |
importnasa.spaceapps.dsos.R; | |
publicclassMapActivityWindextendsAppCompatActivity { | |
privateBottomBar mBottomBar; | |
@Override | |
protectedvoidonCreate(BundlesavedInstanceState) { | |
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this); | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_map); | |
SharedPreferences sp =PreferenceManager.getDefaultSharedPreferences(this); | |
String apiKey = sp.getString("apiKey", getResources().getString(R.string.apiKey)); | |
finalWebView webView = (WebView) findViewById(R.id.webView); | |
webView.getSettings().setJavaScriptEnabled(true); | |
// webView.loadUrl("file:///android_asset/map.html?lat=" + prefs.getFloat("latitude", 0) + "&lon=" + prefs.getFloat("longitude", 0) + "&appid=" + apiKey); | |
webView.loadUrl(" https://earth.nullschool.net/#current/wind/surface/level/orthographic=-270.56,52.36,296"); | |
mBottomBar =BottomBar.attach(this, savedInstanceState); | |
mBottomBar.setItems(R.menu.menu_map_bottom); | |
mBottomBar.setOnMenuTabClickListener(newOnMenuTabClickListener() { | |
@Override | |
publicvoidonMenuTabSelected(@IdResintmenuItemId) { | |
if (menuItemId ==R.id.map_rain) { | |
webView.loadUrl("javascript:map.removeLayer(windLayer);map.removeLayer(tempLayer);map.addLayer(rainLayer);"); | |
} elseif (menuItemId ==R.id.map_wind) { | |
webView.loadUrl("javascript:map.removeLayer(rainLayer);map.removeLayer(tempLayer);map.addLayer(windLayer);"); | |
} elseif (menuItemId ==R.id.map_temperature) { | |
webView.loadUrl("javascript:map.removeLayer(windLayer);map.removeLayer(rainLayer);map.addLayer(tempLayer);"); | |
} | |
} | |
@Override | |
publicvoidonMenuTabReSelected(@IdResintmenuItemId) { | |
} | |
}); | |
} | |
@Override | |
protectedvoidonSaveInstanceState(BundleoutState) { | |
super.onSaveInstanceState(outState); | |
mBottomBar.onSaveInstanceState(outState); | |
} | |
} |
packagenasa.spaceapps.dsos.activities; | |
importandroid.Manifest; | |
importandroid.content.Context; | |
importandroid.content.SharedPreferences; | |
importandroid.content.pm.PackageManager; | |
importandroid.content.res.Resources; | |
importandroid.location.Location; | |
importandroid.location.LocationListener; | |
importandroid.location.LocationManager; | |
importandroid.os.Bundle; | |
importandroid.preference.CheckBoxPreference; | |
importandroid.preference.EditTextPreference; | |
importandroid.preference.ListPreference; | |
importandroid.preference.Preference; | |
importandroid.preference.PreferenceActivity; | |
importandroid.preference.PreferenceManager; | |
importandroid.support.v4.app.ActivityCompat; | |
importandroid.support.v4.content.ContextCompat; | |
importandroid.support.v7.widget.Toolbar; | |
importandroid.view.LayoutInflater; | |
importandroid.view.View; | |
importandroid.widget.LinearLayout; | |
importjava.text.SimpleDateFormat; | |
importjava.util.Date; | |
importnasa.spaceapps.dsos.AlarmReceiver; | |
importnasa.spaceapps.dsos.R; | |
publicclassSettingsActivityextendsPreferenceActivity | |
implementsSharedPreferences.OnSharedPreferenceChangeListener { | |
// Thursday 2016-01-14 16:00:00 | |
DateSAMPLE_DATE=newDate(1452805200000l); | |
@Override | |
publicvoidonCreate(BundlesavedInstanceState) { | |
setTheme(getTheme(PreferenceManager.getDefaultSharedPreferences(this).getString("theme", "fresh"))); | |
super.onCreate(savedInstanceState); | |
LinearLayout root = (LinearLayout) findViewById(android.R.id.list).getParent().getParent().getParent(); | |
View bar =LayoutInflater.from(this).inflate(R.layout.settings_toolbar, root, false); | |
root.addView(bar, 0); | |
Toolbar toolbar = (Toolbar) findViewById(R.id.settings_toolbar); | |
toolbar.setNavigationOnClickListener(newView.OnClickListener() { | |
@Override | |
publicvoidonClick(Viewv) { | |
finish(); | |
} | |
}); | |
addPreferencesFromResource(R.xml.prefs); | |
} | |
@Override | |
publicvoidonResume(){ | |
super.onResume(); | |
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); | |
setCustomDateEnabled(); | |
updateDateFormatList(); | |
// Set summaries to current value | |
setListPreferenceSummary("unit"); | |
setListPreferenceSummary("lengthUnit"); | |
setListPreferenceSummary("speedUnit"); | |
setListPreferenceSummary("pressureUnit"); | |
setListPreferenceSummary("refreshInterval"); | |
setListPreferenceSummary("windDirectionFormat"); | |
setListPreferenceSummary("theme"); | |
} | |
@Override | |
publicvoidonPause(){ | |
super.onPause(); | |
getPreferenceScreen().getSharedPreferences() | |
.unregisterOnSharedPreferenceChangeListener(this); | |
} | |
@Override | |
publicvoidonSharedPreferenceChanged(SharedPreferencessharedPreferences, Stringkey) { | |
switch (key) { | |
case"unit": | |
case"lengthUnit": | |
case"speedUnit": | |
case"pressureUnit": | |
case"windDirectionFormat": | |
setListPreferenceSummary(key); | |
break; | |
case"refreshInterval": | |
setListPreferenceSummary(key); | |
AlarmReceiver.setRecurringAlarm(this); | |
break; | |
case"dateFormat": | |
setCustomDateEnabled(); | |
setListPreferenceSummary(key); | |
break; | |
case"dateFormatCustom": | |
updateDateFormatList(); | |
break; | |
case"theme": | |
// Restart activity to apply theme | |
overridePendingTransition(0, 0); | |
finish(); | |
overridePendingTransition(0, 0); | |
startActivity(getIntent()); | |
break; | |
case"updateLocationAutomatically": | |
if (sharedPreferences.getBoolean(key, false) ==true) { | |
requestReadLocationPermission(); | |
} | |
break; | |
case"apiKey": | |
checkKey(key); | |
} | |
} | |
privatevoidrequestReadLocationPermission() { | |
System.out.println("Calling request location permission"); | |
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=PackageManager.PERMISSION_GRANTED) { | |
if (ActivityCompat.shouldShowRequestPermissionRationale(this, | |
Manifest.permission.ACCESS_FINE_LOCATION)) { | |
// Explanation not needed, since user requests this themself | |
} else { | |
ActivityCompat.requestPermissions(this, | |
newString[]{Manifest.permission.ACCESS_FINE_LOCATION}, | |
MainActivity.MY_PERMISSIONS_ACCESS_FINE_LOCATION); | |
} | |
} else { | |
privacyGuardWorkaround(); | |
} | |
} | |
@Override | |
publicvoidonRequestPermissionsResult(intrequestCode, String[] permissions, int[] grantResults) { | |
if (requestCode ==MainActivity.MY_PERMISSIONS_ACCESS_FINE_LOCATION) { | |
boolean permissionGranted = grantResults.length >0&& grantResults[0] ==PackageManager.PERMISSION_GRANTED; | |
CheckBoxPreference checkBox = (CheckBoxPreference) findPreference("updateLocationAutomatically"); | |
checkBox.setChecked(permissionGranted); | |
if (permissionGranted) { | |
privacyGuardWorkaround(); | |
} | |
} | |
} | |
privatevoidprivacyGuardWorkaround() { | |
// Workaround for CM privacy guard. Register for location updates in order for it to ask us for permission | |
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); | |
try { | |
DummyLocationListener dummyLocationListener =newDummyLocationListener(); | |
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, dummyLocationListener); | |
locationManager.removeUpdates(dummyLocationListener); | |
} catch (SecurityException e) { | |
// This will most probably not happen, as we just got granted the permission | |
} | |
} | |
privatevoidsetListPreferenceSummary(StringpreferenceKey) { | |
ListPreference preference = (ListPreference) findPreference(preferenceKey); | |
preference.setSummary(preference.getEntry()); | |
} | |
privatevoidsetCustomDateEnabled() { | |
SharedPreferences sp = getPreferenceScreen().getSharedPreferences(); | |
Preference customDatePref = findPreference("dateFormatCustom"); | |
customDatePref.setEnabled("custom".equals(sp.getString("dateFormat", ""))); | |
} | |
privatevoidupdateDateFormatList() { | |
SharedPreferences sp =PreferenceManager.getDefaultSharedPreferences(this); | |
Resources res = getResources(); | |
ListPreference dateFormatPref = (ListPreference) findPreference("dateFormat"); | |
String[] dateFormatsValues = res.getStringArray(R.array.dateFormatsValues); | |
String[] dateFormatsEntries =newString[dateFormatsValues.length]; | |
EditTextPreference customDateFormatPref = (EditTextPreference) findPreference("dateFormatCustom"); | |
customDateFormatPref.setDefaultValue(dateFormatsValues[0]); | |
SimpleDateFormat sdformat =newSimpleDateFormat(); | |
for (int i=0; i<dateFormatsValues.length; i++) { | |
String value = dateFormatsValues[i]; | |
if ("custom".equals(value)) { | |
String renderedCustom; | |
try { | |
sdformat.applyPattern(sp.getString("dateFormatCustom", dateFormatsValues[0])); | |
renderedCustom = sdformat.format(SAMPLE_DATE); | |
} catch (IllegalArgumentException e) { | |
renderedCustom = res.getString(R.string.error_dateFormat); | |
} | |
dateFormatsEntries[i] =String.format("%s:\n%s", | |
res.getString(R.string.setting_dateFormatCustom), | |
renderedCustom); | |
} else { | |
sdformat.applyPattern(value); | |
dateFormatsEntries[i] = sdformat.format(SAMPLE_DATE); | |
} | |
} | |
dateFormatPref.setDefaultValue(dateFormatsValues[0]); | |
dateFormatPref.setEntries(dateFormatsEntries); | |
setListPreferenceSummary("dateFormat"); | |
} | |
privatevoidcheckKey(Stringkey){ | |
SharedPreferences sp =PreferenceManager.getDefaultSharedPreferences(this); | |
if (sp.getString(key, "").equals("")){ | |
sp.edit().remove(key).apply(); | |
} | |
} | |
privateintgetTheme(StringthemePref) { | |
switch (themePref) { | |
case"dark": | |
returnR.style.AppTheme_Dark; | |
case"black": | |
returnR.style.AppTheme_Black; | |
case"classic": | |
returnR.style.AppTheme_Classic; | |
case"classicdark": | |
returnR.style.AppTheme_Classic_Dark; | |
case"classicblack": | |
returnR.style.AppTheme_Classic_Black; | |
default: | |
returnR.style.AppTheme; | |
} | |
} | |
publicclassDummyLocationListenerimplementsLocationListener { | |
@Override | |
publicvoidonLocationChanged(Locationlocation) { | |
} | |
@Override | |
publicvoidonStatusChanged(Stringprovider, intstatus, Bundleextras) { | |
} | |
@Override | |
publicvoidonProviderEnabled(Stringprovider) { | |
} | |
@Override | |
publicvoidonProviderDisabled(Stringprovider) { | |
} | |
} | |
} |
packagenasa.spaceapps.dsos.activities; | |
importandroid.content.Intent; | |
importandroid.os.Bundle; | |
importandroid.support.v7.app.AppCompatActivity; | |
publicclassSplashActivityextendsAppCompatActivity { | |
@Override | |
protectedvoidonCreate(BundlesavedInstanceState) { | |
super.onCreate(savedInstanceState); | |
Intent intent =newIntent(this, MainActivity.class); | |
startActivity(intent); | |
finish(); | |
} | |
} |
packagenasa.spaceapps.dsos.activities; | |
importandroid.content.SharedPreferences; | |
importandroid.os.Bundle; | |
importandroid.preference.PreferenceManager; | |
importandroid.support.annotation.IdRes; | |
importandroid.support.v7.app.AppCompatActivity; | |
importandroid.webkit.WebView; | |
importcom.roughike.bottombar.BottomBar; | |
importcom.roughike.bottombar.OnMenuTabClickListener; | |
importnasa.spaceapps.dsos.R; | |
publicclassMapActivityextendsAppCompatActivity { | |
privateBottomBar mBottomBar; | |
@Override | |
protectedvoidonCreate(BundlesavedInstanceState) { | |
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this); | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_map); | |
SharedPreferences sp =PreferenceManager.getDefaultSharedPreferences(this); | |
String apiKey = sp.getString("apiKey", getResources().getString(R.string.apiKey)); | |
finalWebView webView = (WebView) findViewById(R.id.webView); | |
webView.getSettings().setJavaScriptEnabled(true); | |
webView.loadUrl("file:///android_asset/map.html?lat="+ prefs.getFloat("latitude", 0) +"&lon="+ prefs.getFloat("longitude", 0) +"&appid="+ apiKey); | |
mBottomBar =BottomBar.attach(this, savedInstanceState); | |
mBottomBar.setItems(R.menu.menu_map_bottom); | |
mBottomBar.setOnMenuTabClickListener(newOnMenuTabClickListener() { | |
@Override | |
publicvoidonMenuTabSelected(@IdResintmenuItemId) { | |
if (menuItemId ==R.id.map_rain) { | |
webView.loadUrl("javascript:map.removeLayer(windLayer);map.removeLayer(tempLayer);map.addLayer(rainLayer);"); | |
} elseif (menuItemId ==R.id.map_wind) { | |
webView.loadUrl("javascript:map.removeLayer(rainLayer);map.removeLayer(tempLayer);map.addLayer(windLayer);"); | |
} elseif (menuItemId ==R.id.map_temperature) { | |
webView.loadUrl("javascript:map.removeLayer(windLayer);map.removeLayer(rainLayer);map.addLayer(tempLayer);"); | |
} | |
} | |
@Override | |
publicvoidonMenuTabReSelected(@IdResintmenuItemId) { | |
} | |
}); | |
} | |
@Override | |
protectedvoidonSaveInstanceState(BundleoutState) { | |
super.onSaveInstanceState(outState); | |
mBottomBar.onSaveInstanceState(outState); | |
} | |
} |
packagenasa.spaceapps.dsos.activities; | |
importandroid.content.SharedPreferences; | |
importandroid.os.Bundle; | |
importandroid.preference.PreferenceManager; | |
importandroid.support.annotation.IdRes; | |
importandroid.support.v7.app.AppCompatActivity; | |
importandroid.webkit.WebView; | |
importcom.roughike.bottombar.BottomBar; | |
importcom.roughike.bottombar.OnMenuTabClickListener; | |
importnasa.spaceapps.dsos.R; | |
publicclassMapActivityextendsAppCompatActivity { | |
privateBottomBar mBottomBar; | |
@Override | |
protectedvoidonCreate(BundlesavedInstanceState) { | |
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this); | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_map); | |
SharedPreferences sp =PreferenceManager.getDefaultSharedPreferences(this); | |
String apiKey = sp.getString("apiKey", getResources().getString(R.string.apiKey)); | |
finalWebView webView = (WebView) findViewById(R.id.webView); | |
webView.getSettings().setJavaScriptEnabled(true); | |
webView.loadUrl("file:///android_asset/map.html?lat="+ prefs.getFloat("latitude", 0) +"&lon="+ prefs.getFloat("longitude", 0) +"&appid="+ apiKey); | |
mBottomBar =BottomBar.attach(this, savedInstanceState); | |
mBottomBar.setItems(R.menu.menu_map_bottom); | |
mBottomBar.setOnMenuTabClickListener(newOnMenuTabClickListener() { | |
@Override | |
publicvoidonMenuTabSelected(@IdResintmenuItemId) { | |
if (menuItemId ==R.id.map_rain) { | |
webView.loadUrl("javascript:map.removeLayer(windLayer);map.removeLayer(tempLayer);map.addLayer(rainLayer);"); | |
} elseif (menuItemId ==R.id.map_wind) { | |
webView.loadUrl("javascript:map.removeLayer(rainLayer);map.removeLayer(tempLayer);map.addLayer(windLayer);"); | |
} elseif (menuItemId ==R.id.map_temperature) { | |
webView.loadUrl("javascript:map.removeLayer(windLayer);map.removeLayer(rainLayer);map.addLayer(tempLayer);"); | |
} | |
} | |
@Override | |
publicvoidonMenuTabReSelected(@IdResintmenuItemId) { | |
} | |
}); | |
} | |
@Override | |
protectedvoidonSaveInstanceState(BundleoutState) { | |
super.onSaveInstanceState(outState); | |
mBottomBar.onSaveInstanceState(outState); | |
} | |
} |
NASA has long been a pioneer in the discovery of this universe and has always had to answer all the questions.
In our challenge, we want to take advantage of NASA's enormous potential and the data that has been provided by them to take responsibility for saving people from potential disasters
Every year, thousands of people die as a result of the weak infrastructure of some countries in early warning issues
So we created the idea of an artificial intelligence system to process and analyze NASA data to learn about disasters before they occur and to send an alert to people in those disaster areas.
لطالما كانت ناسا السباقة في اكتشاف هذا الكون ولطالما تحملو على عاتقهم الإجابة عن كل التساؤولات .
بدورنا بها التحدي نريد ان نستغل الإمكانات الهائلة لناسا والبيانات التي تم توفيرها من قبلهم لتحمل مسؤولية انقاذ البشر من الكوارث المحتملة
كل عام يموت الاف البشر نتيجة لضعف البنية الحتية لبعض الدول في مواضيع الانذار المبكر
لذلك قمنا بخلق فكرة عمل نظام ذكاء اصطناعي لمعالجة بيانات ناسا وتحليلها لمعرفة الكوارث قبل حدوثها وارسال تنبية للاشخاص الواقعين في مناطق تلك الكوارث .
SpaceApps is a NASA incubator innovation program.