Advertisement
vergepuppeter

MainActivity

Jun 15th, 2016
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 41.34 KB | None | 0 0
  1. public class MainActivity extends AppCompatActivity implements View.OnClickListener,
  2.         ViewPagerFragment.OnViewPagerUpdatePositionListener,
  3.         PrivacyDialogFragment.OnApplyFragmentListener,
  4.         ChangePasswordDialogFragment.OnSaveFragmentListener,
  5.         CustomViewPager.OnSwipeOutListener,
  6.         MapListFragment.OnMapListClickListener,
  7.         MapContainerFragment.OnZoomInToSelectedLocationListener,
  8.         GoogleApiClient.ConnectionCallbacks,
  9.         GoogleApiClient.OnConnectionFailedListener,
  10.         LocationListener,
  11.         ResultCallback<LocationSettingsResult> {
  12.  
  13.     private DrawerLayout drawerLayout;
  14.     private ScrimInsetsFrameLayout rightDrawer;
  15.     private RoundedImageView profileImage;
  16.     private DisplayImageOptions options;
  17.     private RelativeLayout logoutPlaceholder, profilePlaceholder, settingsPLaceholder, passwordPlaceholder, invitePlaceholder;
  18.     protected static final int CAMERA_REQUEST_CODE = 1;
  19.     protected static final int GALLERY_REQUEST_CODE = 2;
  20.     private String picturePath;
  21.     private static final int PLACE_PICKER_REQUEST = 5;
  22.     private Place place;
  23.     private Button backButton, doneButton;
  24.     private ArrayList<FishLocation> arrayList;
  25.     private ViewPagerFragment viewPagerFragment = null;
  26.  
  27.  
  28.     //Google API Location-Aware
  29.     public static final int REQUEST_CHECK_SETTINGS = 0x99;
  30.     //Location-aware variable
  31.     public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 300000;
  32.     public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
  33.             UPDATE_INTERVAL_IN_MILLISECONDS / 2;
  34.     protected final static String KEY_REQUESTING_LOCATION_UPDATES = "requesting-location-updates";
  35.     protected final static String KEY_LOCATION = "location";
  36.     protected final static String KEY_LAST_UPDATED_TIME_STRING = "last-updated-time-string";
  37.     protected GoogleApiClient mGoogleApiClient;
  38.     protected Location mCurrentLocation = null;
  39.     protected LocationSettingsRequest mLocationSettingsRequest;
  40.     protected Boolean mRequestingLocationUpdates = true;
  41.     public static final int MY_PERMISSION_REQUEST_LOCATION_ACCESS = 101;
  42.  
  43.     protected final static String REQUESTING_LOCATION_UPDATES_KEY = "requesting-location-updates-key";
  44.     protected final static String LOCATION_KEY = "location-key";
  45.     protected LocationRequest mLocationRequest;
  46.     public static final String TAG = "LocationManager";
  47.  
  48.     @Override
  49.     protected void onCreate(Bundle savedInstanceState) {
  50.         super.onCreate(savedInstanceState);
  51.         setContentView(R.layout.activity_main);
  52.  
  53.         if (!isNetworkAvailable()) {
  54.             Toast.makeText(MainActivity.this, "No Internet Connection", Toast.LENGTH_LONG).show();
  55.         }
  56.         updateValuesFromBundle(savedInstanceState);
  57.         initView();
  58.         buildGoogleApiClient();
  59.         createLocationRequest();
  60.         buildLocationSettingsRequest();
  61.     }
  62.  
  63.     @Override
  64.     public void onStart() {
  65.         super.onStart();
  66.  
  67.         mGoogleApiClient.connect();
  68.  
  69.         Branch branch = Branch.getInstance();
  70.         branch.initSession(new Branch.BranchReferralInitListener() {
  71.             @Override
  72.             public void onInitFinished(JSONObject referringParams, BranchError error) {
  73.                 if (error == null) {
  74.                     // params are the deep linked params associated with the link that the user clicked before showing up
  75.                     Log.i("BranchConfigTest", "deep link data: " + referringParams.toString());
  76.                 }
  77.             }
  78.         }, this.getIntent().getData(), this);
  79.     }
  80.  
  81.     @Override
  82.     public void onNewIntent(Intent intent) {
  83.         this.setIntent(intent);
  84.     }
  85.  
  86.  
  87.     public void onSaveInstanceState(Bundle savedInstanceState) {
  88.         savedInstanceState.putBoolean(REQUESTING_LOCATION_UPDATES_KEY, mRequestingLocationUpdates);
  89.         savedInstanceState.putParcelable(LOCATION_KEY, mCurrentLocation);
  90.         super.onSaveInstanceState(savedInstanceState);
  91.     }
  92.  
  93.     private void updateValuesFromBundle(Bundle savedInstanceState) {
  94.         if (savedInstanceState != null) {
  95.             // Update the value of mRequestingLocationUpdates from the Bundle, and make sure that
  96.             // the Start Updates and Stop Updates buttons are correctly enabled or disabled.
  97.             if (savedInstanceState.keySet().contains(REQUESTING_LOCATION_UPDATES_KEY)) {
  98.                 mRequestingLocationUpdates = savedInstanceState.getBoolean(
  99.                         REQUESTING_LOCATION_UPDATES_KEY);
  100.             }
  101.  
  102.             // Update the value of mCurrentLocation from the Bundle and update the UI to show the
  103.             // correct latitude and longitude.
  104.             if (savedInstanceState.keySet().contains(LOCATION_KEY)) {
  105.                 // Since LOCATION_KEY was found in the Bundle, we can be sure that mCurrentLocation
  106.                 // is not null.
  107.                 mCurrentLocation = savedInstanceState.getParcelable(LOCATION_KEY);
  108.             }
  109.  
  110.             updateLocationUI();
  111.         }
  112.     }
  113.  
  114.     private void updateLocationUI() {
  115.         if (mCurrentLocation != null) {
  116.             Log.i("CurrentLocation", mCurrentLocation.getLatitude()+"," + mCurrentLocation.getLongitude());
  117.             getApiFishingLocation(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
  118.         }
  119.     }
  120.  
  121.     protected void stopLocationUpdates() {
  122.         // It is a good practice to remove location requests when the activity is in a paused or
  123.         // stopped state. Doing so helps battery performance and is especially
  124.         // recommended in applications that request frequent location updates.
  125.  
  126.         // The final argument to {@code requestLocationUpdates()} is a LocationListener
  127.         // (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
  128.         LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
  129.     }
  130.  
  131.  
  132.     private void initView() {
  133.         LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  134.         drawerLayout = (DrawerLayout) inflater.inflate(R.layout.decor_layout, null); // "null" is important.
  135.         rightDrawer = (ScrimInsetsFrameLayout) drawerLayout.findViewById(R.id.right_drawer);
  136.         profileImage = (RoundedImageView) drawerLayout.findViewById(R.id.profileImage);
  137.         profileImage.setOnClickListener(new View.OnClickListener() {
  138.             @Override
  139.             public void onClick(View view) {
  140.                 //selectImage();
  141.             }
  142.         });
  143.  
  144.         profilePlaceholder = (RelativeLayout) drawerLayout.findViewById(R.id.profile_placeholder);
  145.         settingsPLaceholder = (RelativeLayout) drawerLayout.findViewById(R.id.settings_placeholder);
  146.         passwordPlaceholder = (RelativeLayout) drawerLayout.findViewById(R.id.password_placeholder);
  147.         invitePlaceholder = (RelativeLayout) drawerLayout.findViewById(R.id.invite_placeholder);
  148.         logoutPlaceholder = (RelativeLayout) drawerLayout.findViewById(R.id.logoutPlaceholder);
  149.         logoutPlaceholder.setOnClickListener(this);
  150.         profilePlaceholder.setOnClickListener(this);
  151.         settingsPLaceholder.setOnClickListener(this);
  152.         passwordPlaceholder.setOnClickListener(this);
  153.         invitePlaceholder.setOnClickListener(this);
  154.  
  155.  
  156.         initNavBar(drawerLayout);
  157.  
  158.         options = new DisplayImageOptions.Builder()
  159.                 .cacheInMemory(false)
  160.                 .cacheOnDisk(true)
  161.                 .showImageOnLoading(R.drawable.default_avatar)
  162.                 .showImageForEmptyUri(R.drawable.default_avatar)
  163.                 .showImageOnFail(R.drawable.default_avatar)
  164.                 .considerExifParams(true)
  165.                 .bitmapConfig(Bitmap.Config.RGB_565)
  166.                 .build();
  167.  
  168.         //This is where magic happened.
  169.         stealFirstView(drawerLayout);
  170.  
  171. //        if(mSimpleFacebook.isLogin())
  172. //            ImageLoader.getInstance().displayImage(AppController.getInstance().getFbProfileImage(), profileImage, options);
  173. //        else
  174.         ImageLoader.getInstance().displayImage(AppController.getInstance().getAvatarUrl(), profileImage, options);
  175.  
  176.         viewPagerFragment = new ViewPagerFragment();
  177.         getSupportFragmentManager()
  178.                 .beginTransaction()
  179.                 .replace(R.id.mainContent, viewPagerFragment)
  180.                 .commit();
  181.     }
  182.  
  183.  
  184.     public int getStatusBarHeight() {
  185.         int result = 0;
  186.         int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
  187.         if (resourceId > 0) {
  188.             result = getResources().getDimensionPixelSize(resourceId);
  189.         }
  190.         return result;
  191.     }
  192.  
  193.     private void initNavBar(View view) {
  194.         backButton = (Button) view.findViewById(R.id.backBtn);
  195.         doneButton = (Button) view.findViewById(R.id.doneBtn);
  196.  
  197.         //styling the navigation button
  198.         doneButton.setVisibility(View.VISIBLE);
  199.         doneButton.setBackground(getResources().getDrawable(R.drawable.menu_drawer));
  200.  
  201.         backButton.setVisibility(View.INVISIBLE);
  202.         backButton.setBackground(getResources().getDrawable(R.drawable.back_icon));
  203.  
  204.         backButton.setOnClickListener(new View.OnClickListener() {
  205.             @Override
  206.             public void onClick(View view) {
  207.  
  208.             }
  209.         });
  210.  
  211.         doneButton.setOnClickListener(new View.OnClickListener() {
  212.             @Override
  213.             public void onClick(View view) {
  214.                 //TODO
  215.                 if (drawerLayout.isDrawerOpen(rightDrawer)) {
  216.                     drawerLayout.closeDrawer(rightDrawer);
  217.                 } else {
  218.                     drawerLayout.openDrawer(rightDrawer);
  219.                 }
  220.             }
  221.         });
  222.     }
  223.  
  224.  
  225.     public float dpTopxConverter(int dp) {
  226.         Resources r = getResources();
  227.         return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics());
  228.     }
  229.  
  230.     //This is hack to steal first view to allow drawer to slide on top of actionBar/Toolbar without using design material
  231.     public void stealFirstView(DrawerLayout drawer) {
  232.         ViewGroup decor = (ViewGroup) getWindow().getDecorView();
  233.         View child = decor.getChildAt(0);
  234.         decor.removeView(child);
  235.         LinearLayout mainContainer = (LinearLayout) drawer.findViewById(R.id.mainPlaceholer); // This is the container we defined just now.
  236.         mainContainer.addView(child);
  237.  
  238.         ViewGroup.LayoutParams lp = ((ViewGroup) mainContainer).getLayoutParams();
  239.         if (lp instanceof ViewGroup.MarginLayoutParams) {
  240.             ((ViewGroup.MarginLayoutParams) lp).topMargin = getStatusBarHeight();
  241.         }
  242.  
  243.         // Make the drawer replace the first child
  244.         decor.addView(drawer);
  245.     }
  246.  
  247.  
  248.     @Override
  249.     public void onSwipeOutAtStart() {
  250.  
  251.     }
  252.  
  253.     @Override
  254.     public void onSwipeOutAtEnd() {
  255.         if (drawerLayout.isDrawerOpen(rightDrawer)) {
  256.             drawerLayout.closeDrawer(rightDrawer);
  257.         } else {
  258.             drawerLayout.openDrawer(rightDrawer);
  259.         }
  260.     }
  261.  
  262.  
  263.     public int getDensity(Context context) {
  264.         DisplayMetrics metrics = context.getResources().getDisplayMetrics();
  265.         return (int) metrics.density;
  266.     }
  267.  
  268.  
  269.     @Override
  270.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  271.         switch (requestCode) {
  272.             case CAMERA_REQUEST_CODE:
  273.                 switch (resultCode) {
  274.                     case RESULT_OK:
  275.                         File file = new File(picturePath);
  276.                         if (file.exists()) {
  277.                             uploadProfilePicture(picturePath);
  278.                         }
  279.                         else{
  280.                             uploadProfilePicture(picturePath);
  281.                         }
  282.                         break;
  283.                     case RESULT_CANCELED:
  284.                         break;
  285.                 }
  286.                 break;
  287.             case GALLERY_REQUEST_CODE:
  288.                 switch (resultCode) {
  289.                     case RESULT_OK:
  290.                         try {
  291.                             Uri selectedImage = data.getData();
  292.                             String[] filePath = {MediaStore.Images.Media.DATA};
  293.                             Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
  294.                             c.moveToFirst();
  295.                             int columnIndex = c.getColumnIndex(filePath[0]);
  296.                             picturePath = c.getString(columnIndex);
  297.                             c.close();
  298.  
  299.                             uploadProfilePicture(picturePath);
  300.  
  301.                         } catch (Exception e) {
  302.                             // TODO: handle exception
  303.                         }
  304.                         break;
  305.                     case RESULT_CANCELED:
  306.                         break;
  307.                 }
  308.                 break;
  309.             case PLACE_PICKER_REQUEST:
  310.                 switch (resultCode) {
  311.                     case RESULT_OK:
  312.                         place = PlacePicker.getPlace(data, this);
  313.                         popupDialog();
  314.                         break;
  315.                     case RESULT_CANCELED:
  316.                         break;
  317.                 }
  318.                 break;
  319.             case REQUEST_CHECK_SETTINGS:
  320.                 switch (resultCode) {
  321.                     case RESULT_OK:
  322.                         startLocationUpdate();
  323.                         break;
  324.                     case RESULT_CANCELED:
  325.                         break;
  326.                 }
  327.                 break;
  328.         }
  329.         super.onActivityResult(requestCode, resultCode, data);
  330.     }
  331.  
  332.     private void selectImage() {
  333.  
  334.         final CharSequence[] options = {getResources().getString(R.string.take_photo), getResources().getString(R.string.choose_gallery), getResources().getString(R.string.cancel)};
  335.  
  336.         AlertDialog.Builder builder = new AlertDialog.Builder(this);
  337.         builder.setTitle(getResources().getString(R.string.add_photo));
  338.         builder.setItems(options, new DialogInterface.OnClickListener() {
  339.             @Override
  340.             public void onClick(DialogInterface dialog, int item) {
  341.                 if (options[item].equals(getResources().getString(R.string.take_photo))) {
  342.                     Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  343.                     File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
  344.                             Environment.DIRECTORY_PICTURES), "FishTalk");
  345.                     File f = new File(mediaStorageDir, String.valueOf(System.currentTimeMillis()) + ".jpg");
  346.                     picturePath = f.getAbsolutePath();
  347.                     intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
  348.                     startActivityForResult(intent, CAMERA_REQUEST_CODE);
  349.                 } else if (options[item].equals(getResources().getString(R.string.choose_gallery))) {
  350.                     Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  351.                     startActivityForResult(intent, GALLERY_REQUEST_CODE);
  352.  
  353.                 } else if (options[item].equals(getResources().getString(R.string.cancel))) {
  354.                     dialog.dismiss();
  355.                 }
  356.             }
  357.         });
  358.         builder.show();
  359.     }
  360.  
  361.     public void uploadProfilePicture(String picturePath) {
  362.  
  363.  
  364.         final ProgressDialog progressDialog = new ProgressDialog(this);
  365.         progressDialog.setCancelable(false);
  366.         progressDialog.setMessage("Uploading...");
  367.         progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  368.         progressDialog.show();
  369.         progressDialog.setMax(100);
  370.  
  371.         File file = new File(picturePath);
  372.         Ion.with(this)
  373.                 .load(API_Config.API_DOMAIN() + "api/file/UploadAvatar")
  374.                 .uploadProgressHandler(new ProgressCallback() {
  375.                     @Override
  376.                     public void onProgress(long uploaded, long total) {
  377.                         // Displays the progress bar for the first time.
  378.  
  379.                         if ((int) uploaded == (int) total) {
  380.                             if (progressDialog.isShowing())
  381.                                 progressDialog.dismiss();
  382.                             //Finished, Do nothing
  383.                         } else {
  384.                             int progress = ((int) uploaded / (int) total) * 100;
  385.                             progressDialog.setProgress(progress);
  386.                         }
  387.  
  388.                     }
  389.                 })
  390.                 .setTimeout(60 * 60 * 1000)
  391.                 .setHeader("Authorization", AppController.getInstance().getAccessToken())
  392.                 .setMultipartFile("Avatar", "image/jpeg", file)
  393.                 .asJsonObject()
  394.                         // run a callback on completion
  395.                 .setCallback(new FutureCallback<JsonObject>() {
  396.                     @Override
  397.                     public void onCompleted(Exception e, JsonObject result) {
  398.  
  399.                         if (progressDialog.isShowing())
  400.                             progressDialog.dismiss();
  401.  
  402.                         try {
  403.  
  404.                             JSONObject obj = new JSONObject(result.toString());
  405.                             Log.i("Check result ", result.toString());
  406.                             // When the loop is finished, updates the notification
  407.                             Toast.makeText(MainActivity.this, obj.getString("error_description"), Toast.LENGTH_LONG).show();
  408.  
  409.  
  410.                             AppController.getInstance().deleteAvatarUrl();
  411.  
  412.                             AppController.getInstance().setAvatarUrl(obj.getString("AvatarUrl"));
  413.                             ImageLoader.getInstance().displayImage(obj.getString("AvatarUrl"), profileImage, options);
  414.  
  415.  
  416.                         } catch (NullPointerException f) {
  417.  
  418.                         } catch (JSONException e1) {
  419.                             e1.printStackTrace();
  420.                         }
  421.                     }
  422.                 });
  423.  
  424.     }
  425.  
  426.     public void getAddNewLocationApi(final Place place, String placeName) {
  427.  
  428.         Retrofit retrofit = new Retrofit.Builder()
  429.                 .baseUrl(API_Config.API_DOMAIN())
  430.                 .addConverter(String.class, new ToStringConverter())
  431.                 .build();
  432.  
  433.         Map<String, String> map = new HashMap<>();
  434.         map.put("Latitude", String.valueOf(place.getLatLng().latitude));
  435.         map.put("Longtitude", String.valueOf(place.getLatLng().longitude));
  436.         map.put("Name", placeName);
  437.  
  438.         APIService service = retrofit.create(APIService.class);
  439.         Call<String> call = service.addNewLocationAPI(AppController.getInstance().getAccessToken(), map);
  440.         call.enqueue(new Callback<String>() {
  441.             @Override
  442.             public void onResponse(Response<String> response) {
  443.  
  444.                 sendMapListBroadcast();
  445.  
  446.  
  447.                 try {
  448.                     JSONObject obj = new JSONObject(response.body());
  449.                     if (obj.getInt("error") == 0) {
  450.                         getApiFishingLocation(place.getLatLng().latitude, place.getLatLng().longitude);
  451.                         Toast.makeText(MainActivity.this, obj.getString("error_description"), Toast.LENGTH_LONG).show();
  452.                     }
  453.  
  454.                 } catch (JSONException e) {
  455.                     e.printStackTrace();
  456.                 }
  457.             }
  458.  
  459.             @Override
  460.             public void onFailure(Throwable t) {
  461.                 Toast.makeText(MainActivity.this, t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
  462.             }
  463.         });
  464.     }
  465.  
  466.     private void sendMapListBroadcast() {
  467.         Intent intent = new Intent("MapListFragment");
  468.         LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
  469.     }
  470.  
  471.  
  472.  
  473.     @Override
  474.     public void onUpdatePosition(int position) {
  475.         //Postion 3 will open the drawer
  476.         if (position == 3) {
  477.             if (drawerLayout.isDrawerOpen(rightDrawer)) {
  478.                 drawerLayout.closeDrawer(rightDrawer);
  479.             } else {
  480.                 drawerLayout.openDrawer(rightDrawer);
  481.             }
  482.         } else {
  483.             //TODO
  484.         }
  485.     }
  486.  
  487.     @Override
  488.     public boolean onKeyDown(int keyCode, KeyEvent event) {
  489.         if (keyCode == KeyEvent.KEYCODE_BACK) {
  490.             if (drawerLayout.isDrawerOpen(rightDrawer)) {
  491.                 drawerLayout.closeDrawer(rightDrawer);
  492.             }
  493.             else{
  494.                 moveTaskToBack(true);
  495.             }
  496.         }
  497.         return super.onKeyDown(keyCode, event);
  498.     }
  499.  
  500.     public void popupDialog() {
  501.         View dialoglayout = getLayoutInflater().inflate(R.layout.map_dialog_layout, null);
  502.         AlertDialog.Builder builder = new AlertDialog.Builder(this);
  503.         final EditText placeEditText = (EditText) dialoglayout.findViewById(R.id.placeName);
  504.         builder.setView(dialoglayout);
  505.         builder.setCancelable(false).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
  506.             @Override
  507.             public void onClick(DialogInterface dialog, int id) {
  508.                 getAddNewLocationApi(place, placeEditText.getText().toString());
  509.             }
  510.         }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
  511.             @Override
  512.             public void onClick(DialogInterface dialog, int id) {
  513.  
  514.             }
  515.         });
  516.  
  517.         AlertDialog alert = builder.create();
  518.         alert.show();
  519.  
  520.     }
  521.  
  522.     private void showPrivacyDialog() {
  523.         if (drawerLayout.isDrawerOpen(rightDrawer)) {
  524.             drawerLayout.closeDrawer(rightDrawer);
  525.         }
  526.  
  527.         new Handler().postDelayed(new Runnable() {
  528.             @Override
  529.             public void run() {
  530.                 /* Create an Intent that will start the Menu-Activity. */
  531.                 DialogFragment newFragment = new PrivacyDialogFragment();
  532.                 newFragment.show(getSupportFragmentManager(), "Privacy");
  533.             }
  534.         }, 500);
  535.  
  536.     }
  537.  
  538.     private void showChangePasswordDialog() {
  539.  
  540.         if (drawerLayout.isDrawerOpen(rightDrawer)) {
  541.             drawerLayout.closeDrawer(rightDrawer);
  542.         }
  543.  
  544.         new Handler().postDelayed(new Runnable() {
  545.             @Override
  546.             public void run() {
  547.                 /* Create an Intent that will start the Menu-Activity. */
  548.                 DialogFragment newFragment = new ChangePasswordDialogFragment();
  549.                 newFragment.show(getSupportFragmentManager(), "Change Password");
  550.             }
  551.         }, 500);
  552.  
  553.     }
  554.  
  555.     @Override
  556.     public void onClick(View view) {
  557.         switch (view.getId()) {
  558.             case R.id.logoutPlaceholder:
  559.  
  560.                 AppController.getInstance().deleteUserCredential();
  561.                 getPreferences(Context.MODE_PRIVATE).edit().clear().commit();
  562.                 if (AppController.getInstance().getAccessToken() != null) {
  563.                     Log.i("SharedPref", "Something wrong with sharedPref");
  564.                 } else {
  565.                     Intent intent = new Intent(MainActivity.this, LoginActivity.class);
  566.                     startActivity(intent);
  567.                     finish();
  568.                 }
  569.                 break;
  570.             case R.id.profile_placeholder:
  571.  
  572.                 if (drawerLayout.isDrawerOpen(rightDrawer)) {
  573.                     drawerLayout.closeDrawer(rightDrawer);
  574.                 }
  575.  
  576.                 new Handler().postDelayed(new Runnable() {
  577.                     @Override
  578.                     public void run() {
  579.                         Intent intent = new Intent(MainActivity.this, ProfileActivity.class);
  580.                         startActivity(intent);
  581.                     }
  582.                 }, 200);
  583.  
  584.  
  585.                 break;
  586.             case R.id.settings_placeholder:
  587.                 showPrivacyDialog();
  588.                 break;
  589.             case R.id.password_placeholder:
  590.                 showChangePasswordDialog();
  591.                 break;
  592.             case R.id.invite_placeholder:
  593.                 fishTalkShare();
  594.                 break;
  595.         }
  596.     }
  597.  
  598.     private boolean isNetworkAvailable() {
  599.         ConnectivityManager connectivityManager
  600.                 = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  601.         NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
  602.         return activeNetworkInfo != null && activeNetworkInfo.isConnected();
  603.     }
  604.  
  605.     @Override
  606.     public void onSaveClicked(DialogFragment dialogFragment, String oldPass, String newPass, String confPass) {
  607.  
  608.         dialogFragment.dismiss();
  609.  
  610.         final ProgressDialog progressDialog = new ProgressDialog(this);
  611.         progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
  612.         progressDialog.setMessage("Changing password...");
  613.         progressDialog.setCancelable(false);
  614.         progressDialog.show();
  615.  
  616.         Retrofit retrofit = new Retrofit.Builder()
  617.                 .baseUrl(API_Config.API_DOMAIN())
  618.                 .addConverter(String.class, new ToStringConverter())
  619.                 .build();
  620.  
  621.         Map<String, String> map = new HashMap<>();
  622.         map.put("oldpassword", oldPass);
  623.         map.put("newpassword", newPass);
  624.         map.put("confirmpassword", confPass);
  625.  
  626.         APIService service = retrofit.create(APIService.class);
  627.         Call<String> call = service.changePasswordAPI(AppController.getInstance().getAccessToken(), map);
  628.         call.enqueue(new Callback<String>() {
  629.             @Override
  630.             public void onResponse(Response<String> response) {
  631.  
  632.                 if (progressDialog.isShowing())
  633.                     progressDialog.dismiss();
  634.  
  635.                 Log.i("ChangePassword API", response.body());
  636.  
  637.                 try {
  638.                     JSONObject obj = new JSONObject(response.body());
  639.  
  640.                     if (obj.getInt("error") == 0) {
  641.                         Toast.makeText(MainActivity.this, obj.getString("error_description"), Toast.LENGTH_SHORT).show();
  642.                     }
  643.  
  644.                 } catch (JSONException e) {
  645.                     e.printStackTrace();
  646.                 }
  647.             }
  648.  
  649.             @Override
  650.             public void onFailure(Throwable t) {
  651.  
  652.                 if (progressDialog.isShowing())
  653.                     progressDialog.dismiss();
  654.  
  655.                 try {
  656.                     Log.i("ChangePassword ", t.getMessage());
  657.                 } catch (NullPointerException e) {
  658.  
  659.                 }
  660.             }
  661.         });
  662.     }
  663.  
  664.     @Override
  665.     public void onApplyClicked(DialogFragment dialogFragment, String radius) {
  666.  
  667.         dialogFragment.dismiss();
  668.         AppController.getInstance().setRadiusSetting(radius);
  669.  
  670.         //TODO
  671.     }
  672.  
  673.     public void getApiFishingLocation(final double lat, final double lng) {
  674.         OkHttpClient client = new OkHttpClient();
  675.         client.setConnectTimeout(30, TimeUnit.SECONDS); // connect timeout
  676.         client.setReadTimeout(30, TimeUnit.SECONDS);
  677.  
  678.         Log.i("Current Radius", AppController.getInstance().getRadiusSetting());
  679.  
  680.         Map<String, String> map = new HashMap<>();
  681.         map.put("Latitude", String.valueOf(lat));
  682.         map.put("Longtitude", String.valueOf(lng));
  683.         map.put("Index", "0");
  684.         map.put("Offset", "50");
  685.         map.put("Radius", AppController.getInstance().getRadiusSetting());
  686.  
  687.         Retrofit retrofit = new Retrofit.Builder()
  688.                 .baseUrl(API_Config.API_DOMAIN())
  689.                 .addConverter(String.class, new ToStringConverter())
  690.                 .client(client)
  691.                 .build();
  692.  
  693.         APIService service = retrofit.create(APIService.class);
  694.         final Call<String> call = service.getFishingLocationAPI(AppController.getInstance().getAccessToken(), map);
  695.         call.enqueue(new Callback<String>() {
  696.             @Override
  697.             public void onResponse(Response<String> response) {
  698.  
  699.                 Gson gson = new Gson();
  700.                 Log.i("Check Location", response.body());
  701.                 try {
  702.                     JSONObject obj = new JSONObject(response.body());
  703.                     JSONArray array = obj.getJSONArray("fishlocations");
  704.  
  705.                     arrayList = new ArrayList<FishLocation>();
  706.  
  707.                     for (int i = 0; i < array.length(); i++) {
  708.  
  709.                         JSONObject jsonObject = array.getJSONObject(i);
  710.  
  711.                         FishLocation fishLocation = gson.fromJson(jsonObject.toString(), FishLocation.class);
  712.                         arrayList.add(fishLocation);
  713.                     }
  714.  
  715.  
  716.                     List<Fragment> fragments = getSupportFragmentManager().getFragments();
  717.                     for (Fragment fragment : fragments) {
  718.                         if (fragment instanceof MapContainerFragment) {
  719.                             ((MapContainerFragment) fragment).updateList(arrayList, lat, lng);
  720.                         }
  721.                     }
  722.  
  723.                 } catch (JSONException e) {
  724.                     e.printStackTrace();
  725.                 }
  726.             }
  727.  
  728.             @Override
  729.             public void onFailure(Throwable t) {
  730.  
  731.             }
  732.         });
  733.     }
  734.  
  735.  
  736.     @Override
  737.     public void onMapListClick(LatLng selectedLocation) {
  738.         List<Fragment> fragments = getSupportFragmentManager().getFragments();
  739.  
  740.         if(fragments != null){
  741.             for(Fragment fragment: fragments){
  742.                 if(fragment instanceof MapContainerFragment){
  743.                     ((MapContainerFragment)fragment).zoomInToSelectedLocation(selectedLocation);
  744.                 }
  745.                 //Log.i("Check SelectedMap", fragment.toString()+" "+selectedLocation.latitude+","+selectedLocation.longitude);
  746.             }
  747.         }
  748.     }
  749.  
  750.     @Override
  751.     public void onZoomInToSelectedLocation() {
  752.         if(viewPagerFragment != null)
  753.             viewPagerFragment.setCheckedWhenZoomInLocation();
  754.     }
  755.  
  756.     public void fishTalkShare(){
  757.  
  758.         Log.i("Check GUID", AppController.getInstance().getUserGuid());
  759.  
  760.         BranchUniversalObject branchUniversalObject = new BranchUniversalObject()
  761.                 .setCanonicalIdentifier("jomfishing/"+AppController.getInstance().getUserGuid())
  762.                 .setTitle("FishTalk")
  763.                 .setContentDescription("Our truly unique and engaging mobile app for sharing your awesome fishing moments!")
  764.                 .setContentImageUrl("http://www.jomfishing.com/img/logo.png")
  765.                 .addContentMetadata("userId", AppController.getInstance().getUserGuid())
  766.                 .addContentMetadata("userName", AppController.getInstance().getUserEmail())
  767.                 .addContentMetadata("Name", AppController.getInstance().getProfileName());
  768.  
  769.         LinkProperties linkProperties = new LinkProperties()
  770.                 .setChannel("facebook")
  771.                 .setFeature("sharing");
  772.  
  773.         ShareSheetStyle shareSheetStyle = new ShareSheetStyle(this, "FishTalk", "Our truly unique and engaging mobile app for sharing your awesome fishing moments!")
  774.                 .setCopyUrlStyle(null , "Copy", "Added to clipboard")
  775.                 .setMoreOptionStyle(null, "Show more")
  776.                 .addPreferredSharingOption(SharingHelper.SHARE_WITH.FACEBOOK)
  777.                 .addPreferredSharingOption(SharingHelper.SHARE_WITH.EMAIL);
  778.  
  779.         branchUniversalObject.showShareSheet(this,
  780.                 linkProperties,
  781.                 shareSheetStyle,
  782.                 new Branch.BranchLinkShareListener() {
  783.                     @Override
  784.                     public void onShareLinkDialogLaunched() {
  785.  
  786.                     }
  787.  
  788.                     @Override
  789.                     public void onShareLinkDialogDismissed() {
  790.  
  791.                     }
  792.  
  793.                     @Override
  794.                     public void onLinkShareResponse(String sharedLink, String sharedChannel, BranchError error) {
  795.  
  796.                     }
  797.  
  798.                     @Override
  799.                     public void onChannelSelected(String channelName) {
  800.  
  801.                     }
  802.                 });
  803.     }
  804.  
  805.  
  806.     @Override
  807.     public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
  808.         switch (requestCode) {
  809.             case MY_PERMISSION_REQUEST_LOCATION_ACCESS: {
  810.                 // If request is cancelled, the result arrays are empty.
  811.                 if (grantResults.length > 0
  812.                         && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  813.  
  814.                     // permission was granted, yay! Do the
  815.                     // contacts-related task you need to do.
  816.  
  817.                     Log.i("OnPermission", " is called");
  818.                     buildLocationSettingsRequest();
  819.  
  820.                 } else {
  821.  
  822.                     // permission denied, boo! Disable the
  823.                     // functionality that depends on this permission.
  824.                 }
  825.                 break;
  826.             }
  827.         }
  828.     }
  829.  
  830.     protected synchronized void buildGoogleApiClient() {
  831.         mGoogleApiClient = new GoogleApiClient.Builder(this)
  832.                 .addConnectionCallbacks(this)
  833.                 .addOnConnectionFailedListener(this)
  834.                 .addApi(LocationServices.API)
  835.                 .build();
  836.     }
  837.  
  838.     protected void createLocationRequest() {
  839.         mLocationRequest = new LocationRequest();
  840.  
  841.         // Sets the desired interval for active location updates. This interval is
  842.         // inexact. You may not receive updates at all if no location sources are available, or
  843.         // you may receive them slower than requested. You may also receive updates faster than
  844.         // requested if other applications are requesting location at a faster interval.
  845.         mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
  846.  
  847.         // Sets the fastest rate for active location updates. This interval is exact, and your
  848.         // application will never receive updates faster than this value.
  849.         mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
  850.  
  851.         mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
  852.     }
  853.  
  854.  
  855.     protected void buildLocationSettingsRequest() {
  856.         LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
  857.         builder.setAlwaysShow(true);
  858.         builder.addLocationRequest(mLocationRequest);
  859.         mLocationSettingsRequest = builder.build();
  860.         checkLocationSettings();
  861.     }
  862.  
  863.     protected void checkLocationSettings() {
  864.         PendingResult<LocationSettingsResult> result =
  865.                 LocationServices.SettingsApi.checkLocationSettings(
  866.                         mGoogleApiClient,
  867.                         mLocationSettingsRequest
  868.                 );
  869.         result.setResultCallback(this);
  870.     }
  871.  
  872.     @Override
  873.     protected void onStop() {
  874.         super.onStop();
  875.         if (mGoogleApiClient.isConnected()) {
  876.             mGoogleApiClient.disconnect();
  877.         }
  878.     }
  879.  
  880.     /**
  881.      * Runs when a GoogleApiClient object successfully connects.
  882.      */
  883.     @Override
  884.     public void onConnected(Bundle connectionHint) {
  885.         Log.i("GoogleApiClient", " is connected");
  886.         startLocationUpdate();
  887.         if (mCurrentLocation == null) {
  888.             Log.i("GoogleApiClient", " location is null");
  889.             if (Build.VERSION.SDK_INT >= 23) {
  890.                 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  891.                     Log.i("GoogleApiClient", " request location above 23 true");
  892.                     Utils.checkWriteLocationPermissionFor23(this, MY_PERMISSION_REQUEST_LOCATION_ACCESS);
  893.                 } else {
  894.                     startLocationUpdate();
  895.                 }
  896.             }
  897.             else{
  898.                 startLocationUpdate();
  899.             }
  900.         }
  901.         else{
  902.             updateLocationUI();
  903.         }
  904.     }
  905.  
  906.     private void startLocationUpdate(){
  907.         if (Build.VERSION.SDK_INT >= 23) {
  908.             if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  909.                 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  910.                     Utils.checkLocationPermissionFor23(this, MY_PERMISSION_REQUEST_LOCATION_ACCESS);
  911.                 } else {
  912.                     LocationServices.FusedLocationApi.requestLocationUpdates(
  913.                             mGoogleApiClient,
  914.                             mLocationRequest,
  915.                             this
  916.                     ).setResultCallback(new ResultCallback<Status>() {
  917.                         @Override
  918.                         public void onResult(Status status) {
  919.                             mRequestingLocationUpdates = true;
  920.                         }
  921.                     });
  922.                 }
  923.             }
  924.             else{
  925.                 LocationServices.FusedLocationApi.requestLocationUpdates(
  926.                         mGoogleApiClient,
  927.                         mLocationRequest,
  928.                         this
  929.                 ).setResultCallback(new ResultCallback<Status>() {
  930.                     @Override
  931.                     public void onResult(Status status) {
  932.                         mRequestingLocationUpdates = true;
  933.                     }
  934.                 });
  935.             }
  936.         }
  937.         else{
  938.             LocationServices.FusedLocationApi.requestLocationUpdates(
  939.                     mGoogleApiClient,
  940.                     mLocationRequest,
  941.                     this
  942.             ).setResultCallback(new ResultCallback<Status>() {
  943.                 @Override
  944.                 public void onResult(Status status) {
  945.                     mRequestingLocationUpdates = true;
  946.                 }
  947.             });
  948.         }
  949.     }
  950.  
  951.     @Override
  952.     public void onConnectionFailed(ConnectionResult result) {
  953.         Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
  954.     }
  955.  
  956.  
  957.     @Override
  958.     public void onConnectionSuspended(int cause) {
  959.         Log.i(TAG, "Connection suspended");
  960.         mGoogleApiClient.connect();
  961.     }
  962.  
  963.     @Override
  964.     public void onResult(LocationSettingsResult locationSettingsResult) {
  965.  
  966.         final Status status = locationSettingsResult.getStatus();
  967.         switch (status.getStatusCode()) {
  968.             case LocationSettingsStatusCodes.SUCCESS:
  969.                 Log.i(TAG, "All location settings are satisfied.");
  970.  
  971.                 startLocationUpdate();
  972.                 break;
  973.             case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
  974.                 Log.i(TAG, "Location settings are not satisfied. Show the user a dialog to" +
  975.                         "upgrade location settings ");
  976.  
  977.                 try {
  978.                     // Show the dialog by calling startResolutionForResult(), and check the result
  979.                     // in onActivityResult().
  980.                     status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
  981.                 } catch (IntentSender.SendIntentException e) {
  982.                     Log.i(TAG, "PendingIntent unable to execute request.");
  983.                 }
  984.                 break;
  985.             case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
  986.                 Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog " +
  987.                         "not created.");
  988.                 break;
  989.         }
  990.     }
  991.  
  992.     @Override
  993.     public void onLocationChanged(Location location) {
  994.         mCurrentLocation = location;
  995.         updateLocationUI();
  996.     }
  997.  
  998.  
  999.     @Override
  1000.     public void onResume() {
  1001.         super.onResume();
  1002.         ImageLoader.getInstance().displayImage(AppController.getInstance().getAvatarUrl(), profileImage, options);
  1003.  
  1004.         if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
  1005.             //do something
  1006.         }
  1007.     }
  1008.  
  1009.     @Override
  1010.     protected void onPause() {
  1011.         super.onPause();
  1012.         // Stop location updates to save battery, but don't disconnect the GoogleApiClient object.
  1013.         if (mGoogleApiClient.isConnected()) {
  1014.             stopLocationUpdates();
  1015.         }
  1016.     }
  1017. }
  1018.  
  1019.  
  1020. //getApiFishingLocation
  1021.  List<Fragment> fragments = getSupportFragmentManager().getFragments();
  1022.                     for (Fragment fragment : fragments) {
  1023.                         if (fragment instanceof MapContainerFragment) {
  1024.                             ((MapContainerFragment) fragment).updateList(arrayList, lat, lng);
  1025.                         }
  1026.                     }
  1027.  
  1028. //UpdateList
  1029. public void updateList(ArrayList<FishLocation> fishLocations, Double lat, Double lng){
  1030.  
  1031.         List<Fragment> fragments = getChildFragmentManager().getFragments();
  1032.         if(fragments != null) {
  1033.             for (Fragment fragment : fragments) {
  1034.                 if(fragment instanceof MapsFragment) {
  1035.                     ((MapsFragment) fragment).onRefreshMap(fishLocations, new LatLng(lat, lng));
  1036.                 }
  1037.                 else if (fragment instanceof MapListFragment){
  1038.                     ((MapListFragment)fragment).refreshList(fishLocations, lat, lng);
  1039.                 }
  1040.             }
  1041.         }
  1042.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement