News Weather Traffic - ArshadHishamAPM/Aido_NewsWeatherTraffic GitHub Wiki
In this app the user will be able to find out the upcoming forecast of the weather as well as keep up to date with the latest news on what is all happening around the world.With the help of news weather traffic app the user will be able to find if there is traffic on the road. So the user has all the information he needs right in his hands.All the information is gathered from the internet so all the information will be updated in real time that means the information is gathered as they happen live from the internet. There are 3 segments for the app and they are :
-
- Weather Forecast
-
- News
-
- Traffic
Code
`public class MainActivity extends AppCompatActivity {`
`@Override`
`protected void onCreate(Bundle savedInstanceState) {`
`super.onCreate(savedInstanceState);`
`setContentView(R.layout.activity_main);`
`Intent intent=new Intent(getApplicationContext(),NewsActivity.class);`
`startActivity(intent);`
`}`
`}`
The weather forecast segment will help the user to find the upcoming weather of their current place. It will help the user to find the current weather and the weather of the upcoming days as well.
Code
`public class WeatherForcast extends AppCompatActivity {`
`RecyclerView mRecyclerView;
`RecyclerView.LayoutManager mLayoutManager;`
`RecyclerView.Adapter mAdapter;`
`EditText cityname;`
`TextView result,currentLocation;`
`Button done;`
`WeatherModel weatherModel;`
`static double lat, lng;`
`ArrayList<String> list = new ArrayList<>();`
`private Location mLastLocation;`
`private DrawerLayout mDrawerLayout;`
`private ListView mDrawerList;`
`private ActionBarDrawerToggle mDrawerToggle;`
`ArrayList<WeatherModel> wheatherDataList = new ArrayList<>();`
`LocationManager locationManager;`
`InputMethodManager inputManager;`
`String mprovider;`
`private FusedLocationProviderClient mFusedLocationClient;`
`int LOCATION_REFRESH_TIME = 1000;`
`int LOCATION_REFRESH_DISTANCE = 5;`
`String url="";`
`Geocoder geocoder;`
`List<android.location.Address> addresses;`
`@Override`
`protected void onCreate(Bundle savedInstanceState) {`
`super.onCreate(savedInstanceState);`
`setContentView(R.layout.content_weather_forcast);`
`// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);`
`// setSupportActionBar(toolbar);`
`Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);`
`setSupportActionBar(toolbar);`
`TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);`
`mTitle.setText("Weather");`
`getSupportActionBar().setDisplayHomeAsUpEnabled(true);`
`cityname = (EditText) findViewById(R.id.cityName);`
`cityname.setText("Palo Alto");`
`mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);`
`mRecyclerView.setHasFixedSize(true);`
`// The number of Columns`
`mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);`
`mRecyclerView.setLayoutManager(mLayoutManager);`
`url = "http://api.openweathermap.org/data/2.5/forecast?lat="+37.468319+"&lon="+(-122.143936)+"&appid=291b3a14d9367e0fff371be2a1912b44";`
`getWeather(url);`
`// mAdapter = new RecylerviewAdapter(WeatherForcast.this,wheatherDataList);`
`// mRecyclerView.setAdapter(mAdapter);`
`geocoder = new Geocoder(this, Locale.getDefault());`
`inputManager =`
`(InputMethodManager)`
`getSystemService(Context.INPUT_METHOD_SERVICE);`
`cityname.setOnEditorActionListener(new TextView.OnEditorActionListener() {`
`public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {`
`if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {`
`Log.i("pressed","Enter pressed");`
`inputManager.hideSoftInputFromWindow(`
`getCurrentFocus().getWindowToken(),`
`InputMethodManager.HIDE_NOT_ALWAYS);`
`String name = cityname.getText().toString();`
`if (name != null) {`
`//for 5 days`
`url = "http://api.openweathermap.org/data/2.5/forecast?q="+name+"&appid=291b3a14d9367e0fff371be2a1912b44";`
`//url="http://api.openweathermap.org/data/2.5/weather?q="+name+"&appid=291b3a14d9367e0fff371be2a1912b44";`
`getWeather(url);`
`// mAdapter = new RecylerviewAdapter(WeatherForcast.this,wheatherDataList);`
`// mRecyclerView.setAdapter(mAdapter);`
`//mAdapter.notifyDataSetChanged();`
`// mRecyclerView.setAdapter(new RecylerviewAdapter(WeatherForcast.this,wheatherDataList));`
`// mRecyclerView.invalidate();`
`}`
`else {`
`Toast.makeText(getApplicationContext(),"Please Enter city name",Toast.LENGTH_SHORT).show();`
`}`
`}`
`return true;`
`}`
`});`
`getSupportActionBar().setDisplayHomeAsUpEnabled(true);`
`mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);`
`mDrawerList = (ListView) findViewById(R.id.left_drawer);`
`ArrayList arrayList = new ArrayList();`
`arrayList.add("News");`
`arrayList.add("Traffic");`
`arrayList.add("Weather");`
`// Set the adapter for the list view`
`mDrawerList.setAdapter(new ArrayAdapter<String>(this,`
`R.layout.listtextview, arrayList));`
`mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,`
`R.string.drawer_open, R.string.drawer_close) {`
`/** Called when a drawer has settled in a completely closed state. */`
`public void onDrawerClosed(View view) {`
`super.onDrawerClosed(view);`
`//getActionBar().setTitle("mTitle");`
`invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()`
`}`
`/** Called when a drawer has settled in a completely open state. */`
`public void onDrawerOpened(View drawerView) {`
`super.onDrawerOpened(drawerView);`
`// getActionBar().setTitle("mDrawerTitle");`
`invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()`
`}`
`};`
`// Set the drawer toggle as the DrawerListener`
`mDrawerLayout.setDrawerListener(mDrawerToggle);`
`// Set the list's click listener`
`mDrawerList.setOnItemClickListener(new DrawerItemClickListener());`
`//done = (Button) findViewById(R.id.done);`
`//result = (TextView) findViewById(R.id.weatherinfo);`
`//currentLocation = (TextView) findViewById(R.id.currentLocation);`
`locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);`
`mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);`
`if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {`
`}`
`public void getWeather(String url){`
`// final String[] message = {""};`
`// final String[] description = {null};`
`// final String[] main = {null};`
`// url = "http://api.openweathermap.org/data/2.5/weather?q="+cityname+"&appid=291b3a14d9367e0fff371be2a1912b44";`
`// //for 5 days`
`// url = "http://api.openweathermap.org/data/2.5/forecast?q="+cityname+"&appid=291b3a14d9367e0fff371be2a1912b44";`
`RequestQueue queue = Volley.newRequestQueue(this);`
`JsonObjectRequest jsObjRequest = new JsonObjectRequest`
`(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {`
`@Override`
`public void onResponse(JSONObject response) {`
`wheatherDataList.clear();`
`//mTxtDisplay.setText("Response: " + response.toString());`
`String message="",main=null,description=null;`
`Log.i("response","called");`
`Log.i("response", response.toString());`
`String weatherinfo= null;`
`try {`
`//weatherinfo = response.getString("weather");`
`weatherinfo = response.getString("list");`
`} catch (JSONException e) {`
`e.printStackTrace();`
`}`
`Log.i("weatherinfo",weatherinfo);`
`JSONArray array= null;`
`try {`
`array = new JSONArray(weatherinfo);`
`} catch (JSONException e) {`
`e.printStackTrace();`
`}`
`for(int i=0;i<array.length();i++) {`
`JSONObject jsonPart = null;`
`try {`
`jsonPart = array.getJSONObject(i);`
`Log.i("date", jsonPart.getString("dt_txt"));`
`String date = jsonPart.getString("dt_txt");`
`String object = jsonPart.getString("main");`
`JSONObject object1 = new JSONObject(object);`
`Log.i("temp", object1.getString("temp"));`
`String temp = object1.getString("temp");`
`String humidity = object1.getString("humidity");`
`String pressure = object1.getString("pressure");`
`Log.i("humidity", object1.getString("humidity"));`
`Log.i("pressure", object1.getString("pressure"));`
`String weather = jsonPart.getString("weather");`
`JSONArray array1 = new JSONArray(weather);`
`for (int j = 0; j < array1.length(); j++) {`
`JSONObject jsonPart1 = array1.getJSONObject(j);`
`weatherModel = new WeatherModel();`
`main = jsonPart1.getString("main");`
`Log.i("main", jsonPart1.getString("main"));`
`description = jsonPart1.getString("description");`
`Log.i("description", jsonPart1.getString("description"));`
`message += main + ":" + description + "\r\n";`
`String listcontent = main + ":" + description;`
`list.add(listcontent);`
`weatherModel.setWeatherinfo(description);`
`weatherModel.setDate(date);`
`Log.i("date1", weatherModel.getDate());`
`weatherModel.setHumidity(humidity);`
`weatherModel.setPressure(pressure);`
`weatherModel.setTemp(temp);`
`wheatherDataList.add(weatherModel);`
`}`
`mRecyclerView.setAdapter(new RecylerviewAdapter(WeatherForcast.this,wheatherDataList));`
`// mAdapter.notifyDataSetChanged();`
`// main =jsonPart.getString("main");`
`// Log.i("main",jsonPart.getString("main"));`
`// description =jsonPart.getString("description");`
`// Log.i("description",jsonPart.getString("description"));`
`} catch (JSONException e) {`
`e.printStackTrace();`
`}`
`}`
`// }mRecyclerView.setAdapter(new RecylerviewAdapter(WeatherForcast.this,wheatherDataList));`
`// mRecyclerView.setAdapter(mAdapter);`
`//Log.i("message",message.toString());`
`// result.setText(list.get(0));`
`}`
`}, new Response.ErrorListener() {`
`@Override`
`public void onErrorResponse(VolleyError error) {`
`// TODO Auto-generated method stub`
`Log.i("response",error.toString());`
`}`
`});`
`queue.add(jsObjRequest);`
`}`
`private class DrawerItemClickListener implements ListView.OnItemClickListener {`
`@Override`
`public void onItemClick(AdapterView<?> parent, View view, int position, long id) {`
`if(position==0){`
`// mDrawerLayout.closeDrawers();`
`Intent intent = new Intent(getApplicationContext(),NewsActivity.class);`
`startActivity(intent);`
`finish();`
`}`
`if(position==1){`
`// mDrawerLayout.closeDrawers();`
`Intent intent = new Intent(getApplicationContext(),MapsActivity.class);`
`startActivity(intent);`
`finish();`
`}`
`if(position==2){`
`mDrawerLayout.closeDrawers();`
`// Intent intent = new Intent(getApplicationContext(),WeatherForcast.class);`
`// startActivity(intent);`
`return;`
`}`
`}`
`}`
`@Override`
`public boolean onOptionsItemSelected(MenuItem item) {`
`// Pass the event to ActionBarDrawerToggle`
`// If it returns true, then it has handled`
`// the nav drawer indicator touch event`
`if (mDrawerToggle.onOptionsItemSelected(item)) {`
`return true;`
`}`
`// Handle your other action bar items...`
`return super.onOptionsItemSelected(item);`
`}`
`@Override`
`protected void onPostCreate(Bundle savedInstanceState) {`
`super.onPostCreate(savedInstanceState);`
`mDrawerToggle.syncState();`
`}`
`}`
The new segment of the app is used to get all the latest news.All the news across the globe are gathered and it will be shown to the user.The user can choose which news they want to read.
Code
``public class NewsActivity extends AppCompatActivity {``
``private ViewPager mPager;``
``private ActionBarDrawerToggle mDrawerToggle;``
``NewsModel newsModel;``
``String url;``
``private DrawerLayout mDrawerLayout;``
``private ListView mDrawerList;``
``static ArrayList<NewsModel> list = new ArrayList<>();``
``private PagerAdapter mPagerAdapter;``
``ProgressBar progressBar;``
``@Override``
``protected void onCreate(Bundle savedInstanceState) {``
``super.onCreate(savedInstanceState);``
``setContentView(R.layout.activity_news);``
``progressBar = (ProgressBar)findViewById(R.id.progress) ;``
``progressBar.setVisibility(View.VISIBLE);``
``Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);``
``setSupportActionBar(toolbar);``
``TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);``
``mTitle.setText("News");``
``getSupportActionBar().setDisplayHomeAsUpEnabled(true);``
``mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);``
``mDrawerList = (ListView) findViewById(R.id.left_drawer);``
``ArrayList arrayList = new ArrayList();``
``arrayList.add("News");``
``arrayList.add("Traffic");``
``arrayList.add("Weather");``
``// Set the adapter for the list view``
``mDrawerList.setAdapter(new ArrayAdapter<String>(this,``
``R.layout.listtextview, arrayList));``
``mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,``
``R.string.drawer_open, R.string.drawer_close) {``
``/** Called when a drawer has settled in a completely closed state. */``
``public void onDrawerClosed(View view) {``
``super.onDrawerClosed(view);``
``//getActionBar().setTitle("mTitle");``
``invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()``
``}``
``/** Called when a drawer has settled in a completely open state. */``
``public void onDrawerOpened(View drawerView) {``
``super.onDrawerOpened(drawerView);``
``// getActionBar().setTitle("mDrawerTitle");``
``invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()``
``}``
``};``
``// Set the drawer toggle as the DrawerListener``
``mDrawerLayout.setDrawerListener(mDrawerToggle);``
``// Set the list's click listener``
``mDrawerList.setOnItemClickListener(new DrawerItemClickListener());``
``mPager = (ViewPager) findViewById(R.id.pager);``
``mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager(),list);``
``mPager.setAdapter(mPagerAdapter);``
``// mPagerAdapter.notifyDataSetChanged();``
``mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {``
``@Override``
``public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {``
``}``
``@Override``
``public void onPageSelected(int position) {``
``Log.i("pageNo",String.valueOf(position));``
``//mPagerAdapter.notifyDataSetChanged();``
``}``
``@Override``
``public void onPageScrollStateChanged(int state) {``
``}``
``});``
``getNews();``
``}``
``@Override``
``public void onBackPressed() {``
``if (mPager.getCurrentItem() == 0) {``
``// If the user is currently looking at the first step, allow the system to handle the``
``// Back button. This calls finish() on this activity and pops the back stack.``
``super.onBackPressed();``
``} else {``
``// Otherwise, select the previous step.``
``mPager.setCurrentItem(mPager.getCurrentItem() - 1);``
``}``
``}``
``private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {``
``ArrayList<NewsModel> list1 = new ArrayList<>();``
``public ScreenSlidePagerAdapter(android.support.v4.app.FragmentManager fm,ArrayList<NewsModel> list) {``
``super(fm);``
``list1 = list;``
``}``
``@Override``
``public android.support.v4.app.Fragment getItem(int position) {``
``Log.i("getItem",String.valueOf(position));``
``progressBar.setVisibility(View.INVISIBLE);``
``ScreenSlidePageFragment screenSlidePageFragment = new ScreenSlidePageFragment();``
``// mPagerAdapter.notifyDataSetChanged();``
``return screenSlidePageFragment.newInstance(list1.get(position));``
``}``
``@Override``
``public int getCount() {``
``return list.size();``
``}``
``@Override``
``public int getItemPosition(Object object) {``
``return POSITION_NONE;``
``}``
``// @Override``
``// public int getCount() {``
``// return NUM_PAGES;``
``// }``
``}``
``public void getNews(){``
``//news Api org``
``url = "https://newsapi.org/v1/articles?source=the-next-web&sortBy=latest&apiKey=0d913fbce03540799054a4633035a858";``
``RequestQueue queue = Volley.newRequestQueue(this);``
``JsonObjectRequest jsObjRequest = new JsonObjectRequest``
``(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {``
``@Override``
``public void onResponse(JSONObject response) {``
``Log.i("result",response.toString());``
``try {``
``String articles = response.get("articles").toString();``
``JSONArray array=new JSONArray(articles);``
``for(int i=0;i<array.length();i++){``
``JSONObject jsonpart = array.getJSONObject(i);``
``String title = jsonpart.get("title").toString();``
``String description = jsonpart.get("description").toString();``
``String urlToImage = jsonpart.get("urlToImage").toString();``
``String readmore = jsonpart.get("url").toString();``
``Log.i("title",title);``
``//jsonpart.get("description");``
``//jsonpart.get("urlToImage");``
``newsModel = new NewsModel();``
``newsModel.setTitle(title);``
``newsModel.setDescription(description);``
``newsModel.setReadmore(readmore);``
``newsModel.setUrlofImage(urlToImage);``
``list.add(newsModel);``
``// progress.dismiss();``
``mPagerAdapter.notifyDataSetChanged();``
``}``
``} catch (JSONException e) {``
``e.printStackTrace();``
``}``
``Log.i("list",String.valueOf(list.size()));``
``Log.i("list",list.toString());``
``}``
``}, new Response.ErrorListener() {``
``@Override``
``public void onErrorResponse(VolleyError error) {``
``// TODO Auto-generated method stub``
``Log.i("response",error.toString());``
``}``
``});``
``queue.add(jsObjRequest);``
``}``
``private class DrawerItemClickListener implements ListView.OnItemClickListener {``
``@Override``
``public void onItemClick(AdapterView<?> parent, View view, int position, long id) {``
``if(position==0){``
``// Intent intent = new Intent(getApplicationContext(),NewsActivity.class);``
``// startActivity(intent);``
``mDrawerLayout.closeDrawers();``
``return;``
``}``
``if(position==1){``
``// new Handler().postDelayed(new Runnable() {``
``// @Override``
``// public void run() {``
``Intent intent = new Intent(getApplicationContext(),MapsActivity.class);``
``startActivity(intent);``
``finish();``
``// }``
``// }, 150);``
``// mDrawerLayout.closeDrawers();``
``}``
``if(position==2){``
``// new Handler().postDelayed(new Runnable() {``
``// @Override``
``// public void run() {``
``Intent intent = new Intent(getApplicationContext(),WeatherForcast.class);``
``startActivity(intent);``
``finish();``
``// }``
``// }, 150);``
``//mDrawerLayout.closeDrawers();``
``}``
``}``
``}``
``@Override``
``public boolean onOptionsItemSelected(MenuItem item) {``
``// Pass the event to ActionBarDrawerToggle``
``// If it returns true, then it has handled``
``// the nav drawer indicator touch event``
``if (mDrawerToggle.onOptionsItemSelected(item)) {``
``return true;``
``}``
``// Handle your other action bar items...``
``return super.onOptionsItemSelected(item);``
``}``
``@Override``
``protected void onPostCreate(Bundle savedInstanceState) {``
``super.onPostCreate(savedInstanceState);``
``mDrawerToggle.syncState();``
``}``
The traffic app is used to find if there is any traffic on the road. using the geo location the user will be able to find the traffic near by them and which ever route to take and to avoid.This way the user can avoid traffic and will be able to take the fastest route possible.
**Code**
`public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,`
`GoogleApiClient.OnConnectionFailedListener,`
`LocationListener {`
`private GoogleMap mMap;`
`double lat1,lng1;`
`Polyline polylineFinal;`
`String url;`
`LatLng origin,destination;`
`LocationManager locationManager;`
`static double lat, lng;`
`private DrawerLayout mDrawerLayout;`
`private ListView mDrawerList;`
`private ActionBarDrawerToggle mDrawerToggle;`
`ArrayList<LatLng> MarkerPoints;`
`GoogleApiClient mGoogleApiClient;`
`EditText address;`
`Location mLastLocation;`
`Marker originmarker,destinatiomarker;`
`Marker mCurrLocationMarker;`
`LocationRequest mLocationRequest;`
`private FusedLocationProviderClient mFusedLocationClient;`
`InputMethodManager inputManager;`
`@Override`
`protected void onCreate(Bundle savedInstanceState) {`
`super.onCreate(savedInstanceState);`
`setContentView(R.layout.activity_maps);`
`Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);`
`setSupportActionBar(toolbar);`
`TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);`
`mTitle.setText("Traffic");`
`getSupportActionBar().setDisplayHomeAsUpEnabled(true);`
`// Obtain the SupportMapFragment and get notified when the map is ready to be used.`
`inputManager =`
`(InputMethodManager)`
`getSystemService(Context.INPUT_METHOD_SERVICE);`
`address = (EditText) findViewById(R.id.address);`
`address.setOnEditorActionListener(new TextView.OnEditorActionListener() {`
`public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {`
`if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {`
`Log.i("pressed","Enter pressed");`
`inputManager.hideSoftInputFromWindow(`
`getCurrentFocus().getWindowToken(),`
`InputMethodManager.HIDE_NOT_ALWAYS);`
`String name = address.getText().toString();`
`if(name!=null){`
`String name1 = name.replaceAll(" ","+");`
`getRoute(name1);`
`}`
`else {`
`Toast.makeText(getApplicationContext(),"Please Enter destination",Toast.LENGTH_SHORT).show();`
`}`
`}`
`return true;`
`}`
`});`
`SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()`
`.findFragmentById(R.id.map);`
`mapFragment.getMapAsync(this);`
`locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);`
`mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);`
`getSupportActionBar().setDisplayHomeAsUpEnabled(true);`
`// Toolbar toolbar = (Toolbar) findViewById(R.id.t)`
`mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);`
`mDrawerList = (ListView) findViewById(R.id.left_drawer);`
`ArrayList arrayList = new ArrayList();`
`arrayList.add("News");`
`arrayList.add("Traffic");`
`arrayList.add("Weather");`
`// Set the adapter for the list view`
`mDrawerList.setAdapter(new ArrayAdapter<String>(this,`
`R.layout.listtextview, arrayList));`
`mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,`
`R.string.drawer_open, R.string.drawer_close) {`
`/** Called when a drawer has settled in a completely closed state. */`
`public void onDrawerClosed(View view) {`
`super.onDrawerClosed(view);`
`//getActionBar().setTitle("mTitle");`
`invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()`
`}`
`/** Called when a drawer has settled in a completely open state. */`
`public void onDrawerOpened(View drawerView) {`
`super.onDrawerOpened(drawerView);`
`// getActionBar().setTitle("mDrawerTitle");`
`invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()`
`}`
`};`
`// Set the drawer toggle as the DrawerListener`
`mDrawerLayout.setDrawerListener(mDrawerToggle);`
`// Set the list's click listener`
`mDrawerList.setOnItemClickListener(new DrawerItemClickListener());`
`String provider = locationManager.getBestProvider(new Criteria(), false);`
`if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {`
`// TODO: Consider calling`
`// ActivityCompat#requestPermissions`
`// here to request the missing permissions, and then overriding`
`// public void onRequestPermissionsResult(int requestCode, String[] permissions,`
`// int[] grantResults)`
`// to handle the case where the user grants the permission. See the documentation`
`// for ActivityCompat#requestPermissions for more details.`
`return;`
`}`
`MarkerPoints = new ArrayList<>();`
`//getRoute();`
`}`
`/**`
`* Manipulates the map once available.`
`* This callback is triggered when the map is ready to be used.`
`* This is where we can add markers or lines, add listeners or move the camera. In this case,`
`* we just add a marker near Sydney, Australia.`
`* If Google Play services is not installed on the device, the user will be prompted to install`
`* it inside the SupportMapFragment. This method will only be triggered once the user has`
`* installed Google Play services and returned to the app.`
`*/`
`@Override`
`public void onMapReady(final GoogleMap googleMap) {`
`mMap = googleMap;`
`origin = new LatLng(37.468319,-122.143936);`
`// LatLng current = new LatLng(lat, lng);`
`LatLng current = new LatLng(37.468319, -122.143936);`
`Log.i("latlng", String.valueOf(lat) + " " + String.valueOf(lng));`
`mMap.setTrafficEnabled(true);`
`//Log.i("lastknownLocation", String.valueOf(location.getLatitude()) + " " + String.valueOf(location.getLongitude()));`
`originmarker =mMap.addMarker(new MarkerOptions().position(current).title("Palo Alto "));`
`//options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));`
`mMap.moveCamera(CameraUpdateFactory.newLatLng(current));`
`mMap.animateCamera(CameraUpdateFactory.zoomTo(150));`
`MarkerPoints.add(origin);`
`getRoute("stanford");`
`mFusedLocationClient.getLastLocation()`
`.addOnSuccessListener(this, new OnSuccessListener<Location>() {`
`@Override`
`public void onSuccess(Location location) {`
`// Got last known location. In some rare situations this can be null.`
`if (location != null) {`
`lat = location.getLatitude();`
`lng = location.getLongitude();`
`// origin = new LatLng(lat,lng);`
`origin = new LatLng(37.468319,-122.143936);`
`// LatLng current = new LatLng(lat, lng);`
`LatLng current = new LatLng(37.468319, -122.143936);`
`Log.i("latlng", String.valueOf(lat) + " " + String.valueOf(lng));`
`mMap.setTrafficEnabled(true);`
`Log.i("lastknownLocation", String.valueOf(location.getLatitude()) + " " + String.valueOf(location.getLongitude()));`
`originmarker =mMap.addMarker(new MarkerOptions().position(current).title("Marker on current"));`
`//options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));`
`mMap.moveCamera(CameraUpdateFactory.newLatLng(current));`
`mMap.animateCamera(CameraUpdateFactory.zoomBy(11));`
`mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(37.468319, -122.143936), 15));`
`//CameraUpdateFactory.zoomBy(15);`
`MarkerPoints.add(origin);`
`// ...`
`}`
`else {`
`//Toast.makeText(getApplicationContext(),"Please tun on GPS",Toast.LENGTH_LONG).show();`
`}`
`}`
`});`
`Log.i("lastknownLocation1", String.valueOf(lat) + " " + String.valueOf(lng));`
`// Add a marker in Sydney and move the camera`
`if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {`
`// TODO: Consider calling`
`// ActivityCompat#requestPermissions`
`// here to request the missing permissions, and then overriding`
`// public void onRequestPermissionsResult(int requestCode, String[] permissions,`
`// int[] grantResults)`
`// to handle the case where the user grants the permission. See the documentation`
`// for ActivityCompat#requestPermissions for more details.`
`return;`
`}`
`mMap.setMyLocationEnabled(true);`
`mMap.setTrafficEnabled(true);`
`mMap = googleMap;`
`//Initialize Google Play Services`
`if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {`
`// if (ContextCompat.checkSelfPermission(this,`
`// Manifest.permission.ACCESS_FINE_LOCATION)`
`// == PackageManager.PERMISSION_GRANTED) {`
`buildGoogleApiClient();`
`mMap.setMyLocationEnabled(true);`
`// }`
`} else {`
`buildGoogleApiClient();`
`mMap.setMyLocationEnabled(true);`
`}`
`// Setting onclick event listener for the map`
`Log.i("lat1andlng1",lat1+" "+lng1);`
`mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {`
`@Override`
`public void onMapClick(LatLng point) {
`// Already two locations``
`}`
`// }`
`});`
`}`
`private String getUrl(LatLng origin, LatLng dest) {`
`// Origin of route`
`String str_origin = "origin=" + origin.latitude + "," + origin.longitude;`
`// Destination of route`
`String str_dest = "destination=" + dest.latitude + "," + dest.longitude;`
`// Sensor enabled`
`String sensor = "sensor=false";`
`// Building the parameters to the web service`
`String parameters = str_origin + "&" + str_dest + "&" + sensor;`
`// Output format`
`String output = "json";`
`// Building the url to the web service`
`String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;`
`return url;`
`}`
`/**`
`* A method to download json data from url`
`*/`
`private String downloadUrl(String strUrl) throws IOException {`
`String data = "";`
`InputStream iStream = null;`
`HttpURLConnection urlConnection = null;`
`try {`
`URL url = new URL(strUrl);`
`// Creating an http connection to communicate with url`
`urlConnection = (HttpURLConnection) url.openConnection();`
`// Connecting to url`
`urlConnection.connect();`
`// Reading data from url`
`iStream = urlConnection.getInputStream();`
`BufferedReader br = new BufferedReader(new InputStreamReader(iStream));`
`StringBuffer sb = new StringBuffer();`
`String line = "";`
`while ((line = br.readLine()) != null) {`
`sb.append(line);`
`}`
`data = sb.toString();`
`Log.d("downloadUrl", data.toString());`
`br.close();`
`} catch (Exception e) {`
`Log.d("Exception", e.toString());`
`} finally {`
`iStream.close();`
`urlConnection.disconnect();`
`}`
`return data;`
`}`
`// Fetches data from url passed`
`private class FetchUrl extends AsyncTask<String, Void, String> {`
`@Override`
`protected String doInBackground(String... url) {`
`// For storing data from web service`
`String data = "";`
`try {`
`// Fetching the data from web service`
`data = downloadUrl(url[0]);`
`Log.d("Background Task data", data.toString());`
`} catch (Exception e) {`
`Log.d("Background Task", e.toString());`
`}`
`return data;`
`}`
`@Override`
`protected void onPostExecute(String result) {`
`super.onPostExecute(result);`
`ParserTask parserTask = new ParserTask();`
`// Invokes the thread for parsing the JSON data`
`parserTask.execute(result);`
`}`
`}`
`/**`
`* A class to parse the Google Places in JSON format`
`*/`
`private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {`
`// Parsing the data in non-ui thread`
`@Override`
`protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {`
`JSONObject jObject;`
`List<List<HashMap<String, String>>> routes = null;`
`try {`
`jObject = new JSONObject(jsonData[0]);`
`Log.d("ParserTask", jsonData[0].toString());`
`DataParser parser = new DataParser();`
`Log.d("ParserTask", parser.toString());`
`// Starts parsing data`
`routes = parser.parse(jObject);`
`Log.d("ParserTask", "Executing routes");`
`Log.i("ParserTask", routes.toString());`
`} catch (Exception e) {`
`Log.d("ParserTask", e.toString());`
`e.printStackTrace();`
`}`
`return routes;`
`}`
`// Executes in UI thread, after the parsing process`
`@Override`
`protected void onPostExecute(List<List<HashMap<String, String>>> result) {`
`if((result!=null&&result.size()>0)){`
`ArrayList<LatLng> points;`
`// Polyline polyline = mMap.addPolyline(new PolylineOptions());`
`// polyline.remove();`
`if(polylineFinal!=null){`
`polylineFinal.remove();`
`}`
`PolylineOptions lineOptions = null;`
`// Traversing through all the routes`
`for (int i = 0; i < result.size(); i++) {`
`points = new ArrayList<>();`
`lineOptions = new PolylineOptions();`
`// Fetching i-th route`
`List<HashMap<String, String>> path = result.get(i);`
`// Fetching all the points in i-th route`
`for (int j = 0; j < path.size(); j++) {`
`HashMap<String, String> point = path.get(j);`
`double lat = Double.parseDouble(point.get("lat"));`
`double lng = Double.parseDouble(point.get("lng"));`
`LatLng position = new LatLng(lat, lng);`
`points.add(position);`
`}`
`// Adding all the points in the route to LineOptions`
`lineOptions.addAll(points);`
`lineOptions.width(10);`
`lineOptions.color(Color.RED);`
`Log.d("onPostExecute", "onPostExecute lineoptions decoded");`
`}`
`// Drawing polyline in the Google Map for the i-th route`
`if (lineOptions != null) {`
`polylineFinal=mMap.addPolyline(lineOptions);`
`} else {`
`Log.d("onPostExecute", "without Polylines drawn");`
`}`
`}}`
`}`
`protected synchronized void buildGoogleApiClient() {`
`mGoogleApiClient = new GoogleApiClient.Builder(this)`
`.addConnectionCallbacks(this)`
`.addOnConnectionFailedListener(this)`
`.addApi(LocationServices.API)`
`.build();`
`mGoogleApiClient.connect();`
`}`
`@Override`
`public void onConnected(Bundle bundle) {`
`mLocationRequest = new LocationRequest();`
`mLocationRequest.setInterval(1000);`
`mLocationRequest.setFastestInterval(1000);`
`mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);`
`// if (ContextCompat.checkSelfPermission(this,`
`// Manifest.permission.ACCESS_FINE_LOCATION)`
`// == PackageManager.PERMISSION_GRANTED) {`
`if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {`
`// TODO: Consider calling`
`// ActivityCompat#requestPermissions`
`// here to request the missing permissions, and then overriding`
`// public void onRequestPermissionsResult(int requestCode, String[] permissions,`
`// int[] grantResults)`
`// to handle the case where the user grants the permission. See the documentation`
`// for ActivityCompat#requestPermissions for more details.`
`return;`
`}`
`LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);`
`//}`
`}`
`@Override`
`public void onConnectionSuspended(int i) {`
`}`
`@Override`
`public void onLocationChanged(Location location) {`
`mLastLocation = location;`
`if (mCurrLocationMarker != null) {`
`mCurrLocationMarker.remove();`
`}`
`//Place current location marker`
`LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());`
`MarkerOptions markerOptions = new MarkerOptions();`
`markerOptions.position(latLng);`
`markerOptions.title("Current Position");`
`markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));`
`mCurrLocationMarker = mMap.addMarker(markerOptions);`
`//move map camera`
`mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));`
`mMap.animateCamera(CameraUpdateFactory.zoomTo(11));`
`//stop location updates`
`if (mGoogleApiClient != null) {`
`LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);`
`}`
`}`
`@Override`
`public void onConnectionFailed(ConnectionResult connectionResult) {`
`}`
`public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;`
`@Override`
`public void onRequestPermissionsResult(int requestCode,`
`String permissions[], int[] grantResults) {`
`switch (requestCode) {`
`case MY_PERMISSIONS_REQUEST_LOCATION: {`
`// If request is cancelled, the result arrays are empty.`
`if (grantResults.length > 0`
`&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {`
`// permission was granted. Do the`
`// contacts-related task you need to do.`
`// if (ContextCompat.checkSelfPermission(this,`
`// Manifest.permission.ACCESS_FINE_LOCATION)`
`// == PackageManager.PERMISSION_GRANTED) {`
`if (mGoogleApiClient == null) {`
`buildGoogleApiClient();`
`//}`
`if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {`
`// TODO: Consider calling`
`// ActivityCompat#requestPermissions`
`// here to request the missing permissions, and then overriding`
`// public void onRequestPermissionsResult(int requestCode, String[] permissions,`
`// int[] grantResults)`
`// to handle the case where the user grants the permission. See the documentation`
`// for ActivityCompat#requestPermissions for more details.`
`return;`
`}`
`mMap.setMyLocationEnabled(true);`
`}`
`} else {`
`// Permission denied, Disable the functionality that depends on this permission.`
`Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();`
`}`
`return;`
`}`
`// other 'case' lines to check for other permissions this app might request.`
`// You can add here other case statements according to your requirement.`
`}`
`}`
`public void getRoute(String addressName) {`
`url = "https://maps.googleapis.com/maps/api/geocode/json?address="+addressName+"&key=AIzaSyBu4xO13m6GZCiUWmsZcYo2thfZF390zfo";`
`RequestQueue queue = Volley.newRequestQueue(this);`
`JsonObjectRequest jsObjRequest = new JsonObjectRequest`
`(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {`
`@Override`
`public void onResponse(JSONObject response) {`
`//mTxtDisplay.setText("Response: " + response.toString());`
`//MarkerPoints.clear();`
`if(destinatiomarker!=null){`
`destinatiomarker.remove();`
`}`
`Log.i("response", response.toString());`
`String location = null;`
`try {`
`location = response.getString("results").toString();`
`} catch (JSONException e) {`
`e.printStackTrace();`
`}`
`try {`
`JSONArray array = new JSONArray(location);`
`for(int i=0;i<array.length();i++){`
`JSONObject part = array.getJSONObject(i);`
`String geometry = part.getString("geometry");`
`Log.i("geometry",geometry);`
`JSONObject part1=new JSONObject(geometry);`
`JSONObject part2=part1.getJSONObject("location");`
`lat1 = part2.getDouble("lat");`
`lng1 = part2.getDouble("lng");`
`destination = new LatLng(lat1,lng1);`
`Log.i("lat1andLng1",String.valueOf(lat1)+" "+String.valueOf(lng1));`
`//LatLng latLng = new LatLng(lat1, lng1);`
`MarkerOptions markerOptions = new MarkerOptions();`
`markerOptions.position(destination);`
`markerOptions.title("destination");`
`markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));`
`destinatiomarker = mMap.addMarker(markerOptions);`
`//move map camera`
`mMap.moveCamera(CameraUpdateFactory.newLatLng(destination));`
`//mMap.animateCamera(CameraUpdateFactory.zoomTo(20));`
`if(MarkerPoints.size()>0){`
`MarkerPoints.add(1,destination);`
`}`
`}`
`} catch (JSONException e) {`
`e.printStackTrace();`
`}`
`drawpath();`
`}`
`}, new Response.ErrorListener() {`
`@Override`
`public void onErrorResponse(VolleyError error) {`
`// TODO Auto-generated method stub`
`}`
`});`
`queue.add(jsObjRequest);`
`}`
`private class DrawerItemClickListener implements ListView.OnItemClickListener {`
`@Override`
`public void onItemClick(AdapterView<?> parent, View view, int position, long id) {`
`if(position==0){`
`// mDrawerLayout.closeDrawers();`
`Intent intent = new Intent(getApplicationContext(),NewsActivity.class);`
`startActivity(intent);`
`finish();`
`}`
`if(position==1){`
`// Intent intent = new Intent(getApplicationContext(),MapsActivity.class);`
`// startActivity(intent);`
`mDrawerLayout.closeDrawers();`
`return;`
`}`
`if(position==2){`
`// mDrawerLayout.closeDrawers();`
`Intent intent = new Intent(getApplicationContext(),WeatherForcast.class);`
`startActivity(intent);`
`finish();`
`}`
`}`
`}`
`@Override`
`public boolean onOptionsItemSelected(MenuItem item) {`
`// Pass the event to ActionBarDrawerToggle`
`// If it returns true, then it has handled`
`// the nav drawer indicator touch event`
`if (mDrawerToggle.onOptionsItemSelected(item)) {`
`return true;`
`}`
`// Handle your other action bar items...`
`return super.onOptionsItemSelected(item);`
`}`
`@Override`
`protected void onPostCreate(Bundle savedInstanceState) {`
`super.onPostCreate(savedInstanceState);`
`mDrawerToggle.syncState();`
`}`
`public void drawpath(){`
`if (MarkerPoints.size() >= 2) {`
`LatLng origin = MarkerPoints.get(0);`
`LatLng dest = MarkerPoints.get(1);`
`Log.i("direction","called");`
`// Getting URL to the Google Directions API`
`Log.i("originanddestination",String.valueOf(origin.latitude));`
`String url = getUrl(origin, dest);`
`Log.d("onMapClick", url.toString());`
`FetchUrl FetchUrl = new FetchUrl();`
`// Start downloading json data from Google Directions API`
`FetchUrl.execute(url);`
`//move map camera`
`mMap.moveCamera(CameraUpdateFactory.newLatLng(origin));`
`mMap.animateCamera(CameraUpdateFactory.zoomTo(11));`
`}`
`}`
`}`