commit 5fb9f53be34d79f38f5dc7d84a6f3b644c553508 Author: Dennis Thießen Date: Thu Aug 20 21:49:55 2015 +0200 DT @20.08.2015: First Commit diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build diff --git a/app/app.iml b/app/app.iml new file mode 100644 index 0000000..4bd9dc2 --- /dev/null +++ b/app/app.iml @@ -0,0 +1,152 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/build.gradle b/app/build.gradle new file mode 100644 index 0000000..266c1c0 --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,49 @@ +buildscript { + repositories { + maven { url 'https://maven.fabric.io/public' } + } + + dependencies { + classpath 'io.fabric.tools:gradle:1.+' + } +} +apply plugin: 'com.android.application' +apply plugin: 'io.fabric' +apply plugin: 'com.google.gms.google-services' + +android { + compileSdkVersion 22 + buildToolsVersion "22.0.1" + + defaultConfig { + applicationId "org.deke.risk.riskahead" + minSdkVersion 15 + targetSdkVersion 22 + versionCode 1 + versionName "1.0" + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +repositories { + jcenter() + maven { url 'https://maven.fabric.io/public' } +} + +dependencies { + compile fileTree(dir: 'libs', include: ['*.jar']) + compile 'com.android.support:appcompat-v7:22.2.0' + compile 'com.google.android.gms:play-services:7.5.0' + compile 'com.facebook.android:facebook-android-sdk:4.1.0' + compile 'com.beardedhen:androidbootstrap:+' + compile 'com.mcxiaoke.volley:library:1.0.+' + compile('com.twitter.sdk.android:twitter-core:1.4.1@aar') { + transitive = true; + } + +} diff --git a/app/fabric.properties b/app/fabric.properties new file mode 100644 index 0000000..3272e9b --- /dev/null +++ b/app/fabric.properties @@ -0,0 +1,4 @@ +#Contains API Secret used to validate your application. Commit to internal source control; avoid making secret public. +#Sat Jul 18 18:32:41 CEST 2015 +apiSecret=c93664ec6681827d89cba7fe0f675194c2d647258169cc7912aa627437319d09 +twitterPluginId=55aa7fa76bfe67e9d100a86c diff --git a/app/google-services.json b/app/google-services.json new file mode 100644 index 0000000..42f73ec --- /dev/null +++ b/app/google-services.json @@ -0,0 +1 @@ +{"project_info":{"project_id":"riskahead-61dff","project_number":"498007911848","name":"RiskAhead"},"client":[{"client_info":{"client_id":"android:org.deke.risk.riskahead","client_type":1,"android_client_info":{"package_name":"org.deke.risk.riskahead"}},"oauth_client":[{"client_id":"498007911848-ppr7ct4oa2gs5jjnmrnlnutgui8m365n.apps.googleusercontent.com","client_type":1,"android_info":{"package_name":"org.deke.risk.riskahead","certificate_hash":"4b6c989e6c0d6824f5a2d7b1a10ff36560c3397f"}}],"services":{"analytics_service":{"status":1},"cloud_messaging_service":{"status":1,"apns_config":[]},"appinvite_service":{"status":1,"other_platform_oauth_client":[]},"google_signin_service":{"status":2},"ads_service":{"status":1}}}]} \ No newline at end of file diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..622f32f --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,17 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in C:\Users\Dennis\AppData\Local\Android\sdk/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} diff --git a/app/src/androidTest/java/org/deke/risk/riskahead/ApplicationTest.java b/app/src/androidTest/java/org/deke/risk/riskahead/ApplicationTest.java new file mode 100644 index 0000000..a4884e9 --- /dev/null +++ b/app/src/androidTest/java/org/deke/risk/riskahead/ApplicationTest.java @@ -0,0 +1,13 @@ +package org.deke.risk.riskahead; + +import android.app.Application; +import android.test.ApplicationTestCase; + +/** + * Testing Fundamentals + */ +public class ApplicationTest extends ApplicationTestCase { + public ApplicationTest() { + super(Application.class); + } +} \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..4242adb --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/ic_launcher-web.png b/app/src/main/ic_launcher-web.png new file mode 100644 index 0000000..23db85b Binary files /dev/null and b/app/src/main/ic_launcher-web.png differ diff --git a/app/src/main/java/org/deke/risk/riskahead/AppController.java b/app/src/main/java/org/deke/risk/riskahead/AppController.java new file mode 100644 index 0000000..d4a00b9 --- /dev/null +++ b/app/src/main/java/org/deke/risk/riskahead/AppController.java @@ -0,0 +1,51 @@ +package org.deke.risk.riskahead; + +import android.app.Application; +import android.text.TextUtils; + +import com.android.volley.Request; +import com.android.volley.RequestQueue; +import com.android.volley.toolbox.Volley; + +public class AppController extends Application { + + public static final String TAG = AppController.class.getSimpleName(); + + private RequestQueue mRequestQueue; + + private static AppController mInstance; + + @Override + public void onCreate() { + super.onCreate(); + mInstance = this; + } + + public static synchronized AppController getInstance() { + return mInstance; + } + + public RequestQueue getRequestQueue() { + if (mRequestQueue == null) { + mRequestQueue = Volley.newRequestQueue(getApplicationContext()); + } + + return mRequestQueue; + } + + public void addToRequestQueue(Request req, String tag) { + req.setTag(TextUtils.isEmpty(tag) ? TAG : tag); + getRequestQueue().add(req); + } + + public void addToRequestQueue(Request req) { + req.setTag(TAG); + getRequestQueue().add(req); + } + + public void cancelPendingRequests(Object tag) { + if (mRequestQueue != null) { + mRequestQueue.cancelAll(tag); + } + } +} diff --git a/app/src/main/java/org/deke/risk/riskahead/LoginActivity.java b/app/src/main/java/org/deke/risk/riskahead/LoginActivity.java new file mode 100644 index 0000000..677d547 --- /dev/null +++ b/app/src/main/java/org/deke/risk/riskahead/LoginActivity.java @@ -0,0 +1,454 @@ +package org.deke.risk.riskahead; + +import android.app.ProgressDialog; +import android.support.v4.app.FragmentManager; +import android.support.v4.app.FragmentTransaction; +import android.content.Intent; +import android.net.Uri; +import android.os.Bundle; +import android.support.v7.app.AppCompatActivity; +import android.util.Log; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.Button; +import android.widget.TextView; +import android.widget.Toast; + +import com.facebook.CallbackManager; + +import org.deke.risk.riskahead.fragments.FacebookButtonFragment; +import org.deke.risk.riskahead.fragments.GooglePlusButtonFragment; +import org.deke.risk.riskahead.fragments.TwitterButtonFragment; +import org.deke.risk.riskahead.helper.AppConfig; +import org.deke.risk.riskahead.helper.SQLiteHandler; +import org.deke.risk.riskahead.helper.SessionManager; +import org.json.JSONException; +import org.json.JSONObject; + +import com.android.volley.Request.Method; +import com.android.volley.Response; +import com.android.volley.VolleyError; +import com.android.volley.toolbox.StringRequest; + +import java.util.HashMap; +import java.util.Map; + +public class LoginActivity extends AppCompatActivity implements FacebookButtonFragment.OnFragmentInteractionListener, GooglePlusButtonFragment.OnFragmentInteractionListener, TwitterButtonFragment.OnFragmentInteractionListener{ + + private static final String TAG = LoginActivity.class.getSimpleName(); + private CallbackManager callbackManager; + private Button btnSignUpMY; + private String inputMsg; + private TextView input_email; + private TextView input_full_name; + private TextView input_password; + + private ProgressDialog pDialog; + private SessionManager session; + public final static String EXTRA_MESSAGE = "com.mycompany.myfirstapp.MESSAGE"; + private SQLiteHandler db; + + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + Intent intent = getIntent(); + inputMsg = intent.getStringExtra(StartActivity.EXTRA_MESSAGE); + callbackManager = CallbackManager.Factory.create(); + + // Session manager + session = new SessionManager(getApplicationContext()); + + // Progress dialog + pDialog = new ProgressDialog(this); + pDialog.setCancelable(false); + + // SQLite database handler + db = new SQLiteHandler(getApplicationContext()); + + // Check if user is already logged in or not + if (session.isLoggedIn()) { + // User is already logged in. Take him to main activity + intent = new Intent(LoginActivity.this,MainActivity.class); + startActivity(intent); + finish(); + } + + if(inputMsg.equals("login")){ + setContentView(R.layout.activity_login); + }else if(inputMsg.equals("register")){ + setContentView(R.layout.activity_register); + input_full_name = (TextView) findViewById(R.id.input_full_name); + } + + input_email = (TextView) findViewById(R.id.input_email); + input_password = (TextView) findViewById(R.id.input_password); + + FragmentManager fragmentManager = getSupportFragmentManager(); + FacebookButtonFragment fragmentFB = new FacebookButtonFragment(); + GooglePlusButtonFragment fragmentGP = new GooglePlusButtonFragment(); + + FragmentTransaction transaction = fragmentManager.beginTransaction(); + transaction.add(R.id.fragment_btn_gp, fragmentGP); + transaction.commit(); + + initMySigninButton(); + } + + private void initMySigninButton() { + btnSignUpMY = (Button) findViewById(R.id.btnSignUp); + btnSignUpMY.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (v.getId() == R.id.btnSignUp) { + String email = input_email.getText().toString(); + String password = input_password.getText().toString(); + + if (inputMsg.equals("login")) { + if (isEmpty(input_email) || isEmpty(input_password)) { + showMessage("Please enter all fields before logging in"); + } else { + checkLogin(email, password); + } + } else if (inputMsg.equals("register")) { + String name = input_full_name.getText().toString(); + if (isEmpty(input_email) || isEmpty(input_password) || isEmpty(input_full_name)) { + showMessage("Please enter all fields before registration"); + } else { + registerUser(name, email, password); + } + } + } + } + }); + } + + private boolean isEmpty(TextView etText) { + return etText.getText().toString().trim().length() == 0; + } + + public void showMessage(String statusText){ + Toast.makeText(this, statusText, Toast.LENGTH_LONG).show(); + } + + + public void onFragmentInteraction(Uri uri){ + //you can leave it empty + } + + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.menu_login, menu); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int id = item.getItemId(); + + if (id == R.id.action_settings) { + return true; + } + + return super.onOptionsItemSelected(item); + } + + public void handleSocialMediaLogin(final String key, final String providerType, final String username, final String email){ + if(session.isLoggedIn()){ + Intent intent = new Intent( + LoginActivity.this, + MainActivity.class); + intent.putExtra(EXTRA_MESSAGE, "Social Media Login"); + startActivity(intent); + finish(); + } + + // Tag used to cancel the request + String tag_string_req = "sociallogin"; + db.deleteUsers(); + pDialog.setMessage("Social Media Login ..."); + showDialog(); + + StringRequest strReq = new StringRequest(Method.POST, + AppConfig.URL_REGISTER, new Response.Listener() { + + @Override + public void onResponse(String response) { + Log.d(TAG, "Social Media Login Response: " + response.toString()); + hideDialog(); + + try { + JSONObject jObj = new JSONObject(response); + boolean error = jObj.getBoolean("error"); + if (!error) { + // user successfully logged in + // Create login session + session.setLogin(true); + + // User successfully stored in MySQL + // Now store the user in sqlite + String uid = jObj.getString("uid"); + + JSONObject user = jObj.getJSONObject("user"); + String username = user.getString("username"); + String name = user.getString("name"); + String surname = user.getString("surname"); + String email = user.getString("email"); + String status = user.getString("status"); + String created_at = user.getString("created_at"); + String updated_at = user.getString("updated_at"); + String providerType = user.getString("providerType"); + + // Inserting row in users table + db.addUser(uid, username, name, surname, email, status, providerType, created_at, updated_at); + // Launch login activity + Intent intent = new Intent( + LoginActivity.this, + MainActivity.class); + intent.putExtra(EXTRA_MESSAGE, "Social Media Login"); + startActivity(intent); + finish(); + } else { + + // Error occurred in registration. Get the error + // message + String errorMsg = jObj.getString("error_msg"); + Toast.makeText(getApplicationContext(), + errorMsg, Toast.LENGTH_LONG).show(); + } + } catch (JSONException e) { + e.printStackTrace(); + } + + } + }, new Response.ErrorListener() { + + @Override + public void onErrorResponse(VolleyError error) { + Log.e(TAG, "Registration Error: " + error.getMessage()); + Toast.makeText(getApplicationContext(), + error.getMessage(), Toast.LENGTH_LONG).show(); + hideDialog(); + } + }) { + + @Override + protected Map getParams() { + // Posting params to register url + Map params = new HashMap(); + params.put("tag", "sociallogin"); + params.put("key", key); + params.put("providerType", providerType); + params.put("username", username); + params.put("email",email); + + return params; + } + + }; + + // Adding request to request queue + AppController.getInstance().addToRequestQueue(strReq, tag_string_req); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + if (requestCode == GooglePlusButtonFragment.RC_SIGN_IN) { + GooglePlusButtonFragment fragment = (GooglePlusButtonFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_btn_gp); + fragment.onActivityResult(requestCode, resultCode, data); + } else { + super.onActivityResult(requestCode, resultCode, data); + } + + TwitterButtonFragment twitter_fragment = (TwitterButtonFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_btn_tw); + if (twitter_fragment != null) { + twitter_fragment.onActivityResult(requestCode, resultCode, data); + } + } + + /** + * function to verify login details in mysql db + * */ + private void checkLogin(final String email, final String password) { + // Tag used to cancel the request + String tag_string_req = "req_login"; + db.deleteUsers(); + pDialog.setMessage("Logging in ..."); + showDialog(); + + StringRequest strReq = new StringRequest(Method.POST, AppConfig.URL_REGISTER, new Response.Listener() { + + @Override + public void onResponse(String response) { + Log.d(TAG, "Login Response: " + response.toString()); + hideDialog(); + + try { + JSONObject jObj = new JSONObject(response); + boolean error = jObj.getBoolean("error"); + + // Check for error node in json + if (!error) { + // user successfully logged in + // Create login session + session.setLogin(true); + + // Now store the user in sqlite + String uid = jObj.getString("uid"); + + JSONObject user = jObj.getJSONObject("user"); + String username = user.getString("username"); + String name = user.getString("name"); + String surname = user.getString("surname"); + String email = user.getString("email"); + String status = user.getString("status"); + String created_at = user.getString("created_at"); + String updated_at = user.getString("updated_at"); + String providerType = "local"; + + // Inserting row in users table + db.addUser(uid, username, name, surname, email, status, providerType, created_at, updated_at); + + // Launch main activity + Intent intent = new Intent(LoginActivity.this, MainActivity.class); + startActivity(intent); + finish(); + } else { + // Error in login. Get the error message + String errorMsg = jObj.getString("error_msg"); + Toast.makeText(getApplicationContext(),errorMsg, Toast.LENGTH_LONG).show(); + } + } catch (JSONException e) { + // JSON error + e.printStackTrace(); + } + + } + }, new Response.ErrorListener() { + + @Override + public void onErrorResponse(VolleyError error) { + Log.e(TAG, "Login Error: " + error.getMessage()); + Toast.makeText(getApplicationContext(), + error.getMessage(), Toast.LENGTH_LONG).show(); + hideDialog(); + } + }) { + + @Override + protected Map getParams() { + // Posting parameters to login url + Map params = new HashMap(); + params.put("tag", "login"); + params.put("email", email); + params.put("password", password); + + return params; + } + + }; + + // Adding request to request queue + AppController.getInstance().addToRequestQueue(strReq, tag_string_req); + } + + /** + * Function to store user in MySQL database will post params(tag, name,* email, password) to register url + * */ + private void registerUser(final String username, final String email,final String password) { + // Tag used to cancel the request + String tag_string_req = "req_register"; + db.deleteUsers(); + pDialog.setMessage("Registering ..."); + showDialog(); + + StringRequest strReq = new StringRequest(Method.POST, + AppConfig.URL_REGISTER, new Response.Listener() { + + @Override + public void onResponse(String response) { + Log.d(TAG, "Register Response: " + response.toString()); + hideDialog(); + + try { + JSONObject jObj = new JSONObject(response); + boolean error = jObj.getBoolean("error"); + if (!error) { + // User successfully stored in MySQL + // Now store the user in sqlite + String uid = jObj.getString("uid"); + + JSONObject user = jObj.getJSONObject("user"); + String username = user.getString("username"); + String name = user.getString("name"); + String surname = user.getString("surname"); + String email = user.getString("email"); + String status = user.getString("status"); + String created_at = user.getString("created_at"); + String updated_at = user.getString("updated_at"); + String providerType = "local"; + + // Inserting row in users table + db.addUser(uid, username, name, surname, email, status, providerType, created_at, updated_at); + // Launch login activity + Intent intent = new Intent( + LoginActivity.this, + LoginActivity.class); + intent.putExtra(EXTRA_MESSAGE, "login"); + startActivity(intent); + finish(); + } else { + + // Error occurred in registration. Get the error + // message + String errorMsg = jObj.getString("error_msg"); + Toast.makeText(getApplicationContext(), + errorMsg, Toast.LENGTH_LONG).show(); + } + } catch (JSONException e) { + e.printStackTrace(); + } + + } + }, new Response.ErrorListener() { + + @Override + public void onErrorResponse(VolleyError error) { + Log.e(TAG, "Registration Error: " + error.getMessage()); + Toast.makeText(getApplicationContext(), + error.getMessage(), Toast.LENGTH_LONG).show(); + hideDialog(); + } + }) { + + @Override + protected Map getParams() { + // Posting params to register url + Map params = new HashMap(); + params.put("tag", "register"); + params.put("username", username); + params.put("email", email); + params.put("password", password); + + return params; + } + + }; + + // Adding request to request queue + AppController.getInstance().addToRequestQueue(strReq, tag_string_req); + } + + private void showDialog() { + if (!pDialog.isShowing()) + pDialog.show(); + } + + private void hideDialog() { + if (pDialog.isShowing()) + pDialog.dismiss(); + } + +} diff --git a/app/src/main/java/org/deke/risk/riskahead/MainActivity.java b/app/src/main/java/org/deke/risk/riskahead/MainActivity.java new file mode 100644 index 0000000..086a2ac --- /dev/null +++ b/app/src/main/java/org/deke/risk/riskahead/MainActivity.java @@ -0,0 +1,219 @@ +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 java.util.HashMap; + + +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; + 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); + + 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(); + } + + @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(); + } +} diff --git a/app/src/main/java/org/deke/risk/riskahead/StartActivity.java b/app/src/main/java/org/deke/risk/riskahead/StartActivity.java new file mode 100644 index 0000000..c678db2 --- /dev/null +++ b/app/src/main/java/org/deke/risk/riskahead/StartActivity.java @@ -0,0 +1,82 @@ +package org.deke.risk.riskahead; + +import android.app.ProgressDialog; +import android.content.Intent; +import android.os.Bundle; +import android.support.v7.app.AppCompatActivity; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.Button; +import android.widget.TextView; +import android.widget.Toast; + +import org.deke.risk.riskahead.helper.SessionManager; + + +public class StartActivity extends AppCompatActivity { + + public final static String EXTRA_MESSAGE = "com.mycompany.myfirstapp.MESSAGE"; + + Button btnLogin; + Button btnRegister; + + private SessionManager session; + + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_start); + btnLogin = (Button) findViewById(R.id.btn_start_login); + btnRegister = (Button) findViewById(R.id.btn_start_register); + + // Session manager + session = new SessionManager(getApplicationContext()); + + // Check if user is already logged in or not + if (session.isLoggedIn()) { + // User is already logged in. Take him to main activity + Intent intent = new Intent(StartActivity.this, MainActivity.class); + startActivity(intent); + finish(); + } + } + + public void gotoLogin(View view) { + Intent intent = new Intent(this, LoginActivity.class); + intent.putExtra(EXTRA_MESSAGE, "login"); + startActivity(intent); + } + + public void gotoRegister(View view) { + Intent intent = new Intent(this, LoginActivity.class); + intent.putExtra(EXTRA_MESSAGE, "register"); + startActivity(intent); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.menu_start, menu); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int id = item.getItemId(); + + if (id == R.id.action_settings) { + return true; + } + + return super.onOptionsItemSelected(item); + } + + private boolean isEmpty(TextView etText) { + return etText.getText().toString().trim().length() == 0; + } + + public void showMessage(String statusText){ + Toast.makeText(this, statusText, Toast.LENGTH_LONG).show(); + } +} diff --git a/app/src/main/java/org/deke/risk/riskahead/fragments/FacebookButtonFragment.java b/app/src/main/java/org/deke/risk/riskahead/fragments/FacebookButtonFragment.java new file mode 100644 index 0000000..bb30e87 --- /dev/null +++ b/app/src/main/java/org/deke/risk/riskahead/fragments/FacebookButtonFragment.java @@ -0,0 +1,111 @@ +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.View.OnClickListener; +import android.view.ViewGroup; + +import com.beardedhen.androidbootstrap.BootstrapButton; +import com.facebook.CallbackManager; +import com.facebook.FacebookCallback; +import com.facebook.FacebookException; +import com.facebook.FacebookSdk; +import com.facebook.login.LoginManager; +import com.facebook.login.LoginResult; + +import org.deke.risk.riskahead.LoginActivity; +import org.deke.risk.riskahead.R; + +import java.util.Arrays; + +public class FacebookButtonFragment extends Fragment { + + private BootstrapButton btnLoginFB; + CallbackManager callbackManager; + OnFragmentInteractionListener mListener; + View view; + + public FacebookButtonFragment() { + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + } + + @Override + public void onActivityCreated(Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { + view = inflater.inflate(R.layout.fragment_facebook_button, container, false); + initFacebookButton(); + return view; + } + + @Override + public void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + callbackManager.onActivityResult(requestCode, resultCode, data); + } + + @Override + public void onAttach(Activity activity) { + super.onAttach(activity); + try { + mListener = (OnFragmentInteractionListener) activity; + } catch (ClassCastException e) { + throw new ClassCastException(activity.toString() + + " must implement OnFragmentInteractionListener"); + } + + FacebookSdk.sdkInitialize(activity.getApplicationContext()); + callbackManager = CallbackManager.Factory.create(); + } + + @Override + public void onDetach() { + super.onDetach(); + mListener = null; + } + + public interface OnFragmentInteractionListener { + public void onFragmentInteraction(Uri uri); + } + + private void initFacebookButton() { + btnLoginFB = (BootstrapButton) view.findViewById(R.id.btn_login_fb); + + btnLoginFB.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + LoginManager.getInstance().logInWithReadPermissions(getActivity(), Arrays.asList("public_profile", "user_friends")); + } + }); + + LoginManager.getInstance().registerCallback(callbackManager, + new FacebookCallback() { + @Override + public void onSuccess(LoginResult loginResult) { + ((LoginActivity) getActivity()).handleSocialMediaLogin(loginResult.getAccessToken().getToken(),"facebook",loginResult.getAccessToken().getUserId(),""); + } + + @Override + public void onCancel() { + ((LoginActivity) getActivity()).showMessage("Facebook LogIn canceled"); + } + + @Override + public void onError(FacebookException exception) { + ((LoginActivity) getActivity()).showMessage("Error while SignIn: ErrorMsg: " + exception.toString()); + } + }); + } +} diff --git a/app/src/main/java/org/deke/risk/riskahead/fragments/GooglePlusButtonFragment.java b/app/src/main/java/org/deke/risk/riskahead/fragments/GooglePlusButtonFragment.java new file mode 100644 index 0000000..e1bcd0a --- /dev/null +++ b/app/src/main/java/org/deke/risk/riskahead/fragments/GooglePlusButtonFragment.java @@ -0,0 +1,243 @@ +package org.deke.risk.riskahead.fragments; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.content.IntentSender; +import android.net.Uri; +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.TextView; +import android.widget.Toast; + +import com.beardedhen.androidbootstrap.BootstrapButton; +import com.google.android.gms.common.ConnectionResult; +import com.google.android.gms.common.GooglePlayServicesUtil; +import com.google.android.gms.common.SignInButton; +import com.google.android.gms.common.api.GoogleApiClient; +import com.google.android.gms.plus.Plus; +import com.google.android.gms.plus.model.people.Person; + +import org.deke.risk.riskahead.LoginActivity; +import org.deke.risk.riskahead.R; + +public class GooglePlusButtonFragment extends Fragment implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{ + + public static final int RC_SIGN_IN = 0; + + private static final String TAG = "MainActivity"; + + private static final int PROFILE_PIC_SIZE = 800; + + private GoogleApiClient mGoogleApiClient; + + private boolean mIntentInProgress; + + private boolean mSignInClicked; + + private ConnectionResult mConnectionResult; + + private BootstrapButton btnSignIn; + + private Context mContext; + private Activity mActivity; + + + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + mActivity = getActivity(); + mContext = getActivity().getApplicationContext(); + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { + View view = inflater.inflate(R.layout.fragment_googleplus_button,container, false); + + btnSignIn = (BootstrapButton) view.findViewById(R.id.btn_login_gp); + + mGoogleApiClient = new GoogleApiClient.Builder(view.getContext()) + .addConnectionCallbacks(this) + .addOnConnectionFailedListener(this).addApi(Plus.API) + .addScope(Plus.SCOPE_PLUS_LOGIN).build(); + + btnSignIn.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + performClickAction(); + } + }); + updateUI(mGoogleApiClient.isConnected()); + + return view; + } + + private void performClickAction() { + if(mGoogleApiClient.isConnected()){ + signOutFromGplus(); + }else{ + signInWithGplus(); + } + } + + @Override + public void onStart() { + super.onStart(); + mGoogleApiClient.connect(); + } + + @Override + public void onStop() { + super.onStop(); + if (mGoogleApiClient.isConnected()) { + mGoogleApiClient.disconnect(); + } + } + + @Override + public void onActivityResult(int requestCode, int responseCode, Intent intent) { + + if (requestCode == RC_SIGN_IN) { + if (responseCode != Activity.RESULT_OK) { + mSignInClicked = false; + } + + mIntentInProgress = false; + + if (!mGoogleApiClient.isConnecting()) { + mGoogleApiClient.connect(); + } + } + } + + @Override + public void onConnectionFailed(ConnectionResult result) { + if (!result.hasResolution()) { + GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), + mActivity, 0).show(); + Log.e(TAG, "" + result.getErrorCode()); + return; + } + + if (!mIntentInProgress) { + + mConnectionResult = result; + + if (mSignInClicked) { + + Log.e(TAG, "" + result.getErrorCode()); + resolveSignInError(); + } + } + + } + + @Override + public void onConnected(Bundle arg0) { + Person currentPerson = getProfileInformation(); + if(mSignInClicked) ((LoginActivity) getActivity()).handleSocialMediaLogin(currentPerson.getId(),"google",currentPerson.getDisplayName(),Plus.AccountApi.getAccountName(mGoogleApiClient)); + + mSignInClicked = false; + updateUI(true); + } + + @Override + public void onConnectionSuspended(int arg0) { + mGoogleApiClient.connect(); + updateUI(false); + + } + + private void updateUI(boolean isSignedIn) { + if (isSignedIn) { + this.btnSignIn.setText("Log out from G+"); + } else { + this.btnSignIn.setText("Google+"); + } + } + + /** + * Sign-in into google + * */ + private void signInWithGplus() { + if (!mGoogleApiClient.isConnecting()) { + mSignInClicked = true; + resolveSignInError(); + } + } + + /** + * Method to resolve any signin errors + * */ + private void resolveSignInError() { + if (mConnectionResult.hasResolution()) { + try { + mIntentInProgress = true; + mConnectionResult.startResolutionForResult(mActivity,RC_SIGN_IN); + } catch (IntentSender.SendIntentException e) { + mIntentInProgress = false; + mGoogleApiClient.connect(); + } + } + } + + /** + * Fetching user's information name, email, profile pic + * */ + private Person getProfileInformation() { + Person currentPerson = null; + try { + if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) { + currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient); + String personName = currentPerson.getDisplayName(); + String personPhotoUrl = currentPerson.getImage().getUrl(); + String personGooglePlusProfile = currentPerson.getUrl(); + String email = Plus.AccountApi.getAccountName(mGoogleApiClient); + + Log.e(TAG, "Name: " + personName + ", plusProfile: " + + personGooglePlusProfile + ", email: " + email + + ", Image: " + personPhotoUrl + " user id:" + + currentPerson.getId()); + + } else { + Toast.makeText(mContext, "Person information is null", + Toast.LENGTH_LONG).show(); + } + } catch (Exception e) { + e.printStackTrace(); + } + return currentPerson; + } + + /** + * Sign-out from google + * */ + private void signOutFromGplus() { + if (mGoogleApiClient.isConnected()) { + mGoogleApiClient.clearDefaultAccountAndReconnect(); + updateUI(false); + } + } + + + protected void setGooglePlusButtonText(SignInButton signInButton, String buttonText) { + for (int i = 0; i < signInButton.getChildCount(); i++) { + View v = signInButton.getChildAt(i); + if (v instanceof TextView) { + TextView mTextView = (TextView) v; + mTextView.setAllCaps(false); + mTextView.setText(buttonText); + return; + } + } + } + + public interface OnFragmentInteractionListener { + public void onFragmentInteraction(Uri uri); + } +} 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 new file mode 100644 index 0000000..c69403c --- /dev/null +++ b/app/src/main/java/org/deke/risk/riskahead/fragments/MapFragment.java @@ -0,0 +1,252 @@ +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/TwitterButtonFragment.java b/app/src/main/java/org/deke/risk/riskahead/fragments/TwitterButtonFragment.java new file mode 100644 index 0000000..339e584 --- /dev/null +++ b/app/src/main/java/org/deke/risk/riskahead/fragments/TwitterButtonFragment.java @@ -0,0 +1,153 @@ +package org.deke.risk.riskahead.fragments; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.net.Uri; +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.ImageButton; +import android.widget.Toast; + +import io.fabric.sdk.android.Fabric; + +import com.beardedhen.androidbootstrap.BootstrapButton; +import com.twitter.sdk.android.core.Callback; +import com.twitter.sdk.android.core.Result; +import com.twitter.sdk.android.core.TwitterAuthToken; +import com.twitter.sdk.android.core.TwitterCore; +import com.twitter.sdk.android.core.TwitterAuthConfig; +import com.twitter.sdk.android.core.TwitterException; +import com.twitter.sdk.android.core.TwitterSession; +import com.twitter.sdk.android.core.identity.TwitterAuthClient; + +import org.deke.risk.riskahead.LoginActivity; +import org.deke.risk.riskahead.R; + +public class TwitterButtonFragment extends Fragment { + + private BootstrapButton btnLoginTW; + private TwitterAuthClient client; + TwitterSession session = null; + Context mContext; + View view; + + // Note: Your consumer key and secret should be obfuscated in your source code before shipping. + private static final String TWITTER_KEY = "t8o7YBmzj3JMRf6RjIBg7hF20"; + private static final String TWITTER_SECRET = "HTt4mOqyDStslzq1RXHUqU6HcZpOuSuzC2iWH45MlUsZBRI704"; + + public TwitterButtonFragment() { + // Required empty public constructor + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + } + + @Override + public void onActivityCreated(Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { + mContext = getActivity().getApplicationContext(); + TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET); + Fabric.with(mContext, new TwitterCore(authConfig)); + client = new TwitterAuthClient(); + + view = inflater.inflate(R.layout.fragment_twitter_button, container, false); + btnLoginTW = (BootstrapButton) view.findViewById(R.id.btn_login_twitter); + + btnLoginTW.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + client.authorize(getActivity(), new Callback() { + @Override + public void success(Result result) { + Log.e("Debug", "onSuccess wird ausgeführt"); + session = result.data; + TwitterAuthToken authToken = session.getAuthToken(); + String token = authToken.token; + String secret = authToken.secret; + + ((LoginActivity) getActivity()).handleSocialMediaLogin((Long.toString(session.getUserId())),"twitter",session.getUserName(),""); + } + + @Override + public void failure(TwitterException exception) { + Log.e("Debug", "onFailure wird ausgeführt"); + showMessage("Twitter Login failed with exception " + exception.getMessage().toString()); + } + }); + } + }); + + //TO-DO + if(isAuthed()){ + // log out + }else{ + // log in + } + + + return view; + } + + private void setUpSignOut() { + btnLoginTW.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + TwitterCore.getInstance().getSessionManager().clearActiveSession(); + + Toast.makeText(mContext, "All accounts are cleared",Toast.LENGTH_SHORT).show(); + } + }); + } + + private boolean isAuthed() { + final TwitterSession session = TwitterCore.getInstance().getSessionManager().getActiveSession(); + return session != null && session.getAuthToken() != null; + } + + public void showMessage(String statusText){ + Toast.makeText(mContext,statusText,Toast.LENGTH_LONG).show(); + } + + @Override + public void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + client.onActivityResult(requestCode, resultCode, data); + } + + @Override + public void onResume() { + super.onResume(); + } + + @Override + public void onDestroy() { + super.onDestroy(); + } + + @Override + public void onAttach(Activity activity) { + super.onAttach(activity); + } + + @Override + public void onDetach() { + super.onDetach(); + } + + public interface OnFragmentInteractionListener { + public void onFragmentInteraction(Uri uri); + } + +} 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 new file mode 100644 index 0000000..d5c84c8 --- /dev/null +++ b/app/src/main/java/org/deke/risk/riskahead/fragments/UserInfo.java @@ -0,0 +1,128 @@ +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/AppConfig.java b/app/src/main/java/org/deke/risk/riskahead/helper/AppConfig.java new file mode 100644 index 0000000..f34161c --- /dev/null +++ b/app/src/main/java/org/deke/risk/riskahead/helper/AppConfig.java @@ -0,0 +1,12 @@ +package org.deke.risk.riskahead.helper; + +/** + * Created by Dennis on 09.08.2015. + */ +public class AppConfig { + // Server user login url + public static String URL_LOGIN = "http://192.168.178.31/riskahead/rest/"; + + // Server user register url + public static String URL_REGISTER = "http://192.168.178.31/riskahead/rest/"; +} diff --git a/app/src/main/java/org/deke/risk/riskahead/helper/GeocodeJSONParser.java b/app/src/main/java/org/deke/risk/riskahead/helper/GeocodeJSONParser.java new file mode 100644 index 0000000..0bea48a --- /dev/null +++ b/app/src/main/java/org/deke/risk/riskahead/helper/GeocodeJSONParser.java @@ -0,0 +1,78 @@ +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 org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +public class GeocodeJSONParser { + + /** Receives a JSONObject and returns a list */ + public List> parse(JSONObject jObject){ + + JSONArray jPlaces = null; + try { + /** Retrieves all the elements in the 'places' array */ + jPlaces = jObject.getJSONArray("results"); + } catch (JSONException e) { + e.printStackTrace(); + } + /** Invoking getPlaces with the array of json object + * where each json object represent a place + */ + return getPlaces(jPlaces); + } + + private List> getPlaces(JSONArray jPlaces){ + int placesCount = jPlaces.length(); + List> placesList = new ArrayList>(); + HashMap place = null; + + /** Taking each place, parses and adds to list object */ + for(int i=0; i getPlace(JSONObject jPlace){ + + HashMap place = new HashMap(); + String formatted_address = "-NA-"; + String lat=""; + String lng=""; + + 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"); + + place.put("formatted_address", formatted_address); + place.put("lat", lat); + place.put("lng", lng); + + }catch (JSONException e) { + e.printStackTrace(); + } + return place; + } +} diff --git a/app/src/main/java/org/deke/risk/riskahead/helper/SQLiteHandler.java b/app/src/main/java/org/deke/risk/riskahead/helper/SQLiteHandler.java new file mode 100644 index 0000000..e5e6ca3 --- /dev/null +++ b/app/src/main/java/org/deke/risk/riskahead/helper/SQLiteHandler.java @@ -0,0 +1,147 @@ +package org.deke.risk.riskahead.helper; + +import java.util.HashMap; + +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; +import android.util.Log; + +public class SQLiteHandler extends SQLiteOpenHelper { + + private static final String TAG = SQLiteHandler.class.getSimpleName(); + + // All Static variables + // Database Version + private static final int DATABASE_VERSION = 1; + + // Database Name + private static final String DATABASE_NAME = "android_api"; + + // Login table name + private static final String TABLE_LOGIN = "login"; + + // Login Table Columns names + private static final String KEY_UID = "uid"; + private static final String KEY_USERNAME = "username"; + private static final String KEY_NAME = "name"; + private static final String KEY_SURNAME = "surname"; + private static final String KEY_EMAIL = "email"; + private static final String KEY_STATUS = "status"; + private static final String PROVIDER_TYPE = "providerType"; + private static final String KEY_CREATED_AT = "created_at"; + private static final String KEY_UPDATED_AT = "updated_at"; + + public SQLiteHandler(Context context) { + super(context, DATABASE_NAME, null, DATABASE_VERSION); + } + + // Creating Tables + @Override + public void onCreate(SQLiteDatabase db) { + String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "(" + + KEY_UID + " INTEGER PRIMARY KEY," + + KEY_USERNAME + " TEXT," + + KEY_NAME + " TEXT," + + KEY_SURNAME + " TEXT," + + KEY_EMAIL + " TEXT UNIQUE," + + KEY_STATUS + " TEXT," + + PROVIDER_TYPE + " TEXT," + + KEY_UPDATED_AT + " TEXT," + + KEY_CREATED_AT + " TEXT" + ")"; + db.execSQL(CREATE_LOGIN_TABLE); + + Log.d(TAG, "Database tables created"); + } + + // Upgrading database + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN); + onCreate(db); + } + + /** + * Storing user details in database + * */ + public void addUser(String uid, String username, String name, String surname, String email, String status, String provider_type, String created_at, String updated_at) { + SQLiteDatabase db = this.getWritableDatabase(); + + ContentValues values = new ContentValues(); + values.put(KEY_UID, uid); //UID + values.put(KEY_USERNAME, username); // Username + values.put(KEY_NAME, name); // Name + values.put(KEY_SURNAME, surname); // Surame + values.put(KEY_EMAIL, email); // Email + values.put(KEY_STATUS, status); // Status + values.put(PROVIDER_TYPE, provider_type); // ProviderType + values.put(KEY_CREATED_AT, created_at); // Created At + values.put(KEY_UPDATED_AT, updated_at); // Updated At + + // Inserting Row + long id = db.insert(TABLE_LOGIN, null, values); + db.close(); // Closing database connection + + Log.d(TAG, "New user inserted into sqlite: " + id); + } + + /** + * Getting user data from database + * */ + public HashMap getUserDetails() { + HashMap user = new HashMap(); + String selectQuery = "SELECT * FROM " + TABLE_LOGIN; + + SQLiteDatabase db = this.getReadableDatabase(); + Cursor cursor = db.rawQuery(selectQuery, null); + // Move to first row + cursor.moveToFirst(); + if (cursor.getCount() > 0) { + user.put("uid", cursor.getString(0)); + user.put("username", cursor.getString(1)); + user.put("name", cursor.getString(2)); + user.put("surname", cursor.getString(3)); + user.put("email", cursor.getString(4)); + user.put("status", cursor.getString(5)); + user.put("providerType", cursor.getString(6)); + user.put("created_at", cursor.getString(7)); + user.put("updated_at", cursor.getString(8)); + } + cursor.close(); + db.close(); + // return user + Log.d(TAG, "Fetching user from Sqlite: " + user.toString()); + + return user; + } + + /** + * Getting user login status return true if rows are there in table + * */ + public int getRowCount() { + String countQuery = "SELECT * FROM " + TABLE_LOGIN; + SQLiteDatabase db = this.getReadableDatabase(); + Cursor cursor = db.rawQuery(countQuery, null); + int rowCount = cursor.getCount(); + db.close(); + cursor.close(); + + // return row count + return rowCount; + } + + /** + * Re crate database Delete all tables and create them again + * */ + public void deleteUsers() { + SQLiteDatabase db = this.getWritableDatabase(); + // Delete All Rows + db.delete(TABLE_LOGIN, null, null); + db.close(); + + Log.d(TAG, "Deleted all user info from sqlite"); + } + +} diff --git a/app/src/main/java/org/deke/risk/riskahead/helper/SessionManager.java b/app/src/main/java/org/deke/risk/riskahead/helper/SessionManager.java new file mode 100644 index 0000000..cd9fdc9 --- /dev/null +++ b/app/src/main/java/org/deke/risk/riskahead/helper/SessionManager.java @@ -0,0 +1,45 @@ +package org.deke.risk.riskahead.helper; + +import android.content.Context; +import android.content.SharedPreferences; +import android.content.SharedPreferences.Editor; +import android.util.Log; + +public class SessionManager { + // LogCat tag + private static String TAG = SessionManager.class.getSimpleName(); + + // Shared Preferences + SharedPreferences pref; + + Editor editor; + Context _context; + + // Shared pref mode + int PRIVATE_MODE = 0; + + // Shared preferences file name + private static final String PREF_NAME = "AndroidHiveLogin"; + + private static final String KEY_IS_LOGGEDIN = "isLoggedIn"; + + public SessionManager(Context context) { + this._context = context; + pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE); + editor = pref.edit(); + } + + public void setLogin(boolean isLoggedIn) { + + editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn); + + // commit changes + editor.commit(); + + Log.d(TAG, "User login session modified!"); + } + + public boolean isLoggedIn(){ + return pref.getBoolean(KEY_IS_LOGGEDIN, false); + } +} diff --git a/app/src/main/res/drawable-hdpi/drawer_shadow.9.png b/app/src/main/res/drawable-hdpi/drawer_shadow.9.png new file mode 100644 index 0000000..236bff5 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/drawer_shadow.9.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_drawer.png b/app/src/main/res/drawable-hdpi/ic_drawer.png new file mode 100644 index 0000000..c59f601 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_drawer.png differ diff --git a/app/src/main/res/drawable-mdpi/drawer_shadow.9.png b/app/src/main/res/drawable-mdpi/drawer_shadow.9.png new file mode 100644 index 0000000..ffe3a28 Binary files /dev/null and b/app/src/main/res/drawable-mdpi/drawer_shadow.9.png differ diff --git a/app/src/main/res/drawable-mdpi/ic_drawer.png b/app/src/main/res/drawable-mdpi/ic_drawer.png new file mode 100644 index 0000000..1ed2c56 Binary files /dev/null and b/app/src/main/res/drawable-mdpi/ic_drawer.png differ diff --git a/app/src/main/res/drawable-xhdpi/drawer_shadow.9.png b/app/src/main/res/drawable-xhdpi/drawer_shadow.9.png new file mode 100644 index 0000000..fabe9d9 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/drawer_shadow.9.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_drawer.png b/app/src/main/res/drawable-xhdpi/ic_drawer.png new file mode 100644 index 0000000..a5fa74d Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_drawer.png differ diff --git a/app/src/main/res/drawable-xxhdpi/drawer_shadow.9.png b/app/src/main/res/drawable-xxhdpi/drawer_shadow.9.png new file mode 100644 index 0000000..b91e9d7 Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/drawer_shadow.9.png differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_drawer.png b/app/src/main/res/drawable-xxhdpi/ic_drawer.png new file mode 100644 index 0000000..9c4685d Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/ic_drawer.png differ diff --git a/app/src/main/res/drawable/Thumbs.db b/app/src/main/res/drawable/Thumbs.db new file mode 100644 index 0000000..16b234a Binary files /dev/null and b/app/src/main/res/drawable/Thumbs.db differ diff --git a/app/src/main/res/drawable/logo_riskahead.png b/app/src/main/res/drawable/logo_riskahead.png new file mode 100644 index 0000000..9f56647 Binary files /dev/null and b/app/src/main/res/drawable/logo_riskahead.png differ diff --git a/app/src/main/res/layout/activity_login.xml b/app/src/main/res/layout/activity_login.xml new file mode 100644 index 0000000..85b9bba --- /dev/null +++ b/app/src/main/res/layout/activity_login.xml @@ -0,0 +1,127 @@ + + + + + + + + + + + +