diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 4242adb..74cd344 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -12,21 +12,25 @@ - - + + - - - + + + + + + - @@ -39,6 +43,7 @@ android:label="@string/title_activity_start" > + @@ -57,6 +62,28 @@ android:name=".MainActivity" android:label="@string/title_activity_entrance" > + + + + + + + + + + + + + diff --git a/app/src/main/java/org/deke/risk/riskahead/MainActivity.java b/app/src/main/java/org/deke/risk/riskahead/MainActivity.java index 086a2ac..01b6ef7 100644 --- a/app/src/main/java/org/deke/risk/riskahead/MainActivity.java +++ b/app/src/main/java/org/deke/risk/riskahead/MainActivity.java @@ -1,219 +1,34 @@ package org.deke.risk.riskahead; import android.content.Intent; -import android.content.res.Configuration; -import android.net.Uri; import android.os.Bundle; -import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; -import android.support.v4.app.FragmentTransaction; -import android.support.v4.view.MenuItemCompat; -import android.support.v4.widget.DrawerLayout; -import android.support.v7.app.ActionBarDrawerToggle; -import android.support.v7.app.AppCompatActivity; -import android.support.v7.widget.ShareActionProvider; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.ListView; -import org.deke.risk.riskahead.fragments.MapFragment; -import org.deke.risk.riskahead.fragments.UserInfo; -import org.deke.risk.riskahead.helper.SQLiteHandler; -import org.deke.risk.riskahead.helper.SessionManager; +import org.deke.risk.riskahead.helper.BaseActivity; -import java.util.HashMap; +public class MainActivity extends BaseActivity{ - -public class MainActivity extends AppCompatActivity implements UserInfo.OnFragmentInteractionListener, MapFragment.OnFragmentInteractionListener{ - - public final static String EXTRA_MESSAGE = "com.mycompany.myfirstapp.MESSAGE"; public String inputMsg; - - private ActionBarDrawerToggle mDrawerToggle; - private DrawerLayout mDrawerLayout; - private String mActivityTitle; - ShareActionProvider mShareActionProvider; - private ListView mDrawerList; - private ArrayAdapter mAdapter; - - private SQLiteHandler db; - private SessionManager session; - - public HashMap user; + private String mActivityTitle = "RiskAhead"; public static FragmentManager fragmentManager; - final String[] fragments = {UserInfo.class.getName(),MapFragment.class.getName()}; - @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); + //setContentView(R.layout.activity_main); Intent intent = getIntent(); inputMsg = intent.getStringExtra(StartActivity.EXTRA_MESSAGE); - - // SqLite database handler - db = new SQLiteHandler(getApplicationContext()); - - // session manager - session = new SessionManager(getApplicationContext()); - - if (!session.isLoggedIn()) { - logoutUser(); - } - - // Fetching user details from sqlite - user = db.getUserDetails(); - - mDrawerList = (ListView)findViewById(R.id.navList); - mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout); - addDrawerItems(); - setupDrawer(); - getSupportActionBar().setDisplayHomeAsUpEnabled(true); - getSupportActionBar().setHomeButtonEnabled(true); - mActivityTitle = getTitle().toString(); - fragmentManager = getSupportFragmentManager(); } - private void setupDrawer() { - mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, - R.string.drawer_open, R.string.drawer_close) { - - /** Called when a drawer has settled in a completely open state. */ - public void onDrawerOpened(View drawerView) { - super.onDrawerOpened(drawerView); - getSupportActionBar().setTitle("Navigation!"); - invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() - } - - /** Called when a drawer has settled in a completely closed state. */ - public void onDrawerClosed(View view) { - super.onDrawerClosed(view); - getSupportActionBar().setTitle(mActivityTitle); - invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() - } - }; - - mDrawerToggle.setDrawerIndicatorEnabled(true); - mDrawerLayout.setDrawerListener(mDrawerToggle); - } - - - private void addDrawerItems() { - String[] osArray = { "Start", "Maps", "Profile", "Settings", "Subscription", "Logout" }; - mAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, osArray); - mDrawerList.setAdapter(mAdapter); - - mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView parent, View view, final int position, long id) { - mDrawerLayout.setDrawerListener(new DrawerLayout.SimpleDrawerListener() { - @Override - public void onDrawerClosed(View drawerView) { - super.onDrawerClosed(drawerView); - - FragmentTransaction tx = getSupportFragmentManager().beginTransaction(); - tx.replace(R.id.content, Fragment.instantiate(MainActivity.this, fragments[position])); - tx.commit(); - } - }); - mDrawerLayout.closeDrawer(mDrawerList); - } - }); - - FragmentTransaction tx = getSupportFragmentManager().beginTransaction(); - tx.replace(R.id.content, Fragment.instantiate(MainActivity.this, fragments[0])); - tx.commit(); - } - - @Override - protected void onPostCreate(Bundle savedInstanceState) { - super.onPostCreate(savedInstanceState); - mDrawerToggle.syncState(); + protected int getLayoutResourceId() { + return R.layout.activity_main; } @Override - public void onConfigurationChanged(Configuration newConfig) { - super.onConfigurationChanged(newConfig); - mDrawerToggle.onConfigurationChanged(newConfig); - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - getMenuInflater().inflate(R.menu.menu_main_share, menu); - - // Access the Share Item defined in menu XML - MenuItem shareItem = menu.findItem(R.id.menu_item_share); - - // Access the object responsible for - // putting together the sharing submenu - if (shareItem != null) { - mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareItem); - } - - // Create an Intent to share your content - setShareIntent(); - getMenuInflater().inflate(R.menu.menu_login, menu); - return true; - } - - private void setShareIntent() { - if (mShareActionProvider != null) { - - // create an Intent with the contents of the TextView - Intent shareIntent = new Intent(Intent.ACTION_SEND); - shareIntent.setType("text/plain"); - shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Android Development"); - shareIntent.putExtra(Intent.EXTRA_TEXT, "Ich empfehle RiskAhead!"); - - // Make sure the provider knows - // it should work with that Intent - mShareActionProvider.setShareIntent(shareIntent); - } - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - // Handle action bar item clicks here. The action bar will - // automatically handle clicks on the Home/Up button, so long - // as you specify a parent activity in AndroidManifest.xml. - int id = item.getItemId(); - - //noinspection SimplifiableIfStatement - if (id == R.id.action_settings) { - return true; - } - - // Activate the navigation drawer toggle - if (mDrawerToggle.onOptionsItemSelected(item)) { - return true; - } - - return super.onOptionsItemSelected(item); - } - - @Override - public void onFragmentInteraction(Uri uri) { - - } - - /** - * Logging out the user. Will set isLoggedIn flag to false in shared - * preferences Clears the user data from sqlite users table - * */ - public void logoutUser() { - session.setLogin(false); - db.deleteUsers(); - - // Launching the login activity - Intent intent = new Intent(MainActivity.this, LoginActivity.class); - intent.putExtra(EXTRA_MESSAGE, "login"); - startActivity(intent); - finish(); + protected String getActivityName() { + return mActivityTitle; } } diff --git a/app/src/main/java/org/deke/risk/riskahead/MapsActivity.java b/app/src/main/java/org/deke/risk/riskahead/MapsActivity.java new file mode 100644 index 0000000..b1ca1e8 --- /dev/null +++ b/app/src/main/java/org/deke/risk/riskahead/MapsActivity.java @@ -0,0 +1,191 @@ +package org.deke.risk.riskahead; + +import android.app.SearchManager; +import android.app.SearchableInfo; +import android.content.Context; +import android.content.Intent; +import android.database.Cursor; +import android.os.Bundle; +import android.support.v4.app.LoaderManager; +import android.support.v4.content.CursorLoader; +import android.support.v4.content.Loader; +import android.support.v7.widget.SearchView; +import android.view.Menu; + +import com.google.android.gms.maps.CameraUpdate; +import com.google.android.gms.maps.CameraUpdateFactory; +import com.google.android.gms.maps.GoogleMap; +import com.google.android.gms.maps.SupportMapFragment; +import com.google.android.gms.maps.model.LatLng; +import com.google.android.gms.maps.model.MarkerOptions; + +import org.deke.risk.riskahead.helper.BaseActivity; +import org.deke.risk.riskahead.helper.PlaceProvider; + + +public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCallbacks { + private static GoogleMap mMap; + private static Double latitude, longitude; + private String mActivityTitle = "RiskMap"; + + private void handleIntent(Intent intent){ + if(Intent.ACTION_SEARCH.equals(intent.getAction())) + { + String query = intent.getStringExtra(SearchManager.QUERY); + doSearch(query); + } + else if(Intent.ACTION_VIEW.equals(intent.getAction())) + { + getPlace(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY)); + } + } + + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + setIntent(intent); + handleIntent(intent); + } + + private void doSearch(String query){ + Bundle data = new Bundle(); + data.putString("query", query); + getSupportLoaderManager().restartLoader(0, data, this); + } + + private void getPlace(String query){ + Bundle data = new Bundle(); + data.putString("query", query); + getSupportLoaderManager().restartLoader(1, data, this); + } + + private void showLocations(Cursor c){ + MarkerOptions markerOptions = null; + LatLng position = null; + mMap.clear(); + while(c.moveToNext()){ + markerOptions = new MarkerOptions(); + position = new LatLng(Double.parseDouble(c.getString(1)),Double.parseDouble(c.getString(2))); + markerOptions.position(position); + markerOptions.title(c.getString(0)); + mMap.addMarker(markerOptions); + } + if(position!=null){ + CameraUpdate cameraPosition = CameraUpdateFactory.newLatLng(position); + mMap.animateCamera(cameraPosition); + } + } + + @Override + public void onLoaderReset(Loader arg0) { + // TODO Auto-generated method stub + } + + @Override + public Loader onCreateLoader(int arg0, Bundle query) { + CursorLoader cLoader = null; + if(arg0==0) + cLoader = new CursorLoader(getBaseContext(), PlaceProvider.SEARCH_URI, null, null, new String[]{ query.getString("query") }, null); + else if(arg0==1) + cLoader = new CursorLoader(getBaseContext(), PlaceProvider.DETAILS_URI, null, null, new String[]{ query.getString("query") }, null); + return cLoader; + + } + + @Override + public void onLoadFinished(Loader arg0, Cursor c) { + showLocations(c); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + //setContentView(R.layout.activity_maps); + + // Passing harcoded values for latitude & longitude. Please change as per your need. This is just used to drop a Marker on the Map + latitude = 53.33; + longitude = 10.02; + + setUpMapIfNeeded(); // For setting up the MapFragment + + if (mMap != null) + setUpMap(); + + if (mMap == null) { + // Try to obtain the map from the SupportMapFragment. + mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); // getMap is deprecated + // Check if we were successful in obtaining the map. + if (mMap != null) + setUpMap(); + } + + handleIntent(getIntent()); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + // Inflate the menu; this adds items to the action bar if it is present. + getMenuInflater().inflate(R.menu.menu_maps, menu); + + // Get the SearchView and set the searchable configuration + SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); + SearchView searchView = (SearchView) menu.findItem(R.id.location_search).getActionView(); + SearchableInfo searchInfo = searchManager.getSearchableInfo(getComponentName()); + searchView.setSearchableInfo(searchInfo); + + return true; + } + + /***** Sets up the map if it is possible to do so *****/ + public void setUpMapIfNeeded() { + // Do a null check to confirm that we have not already instantiated the map. + if (mMap == null) { + // Try to obtain the map from the SupportMapFragment. + //mMap = ((SupportMapFragment) MainActivity.fragmentManager.findFragmentById(R.id.location_map)).getMap(); + mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); + // Check if we were successful in obtaining the map. + if (mMap != null) + setUpMap(); + } + } + + /** + * This is where we can add markers or lines, add listeners or move the + * camera. + *

+ * This should only be called once and when we are sure that {@link #mMap} + * is not null. + */ + private static void setUpMap() { + // For showing a move to my loction button + mMap.setMyLocationEnabled(true); + mMap.getUiSettings().setZoomControlsEnabled(true); + // For dropping a marker at a point on the Map + mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("My Home").snippet("Home Address")); + // For zooming automatically to the Dropped PIN Location + mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 12.0f)); + } + + /**** The mapfragment's id must be removed from the FragmentManager + **** or else if the same it is passed on the next time then + **** app will crash ****/ + @Override + public void onDestroy() { + super.onDestroy(); + if (mMap != null) { + getSupportFragmentManager().beginTransaction().remove(getSupportFragmentManager().findFragmentById(R.id.map)).commitAllowingStateLoss(); + mMap = null; + } + } + + @Override + protected int getLayoutResourceId() { + return R.layout.activity_maps; + } + + @Override + protected String getActivityName() { + return mActivityTitle; + } + +} diff --git a/app/src/main/java/org/deke/risk/riskahead/UserConfigActivity.java b/app/src/main/java/org/deke/risk/riskahead/UserConfigActivity.java new file mode 100644 index 0000000..6f0db1a --- /dev/null +++ b/app/src/main/java/org/deke/risk/riskahead/UserConfigActivity.java @@ -0,0 +1,87 @@ +package org.deke.risk.riskahead; + +import android.os.Bundle; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.Button; +import android.widget.TextView; + +import org.deke.risk.riskahead.helper.BaseActivity; +import org.deke.risk.riskahead.helper.SQLiteHandler; +import org.deke.risk.riskahead.helper.SessionManager; + +import java.util.HashMap; + + +public class UserConfigActivity extends BaseActivity { + private TextView txtName; + private TextView txtEmail; + private TextView txtTest; + private Button btnLogout; + private SQLiteHandler db; + public HashMap user; + private SessionManager session; + private String mActivityTitle = "User Profile"; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + //setContentView(R.layout.activity_user_config); + + session = new SessionManager(getApplicationContext()); + + txtTest = (TextView) findViewById(R.id.test); + txtName = (TextView) findViewById(R.id.name); + txtEmail = (TextView) findViewById(R.id.email); + btnLogout = (Button) findViewById(R.id.btnLogout); + + // Logout button click event + btnLogout.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + logoutUser(); + } + }); + + // SqLite database handler + db = new SQLiteHandler(getApplicationContext()); + // Fetching user details from sqlite + user = db.getUserDetails(); + txtName.setText(user.get("username")); + txtEmail.setText(user.get("email")); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + // Inflate the menu; this adds items to the action bar if it is present. + getMenuInflater().inflate(R.menu.menu_user_config, menu); + + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + + //noinspection SimplifiableIfStatement + if (id == R.id.action_settings) { + return true; + } + + return super.onOptionsItemSelected(item); + } + + @Override + protected int getLayoutResourceId() { + return R.layout.activity_user_config; + } + + @Override + protected String getActivityName() { + return mActivityTitle; + } +} diff --git a/app/src/main/java/org/deke/risk/riskahead/fragments/MapFragment.java b/app/src/main/java/org/deke/risk/riskahead/fragments/MapFragment.java deleted file mode 100644 index c69403c..0000000 --- a/app/src/main/java/org/deke/risk/riskahead/fragments/MapFragment.java +++ /dev/null @@ -1,252 +0,0 @@ -package org.deke.risk.riskahead.fragments; - -import android.content.Intent; -import android.net.Uri; -import android.os.AsyncTask; -import android.os.Bundle; - -import android.support.v4.app.Fragment; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.Button; -import android.widget.EditText; -import android.widget.RelativeLayout; -import android.widget.Toast; - -import com.google.android.gms.maps.CameraUpdateFactory; -import com.google.android.gms.maps.GoogleMap; -import com.google.android.gms.maps.SupportMapFragment; -import com.google.android.gms.maps.model.LatLng; -import com.google.android.gms.maps.model.MarkerOptions; - -import org.deke.risk.riskahead.R; -import org.deke.risk.riskahead.helper.GeocodeJSONParser; -import org.json.JSONObject; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLEncoder; -import java.util.HashMap; -import java.util.List; - -public class MapFragment extends Fragment { - - private static View view; - private static GoogleMap mMap; - private static Double latitude, longitude; - Button mBtnFind; - EditText etPlace; - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - if (container == null) { - return null; - } - view = (RelativeLayout) inflater.inflate(R.layout.fragment_map, container, false); - // Passing harcoded values for latitude & longitude. Please change as per your need. This is just used to drop a Marker on the Map - latitude = 53.33; - longitude = 10.02; - - setUpMapIfNeeded(); // For setting up the MapFragment - // Getting reference to the find button - mBtnFind = (Button) view.findViewById(R.id.btn_show); - etPlace = (EditText) view.findViewById(R.id.et_place); - - mBtnFind.setOnClickListener(new View.OnClickListener() { - - @Override - public void onClick(View v) { - // Getting the place entered - String location = etPlace.getText().toString(); - - if(location==null || location.equals("")){ - Toast.makeText(getActivity(), "No Place is entered", Toast.LENGTH_SHORT).show(); - return; - } - - String url = "https://maps.googleapis.com/maps/api/geocode/json?"; - - try { - // encoding special characters like space in the user input place - location = URLEncoder.encode(location, "utf-8"); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - - String address = "address=" + location; - - String sensor = "sensor=false"; - - // url , from where the geocoding data is fetched - url = url + address + "&" + sensor; - - // Instantiating DownloadTask to get places from Google Geocoding service - // in a non-ui thread - DownloadTask downloadTask = new DownloadTask(); - - // Start downloading the geocoding places - downloadTask.execute(url); - } - }); - return view; - } - - /***** Sets up the map if it is possible to do so *****/ - public void setUpMapIfNeeded() { - // Do a null check to confirm that we have not already instantiated the map. - if (mMap == null) { - // Try to obtain the map from the SupportMapFragment. - //mMap = ((SupportMapFragment) MainActivity.fragmentManager.findFragmentById(R.id.location_map)).getMap(); - mMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.location_map)).getMap(); - // Check if we were successful in obtaining the map. - if (mMap != null) - setUpMap(); - } - } - - /** - * This is where we can add markers or lines, add listeners or move the - * camera. - *

- * This should only be called once and when we are sure that {@link #mMap} - * is not null. - */ - private static void setUpMap() { - // For showing a move to my loction button - mMap.setMyLocationEnabled(true); - mMap.getUiSettings().setZoomControlsEnabled(true); - // For dropping a marker at a point on the Map - mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("My Home").snippet("Home Address")); - // For zooming automatically to the Dropped PIN Location - mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude), 12.0f)); - } - - @Override - public void onViewCreated(View view, Bundle savedInstanceState) { - if (mMap != null) - setUpMap(); - - if (mMap == null) { - // Try to obtain the map from the SupportMapFragment. - mMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.location_map)).getMap(); // getMap is deprecated - // Check if we were successful in obtaining the map. - if (mMap != null) - setUpMap(); - } - } - - /**** The mapfragment's id must be removed from the FragmentManager - **** or else if the same it is passed on the next time then - **** app will crash ****/ - @Override - public void onDestroyView() { - super.onDestroyView(); - if (mMap != null) { - getChildFragmentManager().beginTransaction().remove(getChildFragmentManager().findFragmentById(R.id.location_map)).commitAllowingStateLoss(); - mMap = null; - } - } - - public interface OnFragmentInteractionListener { - public void onFragmentInteraction(Uri uri); - } - - 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(); - br.close(); - - }catch(Exception e){ - Log.d("Exception while downloading url", e.toString()); - }finally{ - iStream.close(); - urlConnection.disconnect(); - } - - return data; - } - /** A class, to download Places from Geocoding webservice */ - private class DownloadTask extends AsyncTask { - - String data = null; - - // Invoked by execute() method of this object - @Override - protected String doInBackground(String... url) { - try{ - data = downloadUrl(url[0]); - }catch(Exception e){ - Log.d("Background Task",e.toString()); - } - return data; - } - - // Executed after the complete execution of doInBackground() method - @Override - protected void onPostExecute(String result){ - - // Instantiating ParserTask which parses the json data from Geocoding webservice - // in a non-ui thread - ParserTask parserTask = new ParserTask(); - - // Start parsing the places in JSON format - // Invokes the "doInBackground()" method of the class ParseTask - parserTask.execute(result); - } - } - - /** A class to parse the Geocoding Places in non-ui thread */ - class ParserTask extends AsyncTask>> { - - JSONObject jObject; - - // Invoked by execute() method of this object - @Override - protected List> doInBackground(String... jsonData) { - - List> places = null; - GeocodeJSONParser parser = new GeocodeJSONParser(); - - try { - jObject = new JSONObject(jsonData[0]); - - /** Getting the parsed data as a an ArrayList */ - places = parser.parse(jObject); - - } catch (Exception e) { - Log.d("Exception", e.toString()); - } - return places; - } - } - -} diff --git a/app/src/main/java/org/deke/risk/riskahead/fragments/UserInfo.java b/app/src/main/java/org/deke/risk/riskahead/fragments/UserInfo.java deleted file mode 100644 index d5c84c8..0000000 --- a/app/src/main/java/org/deke/risk/riskahead/fragments/UserInfo.java +++ /dev/null @@ -1,128 +0,0 @@ -package org.deke.risk.riskahead.fragments; - -import android.app.Activity; -import android.content.Intent; -import android.net.Uri; -import android.os.Bundle; -import android.support.v4.app.Fragment; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.Button; -import android.widget.TextView; - -import org.deke.risk.riskahead.LoginActivity; -import org.deke.risk.riskahead.R; -import org.deke.risk.riskahead.helper.SQLiteHandler; -import org.deke.risk.riskahead.helper.SessionManager; - -import java.util.HashMap; - -public class UserInfo extends Fragment { - private TextView txtName; - private TextView txtTest; - private TextView txtEmail; - private Button btnLogout; - Activity mActivity; - private SQLiteHandler db; - public HashMap user; - private OnFragmentInteractionListener mListener; - private SessionManager session; - - public final static String EXTRA_MESSAGE = "com.mycompany.myfirstapp.MESSAGE"; - - - public static UserInfo newInstance(String param1, String param2) { - UserInfo fragment = new UserInfo(); - Bundle args = new Bundle(); - - fragment.setArguments(args); - return fragment; - } - - public UserInfo() { - // Required empty public constructor - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_user_info, container, false); - session = new SessionManager(getActivity().getApplicationContext()); - - txtTest = (TextView) view.findViewById(R.id.test); - txtName = (TextView) view.findViewById(R.id.name); - txtEmail = (TextView) view.findViewById(R.id.email); - btnLogout = (Button) view.findViewById(R.id.btnLogout); - - // Logout button click event - btnLogout.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - logoutUser(); - } - }); - - // SqLite database handler - db = new SQLiteHandler(getActivity().getApplicationContext()); - // Fetching user details from sqlite - user = db.getUserDetails(); - txtName.setText(user.get("username")); - txtEmail.setText(user.get("email")); - - - return view; - } - - - @Override - public void onAttach(Activity activity) { - super.onAttach(activity); - mActivity = activity; - try { - mListener = (OnFragmentInteractionListener) activity; - } catch (ClassCastException e) { - throw new ClassCastException(activity.toString() - + " must implement OnFragmentInteractionListener"); - } - } - - @Override - public void onDetach() { - super.onDetach(); - mListener = null; - } - - /** - * This interface must be implemented by activities that contain this - * fragment to allow an interaction in this fragment to be communicated - * to the activity and potentially other fragments contained in that - * activity. - *

- * See the Android Training lesson Communicating with Other Fragments for more information. - */ - public interface OnFragmentInteractionListener { - public void onFragmentInteraction(Uri uri); - } - - /** - * Logging out the user. Will set isLoggedIn flag to false in shared - * preferences Clears the user data from sqlite users table - * */ - public void logoutUser() { - session.setLogin(false); - db.deleteUsers(); - - // Launching the login activity - Intent intent = new Intent(getActivity(), LoginActivity.class); - intent.putExtra(EXTRA_MESSAGE, "login"); - startActivity(intent); - getActivity().finish(); - } -} diff --git a/app/src/main/java/org/deke/risk/riskahead/helper/BaseActivity.java b/app/src/main/java/org/deke/risk/riskahead/helper/BaseActivity.java new file mode 100644 index 0000000..25ba705 --- /dev/null +++ b/app/src/main/java/org/deke/risk/riskahead/helper/BaseActivity.java @@ -0,0 +1,215 @@ +package org.deke.risk.riskahead.helper; + +import android.content.Intent; +import android.content.res.Configuration; +import android.support.v4.view.MenuItemCompat; +import android.support.v4.widget.DrawerLayout; +import android.os.Bundle; +import android.support.v7.app.ActionBarDrawerToggle; +import android.support.v7.app.AppCompatActivity; +import android.support.v7.widget.ShareActionProvider; +import android.util.Log; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.ListView; + +import org.deke.risk.riskahead.LoginActivity; +import org.deke.risk.riskahead.MainActivity; +import org.deke.risk.riskahead.MapsActivity; +import org.deke.risk.riskahead.R; +import org.deke.risk.riskahead.UserConfigActivity; + +import java.util.HashMap; + +public abstract class BaseActivity extends AppCompatActivity { + + private ActionBarDrawerToggle mDrawerToggle; + private DrawerLayout mDrawerLayout; + private ListView mDrawerList; + private ArrayAdapter mAdapter; + ShareActionProvider mShareActionProvider; + private SQLiteHandler db; + private SessionManager session; + public HashMap user; + + public final static String EXTRA_MESSAGE = "com.mycompany.myfirstapp.MESSAGE"; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(getLayoutResourceId()); + + // SqLite database handler + db = new SQLiteHandler(getApplicationContext()); + + // session manager + session = new SessionManager(getApplicationContext()); + + if (!session.isLoggedIn()) { + logoutUser(); + } + + // Fetching user details from sqlite + user = db.getUserDetails(); + // Get the SearchView and set the searchable configuration + + mDrawerList = (ListView)findViewById(R.id.navList); + mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout); + + addDrawerItems(); + setupDrawer(); + + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + getSupportActionBar().setHomeButtonEnabled(true); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.menu_common, menu); + + // Access the Share Item defined in menu XML + MenuItem shareItem = menu.findItem(R.id.menu_item_share); + + // Access the object responsible for + // putting together the sharing submenu + if (shareItem != null) { + mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareItem); + } + + // Create an Intent to share your content + setShareIntent(); + getMenuInflater().inflate(R.menu.menu_login, menu); + + + + return true; + } + + private void setupDrawer() { + mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) { + + /** Called when a drawer has settled in a completely open state. */ + public void onDrawerOpened(View drawerView) { + super.onDrawerOpened(drawerView); + getSupportActionBar().setTitle("Navigate to..."); + invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() + } + + /** Called when a drawer has settled in a completely closed state. */ + public void onDrawerClosed(View view) { + super.onDrawerClosed(view); + getSupportActionBar().setTitle(getActivityName()); + invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() + } + }; + + mDrawerToggle.setDrawerIndicatorEnabled(true); + mDrawerLayout.setDrawerListener(mDrawerToggle); + } + + private void addDrawerItems() { + String[] osArray = { "Start", "Maps", "Profile", "Settings", "Subscription", "Logout" }; + mAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, osArray); + mDrawerList.setAdapter(mAdapter); + + mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView parent, View view, final int position, long id) { + mDrawerLayout.setDrawerListener(new DrawerLayout.SimpleDrawerListener() { + @Override + public void onDrawerClosed(View drawerView) { + super.onDrawerClosed(drawerView); + Intent intent; + switch (position) { + case 0: + intent = new Intent(getApplicationContext(), MainActivity.class); + startActivity(intent); + break; + case 1: + intent = new Intent(getApplicationContext(), MapsActivity.class); + startActivity(intent); + break; + case 2: + intent = new Intent(getApplicationContext(), UserConfigActivity.class); + startActivity(intent); + break; + default: + Log.d("switch: ", Integer.toString(position)); + break; + } + } + }); + mDrawerLayout.closeDrawer(mDrawerList); + } + }); + } + + @Override + protected void onPostCreate(Bundle savedInstanceState) { + super.onPostCreate(savedInstanceState); + mDrawerToggle.syncState(); + } + + @Override + public void onConfigurationChanged(Configuration newConfig) { + super.onConfigurationChanged(newConfig); + mDrawerToggle.onConfigurationChanged(newConfig); + } + + private void setShareIntent() { + if (mShareActionProvider != null) { + + // create an Intent with the contents of the TextView + Intent shareIntent = new Intent(Intent.ACTION_SEND); + shareIntent.setType("text/plain"); + shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Android Development"); + shareIntent.putExtra(Intent.EXTRA_TEXT, "Ich empfehle RiskAhead!"); + + // Make sure the provider knows + // it should work with that Intent + mShareActionProvider.setShareIntent(shareIntent); + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + + //noinspection SimplifiableIfStatement + if (id == R.id.action_settings) { + return true; + } + + // Activate the navigation drawer toggle + if (mDrawerToggle.onOptionsItemSelected(item)) { + return true; + } + + return super.onOptionsItemSelected(item); + } + + /** + * Logging out the user. Will set isLoggedIn flag to false in shared + * preferences Clears the user data from sqlite users table + * */ + public void logoutUser() { + session.setLogin(false); + db.deleteUsers(); + + // Launching the login activity + Intent intent = new Intent(this, LoginActivity.class); + intent.putExtra(EXTRA_MESSAGE, "login"); + startActivity(intent); + finish(); + } + + protected abstract int getLayoutResourceId(); + + protected abstract String getActivityName(); +} diff --git a/app/src/main/java/org/deke/risk/riskahead/helper/GeocodeJSONParser.java b/app/src/main/java/org/deke/risk/riskahead/helper/PlaceJSONParser.java similarity index 61% rename from app/src/main/java/org/deke/risk/riskahead/helper/GeocodeJSONParser.java rename to app/src/main/java/org/deke/risk/riskahead/helper/PlaceJSONParser.java index 0bea48a..91e784f 100644 --- a/app/src/main/java/org/deke/risk/riskahead/helper/GeocodeJSONParser.java +++ b/app/src/main/java/org/deke/risk/riskahead/helper/PlaceJSONParser.java @@ -1,17 +1,14 @@ package org.deke.risk.riskahead.helper; -/** - * Created by Dennis on 18.08.2015. - */ -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; + import java.util.ArrayList; + import java.util.HashMap; + import java.util.List; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; + import org.json.JSONArray; + import org.json.JSONException; + import org.json.JSONObject; -public class GeocodeJSONParser { +public class PlaceJSONParser { /** Receives a JSONObject and returns a list */ public List> parse(JSONObject jObject){ @@ -19,7 +16,7 @@ public class GeocodeJSONParser { JSONArray jPlaces = null; try { /** Retrieves all the elements in the 'places' array */ - jPlaces = jObject.getJSONArray("results"); + jPlaces = jObject.getJSONArray("predictions"); } catch (JSONException e) { e.printStackTrace(); } @@ -53,24 +50,22 @@ public class GeocodeJSONParser { private HashMap getPlace(JSONObject jPlace){ HashMap place = new HashMap(); - String formatted_address = "-NA-"; - String lat=""; - String lng=""; + + String id=""; + String reference=""; + String description=""; try { - // Extracting formatted address, if available - if(!jPlace.isNull("formatted_address")){ - formatted_address = jPlace.getString("formatted_address"); - } - lat = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat"); - lng = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng"); + description = jPlace.getString("description"); + id = jPlace.getString("id"); + reference = jPlace.getString("reference"); - place.put("formatted_address", formatted_address); - place.put("lat", lat); - place.put("lng", lng); + place.put("description", description); + place.put("_id",id); + place.put("reference",reference); - }catch (JSONException e) { + } catch (JSONException e) { e.printStackTrace(); } return place; diff --git a/app/src/main/java/org/deke/risk/riskahead/helper/PlaceJSONParserDetail.java b/app/src/main/java/org/deke/risk/riskahead/helper/PlaceJSONParserDetail.java new file mode 100644 index 0000000..9051958 --- /dev/null +++ b/app/src/main/java/org/deke/risk/riskahead/helper/PlaceJSONParserDetail.java @@ -0,0 +1,41 @@ +package org.deke.risk.riskahead.helper; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import org.json.JSONException; +import org.json.JSONObject; + +public class PlaceJSONParserDetail { + + /** Receives a JSONObject and returns a list */ + public List> parse(JSONObject jObject){ + + Double lat = Double.valueOf(0); + Double lng = Double.valueOf(0); + String formattedAddress = ""; + + HashMap hm = new HashMap(); + List> list = new ArrayList>(); + + try { + lat = (Double)jObject.getJSONObject("result").getJSONObject("geometry").getJSONObject("location").get("lat"); + lng = (Double)jObject.getJSONObject("result").getJSONObject("geometry").getJSONObject("location").get("lng"); + formattedAddress = (String) jObject.getJSONObject("result").get("formatted_address"); + + } catch (JSONException e) { + e.printStackTrace(); + }catch(Exception e){ + e.printStackTrace(); + } + + hm.put("lat", Double.toString(lat)); + hm.put("lng", Double.toString(lng)); + hm.put("formatted_address",formattedAddress); + + list.add(hm); + + return list; + } +} diff --git a/app/src/main/java/org/deke/risk/riskahead/helper/PlaceProvider.java b/app/src/main/java/org/deke/risk/riskahead/helper/PlaceProvider.java new file mode 100644 index 0000000..f51db8c --- /dev/null +++ b/app/src/main/java/org/deke/risk/riskahead/helper/PlaceProvider.java @@ -0,0 +1,310 @@ +package org.deke.risk.riskahead.helper; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.util.HashMap; +import java.util.List; + +import org.json.JSONException; +import org.json.JSONObject; + +import android.app.SearchManager; +import android.content.ContentProvider; +import android.content.ContentValues; +import android.content.UriMatcher; +import android.database.Cursor; +import android.database.MatrixCursor; +import android.net.Uri; +import android.util.Log; + +public class PlaceProvider extends ContentProvider { + + public static final String AUTHORITY = "org.deke.risk.riskahead.helper.PlaceProvider"; + + public static final Uri SEARCH_URI = Uri.parse("content://"+AUTHORITY+"/search"); + + public static final Uri DETAILS_URI = Uri.parse("content://"+AUTHORITY+"/details"); + + private static final int SEARCH = 1; + private static final int SUGGESTIONS = 2; + private static final int DETAILS = 3; + + // Obtain browser key from https://code.google.com/apis/console + String mKey = "key=AIzaSyALm-1lEf5xualfyHdmNEdAsXlbwOQhbI8"; + + // Defines a set of uris allowed with this content provider + private static final UriMatcher mUriMatcher = buildUriMatcher(); + + private static UriMatcher buildUriMatcher() { + + UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); + + // URI for "Go" button + uriMatcher.addURI(AUTHORITY, "search", SEARCH ); + + // URI for suggestions in Search Dialog + uriMatcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY,SUGGESTIONS); + + // URI for Details + uriMatcher.addURI(AUTHORITY, "details",DETAILS); + + return uriMatcher; + } + + @Override + public Cursor query(Uri uri, String[] projection, String selection, + String[] selectionArgs, String sortOrder) { + Cursor c = null; + + PlaceJSONParser parser = new PlaceJSONParser(); + PlaceJSONParserDetail detailsParser = new PlaceJSONParserDetail(); + + String jsonString = ""; + String jsonPlaceDetails = ""; + + List> list = null; + List> detailsList = null; + + MatrixCursor mCursor = null; + + switch(mUriMatcher.match(uri)){ + case SEARCH: + // Defining a cursor object with columns description, lat and lng + mCursor = new MatrixCursor(new String[] { "description","lat","lng" }); + + // Create a parser object to parse places in JSON format + parser = new PlaceJSONParser(); + + // Create a parser object to parse place details in JSON format + detailsParser = new PlaceJSONParserDetail(); + + // Get Places from Google Places API + jsonString = getPlaces(selectionArgs); + try { + // Parse the places ( JSON => List ) + list = parser.parse(new JSONObject(jsonString)); + + // Finding latitude and longitude for each places using Google Places Details API + for(int i=0;i hMap = (HashMap) list.get(i); + + detailsParser =new PlaceJSONParserDetail(); + + // Get Place details + jsonPlaceDetails = getPlaceDetails(hMap.get("reference")); + + // Parse the details ( JSON => List ) + detailsList = detailsParser.parse(new JSONObject(jsonPlaceDetails)); + + // Creating cursor object with places + for(int j=0;j hMapDetails = detailsList.get(j); + + // Adding place details to cursor + mCursor.addRow(new String[]{ hMap.get("description") , hMapDetails.get("lat") , hMapDetails.get("lng") }); + } + + } + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + c = mCursor; + break; + + case SUGGESTIONS : + + // Defining a cursor object with columns id, SUGGEST_COLUMN_TEXT_1, SUGGEST_COLUMN_INTENT_EXTRA_DATA + mCursor = new MatrixCursor(new String[] { "_id", SearchManager.SUGGEST_COLUMN_TEXT_1, SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA } ); + + // Creating a parser object to parse places in JSON format + parser = new PlaceJSONParser(); + + // Get Places from Google Places API + jsonString = getPlaces(selectionArgs); + + try { + // Parse the places ( JSON => List ) + list = parser.parse(new JSONObject(jsonString)); + + // Creating cursor object with places + for(int i=0;i hMap = (HashMap) list.get(i); + + // Adding place details to cursor + mCursor.addRow(new String[] { Integer.toString(i), hMap.get("description"), hMap.get("reference") }); + } + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + c = mCursor; + break; + + case DETAILS : + // Defining a cursor object with columns description, lat and lng + mCursor = new MatrixCursor(new String[] { "description","lat","lng" }); + + detailsParser = new PlaceJSONParserDetail(); + jsonPlaceDetails = getPlaceDetails(selectionArgs[0]); + try { + detailsList = detailsParser.parse(new JSONObject(jsonPlaceDetails)); + } catch (JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + for(int j=0;j hMapDetails = detailsList.get(j); + mCursor.addRow(new String[]{ hMapDetails.get("formatted_address") , hMapDetails.get("lat") , hMapDetails.get("lng") }); + } + c = mCursor; + break; + } + return c; + } + + @Override + public int delete(Uri uri, String selection, String[] selectionArgs) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public String getType(Uri uri) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Uri insert(Uri uri, ContentValues values) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean onCreate() { + // TODO Auto-generated method stub + return false; + } + + @Override + public int update(Uri uri, ContentValues values, String selection, + String[] selectionArgs) { + // TODO Auto-generated method stub + return 0; + } + + /** 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(); + + br.close(); + + }catch(Exception e){ + Log.d("Exception downloading", e.toString()); + }finally{ + iStream.close(); + urlConnection.disconnect(); + } + return data; + } + + private String getPlaceDetailsUrl(String ref){ + + // reference of place + String reference = "reference="+ref; + + // Sensor enabled + String sensor = "sensor=false"; + + // Building the parameters to the web service + String parameters = reference+"&"+sensor+"&"+mKey; + + // Output format + String output = "json"; + + // Building the url to the web service + String url = "https://maps.googleapis.com/maps/api/place/details/"+output+"?"+parameters; + + return url; + } + + private String getPlacesUrl(String qry){ + + try { + qry = "input=" + URLEncoder.encode(qry, "utf-8"); + } catch (UnsupportedEncodingException e1) { + e1.printStackTrace(); + } + + // Sensor enabled + String sensor = "sensor=false"; + + // place type to be searched + String types = "types=geocode"; + + // Building the parameters to the web service + String parameters = qry+"&"+types+"&"+sensor+"&"+mKey; + + // Output format + String output = "json"; + // Building the url to the web service + String url = "https://maps.googleapis.com/maps/api/place/autocomplete/"+output+"?"+parameters; + return url; + } + + private String getPlaces(String[] params){ + // For storing data from web service + String data = ""; + String url = getPlacesUrl(params[0]); + try{ + // Fetching the data from web service in background + data = downloadUrl(url); + }catch(Exception e){ + Log.d("Background Task",e.toString()); + } + return data; + } + + private String getPlaceDetails(String reference){ + String data = ""; + String url = getPlaceDetailsUrl(reference); + try { + data = downloadUrl(url); + } catch (IOException e) { + e.printStackTrace(); + } + return data; + } +} diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml index 3a1e7db..398a0e8 100644 --- a/app/src/main/res/layout/activity_main.xml +++ b/app/src/main/res/layout/activity_main.xml @@ -6,12 +6,21 @@ android:layout_height="match_parent" tools:context=".MainActivity"> - + android:layout_height="match_parent" > + + + + + + + + + + + diff --git a/app/src/main/res/layout/fragment_user_info.xml b/app/src/main/res/layout/activity_user_config.xml similarity index 73% rename from app/src/main/res/layout/fragment_user_info.xml rename to app/src/main/res/layout/activity_user_config.xml index e05ca09..8a179ea 100644 --- a/app/src/main/res/layout/fragment_user_info.xml +++ b/app/src/main/res/layout/activity_user_config.xml @@ -1,8 +1,13 @@ - + - + + + + diff --git a/app/src/main/res/layout/fragment_map.xml b/app/src/main/res/layout/fragment_map.xml deleted file mode 100644 index ca28263..0000000 --- a/app/src/main/res/layout/fragment_map.xml +++ /dev/null @@ -1,29 +0,0 @@ - -