diff --git a/.idea/gradle.xml b/.idea/gradle.xml index 90099e2..cbbf71c 100644 --- a/.idea/gradle.xml +++ b/.idea/gradle.xml @@ -3,10 +3,9 @@ - + diff --git a/.idea/modules.xml b/.idea/modules.xml index 1157461..b582285 100644 --- a/.idea/modules.xml +++ b/.idea/modules.xml @@ -2,8 +2,8 @@ + - \ No newline at end of file diff --git a/RiskAhead.iml b/RiskAhead-Android.iml similarity index 66% rename from RiskAhead.iml rename to RiskAhead-Android.iml index 16a12ec..69b9b49 100644 --- a/RiskAhead.iml +++ b/RiskAhead-Android.iml @@ -1,5 +1,5 @@ - + @@ -13,7 +13,7 @@ - + \ No newline at end of file diff --git a/app/app-release.apk b/app/app-release.apk deleted file mode 100644 index 324ed24..0000000 Binary files a/app/app-release.apk and /dev/null differ diff --git a/app/app.iml b/app/app.iml index 9916eb4..1b1623c 100644 --- a/app/app.iml +++ b/app/app.iml @@ -9,7 +9,6 @@ - + + - + - + - @@ -57,15 +56,20 @@ - + + + + + + + - @@ -73,7 +77,6 @@ - @@ -81,84 +84,119 @@ - + + + - - - - - - - - - - - - - - - - - - - - - - - - + - + + - + + + + + - + - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/build.gradle b/app/build.gradle index 60c26aa..b3e9471 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -1,26 +1,16 @@ -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 23 - buildToolsVersion "23.0.2" + compileSdkVersion 27 + buildToolsVersion '27.0.3' defaultConfig { applicationId "org.deke.risk.riskahead" minSdkVersion 15 - targetSdkVersion 23 - versionCode 35 - versionName "2.1.1" + targetSdkVersion 25 + versionCode 43 + versionName "3.1" } buildTypes { release { @@ -29,6 +19,9 @@ android { debuggable false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } + debug { + debuggable true + } } lintOptions { abortOnError false @@ -38,28 +31,37 @@ android { repositories { jcenter() maven { url 'https://maven.fabric.io/public' } + maven { url 'https://maven.google.com/' } } dependencies { compile fileTree(dir: 'libs', include: 'Parse-*.jar') + implementation 'com.facebook.android:facebook-android-sdk:4.31.0' compile('com.twitter.sdk.android:twitter-core:1.4.1@aar') { - transitive = true; - } - compile('com.mikepenz:materialdrawer:4.6.4@aar') { transitive = true } - compile 'com.android.support:appcompat-v7:23.1.1' - compile 'com.mikepenz:iconics-core:2.5.5@aar' - compile 'com.mikepenz:google-material-typeface:2.1.0.1.original@aar' - compile 'com.google.android.gms:play-services-gcm:8.4.0' - compile 'com.google.android.gms:play-services-plus:8.4.0' - compile 'com.google.android.gms:play-services-location:8.4.0' - compile 'com.google.android.gms:play-services-ads:8.4.0' - compile 'com.facebook.android:facebook-android-sdk:4.8.1' - compile 'com.beardedhen:androidbootstrap:2.0.1' + + implementation 'com.mikepenz:iconics-core:3.0.3@aar' + implementation 'com.mikepenz:iconics-core:3.0.3@aar' + implementation 'com.mikepenz:google-material-typeface:3.0.1.2.original@aar' + compile('com.mikepenz:materialdrawer:6.0.6@aar') { + transitive = true + } + + compile 'com.android.support:appcompat-v7:27.1.0' + compile 'com.android.support:support-v4:27.1.0' + compile 'com.android.support:design:27.1.0' + + compile 'com.google.android.gms:play-services-gcm:11.8.0' + compile 'com.google.android.gms:play-services-plus:11.8.0' + compile 'com.google.android.gms:play-services-location:11.8.0' + compile 'com.google.android.gms:play-services-ads:11.8.0' + compile 'com.google.android.gms:play-services-maps:11.8.0' + + compile 'com.google.maps.android:android-maps-utils:0.5' + compile 'com.google.code.gson:gson:2.8.0' + compile 'com.beardedhen:androidbootstrap:2.3.2' compile 'com.mcxiaoke.volley:library:1.0.19' - compile 'com.android.support:design:23.1.1' - compile 'com.google.code.gson:gson:2.4' - compile 'com.google.maps.android:android-maps-utils:0.4' - compile 'com.android.support:support-v4:23.1.1' } + +apply plugin: 'com.google.gms.google-services' \ No newline at end of file diff --git a/app/google-services.json b/app/google-services.json index 42f73ec..e3277e1 100644 --- a/app/google-services.json +++ b/app/google-services.json @@ -1 +1,70 @@ -{"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 +{ + "project_info": { + "project_number": "498007911848", + "firebase_url": "https://riskahead-61dff.firebaseio.com", + "project_id": "riskahead-61dff" + }, + "client": [ + { + "client_info": { + "mobilesdk_app_id": "1:498007911848:android:89cfbce52ef79add", + "android_client_info": { + "package_name": "org.deke.risk.riskahead" + } + }, + "oauth_client": [ + { + "client_id": "498007911848-bbfoj739tjtlr22faobmg8e4fls6c5ue.apps.googleusercontent.com", + "client_type": 3 + }, + { + "client_id": "498007911848-rs2ghjusnngqcb487os1s6nt4i8an8d5.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "org.deke.risk.riskahead", + "certificate_hash": "742d036d112c9a727a8c8aec1718eb1ba1e05a91" + } + }, + { + "client_id": "498007911848-belfueqha30j41gmjqe77db3qdrutcoc.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "org.deke.risk.riskahead", + "certificate_hash": "e4559e601888977e334d387d9e30dadedb855cbc" + } + }, + { + "client_id": "498007911848-ppr7ct4oa2gs5jjnmrnlnutgui8m365n.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "org.deke.risk.riskahead", + "certificate_hash": "4b6c989e6c0d6824f5a2d7b1a10ff36560c3397f" + } + } + ], + "api_key": [ + { + "current_key": "AIzaSyAV9_hgRs5tuDN4Okp0ydLboORO-cJgJtA" + } + ], + "services": { + "analytics_service": { + "status": 1 + }, + "appinvite_service": { + "status": 2, + "other_platform_oauth_client": [ + { + "client_id": "498007911848-bbfoj739tjtlr22faobmg8e4fls6c5ue.apps.googleusercontent.com", + "client_type": 3 + } + ] + }, + "ads_service": { + "status": 2 + } + } + } + ], + "configuration_version": "1" +} \ No newline at end of file diff --git a/app/release/app-release.apk b/app/release/app-release.apk new file mode 100644 index 0000000..47ba25f Binary files /dev/null and b/app/release/app-release.apk differ diff --git a/app/release/output.json b/app/release/output.json new file mode 100644 index 0000000..c39aa24 --- /dev/null +++ b/app/release/output.json @@ -0,0 +1 @@ +[{"outputType":{"type":"APK"},"apkInfo":{"type":"MAIN","splits":[],"versionCode":43},"path":"app-release.apk","properties":{"packageId":"org.deke.risk.riskahead","split":"","minSdkVersion":"15"}}] \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index f6dc2b4..52d6cb8 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -5,13 +5,11 @@ - - - - - + + + - - - - - - - + + + + - + android:label="@string/app_name" /> + + @@ -134,6 +121,6 @@ - + diff --git a/app/src/main/java/org/deke/risk/riskahead/LoginActivity.java b/app/src/main/java/org/deke/risk/riskahead/LoginActivity.java index 8446faf..e962a3d 100644 --- a/app/src/main/java/org/deke/risk/riskahead/LoginActivity.java +++ b/app/src/main/java/org/deke/risk/riskahead/LoginActivity.java @@ -8,6 +8,7 @@ import android.content.pm.PackageManager; import android.content.res.Resources; import android.net.ConnectivityManager; import android.net.NetworkInfo; +import android.support.design.widget.TextInputLayout; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.content.Intent; @@ -21,7 +22,6 @@ import android.util.Patterns; import android.view.Menu; import android.view.MenuItem; import android.view.View; -import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.LinearLayout; @@ -43,6 +43,7 @@ import com.android.volley.Request.Method; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; +import com.beardedhen.androidbootstrap.BootstrapButton; import java.util.HashMap; import java.util.Map; @@ -62,6 +63,9 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr private TextView input_username; private TextView input_password; + private TextInputLayout inputLayoutEmail; + private TextInputLayout inputLayoutPassword; + private ProgressDialog pDialog; private SessionManager session; @@ -84,6 +88,14 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr isNetworkAvailable(); checkForMaintenance(); + SessionManager session = new SessionManager(getApplicationContext()); + if (session.isLoggedIn()) { + Log.d(TAG,"User found in sharedPrefs and is therefore logged in. Continue to internal Area."); + Intent intent = new Intent(LoginActivity.this, MapsActivity.class); + startActivity(intent); + finish(); + } + } public void isNetworkAvailable() { @@ -96,7 +108,7 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr .setCancelable(false) .setNeutralButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { - gotoStartActivity(); + //todo What to do when no internet connection is available? } }) .setIcon(android.R.drawable.ic_dialog_alert) @@ -108,9 +120,9 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr Intent intent = getIntent(); String msg_intent = intent.getStringExtra(AppConfig.EXTRA_MESSAGE); - if(msg_intent.equals(AppConfig.INTENT_LOGIN)){ + if(msg_intent != null && msg_intent.equals(AppConfig.INTENT_LOGIN)){ initLoginView(); - }else if(msg_intent.equals(AppConfig.INTENT_REGISTER)){ + }else if((msg_intent == null) || msg_intent.equals(AppConfig.INTENT_REGISTER)){ initRegisterView(); } } @@ -125,10 +137,22 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr setContentView(R.layout.activity_login); input_email = (TextView) findViewById(R.id.input_register_email); + inputLayoutEmail = (TextInputLayout) findViewById(R.id.input_layout_email); + input_password = (TextView) findViewById(R.id.input_register_password); + inputLayoutPassword = (TextInputLayout) findViewById(R.id.input_layout_password); + TextView btn_requestPW = (TextView) findViewById(R.id.lbl_login_resendPW); - Button btn_login = (Button) findViewById(R.id.btn_login); + BootstrapButton btn_gotoregistration = (BootstrapButton) findViewById(R.id.btn_switchtoregistration); + btn_gotoregistration.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + gotoRegister(v); + } + }); + + BootstrapButton btn_login = (BootstrapButton) findViewById(R.id.btn_login); btn_login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -136,7 +160,7 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr String email = input_email.getText().toString(); String password = input_password.getText().toString(); - if (input_password.getError() != null || input_email.getError() != null) { + if (inputLayoutPassword.getError() != null || inputLayoutEmail.getError() != null) { showMessage(getString(R.string.error_validation)); } else { showDialog(); @@ -145,20 +169,24 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr } }); - input_email.addTextChangedListener(new TextValidator(input_email, getApplicationContext()) { + input_email.addTextChangedListener(new TextValidator(input_email, inputLayoutEmail, getApplicationContext()) { @Override - public void validate(TextView textView, String text) { + public void validate(TextView textView, TextInputLayout inputLayout, String text) { if (!Patterns.EMAIL_ADDRESS.matcher(text).matches()) { - textView.setError(getString(R.string.error_email)); + inputLayout.setError(getString(R.string.error_email)); + } else { + inputLayout.setErrorEnabled(false); } } }); - input_password.addTextChangedListener(new TextValidator(input_password, getApplicationContext()) { + input_password.addTextChangedListener(new TextValidator(input_password, inputLayoutPassword,getApplicationContext()) { @Override - public void validate(TextView textView, String text) { + public void validate(TextView textView, TextInputLayout inputLayout,String text) { if (text.length() < 5) { - textView.setError(getString(R.string.error_password)); + inputLayout.setError(getString(R.string.error_password)); + } else { + inputLayout.setErrorEnabled(false); } } }); @@ -175,39 +203,43 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr setContentView(R.layout.activity_register); input_username = (TextView) findViewById(R.id.input_register_name); + final TextInputLayout inputLayoutUsername = (TextInputLayout) findViewById(R.id.input_layout_username); input_email = (TextView) findViewById(R.id.input_register_email); + final TextInputLayout inputLayoutEmail = (TextInputLayout) findViewById(R.id.input_layout_email); input_password = (TextView) findViewById(R.id.input_register_password); - Button btn_login = (Button) findViewById(R.id.btn_register); + final TextInputLayout inputLayoutPassword = (TextInputLayout) findViewById(R.id.input_layout_password); + BootstrapButton btn_login = (BootstrapButton) findViewById(R.id.btn_register); + TextView btn_switchtologin = (TextView) findViewById(R.id.lbl_register_switchtologin); - input_username.addTextChangedListener(new TextValidator(input_username, getApplicationContext()) { + input_username.addTextChangedListener(new TextValidator(input_username, inputLayoutUsername, getApplicationContext()) { @Override - public void validate(TextView textView, String text) { + public void validate(TextView textView, TextInputLayout inputLayout, String text) { if (text.trim().length() < 5) { - textView.setError(getString(R.string.error_anytext)); + inputLayout.setError(getString(R.string.error_anytext)); } else { - textView.setError(null); + inputLayout.setErrorEnabled(false); } } }); - input_email.addTextChangedListener(new TextValidator(input_email, getApplicationContext()) { + input_email.addTextChangedListener(new TextValidator(input_email, inputLayoutEmail, getApplicationContext()) { @Override - public void validate(TextView textView, String text) { + public void validate(TextView textView, TextInputLayout inputLayout, String text) { if (!Patterns.EMAIL_ADDRESS.matcher(text).matches()) { - textView.setError(getString(R.string.error_email)); + inputLayout.setError(getString(R.string.error_email)); }else{ - textView.setError(null); + inputLayout.setErrorEnabled(false); } } }); - input_password.addTextChangedListener(new TextValidator(input_password, getApplicationContext()) { + input_password.addTextChangedListener(new TextValidator(input_password, inputLayoutPassword, getApplicationContext()) { @Override - public void validate(TextView textView, String text) { + public void validate(TextView textView, TextInputLayout inputLayout, String text) { if (text.length() < 5) { - textView.setError(getString(R.string.error_password)); + inputLayout.setError(getString(R.string.error_password)); } else { - textView.setError(null); + inputLayout.setErrorEnabled(false); } } }); @@ -219,7 +251,7 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr String password = input_password.getText().toString(); String name = input_username.getText().toString(); - if (input_password.getError() != null || input_email.getError() != null || input_username.getError() != null || input_email.getText().toString().trim().length() == 0 || input_username.getText().toString().trim().length() == 0 || input_password.getText().toString().trim().length() == 0) { + if (inputLayoutPassword.getError() != null || inputLayoutEmail.getError() != null || inputLayoutUsername.getError() != null || input_email.getText().toString().trim().length() == 0 || input_username.getText().toString().trim().length() == 0 || input_password.getText().toString().trim().length() == 0) { showMessage(getString(R.string.error_validation)); } else { showDialog(); @@ -227,11 +259,17 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr } } }); + + btn_switchtologin.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + gotoLogin(v); + } + }); } private void initSocialLoginButtons() { FragmentManager fragmentManager = getSupportFragmentManager(); - //FacebookButtonFragment fragmentFB = new FacebookButtonFragment(); new FacebookButtonFragment(); GooglePlusButtonFragment fragmentGP = new GooglePlusButtonFragment(); @@ -247,11 +285,11 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr } private StringRequest getStringRequestCheckForMaintenance() { - return new StringRequest(Method.POST, AppConfig.URL_ENCRYPTED, new Response.Listener() { + return new StringRequest(Method.POST, AppConfig.REST_CHECK_MAINTENANCE, new Response.Listener() { @Override public void onResponse(String response) { - Log.d(TAG, "Check User Exists Response: " + response); + Log.d(TAG, "Check for Maintenance Response: " + response); hideDialog(); try { @@ -261,7 +299,6 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr if (!error) { if(jObj.getBoolean("maintenancemode")){ showMessage(jObj.getString("maintenancemsg")); - gotoStartActivity(); } } } catch (JSONException e) { @@ -277,18 +314,20 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr @Override protected Map getParams() { - Map params = new HashMap<>(); - params.put("tag", AppConfig.REST_CHECK_MAINTENANCE); - - return params; + return new HashMap<>(); } }; } - private void gotoStartActivity() { - Intent intent = new Intent( - LoginActivity.this, - StartActivity.class); + public void gotoLogin(View view) { + Intent intent = new Intent(this, LoginActivity.class); + intent.putExtra(AppConfig.EXTRA_MESSAGE, AppConfig.INTENT_LOGIN); + startActivity(intent); + } + + public void gotoRegister(View view) { + Intent intent = new Intent(this, LoginActivity.class); + intent.putExtra(AppConfig.EXTRA_MESSAGE, AppConfig.INTENT_REGISTER); startActivity(intent); } @@ -299,11 +338,11 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr } private StringRequest getStringRequestCheckIfVersionSupported() { - return new StringRequest(Method.POST, AppConfig.URL_ENCRYPTED, new Response.Listener() { + return new StringRequest(Method.POST, AppConfig.REST_CHECK_VERSION, new Response.Listener() { @Override public void onResponse(String response) { - Log.d(TAG, "Check User Exists Response: " + response); + Log.d(TAG, "Check Version Response: " + response); hideDialog(); try { @@ -339,7 +378,6 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr e.printStackTrace(); } - params.put("tag", AppConfig.REST_CHECK_VERSION); params.put("version", Integer.toString(versionCode)); return params; } @@ -409,7 +447,7 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr if(session.isLoggedIn()){ Intent intent = new Intent( LoginActivity.this, - MainActivity.class); + MapsActivity.class); intent.putExtra(AppConfig.EXTRA_MESSAGE, AppConfig.INTENT_SOCIALMEDIALOGIN); startActivity(intent); finish(); @@ -424,7 +462,7 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr } public void onRequestNewPasswordClick(View view){ - if((input_email.getText() != null && input_email.getText().toString().isEmpty()) || (input_email.getError() != null)){ + if((input_email.getText() != null && input_email.getText().toString().isEmpty()) || (inputLayoutEmail.getError() != null)){ showMessage(getString(R.string.message_enteremail)); return; } @@ -459,7 +497,7 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr } private StringRequest getStringRequestSocialMediaLogin(final String key, final String providerType, final String username, final String email) { - return new StringRequest(Method.POST,AppConfig.URL_ENCRYPTED, new Response.Listener() { + return new StringRequest(Method.POST,AppConfig.REST_LOGIN_SOCIAL, new Response.Listener() { @Override public void onResponse(String response) { @@ -505,7 +543,7 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr Intent intent = new Intent( LoginActivity.this, - MainActivity.class); + MapsActivity.class); intent.putExtra(AppConfig.EXTRA_MESSAGE, AppConfig.INTENT_SOCIALMEDIALOGIN); startActivity(intent); finish(); @@ -532,9 +570,8 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr @Override protected Map getParams() { Map params = new HashMap<>(); - params.put("tag", AppConfig.REST_LOGIN_SOCIAL); params.put("key", key); - params.put("providerType", providerType); + params.put("providertype", providerType); params.put("username", username); params.put("email",email); @@ -545,7 +582,7 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr } private StringRequest getStringRequestLogin(final String email, final String password) { - return new StringRequest(Method.POST, AppConfig.URL_ENCRYPTED, new Response.Listener() { + return new StringRequest(Method.POST, AppConfig.REST_LOGIN, new Response.Listener() { @Override public void onResponse(String response) { @@ -612,7 +649,7 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr hideDialog(); - Intent intent = new Intent(LoginActivity.this, MainActivity.class); + Intent intent = new Intent(LoginActivity.this, MapsActivity.class); startActivity(intent); finish(); } @@ -638,7 +675,6 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr @Override protected Map getParams() { Map params = new HashMap<>(); - params.put("tag", AppConfig.REST_LOGIN); params.put("email", email); params.put("password", password); @@ -648,7 +684,7 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr } private StringRequest getStringRequestCheckUserExists(final String username, final String email, final String password) { - return new StringRequest(Method.POST, AppConfig.URL_ENCRYPTED, new Response.Listener() { + return new StringRequest(Method.POST, AppConfig.REST_USEREXISTS, new Response.Listener() { @Override public void onResponse(String response) { @@ -691,7 +727,6 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr @Override protected Map getParams() { Map params = new HashMap<>(); - params.put("tag", AppConfig.REST_LOGIN_EXISTS); params.put("email", email); return params; @@ -700,11 +735,11 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr } private StringRequest getStringRequestCheckSocialUserExists(final String key, final String providerType, final String username, final String email) { - return new StringRequest(Method.POST, AppConfig.URL_ENCRYPTED, new Response.Listener() { + return new StringRequest(Method.POST, AppConfig.REST_USEREXISTS, new Response.Listener() { @Override public void onResponse(String response) { - Log.d(TAG, "Check User Exists Response: " + response); + Log.d(TAG, "Check Social User Exists Response: " + response); hideDialog(); try { @@ -718,8 +753,6 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr createAndShowPrivacyDialogForSocialUser( key,providerType, username, email); } - - } else { String errorMsg = jObj.getString("error_msg"); Log.e(TAG, "Error occured: "+errorMsg); @@ -743,7 +776,6 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr @Override protected Map getParams() { Map params = new HashMap<>(); - params.put("tag", AppConfig.REST_LOGIN_EXISTS); params.put("key", key); return params; @@ -873,7 +905,7 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr } private StringRequest getStringRequestResetPW(final String email) { - return new StringRequest(Method.POST, AppConfig.URL_ENCRYPTED, new Response.Listener() { + return new StringRequest(Method.POST, AppConfig.REST_REQUESTPWRESET, new Response.Listener() { @Override public void onResponse(String response) { @@ -910,7 +942,6 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr @Override protected Map getParams() { Map params = new HashMap<>(); - params.put("tag", AppConfig.REST_REQUESTPWRESET); params.put("email", email); return params; @@ -919,7 +950,7 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr } private StringRequest getStringRequestActivationLinkUser(final String email) { - return new StringRequest(Method.POST, AppConfig.URL_ENCRYPTED, new Response.Listener() { + return new StringRequest(Method.POST, AppConfig.REST_SENDACTIVATIONMAIL, new Response.Listener() { @Override public void onResponse(String response) { @@ -933,7 +964,7 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr String errorMsg = jObj.getString("error_msg"); Log.e(TAG,"Resend E-Mail returned error value: "+errorMsg); Toast.makeText(getApplicationContext(), - getResources().getString(R.string.txt_errormsg_getactivationlink), Toast.LENGTH_LONG).show(); + getResources().getString(R.string.txt_errormsg_getactivationlink) + ":"+errorMsg, Toast.LENGTH_LONG).show(); } } catch (JSONException e) { e.printStackTrace(); @@ -944,7 +975,7 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr @Override public void onErrorResponse(VolleyError error) { - Log.e(TAG, "E-Mail pw resend Error: " + error.getMessage()); + Log.e(TAG, "E-Mail pw resend error: " + error.getMessage()); Toast.makeText(getApplicationContext(), getResources().getString(R.string.txt_errormsg_getactivationlink), Toast.LENGTH_LONG).show(); hideDialog(); @@ -954,7 +985,6 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr @Override protected Map getParams() { Map params = new HashMap<>(); - params.put("tag", AppConfig.REST_RESENDACTIVATIONMAIL); params.put("email", email); return params; @@ -963,7 +993,7 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr } private StringRequest getStringRequestRegisterUser(final String username, final String email, final String password) { - return new StringRequest(Method.POST, AppConfig.URL_ENCRYPTED, new Response.Listener() { + return new StringRequest(Method.POST, AppConfig.REST_REGISTER, new Response.Listener() { @Override public void onResponse(String response) { @@ -1012,7 +1042,6 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr @Override protected Map getParams() { Map params = new HashMap<>(); - params.put("tag", AppConfig.REST_REGISTER); params.put("username", username); params.put("email", email); params.put("password", password); @@ -1040,12 +1069,6 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr pDialog.dismiss(); } - @Override - public void onBackPressed() { - gotoStartActivity(); - finish(); - } - @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_common, menu); @@ -1092,4 +1115,5 @@ public class LoginActivity extends AppCompatActivity implements FacebookButtonFr } } + } diff --git a/app/src/main/java/org/deke/risk/riskahead/MainActivity.java b/app/src/main/java/org/deke/risk/riskahead/MainActivity.java deleted file mode 100644 index 34095b1..0000000 --- a/app/src/main/java/org/deke/risk/riskahead/MainActivity.java +++ /dev/null @@ -1,218 +0,0 @@ -package org.deke.risk.riskahead; - -import android.graphics.drawable.Drawable; -import android.os.Bundle; -import android.os.Handler; -import android.support.v4.content.ContextCompat; -import android.util.Log; -import android.view.View; -import android.widget.Button; -import android.widget.ImageView; -import android.widget.TextView; - -import com.android.volley.Request; -import com.android.volley.Response; -import com.android.volley.VolleyError; -import com.android.volley.toolbox.StringRequest; -import com.mikepenz.google_material_typeface_library.GoogleMaterial; -import com.mikepenz.iconics.IconicsDrawable; - -import org.deke.risk.riskahead.helper.AppConfig; -import org.deke.risk.riskahead.helper.AppController; -import org.deke.risk.riskahead.helper.BaseActivity; -import org.deke.risk.riskahead.helper.SessionManager; -import org.json.JSONException; -import org.json.JSONObject; - -import java.text.DecimalFormat; -import java.util.HashMap; -import java.util.Map; - -/** - * - * (C) Copyright 2016 RiskAhead (http://www.riskahead.net) - * Developer & Contributor: Dennis Thießen (dennis.thiessen@riskahead.net) - * Date of Release: 10.02.2016 - * - */ -public class MainActivity extends BaseActivity{ - - private final static String TAG = MainActivity.class.getSimpleName(); - - private Handler mHandler = new Handler(); - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - userHasToBeLoggedIn(); - showDialog(); - - initButtons(); - } - - private void initButtons() { - runOnUiThread(new Runnable() { - @Override - public void run() { - ImageView bg = (ImageView) findViewById(R.id.imageView); - bg.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.bg_withlogo_2)); - - - Button report = (Button) findViewById(R.id.btn_main_report); - report.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - gotoReportActivity(); - } - }); - - Drawable reportIcon = new IconicsDrawable(getApplicationContext()) - .icon(GoogleMaterial.Icon.gmd_room) - .color(ContextCompat.getColor(getApplicationContext(), R.color.white)) - .sizeDp(24); - - report.setCompoundDrawables(reportIcon, null, null, null); - report.setBackgroundResource(R.drawable.activity_main_button); - - Button map = (Button) findViewById(R.id.btn_main_viewmap); - - map.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - gotoMapActivity(); - } - }); - - Drawable mapIcon = new IconicsDrawable(getApplicationContext()) - .icon(GoogleMaterial.Icon.gmd_map) - .color(ContextCompat.getColor(getApplicationContext(), R.color.white)) - .sizeDp(24); - - map.setCompoundDrawables(null, null, mapIcon, null); - map.setBackgroundResource(R.drawable.activity_main_button); - } - }); - } - - Runnable mHandlerTask = new Runnable() - { - @Override - public void run() { - requestNumberOfIncidents(); - - TextView notificationStatus = (TextView) findViewById(R.id.lbl_main_notifystatus_status); - if(session.getNotificationEnabled()){ - if(session.getNotificationServiceReady()){ - notificationStatus.setText(getString(R.string.txt_notifystatus_activated)); - - notificationStatus.setTextColor(ContextCompat.getColor(getApplicationContext(),R.color.md_green_400)); - }else{ - notificationStatus.setText(getString(R.string.txt_notifystatus_activatedbutnotready)); - notificationStatus.setTextColor(ContextCompat.getColor(getApplicationContext(),R.color.md_yellow_400)); - } - }else{ - notificationStatus.setText(getString(R.string.txt_notifystatus_deactivated)); - notificationStatus.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.md_red_400)); - } - - mHandler.postDelayed(mHandlerTask, AppConfig.UPDATE_COUNT_INTERVAL); - } - }; - - private void requestNumberOfIncidents() { - StringRequest strReq = getStringRequestIncidentCount(); - String tag_string_req = "req_incidents"; - AppController.getInstance().addToRequestQueue(strReq, tag_string_req); - } - - private StringRequest getStringRequestIncidentCount() { - return new StringRequest(Request.Method.POST, AppConfig.URL_DEFAULT, new Response.Listener() { - - @Override - public void onResponse(String response) { - hideDialog(); - Log.d(TAG, "Incident count: " + response); - - try { - JSONObject jObj = new JSONObject(response); - boolean error = jObj.getBoolean("error"); - - if (!error) { - JSONObject jCount = jObj.getJSONObject("msg"); - - displayNumberOfIncidents(jCount); - } else { - String errorMsg = jObj.getString("error_msg"); - Log.e(TAG, "Error getting incident count (server returned error): " + errorMsg); - } - } catch (JSONException e) { - e.printStackTrace(); - } - - } - }, new Response.ErrorListener() { - - @Override - public void onErrorResponse(VolleyError error) { - Log.e(TAG, "Error getting incident count: " + error.getMessage()); - handleVolleyErrorResponse(); - stopRepeatingTask(); - hideDialog(); - } - }) { - - @Override - protected Map getParams() { - Map params = new HashMap<>(); - params.put("tag", AppConfig.REST_GET_NUMOFINCIDENTS); - params.put("uid", user.get(SessionManager.KEY_UID)); - params.put("token", user.get(SessionManager.TOKEN)); - return params; - } - }; - } - - private void displayNumberOfIncidents(JSONObject jCount) throws JSONException { - TextView count = (TextView) findViewById(R.id.txt_main_incidents); - DecimalFormat nf = new DecimalFormat(); - String decimalNumber = nf.format(jCount.getInt("total")); - count.setText(decimalNumber); - } - - void startRepeatingTask() - { - mHandlerTask.run(); - } - - void stopRepeatingTask() - { - mHandler.removeCallbacks(mHandlerTask); - } - - @Override - protected void onResume(){ - super.onResume(); - navDrawer.setSelection(mainAvtivityID, false); - startRepeatingTask(); - } - - @Override - protected void onPause(){ - super.onPause(); - stopRepeatingTask(); - } - - @Override - protected int getLayoutResourceId() { - return R.layout.activity_main; - } - - @Override - protected String getActivityName() { - return getResources().getString(R.string.title_activity_start); - } - - - -} diff --git a/app/src/main/java/org/deke/risk/riskahead/MapsActivity.java b/app/src/main/java/org/deke/risk/riskahead/MapsActivity.java index 7ef89fe..b1be5b2 100644 --- a/app/src/main/java/org/deke/risk/riskahead/MapsActivity.java +++ b/app/src/main/java/org/deke/risk/riskahead/MapsActivity.java @@ -9,6 +9,8 @@ import android.content.res.ColorStateList; import android.database.Cursor; import android.graphics.Color; import android.graphics.drawable.Drawable; +import android.location.Location; +import android.location.LocationManager; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.ActivityCompat; @@ -23,11 +25,15 @@ import android.view.View; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.RatingBar; +import android.widget.RelativeLayout; import android.widget.TextView; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; + +import android.location.LocationListener; + import com.android.volley.toolbox.StringRequest; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; @@ -65,11 +71,9 @@ import java.util.Locale; import java.util.Map; /** - * * (C) Copyright 2016 RiskAhead (http://www.riskahead.net) * Developer & Contributor: Dennis Thießen (dennis.thiessen@riskahead.net) * Date of Release: 10.02.2016 - * */ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCallbacks, ClusterManager.OnClusterItemInfoWindowClickListener, ClusterManager.OnClusterClickListener, ClusterManager.OnClusterItemClickListener, OnMapReadyCallback { @@ -96,6 +100,13 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa private Marker markerShowingInfoWindow; private IncidentReport clickedClusterItem; + private LocationManager locationManager; + private LocationListener locationListener; + private Location location; + + private static final int MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters + private static final int MIN_TIME_BW_UPDATES = 1000 * 60; // 1 minute + private LatLng myLocation; private LatLng markedLocation; private LatLng curNortheastBounds; @@ -122,13 +133,14 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa mapFragment.getMapAsync(this); findViewById(R.id.fab_reportwf_map).setVisibility(View.INVISIBLE); - } + @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; initMap(); + handleIntent(getIntent()); initClustering(); } @@ -141,33 +153,51 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { + Log.d(TAG, "Getting permission results..."); switch (requestCode) { case MY_PERMISSIONS_REQUEST_LOCATION: { - // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + Log.d(TAG, "Permission was granted by user"); + enableMyLocationButton(); + getLocation(); - try{ - mMap.setMyLocationEnabled(true); - }catch(SecurityException e){ - Log.e(TAG,"Security Exception: "+e.toString()); + } else { + Log.d(TAG, "Permission was not granted by user"); + + String sDefSystemLanguage = Locale.getDefault().getLanguage(); + + switch (sDefSystemLanguage) { + case "en": + mMap.animateCamera(CameraUpdateFactory.newLatLngZoom( + new LatLng(51.507351, -0.127758), DEFAULT_ZOOM_LEVEL)); + break; + case "de": + mMap.animateCamera(CameraUpdateFactory.newLatLngZoom( + new LatLng(52.518594, 13.376188), DEFAULT_ZOOM_LEVEL)); + break; + default: + mMap.animateCamera(CameraUpdateFactory.newLatLngZoom( + new LatLng(19.410704, -99.132385), DEFAULT_ZOOM_LEVEL)); + break; } } } - - // other 'case' lines to check for other - // permissions this app might request } } - private void initMap() { + Log.d(TAG, "Init Map"); mMap.getUiSettings().setZoomControlsEnabled(true); - if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { - ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION,android.Manifest.permission.ACCESS_COARSE_LOCATION},1); - }else{ - mMap.setMyLocationEnabled(true); - } + mMap.setMinZoomPreference(MIN_ZOOM_LEVEL); + mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() { + @Override + public boolean onMyLocationButtonClick() { + getLocation(); + return false; + } + }); + enableMyLocationButton(); mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() { @Override @@ -218,13 +248,13 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa addButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - session.setLocation(Double.doubleToRawLongBits(markedLocation.latitude), Double.doubleToRawLongBits(markedLocation.longitude)); + session.setManualLocation(Double.doubleToRawLongBits(markedLocation.latitude), Double.doubleToRawLongBits(markedLocation.longitude)); Log.d(TAG, "MARKED LOCATION: " + markedLocation.latitude + " " + markedLocation.longitude); gotoSettingsActivity(); } }); } - }else{ + } else { addButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -239,31 +269,23 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa }); } - public GoogleMap.OnCameraChangeListener getCameraChangeListener() { - return new GoogleMap.OnCameraChangeListener() - { + public GoogleMap.OnCameraIdleListener getCameraChangeListener() { + return new GoogleMap.OnCameraIdleListener() { @Override - public void onCameraChange(CameraPosition position) - { - mClusterManager.onCameraChange(position); - - if((position.zoom < MIN_ZOOM_LEVEL) && !session.getSubsPremium()) { - mMap.animateCamera(CameraUpdateFactory.zoomTo(MIN_ZOOM_LEVEL)); - showMessage(getString(R.string.txt_map_zoomoutpremium)); - return; - } - + public void onCameraIdle() { + mClusterManager.onCameraIdle(); + CameraPosition position = mMap.getCameraPosition(); current_zoom_level = position.zoom; - if(position.zoom > 13) { + if (position.zoom > 13) { PRELOAD_PERCENTAGE = 0.7; - }else{ + } else { PRELOAD_PERCENTAGE = 0.3; } LatLngBounds bounds = mMap.getProjection().getVisibleRegion().latLngBounds; - Log.d("OnCameraChangeListener", "Position: "+bounds.getCenter()+" Zoom: "+position.zoom + " Bounds: NE:" + bounds.northeast + " SW: " + bounds.southwest); + Log.d("OnCameraChangeListener", "Position: " + bounds.getCenter() + " Zoom: " + position.zoom + " Bounds: NE:" + bounds.northeast + " SW: " + bounds.southwest); Log.d("OnCameraChangeListener", "Saved Position - Bounds: NE:" + curNortheastBounds + " SW: " + curSouthwestBounds); boolean isOutOfBounds = false; @@ -274,39 +296,39 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa double southwestLat, southwestLng; double northeastLat, northeastLng; - if(bounds.southwest.latitude < bounds.northeast.latitude){ + if (bounds.southwest.latitude < bounds.northeast.latitude) { southwestLat = bounds.southwest.latitude - distanceLat * PRELOAD_PERCENTAGE; northeastLat = bounds.northeast.latitude + distanceLat * PRELOAD_PERCENTAGE; - if((curSouthwestBounds != null) && ((bounds.southwest.latitude < curSouthwestBounds.latitude) || (bounds.northeast.latitude > curNortheastBounds.latitude))){ + if ((curSouthwestBounds != null) && ((bounds.southwest.latitude < curSouthwestBounds.latitude) || (bounds.northeast.latitude > curNortheastBounds.latitude))) { isOutOfBounds = true; } } else { southwestLat = bounds.southwest.latitude + distanceLat * PRELOAD_PERCENTAGE; northeastLat = bounds.northeast.latitude - distanceLat * PRELOAD_PERCENTAGE; - if((curSouthwestBounds != null) && ((bounds.southwest.latitude > curSouthwestBounds.latitude) || (bounds.northeast.latitude < curNortheastBounds.latitude))){ + if ((curSouthwestBounds != null) && ((bounds.southwest.latitude > curSouthwestBounds.latitude) || (bounds.northeast.latitude < curNortheastBounds.latitude))) { isOutOfBounds = true; } } - if(bounds.southwest.longitude < bounds.northeast.longitude){ + if (bounds.southwest.longitude < bounds.northeast.longitude) { southwestLng = bounds.southwest.longitude - distanceLon * PRELOAD_PERCENTAGE; northeastLng = bounds.northeast.longitude + distanceLon * PRELOAD_PERCENTAGE; - if((curSouthwestBounds != null) && ((bounds.southwest.longitude < curSouthwestBounds.longitude) || (bounds.northeast.longitude > curNortheastBounds.longitude))){ + if ((curSouthwestBounds != null) && ((bounds.southwest.longitude < curSouthwestBounds.longitude) || (bounds.northeast.longitude > curNortheastBounds.longitude))) { isOutOfBounds = true; } } else { southwestLng = bounds.southwest.longitude + distanceLon * PRELOAD_PERCENTAGE; northeastLng = bounds.northeast.longitude - distanceLon * PRELOAD_PERCENTAGE; - if((curSouthwestBounds != null) && ((bounds.southwest.longitude > curSouthwestBounds.longitude) || (bounds.northeast.longitude < curNortheastBounds.longitude))){ + if ((curSouthwestBounds != null) && ((bounds.southwest.longitude > curSouthwestBounds.longitude) || (bounds.northeast.longitude < curNortheastBounds.longitude))) { isOutOfBounds = true; } } - if((curSouthwestBounds == null) || isOutOfBounds) { + if ((curSouthwestBounds == null) || isOutOfBounds) { curNortheastBounds = new LatLng(northeastLat, northeastLng); curSouthwestBounds = new LatLng(southwestLat, southwestLng); @@ -321,7 +343,7 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa refreshIncidentHeatMap(curNortheastBounds, curSouthwestBounds); markersShown = false; } - } else if((position.zoom >= THRESHOLD_ZOOM_LEVEL) && !markersShown){ + } else if ((position.zoom >= THRESHOLD_ZOOM_LEVEL) && !markersShown) { curNortheastBounds = new LatLng(northeastLat, northeastLng); curSouthwestBounds = new LatLng(southwestLat, southwestLng); @@ -330,7 +352,7 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa refreshIncidentHeatMap(curNortheastBounds, curSouthwestBounds); refreshIncidentMarkers(curNortheastBounds, curSouthwestBounds); markersShown = true; - } else if((position.zoom < THRESHOLD_ZOOM_LEVEL) && !markersShown){ + } else if ((position.zoom < THRESHOLD_ZOOM_LEVEL) && !markersShown) { mClusterManager.clearItems(); markersShown = false; } @@ -338,19 +360,18 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa }; } - private void refreshIncidentMarkers(LatLng northeast, LatLng southwest){ + private void refreshIncidentMarkers(LatLng northeast, LatLng southwest) { showProgress(); String tag_string_req = "getincidentsfrombound"; - StringRequest strReq = getStringRequestGetAllIncidentsFromBound(northeast,southwest); + StringRequest strReq = getStringRequestGetAllIncidentsFromBound(northeast, southwest); AppController.getInstance().addToRequestQueue(strReq, tag_string_req); } - private void addIncidentMarkersOnMap(JSONArray incidents){ - + private void addIncidentMarkersOnMap(JSONArray incidents) { mClusterManager.clearItems(); - for(int i = 0; i < incidents.length();i++){ + for (int i = 0; i < incidents.length(); i++) { try { mClusterManager.addItem(new IncidentReport(incidents.getJSONObject(i))); } catch (JSONException e) { @@ -361,7 +382,7 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa mClusterManager.cluster(); } - private void refreshIncidentHeatMap(LatLng northeast, LatLng southwest){ + private void refreshIncidentHeatMap(LatLng northeast, LatLng southwest) { showProgress(); String tag_string_req = "getincidentsforheatmapfrombound"; @@ -369,10 +390,10 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa AppController.getInstance().addToRequestQueue(strReq, tag_string_req); } - private void addIncidentMarkersOnHeatMap(JSONArray incidents){ + private void addIncidentMarkersOnHeatMap(JSONArray incidents) { ArrayList heatMapPositions = new ArrayList<>(); - for(int i = 0; i < incidents.length();i++){ + for (int i = 0; i < incidents.length(); i++) { try { heatMapPositions.add(new WeightedLatLng(new LatLng(incidents.getJSONObject(i).getDouble("latitude"), incidents.getJSONObject(i).getDouble("longitude")), 1.0)); } catch (JSONException e) { @@ -380,25 +401,22 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa } } - if(mProvider == null){ + if (mProvider == null) { mProvider = new HeatmapTileProvider.Builder() .radius(50) .weightedData(heatMapPositions) .opacity(0.7) .build(); - mOverlay = mMap.addTileOverlay(new TileOverlayOptions().tileProvider(mProvider)); - Log.d("HEATMAP", "HeatMap initialized"); - }else{ + } else { mProvider.setWeightedData(heatMapPositions); mOverlay.clearTileCache(); - Log.d("HEATMAP", "HeatMap updated"); } } private StringRequest getStringRequestGetAllIncidentsForHeatMapFromBound(final LatLng northeast, final LatLng southwest) { - return new StringRequest(Request.Method.POST, AppConfig.URL_DEFAULT, new Response.Listener() { + return new StringRequest(Request.Method.POST, AppConfig.REST_GET_INCIDENTS_FROMBOUND_FORHEATMAP, new Response.Listener() { @Override public void onResponse(String response) { @@ -410,7 +428,7 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa if (!error) { JSONArray incidents = jObj.getJSONArray("msg"); - Log.d(TAG, "HeatMap positions response length: " + incidents .length()); + Log.d(TAG, "HeatMap positions response length: " + incidents.length()); addIncidentMarkersOnHeatMap(incidents); } else { String errorMsg = jObj.getString("error_msg"); @@ -432,7 +450,6 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa @Override protected Map getParams() { Map params = new HashMap<>(); - params.put("tag", AppConfig.REST_GET_INCIDENTS_FROMBOUND_FORHEATMAP); params.put("uid", user.get(SessionManager.KEY_UID)); params.put("token", user.get(SessionManager.TOKEN)); params.put("nelat", Double.toString(northeast.latitude)); @@ -446,7 +463,7 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa } private StringRequest getStringRequestGetAllIncidentsFromBound(final LatLng northeast, final LatLng southwest) { - return new StringRequest(Request.Method.POST, AppConfig.URL_DEFAULT, new Response.Listener() { + return new StringRequest(Request.Method.POST, AppConfig.REST_GET_INCIDENTS_FROMBOUND, new Response.Listener() { @Override public void onResponse(String response) { @@ -480,7 +497,6 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa @Override protected Map getParams() { Map params = new HashMap<>(); - params.put("tag", AppConfig.REST_GET_INCIDENTS_FROMBOUND); params.put("uid", user.get(SessionManager.KEY_UID)); params.put("token", user.get(SessionManager.TOKEN)); params.put("nelat", Double.toString(northeast.latitude)); @@ -495,7 +511,7 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa private void initClustering() { mClusterManager = new ClusterManager<>(this, mMap); - mMap.setOnCameraChangeListener(getCameraChangeListener()); + mMap.setOnCameraIdleListener(getCameraChangeListener()); mClusterManager.setRenderer(new OwnIconRendered(MapsActivity.this, mMap, mClusterManager)); @@ -519,7 +535,7 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa new MyCustomAdapterForItems()); } - private void loadInfoWindowInformation(View infoView, String incidentID){ + private void loadInfoWindowInformation(View infoView, String incidentID) { showProgress(); String tag_string_req = "getincidentscoreforinfowindow"; @@ -528,7 +544,7 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa } private StringRequest getStringRequestGetIncidentScoreForInfoWindow(final View infoView, final String incidentID) { - return new StringRequest(Request.Method.POST, AppConfig.URL_DEFAULT, new Response.Listener() { + return new StringRequest(Request.Method.POST, AppConfig.REST_GET_INCIDENT, new Response.Listener() { @Override public void onResponse(String response) { @@ -545,7 +561,7 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa TextView tvUsername = ((TextView) infoView.findViewById(R.id.txt_infowindow_fromuser)); RatingBar rbScore = ((RatingBar) infoView.findViewById(R.id.rb_infowindow_rating)); - tvUsername.setText(String.format("%s %s",getString(R.string.lbl_mapsinfowindow_author),clickedClusterItem.getFromUsername())); + tvUsername.setText(String.format("%s %s", getString(R.string.lbl_mapsinfowindow_author), clickedClusterItem.getFromUsername())); rbScore.setRating(clickedClusterItem.getScoreStars()); if (markerShowingInfoWindow != null && markerShowingInfoWindow.isInfoWindowShown()) { @@ -554,7 +570,7 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa } } else { String errorMsg = jObj.getString("error_msg"); - Log.e(TAG, "Error getting incident details (server returned error): " + errorMsg); + Log.i(TAG, "Error getting incident details (server returned error): " + errorMsg); showMessage(getResources().getString(R.string.txt_errormsg_getinfowindow)); } } catch (JSONException e) { @@ -573,7 +589,6 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa @Override protected Map getParams() { Map params = new HashMap<>(); - params.put("tag", "getincidentfromincidentid"); params.put("uid", user.get(SessionManager.KEY_UID)); params.put("token", user.get(SessionManager.TOKEN)); params.put("incidentid", incidentID); @@ -583,9 +598,7 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa }; } - - public class MyCustomAdapterForItems implements GoogleMap.InfoWindowAdapter { - + private class MyCustomAdapterForItems implements GoogleMap.InfoWindowAdapter { private final View myContentsView; MyCustomAdapterForItems() { @@ -618,59 +631,42 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa tvCategory.setText(clickedClusterItem.getIncidentCategoryName(getApplicationContext())); tvSubcategory.setText(clickedClusterItem.getIncidentSubCategoryName(getApplicationContext())); - tvSuspect.setText(String.format("%s %s",getString(R.string.lbl_mapsinfowindow_suspect),clickedClusterItem.getSuspectString(getApplicationContext()))); - tvVictim.setText(String.format("%s %s",getString(R.string.lbl_mapsinfowindow_victim),clickedClusterItem.getVictimString(getApplicationContext()))); + tvSuspect.setText(String.format("%s %s", getString(R.string.lbl_mapsinfowindow_suspect), clickedClusterItem.getSuspectString(getApplicationContext()))); + tvVictim.setText(String.format("%s %s", getString(R.string.lbl_mapsinfowindow_victim), clickedClusterItem.getVictimString(getApplicationContext()))); tvTime.setText(String.format("%s %s", getString(R.string.lbl_mapsinfowindow_time), clickedClusterItem.getTimeString(getApplicationContext()))); } return myContentsView; } } - private void handleIntent(Intent intent){ - if(Intent.ACTION_SEARCH.equals(intent.getAction())) - { + 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())) { + } else if (Intent.ACTION_VIEW.equals(intent.getAction())) { getPlace(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY)); } else { String intentMessage = intent.getStringExtra(EXTRA_MESSAGE); - if(intentMessage != null && intentMessage.contains(":")) { + if (intentMessage != null && intentMessage.contains(":")) { String[] position = intentMessage.split(":"); String latitude = position[0]; String longitude = position[1]; - LatLng point = new LatLng(Double.parseDouble(latitude),Double.parseDouble(longitude)); + LatLng point = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)); mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(point, DEFAULT_ZOOM_LEVEL)); - if(getIntent().hasExtra(AppConfig.EXTRA_MAP_TYPE)) mMarker = mMap.addMarker(new MarkerOptions().position(point)); + if (getIntent().hasExtra(AppConfig.EXTRA_MAP_TYPE)) + mMarker = mMap.addMarker(new MarkerOptions().position(point)); } else { LatLng myPosition = session.getLocation(); - if ((myPosition != null) && (myPosition.latitude != 0.0) && (myPosition.longitude != 0.0)) - { + if ((myPosition != null) && (myPosition.latitude != 0.0) && (myPosition.longitude != 0.0)) { mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(myPosition.latitude, myPosition.longitude), DEFAULT_ZOOM_LEVEL)); - }else{ - String sDefSystemLanguage = Locale.getDefault().getLanguage(); - - switch (sDefSystemLanguage) { - case "en": - mMap.animateCamera(CameraUpdateFactory.newLatLngZoom( - new LatLng(51.507351, -0.127758), DEFAULT_ZOOM_LEVEL)); - break; - case "de": - mMap.animateCamera(CameraUpdateFactory.newLatLngZoom( - new LatLng(52.518594, 13.376188), DEFAULT_ZOOM_LEVEL)); - break; - default: - mMap.animateCamera(CameraUpdateFactory.newLatLngZoom( - new LatLng(19.410704, -99.132385), DEFAULT_ZOOM_LEVEL)); - break; - } + } else { + getLocation(); } } - } } @@ -680,7 +676,9 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa } @Override - public boolean onClusterClick(Cluster cluster) { return false; } + public boolean onClusterClick(Cluster cluster) { + return false; + } @Override public void onClusterItemInfoWindowClick(IncidentReport incidentReport) { @@ -694,53 +692,162 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa handleIntent(intent); } - private void doSearch(String query){ + private void doSearch(String query) { Bundle data = new Bundle(); data.putString("query", query); getSupportLoaderManager().restartLoader(0, data, this); } - private void getPlace(String query){ + private void getPlace(String query) { Bundle data = new Bundle(); data.putString("query", query); getSupportLoaderManager().restartLoader(1, data, this); } - private void showLocations(Cursor c){ + private void showLocations(Cursor c) { MarkerOptions markerOptions; LatLng position = null; - while(c.moveToNext()){ + while (c.moveToNext()) { markerOptions = new MarkerOptions(); - position = new LatLng(Double.parseDouble(c.getString(1)),Double.parseDouble(c.getString(2))); + position = new LatLng(Double.parseDouble(c.getString(1)), Double.parseDouble(c.getString(2))); markerOptions.position(position); markerOptions.title(c.getString(0)); } - if(position!=null){ + if (position != null) { CameraUpdate cameraPosition = CameraUpdateFactory.newLatLng(position); mMap.animateCamera(cameraPosition); } if (position != null) { - myLocation = new LatLng(position.latitude,position.longitude); + myLocation = new LatLng(position.latitude, position.longitude); } mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myLocation, DEFAULT_ZOOM_LEVEL)); } @Override - public void onLoaderReset(Loader arg0) {} + public void onLoaderReset(Loader arg0) { + } @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); + 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; } + private class MyLocationListener implements LocationListener { + + @Override + public void onLocationChanged(Location loc) { + if (loc.getLongitude() != 0.0 && loc.getLatitude() != 0.0) { + Log.d(TAG, "Save GPS as new location..."); + if (session.getLocation() == null || session.getLocation().latitude == 0.0 || session.getLocation().longitude == 0.0) { + session.setLocation(Double.doubleToRawLongBits(loc.getLatitude()), Double.doubleToRawLongBits(loc.getLongitude())); + } else { + session.setLocation(Double.doubleToRawLongBits(loc.getLatitude()), Double.doubleToRawLongBits(loc.getLongitude())); + } + + session.setNotificationServiceReady(true); + } + } + + @Override + public void onProviderDisabled(String provider) { + } + + @Override + public void onProviderEnabled(String provider) { + } + + @Override + public void onStatusChanged(String provider, int status, Bundle extras) { + } + } + + private boolean isLocationEnabled() { + return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || + locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); + } + + public Location getLocation() { + //check for permission + Log.d(TAG, "Permission for GPS not granted yet - ask for permission now"); + if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { + ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION); + } else { + Log.d(TAG, "Permission for GPS granted - get position"); + locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); + locationListener = new MyLocationListener(); + + try { + + if (!isLocationEnabled()) { + showMessage("Please activate GPS in your android settings."); + Log.d(TAG, "Locationservice not enabled"); + } else { + Log.d(TAG, "Locationservice enabled - check type"); + + // if GPS Enabled get lat/long using GPS Services + if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { + Log.d(TAG, "Locationservice enabled - GPS Provider Found"); + if (location == null) { + locationManager.requestLocationUpdates( + LocationManager.GPS_PROVIDER, + MIN_TIME_BW_UPDATES, + MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener); + Log.d(TAG, "GPS location from GPS Service activated"); + if (locationManager != null) { + location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); + if (location != null) { + myLocation = new LatLng(location.getLatitude(), location.getLongitude()); + } + } + } + } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { + // get location from Network Provider + Log.d(TAG, "Locationservice enabled - Network Provider Found"); + locationManager.requestLocationUpdates( + LocationManager.NETWORK_PROVIDER, + MIN_TIME_BW_UPDATES, + MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener); + Log.d(TAG, "GPS location from Network Provider activated"); + if (locationManager != null) { + location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); + if (location != null) { + myLocation = new LatLng(location.getLatitude(), location.getLongitude()); + } + } + } + + mMap.moveCamera(CameraUpdateFactory.newLatLng(myLocation)); + + } + + } catch (Exception e) { + e.printStackTrace(); + } + } + + return location; + } + + private void enableMyLocationButton() { + try{ + mMap.setMyLocationEnabled(true); + MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.frag_maps_map); + View locationButton = ((View) mapFragment.getView().findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2")); + RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) locationButton.getLayoutParams(); + rlp.setMargins(0, 250, 30, 30); + }catch(SecurityException se){ + ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION); + } + } + @Override public void onLoadFinished(Loader arg0, Cursor c) { showLocations(c); @@ -756,19 +863,27 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa SearchableInfo searchInfo = searchManager.getSearchableInfo(getComponentName()); searchView.setSearchableInfo(searchInfo); - EditText txtSearch = ((EditText)searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text)); + EditText txtSearch = ((EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text)); txtSearch.setHint(getResources().getString(R.string.search_hint)); - txtSearch.setHintTextColor(Color.LTGRAY); - txtSearch.setTextColor(Color.WHITE); + txtSearch.setHintTextColor(Color.DKGRAY); + txtSearch.setTextColor(Color.BLACK); return true; } @Override - protected void onPause(){ - super.onPause(); - if(showAdd) showAd(); + protected void onPause() { + Log.d(TAG,"onPause executed: LM: "+(locationManager != null)+" LL: "+(locationListener!=null)); + if(locationManager != null && locationListener != null) { + locationManager.removeUpdates(locationListener); + locationListener = null; + locationManager = null; + } + + super.onPause(); + + if (showAdd) showAd(); } @Override @@ -781,21 +896,21 @@ public class MapsActivity extends BaseActivity implements LoaderManager.LoaderCa return getResources().getString(R.string.title_activity_maps); } - private void showProgress(){ + private void showProgress() { findViewById(R.id.pb_map_progress).setVisibility(View.VISIBLE); pbCounter++; } @Override - protected void onResume(){ + protected void onResume() { super.onResume(); navDrawer.setSelection(mapAvtivityID, false); showAdd = true; } - private void hideProgress(){ + private void hideProgress() { pbCounter--; - if(pbCounter == 0){ + if (pbCounter == 0) { findViewById(R.id.pb_map_progress).setVisibility(View.GONE); } } diff --git a/app/src/main/java/org/deke/risk/riskahead/ReportWFActivity.java b/app/src/main/java/org/deke/risk/riskahead/ReportWFActivity.java index 20c9980..55ed95a 100644 --- a/app/src/main/java/org/deke/risk/riskahead/ReportWFActivity.java +++ b/app/src/main/java/org/deke/risk/riskahead/ReportWFActivity.java @@ -29,8 +29,6 @@ import com.android.volley.toolbox.StringRequest; import com.beardedhen.androidbootstrap.BootstrapButton; import com.beardedhen.androidbootstrap.api.defaults.DefaultBootstrapBrand; import com.google.android.gms.maps.model.LatLng; -import com.google.android.gms.plus.Plus; -import com.google.android.gms.plus.model.people.Person; import com.google.gson.Gson; import org.deke.risk.riskahead.fragment.BaseReportWFFragment; @@ -123,7 +121,7 @@ public class ReportWFActivity extends BaseActivity implements ReportWF_1_Fragmen private void initButtonsAndElements() { btnContinue = (BootstrapButton) findViewById(R.id.btn_reportwf_next); - btnContinue.setVisibility(View.INVISIBLE); + btnContinue.setEnabled(false); btnContinue.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -133,7 +131,7 @@ public class ReportWFActivity extends BaseActivity implements ReportWF_1_Fragmen }); btnReportNow = (BootstrapButton) findViewById(R.id.btn_reportwf_reportnow); - btnReportNow.setVisibility(View.INVISIBLE); + btnReportNow.setEnabled(false); btnReportNow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -171,8 +169,8 @@ public class ReportWFActivity extends BaseActivity implements ReportWF_1_Fragmen } if(state == (fragList.size()-1)){ - btnContinue.setVisibility(View.INVISIBLE); - btnReportNow.setVisibility(View.INVISIBLE); + btnContinue.setEnabled(false); + btnReportNow.setEnabled(false); siteIndicator.setVisibility(View.INVISIBLE); }else{ siteIndicator.setVisibility(View.VISIBLE); @@ -254,15 +252,15 @@ public class ReportWFActivity extends BaseActivity implements ReportWF_1_Fragmen } if((currentState == 1 && finished) || (currentState > 1)){ - btnReportNow.setVisibility(View.VISIBLE); + btnReportNow.setEnabled(true); }else{ - btnReportNow.setVisibility(View.INVISIBLE); + btnReportNow.setEnabled(false); } if(finished || currentState > 1){ - btnContinue.setVisibility(View.VISIBLE); + btnContinue.setEnabled(true); }else{ - btnContinue.setVisibility(View.INVISIBLE); + btnContinue.setEnabled(false); } } @@ -315,7 +313,7 @@ public class ReportWFActivity extends BaseActivity implements ReportWF_1_Fragmen private StringRequest getStringRequestAddIncidentWithPosition(final IncidentReport incident) { showDialog(); - return new StringRequest(Request.Method.POST, AppConfig.URL_DEFAULT, new Response.Listener() { + return new StringRequest(Request.Method.POST, AppConfig.REST_ADD_INCIDENT_WITHPOSITION, new Response.Listener() { @Override public void onResponse(String response) { @@ -327,8 +325,7 @@ public class ReportWFActivity extends BaseActivity implements ReportWF_1_Fragmen if (!error) { showMessage(getString(R.string.txt_success_addreport)); - - showDialogWhenReportAdded(incident); + showShareDialog(incident); } else { String errorMsg = jObj.getString("error_msg"); Log.e(TAG, "Error adding incident (Server returned error): " + errorMsg); @@ -352,7 +349,6 @@ public class ReportWFActivity extends BaseActivity implements ReportWF_1_Fragmen @Override protected Map getParams() { Map params = new HashMap<>(); - params.put("tag", AppConfig.REST_ADD_INCIDENT_WITHPOSITION); params.put("uid", user.get(SessionManager.KEY_UID)); params.put("token", user.get(SessionManager.TOKEN)); params.put("latitude", Double.toString(incident.getPosition().latitude)); @@ -389,33 +385,20 @@ public class ReportWFActivity extends BaseActivity implements ReportWF_1_Fragmen }; } - private void showDialogWhenReportAdded(final IncidentReport incident) { - if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { - ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_STORAGE); - return; - }else{ - showShareDialog(incident); - } + private void requestPermission(){ + ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_STORAGE); } @Override - public void onRequestPermissionsResult(int requestCode, - String permissions[], int[] grantResults) { + public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_STORAGE: { - // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { - - showShareDialog(incident); - + startShareIncidentIntent(incident); } else { finishReportAndGotoMap(incident); } - return; } - - // other 'case' lines to check for other - // permissions this app might request } } @@ -425,13 +408,7 @@ public class ReportWFActivity extends BaseActivity implements ReportWF_1_Fragmen .setMessage(R.string.txt_share_message) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { - resetStateAndIncident(); - gotoMapActivity(incident.getPosition().latitude + ":" + incident.getPosition().longitude); - - startShareIncidentIntent(incident); - - } }) .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { @@ -441,28 +418,47 @@ public class ReportWFActivity extends BaseActivity implements ReportWF_1_Fragmen }) .setIcon(android.R.drawable.ic_dialog_alert) .show(); + } private void startShareIncidentIntent(IncidentReport incident) { - Intent sharingIntent = new Intent(Intent.ACTION_SEND); - Bitmap icon = BitmapFactory.decodeResource(getApplicationContext().getResources(), - R.drawable.ra_qrcode); - String text = getString(R.string.txt_share_hint) - +getString(R.string.txt_share_hint2)+": "+ incident.getIncidentCategoryName(getApplicationContext()) - +" - "+incident.getIncidentSubCategoryName(getApplicationContext())+"\n" - +getString(R.string.txt_share_hint3)+": "+ incident.getIncidentPositionDescription().split("\\n")[0] + " - " + incident.getIncidentPositionDescription().split("\\n")[1] + "\n" - +getString(R.string.txt_share_page); + if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { - sharingIntent.putExtra(Intent.EXTRA_TEXT, text); - sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(MediaStore.Images.Media.insertImage(getApplicationContext().getContentResolver(), icon, "Share incident", null))); - sharingIntent.setType("image/*"); - sharingIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); - startActivity(Intent.createChooser(sharingIntent, getString(R.string.txt_share_acttitle))); + AlertDialog alertDialog = new AlertDialog.Builder(this).create(); + alertDialog.setTitle("Request Permission"); + alertDialog.setMessage("If you want to use the sharing feature in the future we need storage permission to generate the message which should be shared."); + alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + requestPermission(); + } + }); + alertDialog.show(); + + }else{ + resetStateAndIncident(); + gotoMapActivity(incident.getPosition().latitude + ":" + incident.getPosition().longitude); + + Intent sharingIntent = new Intent(Intent.ACTION_SEND); + Bitmap icon = BitmapFactory.decodeResource(getApplicationContext().getResources(), + R.drawable.ra_qrcode); + String text = getString(R.string.txt_share_hint) + +getString(R.string.txt_share_hint2)+": "+ incident.getIncidentCategoryName(getApplicationContext()) + +" - "+incident.getIncidentSubCategoryName(getApplicationContext())+"\n" + +getString(R.string.txt_share_hint3)+": "+ incident.getIncidentPositionDescription().split("\\n")[0] + " - " + incident.getIncidentPositionDescription().split("\\n")[1] + "\n" + +getString(R.string.txt_share_page); + + sharingIntent.putExtra(Intent.EXTRA_TEXT, text); + sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(MediaStore.Images.Media.insertImage(getApplicationContext().getContentResolver(), icon, "Share incident", null))); + sharingIntent.setType("image/*"); + sharingIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + startActivity(Intent.createChooser(sharingIntent, getString(R.string.txt_share_acttitle))); + } } private void finishReportAndGotoMap(IncidentReport incident) { resetStateAndIncident(); - showAd(); gotoMapActivity(incident.getPosition().latitude + ":" + incident.getPosition().longitude); } diff --git a/app/src/main/java/org/deke/risk/riskahead/StartActivity.java b/app/src/main/java/org/deke/risk/riskahead/StartActivity.java deleted file mode 100644 index 9d45151..0000000 --- a/app/src/main/java/org/deke/risk/riskahead/StartActivity.java +++ /dev/null @@ -1,72 +0,0 @@ -package org.deke.risk.riskahead; - -import android.content.Intent; -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 org.deke.risk.riskahead.helper.AppConfig; -import org.deke.risk.riskahead.helper.SessionManager; - -/** - * - * (C) Copyright 2016 RiskAhead (http://www.riskahead.net) - * Developer & Contributor: Dennis Thießen (dennis.thiessen@riskahead.net) - * Date of Release: 10.02.2016 - * - */ -public class StartActivity extends AppCompatActivity { - - private final static String TAG = StartActivity.class.getSimpleName(); - - Button btnLogin; - Button btnRegister; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - Log.d(TAG,"RiskAhead started."); - - setContentView(R.layout.activity_start); - - btnLogin = (Button) findViewById(R.id.btn_start_login); - btnRegister = (Button) findViewById(R.id.btn_start_register); - - SessionManager session = new SessionManager(getApplicationContext()); - if (session.isLoggedIn()) { - Log.d(TAG,"User found in sharedPrefs and is therefore logged in. Continue to internal Area."); - 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(AppConfig.EXTRA_MESSAGE, AppConfig.INTENT_LOGIN); - startActivity(intent); - } - - public void gotoRegister(View view) { - Intent intent = new Intent(this, LoginActivity.class); - intent.putExtra(AppConfig.EXTRA_MESSAGE, AppConfig.INTENT_REGISTER); - startActivity(intent); - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - getMenuInflater().inflate(R.menu.menu_common, menu); - return true; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - return super.onOptionsItemSelected(item); - } - -} diff --git a/app/src/main/java/org/deke/risk/riskahead/SubscriptionsActivity.java b/app/src/main/java/org/deke/risk/riskahead/SubscriptionsActivity.java index d6b618b..2a6c350 100644 --- a/app/src/main/java/org/deke/risk/riskahead/SubscriptionsActivity.java +++ b/app/src/main/java/org/deke/risk/riskahead/SubscriptionsActivity.java @@ -309,7 +309,7 @@ public class SubscriptionsActivity extends BaseActivity{ } private StringRequest getStringAddSubscription(final String productId, final String type, final String price, final String currency) { - return new StringRequest(Request.Method.POST, AppConfig.URL_DEFAULT, new Response.Listener() { + return new StringRequest(Request.Method.POST, AppConfig.REST_ADD_SUBSCRIPTIONS, new Response.Listener() { @Override public void onResponse(String response) { @@ -345,7 +345,6 @@ public class SubscriptionsActivity extends BaseActivity{ @Override protected Map getParams() { Map params = new HashMap<>(); - params.put("tag", "addsubscription"); params.put("uid", user.get(SessionManager.KEY_UID)); params.put("token", user.get(SessionManager.TOKEN)); params.put("productid", productId); @@ -365,7 +364,7 @@ public class SubscriptionsActivity extends BaseActivity{ } private StringRequest getStringGetSubscriptions(final String userId) { - return new StringRequest(Request.Method.POST, AppConfig.URL_DEFAULT, new Response.Listener() { + return new StringRequest(Request.Method.POST, AppConfig.REST_GET_SUBSCRIPTIONS, new Response.Listener() { @Override public void onResponse(String response) { @@ -407,7 +406,6 @@ public class SubscriptionsActivity extends BaseActivity{ @Override protected Map getParams() { Map params = new HashMap<>(); - params.put("tag", "getsubscriptions"); params.put("uid", user.get(SessionManager.KEY_UID)); params.put("token", user.get(SessionManager.TOKEN)); params.put("userid", userId); @@ -426,7 +424,7 @@ public class SubscriptionsActivity extends BaseActivity{ } private StringRequest getStringDeactivateSubscriptions(final String subscriptionId) { - return new StringRequest(Request.Method.POST, AppConfig.URL_DEFAULT, new Response.Listener() { + return new StringRequest(Request.Method.POST, AppConfig.REST_DEACTIVATE_SUBSCRIPTIONS, new Response.Listener() { @Override public void onResponse(String response) { @@ -457,7 +455,6 @@ public class SubscriptionsActivity extends BaseActivity{ @Override protected Map getParams() { Map params = new HashMap<>(); - params.put("tag", "deactivatesubscription"); params.put("uid", user.get(SessionManager.KEY_UID)); params.put("token", user.get(SessionManager.TOKEN)); params.put("subid", subscriptionId); diff --git a/app/src/main/java/org/deke/risk/riskahead/ViewReportActivity.java b/app/src/main/java/org/deke/risk/riskahead/ViewReportActivity.java index 8991993..830dd9e 100644 --- a/app/src/main/java/org/deke/risk/riskahead/ViewReportActivity.java +++ b/app/src/main/java/org/deke/risk/riskahead/ViewReportActivity.java @@ -158,7 +158,7 @@ public class ViewReportActivity extends BaseActivity { } private StringRequest getStringRequestDeleteIncident(final Integer incidentid) { - return new StringRequest(Request.Method.POST, AppConfig.URL_DEFAULT, new Response.Listener() { + return new StringRequest(Request.Method.POST, AppConfig.REST_DEACTIVATE_INCIDENT, new Response.Listener() { @Override public void onResponse(String response) { @@ -194,7 +194,6 @@ public class ViewReportActivity extends BaseActivity { @Override protected Map getParams() { Map params = new HashMap<>(); - params.put("tag", AppConfig.REST_DEACTIVATE_INCIDENT); params.put("uid", user.get(SessionManager.KEY_UID)); params.put("token", user.get(SessionManager.TOKEN)); params.put("incidentid", incidentid.toString()); @@ -213,7 +212,7 @@ public class ViewReportActivity extends BaseActivity { } private StringRequest getStringRequestGetIncidentWithPositionFromID(final Integer incidentid) { - return new StringRequest(Request.Method.POST, AppConfig.URL_DEFAULT, new Response.Listener() { + return new StringRequest(Request.Method.POST, AppConfig.REST_GET_INCIDENT, new Response.Listener() { @Override public void onResponse(String response) { @@ -253,7 +252,6 @@ public class ViewReportActivity extends BaseActivity { protected Map getParams() { // Posting parameters to login url Map params = new HashMap<>(); - params.put("tag", AppConfig.REST_GET_INCIDENTS_FROMINCIDENTID); params.put("uid", user.get(SessionManager.KEY_UID)); params.put("token", user.get(SessionManager.TOKEN)); params.put("incidentid", incidentid.toString()); @@ -447,7 +445,7 @@ public class ViewReportActivity extends BaseActivity { } private StringRequest getStringRequestAddVote(final Integer incidentid, final String votetype) { - return new StringRequest(Request.Method.POST, AppConfig.URL_DEFAULT, new Response.Listener() { + return new StringRequest(Request.Method.POST, AppConfig.REST_ADD_VOTE, new Response.Listener() { @Override public void onResponse(String response) { @@ -484,7 +482,6 @@ public class ViewReportActivity extends BaseActivity { @Override protected Map getParams() { Map params = new HashMap<>(); - params.put("tag", AppConfig.REST_ADD_VOTE); params.put("uid", user.get(SessionManager.KEY_UID)); params.put("token", user.get(SessionManager.TOKEN)); params.put("incidentid", incidentid.toString()); @@ -502,7 +499,7 @@ public class ViewReportActivity extends BaseActivity { } private StringRequest getStringRequestDeleteVote(final Integer incidentid) { - return new StringRequest(Request.Method.POST, AppConfig.URL_DEFAULT, new Response.Listener() { + return new StringRequest(Request.Method.POST, AppConfig.REST_DELETE_VOTE, new Response.Listener() { @Override public void onResponse(String response) { @@ -537,7 +534,6 @@ public class ViewReportActivity extends BaseActivity { @Override protected Map getParams() { Map params = new HashMap<>(); - params.put("tag", AppConfig.REST_DELETE_VOTE); params.put("uid", user.get(SessionManager.KEY_UID)); params.put("token", user.get(SessionManager.TOKEN)); params.put("incidentid", incidentid.toString()); diff --git a/app/src/main/java/org/deke/risk/riskahead/fragment/FacebookButtonFragment.java b/app/src/main/java/org/deke/risk/riskahead/fragment/FacebookButtonFragment.java index 7718aec..52c5f28 100644 --- a/app/src/main/java/org/deke/risk/riskahead/fragment/FacebookButtonFragment.java +++ b/app/src/main/java/org/deke/risk/riskahead/fragment/FacebookButtonFragment.java @@ -76,8 +76,6 @@ public class FacebookButtonFragment extends Fragment { FacebookSdk.sdkInitialize(getContext()); callbackManager = CallbackManager.Factory.create(); initFacebookButton(); - - } @Override @@ -112,13 +110,13 @@ public class FacebookButtonFragment extends Fragment { @Override public void onCancel() { Log.d("FB","OnCancel"); - ((LoginActivity) getActivity()).showMessage("Facebook LogIn canceled"); + ((LoginActivity) getActivity()).showMessage("Facebook LogIn canceled. Please use E-Mail instead."); } @Override public void onError(FacebookException exception) { - Log.d("FB","OnError"); - ((LoginActivity) getActivity()).showMessage("Error while SignIn: ErrorMsg: " + exception.toString()); + Log.d("FB","OnError: " + exception.toString()); + ((LoginActivity) getActivity()).showMessage("Could not log in with Facebook. Please use E-Mail instead or try again later."); } }); } @@ -127,7 +125,6 @@ public class FacebookButtonFragment extends Fragment { GraphRequest request = GraphRequest.newMeRequest(accesstoken, new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject objects, GraphResponse response) { - try { ((LoginActivity) getActivity()).handleSocialMediaLogin(objects.getString("id"), "facebook", objects.getString("first_name"), objects.getString("email")); } catch (JSONException e) { diff --git a/app/src/main/java/org/deke/risk/riskahead/fragment/GooglePlusButtonFragment.java b/app/src/main/java/org/deke/risk/riskahead/fragment/GooglePlusButtonFragment.java index 7e87034..0ebfaef 100644 --- a/app/src/main/java/org/deke/risk/riskahead/fragment/GooglePlusButtonFragment.java +++ b/app/src/main/java/org/deke/risk/riskahead/fragment/GooglePlusButtonFragment.java @@ -2,7 +2,9 @@ package org.deke.risk.riskahead.fragment; import android.Manifest; import android.app.Activity; +import android.app.AlertDialog; import android.content.Context; +import android.content.DialogInterface; import android.content.Intent; import android.content.IntentSender; import android.content.pm.PackageManager; @@ -82,11 +84,28 @@ public class GooglePlusButtonFragment extends Fragment implements GoogleApiClien } private void performClickAction() { - + Log.d(TAG,"Click on Google+ Button performed"); if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) { - ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.GET_ACCOUNTS}, MY_PERMISSIONS_REQUEST_ACCOUNTS); + Log.d(TAG,"Permission not granted yet - request now"); + + // Should we show an explanation? + AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create(); + alertDialog.setTitle("Request Permission"); + alertDialog.setMessage("Google needs permission to see your profile (Contact List) in order to enable log-in with Google+. However, if you do not grant permission, log in with Google+ will not be available."); + alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + requestPermissions(new String[]{Manifest.permission.GET_ACCOUNTS}, MY_PERMISSIONS_REQUEST_ACCOUNTS); + } + }); + alertDialog.show(); + + }else{ + Log.d(TAG,"Permission already granted"); + if(mGoogleApiClient.isConnected()){ Person currentPerson = getProfileInformation(); ((LoginActivity) getActivity()).handleSocialMediaLogin(currentPerson.getId(),"google",currentPerson.getDisplayName(),Plus.AccountApi.getAccountName(mGoogleApiClient)); @@ -97,28 +116,28 @@ public class GooglePlusButtonFragment extends Fragment implements GoogleApiClien } @Override - public void onRequestPermissionsResult(int requestCode, - String permissions[], int[] grantResults) { + public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { + Log.d(TAG,"RequestCode: "+requestCode); + switch (requestCode) { case MY_PERMISSIONS_REQUEST_ACCOUNTS: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + Log.d(TAG,"Permission granted"); if(mGoogleApiClient.isConnected()){ Person currentPerson = getProfileInformation(); ((LoginActivity) getActivity()).handleSocialMediaLogin(currentPerson.getId(),"google",currentPerson.getDisplayName(),Plus.AccountApi.getAccountName(mGoogleApiClient)); }else{ - signInWithGplus(); + signInWithGplus(); } } else { - + Log.d(TAG,"Permission not granted - what now?"); + Toast.makeText(mContext, "Could not log in with Google+. Please use E-Mail instead or try again later.", + Toast.LENGTH_LONG).show(); } - return; } - - // other 'case' lines to check for other - // permissions this app might request } } @@ -162,7 +181,6 @@ public class GooglePlusButtonFragment extends Fragment implements GoogleApiClien } if (!mIntentInProgress) { - mConnectionResult = result; if (mSignInClicked) { @@ -171,7 +189,6 @@ public class GooglePlusButtonFragment extends Fragment implements GoogleApiClien resolveSignInError(); } } - } @Override @@ -187,8 +204,6 @@ public class GooglePlusButtonFragment extends Fragment implements GoogleApiClien mGoogleApiClient.connect(); } - - /** * Sign-in into google * */ diff --git a/app/src/main/java/org/deke/risk/riskahead/fragment/ProfileStatisticsFragment.java b/app/src/main/java/org/deke/risk/riskahead/fragment/ProfileStatisticsFragment.java index 70ee779..c5cd32a 100644 --- a/app/src/main/java/org/deke/risk/riskahead/fragment/ProfileStatisticsFragment.java +++ b/app/src/main/java/org/deke/risk/riskahead/fragment/ProfileStatisticsFragment.java @@ -86,7 +86,7 @@ public class ProfileStatisticsFragment extends Fragment { } private StringRequest getStringRequestProfileStats() { - return new StringRequest(Request.Method.POST, AppConfig.URL_DEFAULT, new Response.Listener() { + return new StringRequest(Request.Method.POST, AppConfig.REST_GET_USERSTATS, new Response.Listener() { @Override public void onResponse(String response) { @@ -96,11 +96,12 @@ public class ProfileStatisticsFragment extends Fragment { JSONObject jObj = new JSONObject(response); boolean error = jObj.getBoolean("error"); if (!error) { - jObj = jObj.getJSONObject("msg"); - points.setText(jObj.getString("points")); - ranking.setText(jObj.getString("rank")); posts.setText(jObj.getString("numberOfPosts")); - txtMemberSince.setText(jObj.getString("created_at")); + + JSONObject subJObj = jObj.getJSONObject("msg"); + points.setText(subJObj.getString("points")); + ranking.setText(subJObj.getString("rank")); + txtMemberSince.setText(subJObj.getString("created_at")); JSONArray jSubs = jObj.getJSONArray("subs"); @@ -158,7 +159,6 @@ public class ProfileStatisticsFragment extends Fragment { @Override protected Map getParams() { Map params = new HashMap<>(); - params.put("tag", AppConfig.REST_GET_USERSTATS); params.put("uid", parent.user.get(SessionManager.KEY_UID)); params.put("token", parent.user.get(SessionManager.TOKEN)); params.put("userstatsid", uid); diff --git a/app/src/main/java/org/deke/risk/riskahead/fragment/ReportListFragment.java b/app/src/main/java/org/deke/risk/riskahead/fragment/ReportListFragment.java index 7e87e01..e16cb8a 100644 --- a/app/src/main/java/org/deke/risk/riskahead/fragment/ReportListFragment.java +++ b/app/src/main/java/org/deke/risk/riskahead/fragment/ReportListFragment.java @@ -86,7 +86,7 @@ public class ReportListFragment extends Fragment{ } private StringRequest getStringRequestGetIncidentsWithPositionFromUserID() { - return new StringRequest(Request.Method.POST, AppConfig.URL_DEFAULT, new Response.Listener() { + return new StringRequest(Request.Method.POST, AppConfig.REST_GET_INCIDENTS_FROMUSERID, new Response.Listener() { @Override public void onResponse(String response) { @@ -136,7 +136,6 @@ public class ReportListFragment extends Fragment{ @Override protected Map getParams() { Map params = new HashMap<>(); - params.put("tag", AppConfig.REST_GET_INCIDENTS_FROMUSERID); params.put("uid", parent.user.get(SessionManager.KEY_UID)); params.put("token", parent.user.get(SessionManager.TOKEN)); params.put("userincidentid", uid); diff --git a/app/src/main/java/org/deke/risk/riskahead/fragment/ReportWF_1_Fragment.java b/app/src/main/java/org/deke/risk/riskahead/fragment/ReportWF_1_Fragment.java index 5e24018..277c30c 100644 --- a/app/src/main/java/org/deke/risk/riskahead/fragment/ReportWF_1_Fragment.java +++ b/app/src/main/java/org/deke/risk/riskahead/fragment/ReportWF_1_Fragment.java @@ -25,12 +25,10 @@ import org.deke.risk.riskahead.adapter.SpinnerHintAdapter; * */ public class ReportWF_1_Fragment extends BaseReportWFFragment{ - private final static int VIOLANCE_GENERAL = 1; - private final static int VIOLANCE_VERBAL = 2; - private final static int VIOLANCE_LIGHT = 3; - private final static int VIOLANCE_HARD = 4; - private final static int VIOLANCE_NATURE = 5; - private final static int VIOLANCE_INFRASTRUCTURE = 6; + private final static int VIOLANCE_THREAT = 1; + private final static int VIOLANCE_PHYSICAL = 2; + private final static int VIOLANCE_LIFETHREAT = 3; + private final static int VIOLANCE_DISASTER = 4; private View viewFragment; @@ -89,25 +87,19 @@ public class ReportWF_1_Fragment extends BaseReportWFFragment{ switch (position) { case 1: - stringId = R.array.cat_situation_sub_general; + stringId = R.array.cat_situation_sub_threat; break; case 2: - stringId = R.array.cat_situation_sub_verbal; + stringId = R.array.cat_situation_sub_physical; break; case 3: - stringId = R.array.cat_situation_sub_force; + stringId = R.array.cat_situation_sub_lifethreat; break; case 4: - stringId = R.array.cat_situation_sub_force_serious; - break; - case 5: - stringId = R.array.cat_situation_sub_nature; - break; - case 6: - stringId = R.array.cat_situation_sub_infrastructure; + stringId = R.array.cat_situation_sub_disaster; break; default: - stringId = R.array.cat_situation_sub_general; + stringId = R.array.cat_situation_sub_threat; break; } @@ -120,9 +112,6 @@ public class ReportWF_1_Fragment extends BaseReportWFFragment{ checkIfFinished(); } - - - } @Override diff --git a/app/src/main/java/org/deke/risk/riskahead/fragment/ReportWF_2_Fragment.java b/app/src/main/java/org/deke/risk/riskahead/fragment/ReportWF_2_Fragment.java index bfb37af..8f6d6b5 100644 --- a/app/src/main/java/org/deke/risk/riskahead/fragment/ReportWF_2_Fragment.java +++ b/app/src/main/java/org/deke/risk/riskahead/fragment/ReportWF_2_Fragment.java @@ -6,6 +6,9 @@ import android.support.v4.app.DialogFragment; import android.app.TimePickerDialog; import android.content.Context; import android.os.Bundle; +import android.support.v4.app.FragmentManager; +import android.text.Editable; +import android.text.TextWatcher; import android.text.format.DateFormat; import android.view.LayoutInflater; import android.view.View; @@ -46,19 +49,22 @@ public class ReportWF_2_Fragment extends BaseReportWFFragment { private Spinner timeCategory; private Spinner timeSubCategory; - private EditText inputTimeFrom; - private EditText inputDateFrom; - private EditText inputTimeTo; - private EditText inputDateTo; + private static EditText inputTimeFrom; + private static EditText inputDateFrom; + private static EditText inputTimeTo; + private static EditText inputDateTo; - private EditText tmpInput; + private static EditText tmpInput; private IncidentReport incident; private OnInputFinishedListener mCallback; - private boolean tmpIsToDate = false; - private boolean tmpIsToTime = false; + public static boolean tmpIsToDate = false; + public static boolean tmpIsToTime = false; + + private DialogFragment timePickerFragment; + private DialogFragment datePickerFragment; public interface OnInputFinishedListener { void onInputFinished(boolean finished); @@ -194,6 +200,22 @@ public class ReportWF_2_Fragment extends BaseReportWFFragment { @Override public void onClick(View v) { tmpInput = inputDateFrom; + tmpInput.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + + } + + @Override + public void afterTextChanged(Editable s) { + checkIfFinished(); + } + }); showDatePickerDialog(); } }); @@ -202,6 +224,22 @@ public class ReportWF_2_Fragment extends BaseReportWFFragment { @Override public void onClick(View v) { tmpInput = inputTimeFrom; + tmpInput.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + + } + + @Override + public void afterTextChanged(Editable s) { + checkIfFinished(); + } + }); showTimePickerDialog(); } }); @@ -233,7 +271,7 @@ public class ReportWF_2_Fragment extends BaseReportWFFragment { }); } - public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener { + public static class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { @@ -247,17 +285,22 @@ public class ReportWF_2_Fragment extends BaseReportWFFragment { public void onTimeSet(TimePicker view, int hourOfDay, int minute) { tmpInput.setText(String.format("%02d:%02d",hourOfDay,minute)); - checkIfFinished(); + //checkIfFinished(); } } public void showTimePickerDialog() { - DialogFragment newFragment = new TimePickerFragment(); + FragmentManager fm = getFragmentManager(); + timePickerFragment = (TimePickerFragment) fm.findFragmentByTag("Pick Time"); - newFragment.show(getActivity().getSupportFragmentManager(), "Pick Time"); + if(timePickerFragment == null){ + timePickerFragment = new TimePickerFragment(); + } + + timePickerFragment.show(fm, "Pick Time"); } - public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { + public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { @@ -286,13 +329,20 @@ public class ReportWF_2_Fragment extends BaseReportWFFragment { public void onDateSet(DatePicker view, int year, int month, int day) { tmpInput.setText(String.format("%04d-%02d-%02d",year,month + 1,day)); - checkIfFinished(); + //checkIfFinished(); } } public void showDatePickerDialog() { - DialogFragment newFragment = new DatePickerFragment(); - newFragment.show(getActivity().getSupportFragmentManager(), "Pick Date"); + + FragmentManager fm = getFragmentManager(); + datePickerFragment = (DatePickerFragment) fm.findFragmentByTag("Pick Date"); + + if(datePickerFragment == null){ + datePickerFragment = new DatePickerFragment(); + } + + datePickerFragment.show(fm, "Pick Date"); } private void checkIfFinished(){ @@ -361,6 +411,25 @@ public class ReportWF_2_Fragment extends BaseReportWFFragment { checkIfFinished(); } + @Override + public void onStop() { + super.onStop(); + //invalidate the DialogFragment to avoid stupid memory leak + if (timePickerFragment != null) { + if (timePickerFragment.isVisible()) { + timePickerFragment.dismiss(); + } + timePickerFragment = null; + } + + if (datePickerFragment != null) { + if (datePickerFragment.isVisible()) { + datePickerFragment.dismiss(); + } + datePickerFragment = null; + } + } + @Override public void onPause() { super.onPause(); diff --git a/app/src/main/java/org/deke/risk/riskahead/fragment/SettingsFragment.java b/app/src/main/java/org/deke/risk/riskahead/fragment/SettingsFragment.java index 6142333..b4cc77a 100644 --- a/app/src/main/java/org/deke/risk/riskahead/fragment/SettingsFragment.java +++ b/app/src/main/java/org/deke/risk/riskahead/fragment/SettingsFragment.java @@ -128,7 +128,9 @@ public class SettingsFragment extends PreferenceFragment { prefLocation.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { - if (session.getLocation().longitude != 0.0 && session.getLocation().latitude != 0.0) { + if (session.getManualLocation().longitude != 0.0 && session.getManualLocation().latitude != 0.0) { + ((SettingsActivity) getActivity()).getNotifyLocationFromMapActivity(Double.toString(session.getManualLocation().latitude) + " : " + Double.toString(session.getManualLocation().longitude)); + } else if(session.getLocation().longitude != 0.0 && session.getLocation().latitude != 0.0){ ((SettingsActivity) getActivity()).getNotifyLocationFromMapActivity(Double.toString(session.getLocation().latitude) + " : " + Double.toString(session.getLocation().longitude)); } else { ((SettingsActivity) getActivity()).getNotifyLocationFromMapActivity(); @@ -218,7 +220,7 @@ public class SettingsFragment extends PreferenceFragment { prefRadius.setValue(Integer.toString(session.getNotificationRadius())); prefRadius.setSummary(prefRadius.getEntry()); prefGPSENabled.setChecked(session.isGPSForNotificationsEnabled()); - prefLocation.setSummary(getResources().getString(R.string.txt_settings_gps_loca_sum)+":\n"+Double.toString(session.getLocation().latitude)+" : "+Double.toString(session.getLocation().longitude)); + prefLocation.setSummary(getResources().getString(R.string.txt_settings_gps_loca_sum)+":\n"+Double.toString(session.getManualLocation().latitude)+" : "+Double.toString(session.getManualLocation().longitude)); if(session.getSubsPremium()){ if(session.isGPSForNotificationsEnabled()){ @@ -239,7 +241,7 @@ public class SettingsFragment extends PreferenceFragment { private StringRequest getStringRequestResetPW(final String email) { ((SettingsActivity) getActivity()).showDialog(); - return new StringRequest(Request.Method.POST, AppConfig.URL_DEFAULT, new Response.Listener() { + return new StringRequest(Request.Method.POST, AppConfig.REST_REQUESTPWRESET, new Response.Listener() { @Override public void onResponse(String response) { @@ -275,7 +277,6 @@ public class SettingsFragment extends PreferenceFragment { @Override protected Map getParams() { Map params = new HashMap<>(); - params.put("tag", AppConfig.REST_REQUESTPWRESET); params.put("email", email); return params; @@ -304,7 +305,7 @@ public class SettingsFragment extends PreferenceFragment { } private StringRequest getStringChangeUserSettings(final String username, final String name, final String surname, final String email) { - return new StringRequest(Request.Method.POST, AppConfig.URL_DEFAULT, new Response.Listener() { + return new StringRequest(Request.Method.POST, AppConfig.REST_UPDATE_USER, new Response.Listener() { @Override public void onResponse(String response) { @@ -364,7 +365,6 @@ public class SettingsFragment extends PreferenceFragment { @Override protected Map getParams() { Map params = new HashMap<>(); - params.put("tag", AppConfig.REST_UPDATE_USER); params.put("uid", user.get(SessionManager.KEY_UID)); params.put("token", user.get(SessionManager.TOKEN)); params.put("username", username); diff --git a/app/src/main/java/org/deke/risk/riskahead/fragment/Top10Fragment.java b/app/src/main/java/org/deke/risk/riskahead/fragment/Top10Fragment.java index d08ca7d..dca2368 100644 --- a/app/src/main/java/org/deke/risk/riskahead/fragment/Top10Fragment.java +++ b/app/src/main/java/org/deke/risk/riskahead/fragment/Top10Fragment.java @@ -79,7 +79,7 @@ public class Top10Fragment extends Fragment { private StringRequest getStringRequestTop10() { - return new StringRequest(Request.Method.POST, AppConfig.URL_DEFAULT, new Response.Listener() { + return new StringRequest(Request.Method.POST, AppConfig.REST_GET_TOP10, new Response.Listener() { @Override public void onResponse(String response) { @@ -129,7 +129,6 @@ public class Top10Fragment extends Fragment { @Override protected Map getParams() { Map params = new HashMap<>(); - params.put("tag", AppConfig.REST_GET_TOP10); params.put("uid", parent.user.get(SessionManager.KEY_UID)); params.put("token", parent.user.get(SessionManager.TOKEN)); diff --git a/app/src/main/java/org/deke/risk/riskahead/fragment/TwitterButtonFragment.java b/app/src/main/java/org/deke/risk/riskahead/fragment/TwitterButtonFragment.java index 2784940..d900267 100644 --- a/app/src/main/java/org/deke/risk/riskahead/fragment/TwitterButtonFragment.java +++ b/app/src/main/java/org/deke/risk/riskahead/fragment/TwitterButtonFragment.java @@ -87,8 +87,8 @@ public class TwitterButtonFragment extends Fragment { @Override public void failure(TwitterException exception) { - Log.e("Debug", "onFailure wird ausgeführt"); - showMessage("Twitter Login failed with exception " + exception.getMessage()); + Log.e("Twitter", "onFailure wird ausgeführt: "+exception); + showMessage("Could not log in with Twitter. Please use E-Mail instead or try again later."); } }); } 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 index d4125ee..d26bcac 100644 --- a/app/src/main/java/org/deke/risk/riskahead/helper/AppConfig.java +++ b/app/src/main/java/org/deke/risk/riskahead/helper/AppConfig.java @@ -11,13 +11,11 @@ public class AppConfig { /** GENERAL **/ public final static String APP_PNAME = "org.deke.risk.riskahead"; - /** URLs **/ - public final static String URL_ENCRYPTED = "https://www.riskahead.de/helper/rest/"; - public final static String URL_DEFAULT = "http://www.riskahead.de/helper/rest/"; + public final static String URL_ENCRYPTED = "https://www.riskahead.de/api/v1"; - public final static String URL_ABOUT = "http://www.riskahead.de/en/about/"; - public final static String URL_CONTACT = "http://www.riskahead.de/en/contact/"; + public final static String URL_ABOUT = "https://www.riskahead.net/about/"; + public final static String URL_CONTACT = "https://www.riskahead.net/contact/"; /** INTENT MESSAGES **/ public final static String EXTRA_MESSAGE = "org.deke.risk.riskahead.MESSAGE"; @@ -39,27 +37,45 @@ public class AppConfig { public final static int VOTETYPE_DOWNVOTE = 2; /** REST WEBSERVICE **/ - public final static String REST_LOGIN = "login"; - public final static String REST_LOGIN_SOCIAL = "sociallogin"; - public final static String REST_LOGIN_EXISTS= "checkifuserexists"; - public final static String REST_REGISTER = "register"; - public final static String REST_RESENDACTIVATIONMAIL = "resendactivationusermail"; - public final static String REST_REQUESTPWRESET = "requestpwreset"; - public final static String REST_GET_NUMOFINCIDENTS = "getincidentcount"; - public final static String REST_GET_INCIDENTS_FROMBOUND = "getincidentsfrombound"; - public final static String REST_GET_INCIDENTS_FROMBOUND_FORHEATMAP = "getincidentsforheatmapfrombound"; - public final static String REST_GET_INCIDENTS_FROMUSERID = "getincidentsfromuserid"; - public final static String REST_GET_INCIDENTS_FROMINCIDENTID = "getincidentfromincidentid"; - public final static String REST_ADD_INCIDENT_WITHPOSITION = "addincidentwithposition"; - public final static String REST_UPDATE_USER = "updateuser"; - public final static String REST_GET_USERSTATS = "getuserstats"; - public final static String REST_GET_INCIDENTS_FROMAREATIME = "getincidentsinareaandtime"; - public final static String REST_GET_TOP10 = "gettop10"; - public final static String REST_ADD_VOTE = "addvote"; - public final static String REST_DELETE_VOTE = "deletevote"; - public final static String REST_SEND_FEEDBACK = "sendfeedback"; - public final static String REST_DEACTIVATE_INCIDENT = "deactivateincident"; + public final static String ROUTE_PUB = "/public"; + public final static String ROUTE_AUTH = "/auth"; - public static final String REST_CHECK_MAINTENANCE = "checkformaintenance"; - public static final String REST_CHECK_VERSION= "checkifversionvalid"; + public final static String ROUTE_GROUP_USERS = "/users"; + public final static String ROUTE_GROUP_SOCIALMEDIAS = "/socialmedias"; + public final static String ROUTE_GROUP_VALIDATIONS = "/validations"; + public final static String ROUTE_GROUP_INCIDENTS = "/incidents"; + public final static String ROUTE_GROUP_SUBSCRIPTIONS = "/subscriptions"; + public final static String ROUTE_GROUP_VOTES = "/votes"; + + public final static String REST_LOGIN = URL_ENCRYPTED + ROUTE_PUB + ROUTE_GROUP_USERS + "/login/"; + public final static String REST_REGISTER = URL_ENCRYPTED + ROUTE_PUB + ROUTE_GROUP_USERS + "/register/"; + public final static String REST_USEREXISTS = URL_ENCRYPTED + ROUTE_PUB + ROUTE_GROUP_USERS + "/exists/"; + public final static String REST_LOGIN_SOCIAL = URL_ENCRYPTED + ROUTE_PUB + ROUTE_GROUP_SOCIALMEDIAS + "/login/"; + + public final static String REST_SENDACTIVATIONMAIL = URL_ENCRYPTED + ROUTE_PUB + ROUTE_GROUP_USERS + "/sendactivation/"; + public final static String REST_REQUESTPWRESET = URL_ENCRYPTED + ROUTE_PUB + ROUTE_GROUP_USERS + "/sendpwreset/"; + + public final static String REST_GET_NUMOFINCIDENTS = URL_ENCRYPTED + ROUTE_AUTH + ROUTE_GROUP_INCIDENTS + "/get/number/"; + public final static String REST_GET_INCIDENT = URL_ENCRYPTED + ROUTE_AUTH + ROUTE_GROUP_INCIDENTS + "/get/incidentid/"; + public final static String REST_GET_INCIDENTS_FROMUSERID = URL_ENCRYPTED + ROUTE_AUTH + ROUTE_GROUP_INCIDENTS + "/get/userid/"; + public final static String REST_GET_INCIDENTS_FROMBOUND = URL_ENCRYPTED + ROUTE_AUTH + ROUTE_GROUP_INCIDENTS + "/get/activefrombound/"; + public final static String REST_GET_INCIDENTS_FROMBOUND_FORHEATMAP = URL_ENCRYPTED + ROUTE_AUTH + ROUTE_GROUP_INCIDENTS + "/get/activefromboundreduced/"; + public final static String REST_GET_INCIDENTS_FROMAREATIME = URL_ENCRYPTED + ROUTE_AUTH + ROUTE_GROUP_INCIDENTS + "/get/boundandtime/"; + + public final static String REST_DEACTIVATE_INCIDENT = URL_ENCRYPTED + ROUTE_AUTH + ROUTE_GROUP_INCIDENTS + "/deactivate/"; + public final static String REST_ADD_INCIDENT_WITHPOSITION = URL_ENCRYPTED + ROUTE_AUTH + ROUTE_GROUP_INCIDENTS + "/add/withposition/"; + + public final static String REST_UPDATE_USER = URL_ENCRYPTED + ROUTE_AUTH + ROUTE_GROUP_USERS + "/update/"; + public final static String REST_GET_USERSTATS = URL_ENCRYPTED + ROUTE_AUTH + ROUTE_GROUP_USERS + "/statistics/"; + public final static String REST_GET_TOP10 = URL_ENCRYPTED + ROUTE_AUTH + ROUTE_GROUP_USERS + "/top10/"; + public final static String REST_SEND_FEEDBACK = URL_ENCRYPTED + ROUTE_AUTH + ROUTE_GROUP_USERS + "/feedback/"; + public final static String REST_GET_SUBSCRIPTIONS = URL_ENCRYPTED + ROUTE_AUTH + ROUTE_GROUP_USERS + ROUTE_GROUP_SUBSCRIPTIONS + "/"; + public final static String REST_ADD_SUBSCRIPTIONS = URL_ENCRYPTED + ROUTE_AUTH + ROUTE_GROUP_USERS + ROUTE_GROUP_SUBSCRIPTIONS + "/add/"; + public final static String REST_DEACTIVATE_SUBSCRIPTIONS = URL_ENCRYPTED + ROUTE_AUTH + ROUTE_GROUP_USERS + ROUTE_GROUP_SUBSCRIPTIONS + "/deactivate/"; + + public final static String REST_ADD_VOTE = URL_ENCRYPTED + ROUTE_AUTH + ROUTE_GROUP_USERS + ROUTE_GROUP_VOTES + "/add/"; + public final static String REST_DELETE_VOTE = URL_ENCRYPTED + ROUTE_AUTH + ROUTE_GROUP_USERS + ROUTE_GROUP_VOTES + "/delete/"; + + public static final String REST_CHECK_MAINTENANCE = URL_ENCRYPTED + ROUTE_PUB + ROUTE_GROUP_VALIDATIONS + "/maintenance/"; + public static final String REST_CHECK_VERSION = URL_ENCRYPTED + ROUTE_PUB + ROUTE_GROUP_VALIDATIONS + "/version/"; } 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 index a673863..95b14a2 100644 --- a/app/src/main/java/org/deke/risk/riskahead/helper/BaseActivity.java +++ b/app/src/main/java/org/deke/risk/riskahead/helper/BaseActivity.java @@ -56,7 +56,6 @@ import com.mikepenz.materialdrawer.model.ProfileDrawerItem; import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem; 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.ProfileActivity; @@ -72,11 +71,9 @@ import java.util.Locale; import java.util.Map; /** - * * (C) Copyright 2016 RiskAhead (http://www.riskahead.net) * Developer & Contributor: Dennis Thießen (dennis.thiessen@riskahead.net) * Date of Release: 10.02.2016 - * */ public abstract class BaseActivity extends AppCompatActivity { @@ -107,14 +104,14 @@ public abstract class BaseActivity extends AppCompatActivity { int onStartCount = 0; - public void userHasToBeLoggedIn(){ + public void userHasToBeLoggedIn() { if (!session.isLoggedIn()) { logout(); } isNetworkAvailable(); } - public HashMap getUser(){ + public HashMap getUser() { user = session.getUserDetails(); return user; } @@ -138,14 +135,11 @@ public abstract class BaseActivity extends AppCompatActivity { super.onCreate(savedInstanceState); - onStartCount = 1; - if (savedInstanceState == null) - { + if (savedInstanceState == null) { this.overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left); - } else - { + } else { onStartCount = 2; } @@ -157,22 +151,15 @@ public abstract class BaseActivity extends AppCompatActivity { session = new SessionManager(getApplicationContext()); user = session.getUserDetails(); - Log.d(TAG,user.get(SessionManager.KEY_UID)); + Log.d(TAG, user.get(SessionManager.KEY_UID)); mToolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(mToolbar); initNavigationDrawer(savedInstanceState); - - if(!isMyNotificationServiceRunning() && session.getNotificationEnabled()){ - - if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { - ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},1); - return; - } - - Log.d(TAG,"onCreate: NotificationService not running. Starting service..."); + if (!isMyNotificationServiceRunning()) { + Log.d(TAG, "onCreate: NotificationService not running. Starting service..."); Intent wtdSServiceIntent = new Intent(this, NotificationService.class); PendingIntent wtdSServicePendingIntent = PendingIntent.getService(this, 0, wtdSServiceIntent, 0); @@ -183,13 +170,12 @@ public abstract class BaseActivity extends AppCompatActivity { AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); am.setInexactRepeating(AlarmManager.RTC, firstStart, interval, - wtdSServicePendingIntent); + wtdSServicePendingIntent); - Log.d(TAG, "AlarmManager set"); startService(new Intent(this, NotificationService.class)); - }else{ - Log.d(TAG,"onCreate: NotificationService already running. Not starting more services."); + } else { + Log.d(TAG, "onCreate: NotificationService already running. Not starting more services."); } AppRater.app_launched(BaseActivity.this); @@ -204,30 +190,29 @@ public abstract class BaseActivity extends AppCompatActivity { } @Override - protected void onDestroy(){ + protected void onDestroy() { super.onDestroy(); unregisterBroadcastReceiver(); } @Override - protected void onResume(){ + protected void onResume() { super.onResume(); registerBroadcastReceiver(); - } - public void registerBroadcastReceiver(){ + public void registerBroadcastReceiver() { IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(AppConfig.INTENT_LOGOUT); myReceiver = new LogoutReceiver(); registerReceiver(myReceiver, intentFilter); } - public void unregisterBroadcastReceiver(){ - try{ + public void unregisterBroadcastReceiver() { + try { unregisterReceiver(myReceiver); - }catch(final Exception e){ + } catch (final Exception e) { e.printStackTrace(); } } @@ -254,11 +239,6 @@ public abstract class BaseActivity extends AppCompatActivity { } private void initNavigationDrawer(Bundle savedInstanceState) { - PrimaryDrawerItem item1 = new PrimaryDrawerItem() - .withName(R.string.navigation_start) - .withIdentifier(mainAvtivityID) - .withIcon(GoogleMaterial.Icon.gmd_home); - PrimaryDrawerItem item2 = new PrimaryDrawerItem() .withName(R.string.navigation_report) .withIdentifier(reportAvtivityID) @@ -311,7 +291,7 @@ public abstract class BaseActivity extends AppCompatActivity { @Override public void onDrawerClosed(View drawerView) { android.support.v7.app.ActionBar actionBar = getSupportActionBar(); - if(actionBar != null) actionBar.setTitle(getActivityName()); + if (actionBar != null) actionBar.setTitle(getActivityName()); } @Override @@ -322,7 +302,6 @@ public abstract class BaseActivity extends AppCompatActivity { .withSavedInstance(savedInstanceState) .withSelectedItem(-1) .addDrawerItems( - item1, item2, item3, new DividerDrawerItem(), @@ -331,41 +310,37 @@ public abstract class BaseActivity extends AppCompatActivity { new DividerDrawerItem(), item6, item7).withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() { - @Override - public boolean onItemClick(View view, int position, IDrawerItem drawerItem) { + @Override + public boolean onItemClick(View view, int position, IDrawerItem drawerItem) { - switch (drawerItem.getIdentifier()) { - case 1: - gotoMainActivity(); - return false; - case 2: - gotoReportActivity(); - return false; - case 3: - gotoMapActivity(); - return false; - case 4: - gotoProfileActivity(); - return false; - case 5: - gotoSettingsActivity(); - return false; - case 6: - gotoSubscriptionsActivity(); - return false; - case 7: - logoutUser(); - break; - default: - Log.d("Unknown switch page: ", Integer.toString(position)); - break; - } - - return false; - } - }).build(); + switch ((int) drawerItem.getIdentifier()) { + case 2: + gotoReportActivity(); + return false; + case 3: + gotoMapActivity(); + return false; + case 4: + gotoProfileActivity(); + return false; + case 5: + gotoSettingsActivity(); + return false; + case 6: + gotoSubscriptionsActivity(); + return false; + case 7: + logoutUser(); + break; + default: + Log.d("Unknown switch page: ", Integer.toString(position)); + break; + } + return false; + } + }).build(); } @@ -376,25 +351,23 @@ public abstract class BaseActivity extends AppCompatActivity { mInterstitialAd.loadAd(adRequest); } - public void showAd(){ - if(System.currentTimeMillis() == 0) session.setLastAddShown(System.currentTimeMillis()); + public void showAd() { + if (session.getLastAddShown() == 0) session.setLastAddShown(System.currentTimeMillis()); - if(System.currentTimeMillis() > session.getLastAddShown()+120000){ + if (System.currentTimeMillis() > (session.getLastAddShown() + 120000)) { Log.d(TAG, "SHOW ADD!"); - if (mInterstitialAd.isLoaded()) { - Log.d(TAG, "Loading Add..."); - if(!(session.getSubsNoAds() || session.getSubsPremium())){ - + if (mInterstitialAd.isLoaded()) { + Log.d(TAG, "Loading Add..."); + if (!(session.getSubsNoAds() || session.getSubsPremium())) { mInterstitialAd.show(); session.setLastAddShown(System.currentTimeMillis()); - - }else{ - Log.d(TAG,"Add not shown because user has status."); + } else { + Log.d(TAG, "Add not shown because user has status."); + } } - } - }else{ + } else { Log.d(TAG, "SHOW NO ADD ( TIME NOT OUT ) !"); } } @@ -403,7 +376,7 @@ public abstract class BaseActivity extends AppCompatActivity { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); - if(activeNetworkInfo == null){ + if (activeNetworkInfo == null) { new AlertDialog.Builder(this) .setTitle(getString(R.string.alert_internetconnection_title)) .setMessage(getString(R.string.alert_internetconnection_text)) @@ -451,19 +424,13 @@ public abstract class BaseActivity extends AppCompatActivity { return true; } - public void gotoMainActivity(){ - Intent intent; - intent = new Intent(getApplicationContext(), MainActivity.class); - startActivity(intent); - } - - public void gotoReportActivity(){ + public void gotoReportActivity() { Intent intent; intent = new Intent(getApplicationContext(), ReportWFActivity.class); startActivity(intent); } - public void gotoReportActivity(String position){ + public void gotoReportActivity(String position) { Intent intent; intent = new Intent(getApplicationContext(), ReportWFActivity.class); intent.putExtra(EXTRA_MESSAGE, position); @@ -471,34 +438,34 @@ public abstract class BaseActivity extends AppCompatActivity { finish(); } - public void gotoMapActivity(){ + public void gotoMapActivity() { Intent intent; intent = new Intent(BaseActivity.this, MapsActivity.class); BaseActivity.this.startActivity(intent); } - public void gotoMapActivity(String position){ + public void gotoMapActivity(String position) { Intent intent; intent = new Intent(getApplicationContext(), MapsActivity.class); intent.putExtra(EXTRA_MESSAGE, position); startActivity(intent); } - public void getNotifyLocationFromMapActivity(){ + public void getNotifyLocationFromMapActivity() { Intent intent; intent = new Intent(getApplicationContext(), MapsActivity.class); intent.putExtra(AppConfig.EXTRA_MAP_TYPE, AppConfig.INTENT_MAP_GETNOTIFY); startActivity(intent); } - public void getIncidentLocationFromMapActivity(){ + public void getIncidentLocationFromMapActivity() { Intent intent; intent = new Intent(getApplicationContext(), MapsActivity.class); intent.putExtra(AppConfig.EXTRA_MAP_TYPE, AppConfig.INTENT_MAP_GETINCLOC); startActivity(intent); } - public void getNotifyLocationFromMapActivity(String position){ + public void getNotifyLocationFromMapActivity(String position) { Intent intent; intent = new Intent(getApplicationContext(), MapsActivity.class); intent.putExtra(EXTRA_MESSAGE, position); @@ -506,7 +473,7 @@ public abstract class BaseActivity extends AppCompatActivity { startActivity(intent); } - public void getIncidentLocationFromMapActivity(String position){ + public void getIncidentLocationFromMapActivity(String position) { Intent intent; intent = new Intent(getApplicationContext(), MapsActivity.class); intent.putExtra(EXTRA_MESSAGE, position); @@ -514,32 +481,32 @@ public abstract class BaseActivity extends AppCompatActivity { startActivity(intent); } - public void gotoProfileActivity(){ + public void gotoProfileActivity() { Intent intent; intent = new Intent(getApplicationContext(), ProfileActivity.class); startActivity(intent); } - public void gotoProfileActivity(String uid){ + public void gotoProfileActivity(String uid) { Intent intent; intent = new Intent(getApplicationContext(), ProfileActivity.class); intent.putExtra(EXTRA_MESSAGE, uid); startActivity(intent); } - public void gotoSettingsActivity(){ + public void gotoSettingsActivity() { Intent intent; intent = new Intent(getApplicationContext(), SettingsActivity.class); startActivity(intent); } - public void gotoSubscriptionsActivity(){ + public void gotoSubscriptionsActivity() { Intent intent; intent = new Intent(getApplicationContext(), SubscriptionsActivity.class); startActivity(intent); } - public void gotoViewReportActivity(Integer uid){ + public void gotoViewReportActivity(Integer uid) { Intent intent; intent = new Intent(getApplicationContext(), ViewReportActivity.class); intent.putExtra(EXTRA_MESSAGE, uid); @@ -550,36 +517,36 @@ public abstract class BaseActivity extends AppCompatActivity { public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); - if((id == R.id.menu_action_exit)){ + if ((id == R.id.menu_action_exit)) { Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); - }else if((id == R.id.menu_action_about)){ + } else if ((id == R.id.menu_action_about)) { showAboutInfoDialog(); - }else if((id == R.id.menu_action_language)){ + } else if ((id == R.id.menu_action_language)) { showLanguageDialog(); - }else if((id == R.id.menu_action_help)){ + } else if ((id == R.id.menu_action_help)) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.riskahead.net/contact/")); startActivity(browserIntent); - }else if((id == R.id.menu_action_feedback)){ + } else if ((id == R.id.menu_action_feedback)) { showFeedbackDialog(); } return super.onOptionsItemSelected(item); } - private void showLanguageDialog(){ + private void showLanguageDialog() { AlertDialog.Builder b = new AlertDialog.Builder(this); b.setTitle(R.string.txt_language_title); - String[] types = {"ar - العربية", "de - Deutsch", "en - English", "es - Español", "et - Eesti keel", "fi - Suomi", "fr - Français", "lv - Latviešu valoda", "mn - Монгол хэл", "nl - Nederlands", "pl - Polszczyzna", "pt - Português do Brasil", "ru - Pусский", "tr - Türkçe"}; + String[] types = {"ar - العربية", "de - Deutsch", "en - English", "es - Español", "et - Eesti keel", "fi - Suomi", "fr - Français", "lv - Latviešu valoda", "mn - Монгол хэл", "nl - Nederlands", "pl - Polszczyzna", "pt - Português do Brasil", "ru - Pусский", "tr - Türkçe"}; b.setItems(types, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); - switch(which){ + switch (which) { case 0: setLocale("ar"); break; @@ -651,12 +618,12 @@ public abstract class BaseActivity extends AppCompatActivity { ((TextView) dialoglayout.findViewById(R.id.txt_about_terms)).setMovementMethod(LinkMovementMethod.getInstance()); try { - ((TextView) dialoglayout.findViewById(R.id.lbl_about_version)).setText(String.format("Version: %s",getPackageManager().getPackageInfo(getPackageName(), 0).versionName)); + ((TextView) dialoglayout.findViewById(R.id.lbl_about_version)).setText(String.format("Version: %s", getPackageManager().getPackageInfo(getPackageName(), 0).versionName)); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } - AlertDialog.Builder builder = new AlertDialog.Builder(BaseActivity.this) + AlertDialog.Builder builder = new AlertDialog.Builder(BaseActivity.this) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { //do nothing @@ -668,7 +635,7 @@ public abstract class BaseActivity extends AppCompatActivity { } private void showFeedbackDialog() { - AlertDialog.Builder alert=new AlertDialog.Builder(this); + AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle(R.string.menu_action_feedback); alert.setMessage(R.string.txt_feedback_message); @@ -680,7 +647,7 @@ public abstract class BaseActivity extends AppCompatActivity { input.setLayoutParams(lp); input.setLines(4); - input.setBackgroundColor(ContextCompat.getColor(getApplicationContext(),R.color.bootstrap_gray_lightest)); + input.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.bootstrap_gray_lightest)); input.setGravity(Gravity.TOP); input.setHint(R.string.txt_feedback_hint); @@ -702,7 +669,7 @@ public abstract class BaseActivity extends AppCompatActivity { }); AlertDialog ad = alert.create(); - ad.setView(input,0,50,0,20); + ad.setView(input, 0, 50, 0, 20); ad.show(); } @@ -713,17 +680,17 @@ public abstract class BaseActivity extends AppCompatActivity { while (e.hasMoreElements()) { String k = (String) e.nextElement(); String v = props.getProperty(k); - sysprop += k+": "+v+"\n"; + sysprop += k + ": " + v + "\n"; } - StringRequest strReq = getStringRequestSendFeedback(feedback,sysprop); + StringRequest strReq = getStringRequestSendFeedback(feedback, sysprop); String tag_string_req = "reqsendfeedback"; AppController.getInstance().addToRequestQueue(strReq, tag_string_req); } private StringRequest getStringRequestSendFeedback(final String feedback, final String sysprop) { - return new StringRequest(Request.Method.POST, AppConfig.URL_DEFAULT, new Response.Listener() { + return new StringRequest(Request.Method.POST, AppConfig.REST_SEND_FEEDBACK, new Response.Listener() { @Override public void onResponse(String response) { @@ -755,7 +722,6 @@ public abstract class BaseActivity extends AppCompatActivity { @Override protected Map getParams() { Map params = new HashMap<>(); - params.put("tag", AppConfig.REST_SEND_FEEDBACK); params.put("uid", user.get(SessionManager.KEY_UID)); params.put("token", user.get(SessionManager.TOKEN)); params.put("feedback", feedback); @@ -765,7 +731,7 @@ public abstract class BaseActivity extends AppCompatActivity { }; } - public void showMessage(String statusText){ + public void showMessage(String statusText) { Toast.makeText(this, statusText, Toast.LENGTH_LONG).show(); } @@ -812,5 +778,4 @@ public abstract class BaseActivity extends AppCompatActivity { } - } diff --git a/app/src/main/java/org/deke/risk/riskahead/helper/IncidentReport.java b/app/src/main/java/org/deke/risk/riskahead/helper/IncidentReport.java index c583400..c4afd01 100644 --- a/app/src/main/java/org/deke/risk/riskahead/helper/IncidentReport.java +++ b/app/src/main/java/org/deke/risk/riskahead/helper/IncidentReport.java @@ -315,32 +315,22 @@ public class IncidentReport implements ClusterItem { switch(this.fidIncidentCategory){ case 1: - stringArray = context.getResources().getStringArray(R.array.cat_situation_sub_general); + stringArray = context.getResources().getStringArray(R.array.cat_situation_sub_threat); returnValue = stringArray[this.fidIncidentSubCategory-1]; break; case 2: - stringArray = context.getResources().getStringArray(R.array.cat_situation_sub_verbal); + stringArray = context.getResources().getStringArray(R.array.cat_situation_sub_physical); returnValue = stringArray[this.fidIncidentSubCategory-1]; break; case 3: - stringArray = context.getResources().getStringArray(R.array.cat_situation_sub_force); + stringArray = context.getResources().getStringArray(R.array.cat_situation_sub_lifethreat); returnValue = stringArray[this.fidIncidentSubCategory-1]; break; case 4: - stringArray = context.getResources().getStringArray(R.array.cat_situation_sub_force_serious); - returnValue = stringArray[this.fidIncidentSubCategory-1]; - - break; - case 5: - stringArray = context.getResources().getStringArray(R.array.cat_situation_sub_nature); - returnValue = stringArray[this.fidIncidentSubCategory-1]; - - break; - case 6: - stringArray = context.getResources().getStringArray(R.array.cat_situation_sub_infrastructure); + stringArray = context.getResources().getStringArray(R.array.cat_situation_sub_disaster); returnValue = stringArray[this.fidIncidentSubCategory-1]; break; @@ -612,6 +602,16 @@ public class IncidentReport implements ClusterItem { return this.incidentPosition; } + @Override + public String getTitle() { + return "Title"; + } + + @Override + public String getSnippet() { + return "Snippet"; + } + public int getVotedScore(){ return this.votedScore; } diff --git a/app/src/main/java/org/deke/risk/riskahead/helper/NotificationService.java b/app/src/main/java/org/deke/risk/riskahead/helper/NotificationService.java index a8ff2d2..a0d5dda 100644 --- a/app/src/main/java/org/deke/risk/riskahead/helper/NotificationService.java +++ b/app/src/main/java/org/deke/risk/riskahead/helper/NotificationService.java @@ -49,10 +49,18 @@ public class NotificationService extends Service { Handler mNotifyHandler = new Handler(); NotificationManager mNotificationManager; + private static final int MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters + private static final int MIN_TIME_BW_UPDATES = 1000 * 60; // 1 minute + private static int gpscounter = 0; + public SessionManager session; + public HashMap user; - public LocationManager locationManager; + private LocationManager locationManager; + private LocationListener locationListener; + + private LatLng myPosition; public NotificationService() { super(); @@ -60,51 +68,87 @@ public class NotificationService extends Service { @Override public void onCreate() { - Log.d(TAG, "onCreate NotificationService"); - mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); session = new SessionManager(getApplicationContext()); user = session.getUserDetails(); - locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); - LocationListener locationListener = new MyLocationListener(); - - if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { - //ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},1); - }else{ - locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 10, locationListener); - } - - - Log.d(TAG, "Service Created. Starting notification task..."); + Log.d(TAG, "NotificationService created. Starting notification task..."); mNotifyTask.run(); } - private class MyLocationListener implements LocationListener { + private void initAndGetPosition() { + Log.d(TAG,"Trying to get a position. GPS enabled: "+session.isGPSForNotificationsEnabled()); + if(session.isGPSForNotificationsEnabled()) { + if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { + locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); + locationListener = new MyLocationListener(); + + if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { + Log.d(TAG, "Locationservice enabled - GPS Provider Found"); + + locationManager.requestLocationUpdates( + LocationManager.GPS_PROVIDER, + MIN_TIME_BW_UPDATES, + MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener); + Log.d(TAG, "GPS Provider enabled"); + + if (locationManager != null) { + Location tmpLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); + if (tmpLocation != null) { + Log.d(TAG,"Last known position found from GPS Provider"); + removeLocationListener(); + session.setLocation(Double.doubleToRawLongBits(tmpLocation.getLatitude()), Double.doubleToRawLongBits(tmpLocation.getLongitude())); + myPosition = session.getLocation(); + session.setNotificationServiceReady(true); + } + } + } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { + // get location from Network Provider + Log.d(TAG, "Locationservice enabled - Network Provider Found"); + locationManager.requestLocationUpdates( + LocationManager.NETWORK_PROVIDER, + MIN_TIME_BW_UPDATES, + MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener); + Log.d(TAG, "Network Provider enabled"); + if (locationManager != null) { + Location tmpLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); + if (tmpLocation != null) { + Log.d(TAG,"Last known position found from Network Provider"); + removeLocationListener(); + session.setLocation(Double.doubleToRawLongBits(tmpLocation.getLatitude()), Double.doubleToRawLongBits(tmpLocation.getLongitude())); + myPosition = session.getLocation(); + session.setNotificationServiceReady(true); + } + } + } + } + }else{ + myPosition = session.getManualLocation(); + } + } + + private void removeLocationListener() { + if(locationManager != null && locationListener != null){ + locationManager.removeUpdates(locationListener); + locationListener = null; + locationManager = null; + } + } + + private class MyLocationListener implements LocationListener { @Override public void onLocationChanged(Location loc) { - String longitude = "Longitude: " + loc.getLongitude(); - Log.v(TAG, longitude); - String latitude = "Latitude: " + loc.getLatitude(); - Log.v(TAG, latitude); + Log.d(TAG,"onLocationChanged: "+gpscounter); + session.setLocation(Double.doubleToRawLongBits(loc.getLatitude()), Double.doubleToRawLongBits(loc.getLongitude())); + session.setNotificationServiceReady(true); - if(session.isGPSForNotificationsEnabled() && loc.getLongitude() != 0.0 && loc.getLatitude() != 0.0) { - Log.d(TAG, "Save GPS as new location..."); - if(session.getLocation() == null || session.getLocation().latitude == 0.0 || session.getLocation().longitude == 0.0){ - session.setLocation(Double.doubleToRawLongBits(loc.getLatitude()), Double.doubleToRawLongBits(loc.getLongitude())); - mNotifyHandler.removeCallbacksAndMessages(null); - mNotifyTask.run(); - }else{ - session.setLocation(Double.doubleToRawLongBits(loc.getLatitude()), Double.doubleToRawLongBits(loc.getLongitude())); - } - - session.setNotificationServiceReady(true); - - }else{ - Log.d(TAG,"Don't Save GPS as new location because GPS for notifications is disabled...: "+session.isGPSForNotificationsEnabled()); + if(gpscounter > 3){ + removeLocationListener(); } + + gpscounter++; } @Override @@ -127,14 +171,15 @@ public class NotificationService extends Service { public void run() { android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); - LatLng myPosition = session.getLocation(); + boolean notifyEnabled = session.getNotificationEnabled(); int radius = session.getNotificationRadius(); int pollFrequency = session.getNotificationPollFreq() * 1000 * 60; - boolean notifyEnabled = session.getNotificationEnabled(); Log.d(this.toString(), "Run Notification Task. Notifications enabled = " + notifyEnabled); if(notifyEnabled && session.isLoggedIn()){ + initAndGetPosition(); + if ((myPosition != null) && (myPosition.latitude != 0.0) && (myPosition.longitude != 0.0)) { session.setNotificationServiceReady(true); String lastNotificationTime; @@ -145,7 +190,7 @@ public class NotificationService extends Service { lastNotificationTime = session.getLastNotification(); } - Log.d(this.toString(), "Lookup location with position: " + myPosition + " Radius: "+ radius +" PollFrequency: "+ pollFrequency +" lastNotifyTime: " + lastNotificationTime); + Log.d(this.toString(), "Lookup location with position: " + myPosition + " Radius: "+ radius +" PollFrequency: "+ pollFrequency +" lastNotifyTime: " + lastNotificationTime + " GPSActivated: "+session.isGPSForNotificationsEnabled()); StringRequest strReq = getStringRequestIncidentsFromAreaAndTime(myPosition.latitude, myPosition.longitude, radius, lastNotificationTime); String tag_string_req = "req_incidents"; @@ -162,7 +207,7 @@ public class NotificationService extends Service { }; private StringRequest getStringRequestIncidentsFromAreaAndTime(final Double latitude, final Double longitude, final int radius, final String time) { - return new StringRequest(Request.Method.POST, AppConfig.URL_DEFAULT, new Response.Listener() { + return new StringRequest(Request.Method.POST, AppConfig.REST_GET_INCIDENTS_FROMAREATIME, new Response.Listener() { @Override public void onResponse(String response) { @@ -196,7 +241,6 @@ public class NotificationService extends Service { @Override protected Map getParams() { Map params = new HashMap<>(); - params.put("tag", AppConfig.REST_GET_INCIDENTS_FROMAREATIME); params.put("uid", user.get(SessionManager.KEY_UID)); params.put("token", user.get(SessionManager.TOKEN)); params.put("latitude", Double.toString(latitude)); @@ -246,18 +290,16 @@ public class NotificationService extends Service { ); mBuilder.setContentIntent(resultPendingIntent); - int mId = 1; - mNotificationManager.notify(mId, mBuilder.build()); - + mNotificationManager.notify(1, mBuilder.build()); session.setLastNotification(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime())); - } @Override public void onDestroy(){ + if(locationManager != null && locationListener != null) locationManager.removeUpdates(locationListener); + super.onDestroy(); + Log.d(TAG, "Destroy NotificationService"); } - - } 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 index c6f25d7..3092eba 100644 --- a/app/src/main/java/org/deke/risk/riskahead/helper/SessionManager.java +++ b/app/src/main/java/org/deke/risk/riskahead/helper/SessionManager.java @@ -49,6 +49,9 @@ public class SessionManager { public static final String KEY_LOCATION_LAT = "location_latitude"; public static final String KEY_LOCATION_LNG = "location_longitude"; + public static final String KEY_MAN_LOCATION_LAT = "man_location_latitude"; + public static final String KEY_MAN_LOCATION_LNG = "man_location_longitude"; + public static final String KEY_LAST_NOTIFICATION = "lastNotificationTime"; public static final String KEY_NOTIFY_ENABLED = "notifyEnabled" ; public static final String KEY_NOTIFY_RADIUS = "notifyRadius"; @@ -88,6 +91,16 @@ public class SessionManager { return new LatLng(Double.longBitsToDouble(status.getLong(KEY_LOCATION_LAT, 0)), Double.longBitsToDouble(status.getLong(KEY_LOCATION_LNG, 0))); } + public void setManualLocation(Long latitude, Long longitude){ + statusEditor.putLong(KEY_MAN_LOCATION_LAT, latitude); + statusEditor.putLong(KEY_MAN_LOCATION_LNG, longitude); + statusEditor.apply(); + } + + public LatLng getManualLocation(){ + return new LatLng(Double.longBitsToDouble(status.getLong(KEY_MAN_LOCATION_LAT, 0)), Double.longBitsToDouble(status.getLong(KEY_MAN_LOCATION_LNG, 0))); + } + public void setGPSForNotificationsEnabled(boolean isEnabled){ statusEditor.putBoolean(KEY_NOTIFY_GPS, isEnabled); statusEditor.apply(); diff --git a/app/src/main/java/org/deke/risk/riskahead/helper/TextValidator.java b/app/src/main/java/org/deke/risk/riskahead/helper/TextValidator.java index 3eaf504..371e401 100644 --- a/app/src/main/java/org/deke/risk/riskahead/helper/TextValidator.java +++ b/app/src/main/java/org/deke/risk/riskahead/helper/TextValidator.java @@ -1,6 +1,7 @@ package org.deke.risk.riskahead.helper; import android.content.Context; +import android.support.design.widget.TextInputLayout; import android.text.Editable; import android.text.TextWatcher; import android.widget.TextView; @@ -14,12 +15,14 @@ import android.widget.TextView; */ public abstract class TextValidator implements TextWatcher { private final TextView textView; + private final TextInputLayout textLayout; - public TextValidator(TextView textView, Context context) { + public TextValidator(TextView textView, TextInputLayout textLayout, Context context) { this.textView = textView; + this.textLayout = textLayout; } - public abstract void validate(TextView textView, String text); + public abstract void validate(TextView textView, TextInputLayout textLayout, String text); @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { @@ -33,6 +36,6 @@ public abstract class TextValidator implements TextWatcher { @Override public void afterTextChanged(Editable s) { String text = textView.getText().toString(); - validate(textView, text); + validate(textView, textLayout, text); } } diff --git a/app/src/main/java/org/deke/risk/riskahead/helper/ValidatedEditTextPreference.java b/app/src/main/java/org/deke/risk/riskahead/helper/ValidatedEditTextPreference.java index e979ab9..229a422 100644 --- a/app/src/main/java/org/deke/risk/riskahead/helper/ValidatedEditTextPreference.java +++ b/app/src/main/java/org/deke/risk/riskahead/helper/ValidatedEditTextPreference.java @@ -5,6 +5,7 @@ import android.content.Context; import android.os.Bundle; import android.preference.EditTextPreference; import android.app.AlertDialog; +import android.support.design.widget.TextInputLayout; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; @@ -12,6 +13,7 @@ import android.util.AttributeSet; import android.util.Log; import android.util.Patterns; import android.widget.Button; +import android.widget.LinearLayout; import org.deke.risk.riskahead.R; @@ -62,7 +64,11 @@ public class ValidatedEditTextPreference extends EditTextPreference if((getEditText().getInputType() & InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS) != 0){ if (!Patterns.EMAIL_ADDRESS.matcher(value).matches()) { - getEditText().setError(getEditText().getContext().getResources().getString(R.string.error_email)); + if(getEditText().getParent().getClass() == TextInputLayout.class){ + ((TextInputLayout) getEditText().getParent()).setError(getEditText().getContext().getResources().getString(R.string.error_email)); + }else{ + getEditText().setError(getEditText().getContext().getResources().getString(R.string.error_email)); + } enable = false; } }else{ @@ -81,7 +87,6 @@ public class ValidatedEditTextPreference extends EditTextPreference Dialog dlg = getDialog(); - if(dlg instanceof AlertDialog){ AlertDialog alertDlg = (AlertDialog)dlg; Button btn = alertDlg.getButton(AlertDialog.BUTTON_POSITIVE); @@ -89,7 +94,6 @@ public class ValidatedEditTextPreference extends EditTextPreference Log.d("SettingValidator", "btnSetEnable durchgeführt: "+btn.isEnabled()); } - } @Override diff --git a/app/src/main/res/layout/activity_login.xml b/app/src/main/res/layout/activity_login.xml index 9cac3b7..aebbbdd 100644 --- a/app/src/main/res/layout/activity_login.xml +++ b/app/src/main/res/layout/activity_login.xml @@ -1,126 +1,158 @@ - - - - - - -