com.kayzook.bracediary.BaseActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.kayzook.bracediary.BaseActivity.java

Source

/*
 * Copyright 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.kayzook.bracediary;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.kayzook.bracediary.Controller.UserController;
import com.kayzook.bracediary.Model.UserProfile;
import com.kayzook.bracediary.Util.AsyncHttpTaskListener;
import com.kayzook.bracediary.Util.AsyncTaskResponse;
import com.kayzook.bracediary.Util.ExceptionHandler;
import com.kayzook.bracediary.Util.FileUtil;
import com.kayzook.bracediary.ViewActivity.ClinicActivityFragment;
import com.kayzook.bracediary.ViewActivity.PointHistoryActivityFragment;
import com.kayzook.bracediary.ViewActivity.RewardListActivityFragment;
import com.kayzook.bracediary.ViewActivity.UserEditProfileActivityFragment;
import com.kayzook.bracediary.ViewCustom.CustomDrawerListAdapter;
import com.kayzook.bracediary.ViewCustom.CustomDrawerListData;
import com.kayzook.bracediary.ViewFragment.FindClinicsFragment;
import com.kayzook.bracediary.ViewFragment.HelpPageFragment;
import com.kayzook.bracediary.ViewFragment.TimelineFragment;
import com.makeramen.RoundedImageView;
import com.soundcloud.android.crop.Crop;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

public class BaseActivity extends FragmentActivity implements AsyncHttpTaskListener {

    private static final int CAPTURE_IMAGE_ACTIVITY_REQ = 0;
    private static final int GALLERY_INTENT_CALLED = 1;
    private static final int GALLERY_KITKAT_INTENT_CALLED = 11;
    private static final String KEY_NAV_ACTION = "action";
    private static final String KEY_NAV_ACTION_DETAIL = "action_detail";
    private static final String KEY_NAV_IMAGE = "image_id";
    private final String TAG = "BaseActivity";
    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the
     * three primary sections of the app. We use a {@link android.support.v4.app.FragmentPagerAdapter}
     * derivative, which will keep every loaded fragment in memory. If this becomes too memory
     * intensive, it may be best to switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */

    private final int RELOAD_DATA_ON_TIMELINE = 9999;
    private Uri mCroppedImageUri = null;
    private Context mContext = this;
    private ImageView mProfilePicture = null;
    private Uri fileUri = null;
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private LinearLayout mDrawer;
    private ActionBarDrawerToggle mDrawerToggle;

    private CharSequence mDrawerTitle;
    private CharSequence mTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!BuildConfig.DEBUG) {
            Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
        }

        setContentView(R.layout.activity_base);

        mTitle = mDrawerTitle = getTitle();
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer_list);
        mDrawer = (LinearLayout) findViewById(R.id.left_drawer);

        ArrayList<CustomDrawerListData> objects = new ArrayList<CustomDrawerListData>();
        for (int i = 0; i < 5; i++) {
            CustomDrawerListData item = new CustomDrawerListData();
            HashMap<String, Object> map = getHashMapForNaviMenu(i);
            Log.d(TAG, String.valueOf(map.get(KEY_NAV_ACTION)));
            item.setActionName(String.valueOf(map.get(KEY_NAV_ACTION)));
            item.setActionDetail(String.valueOf(map.get(KEY_NAV_ACTION_DETAIL)));
            item.setImageId((Integer) map.get(KEY_NAV_IMAGE));
            objects.add(item);
        }

        CustomDrawerListAdapter customAdapater = new CustomDrawerListAdapter(this, R.id.drawer_layout, objects);
        mDrawerList.setAdapter(customAdapater);
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        // enable ActionBar app icon to behave as action to toggle nav drawer
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the sliding drawer and the action bar app icon
        mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
                mDrawerLayout, /* DrawerLayout object */
                R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
                0, /* "open drawer" description for accessibility */
                0 /* "close drawer" description for accessibility */
        ) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            selectItem(0);
        }

        //set up usernames
        TextView currentPoint = (TextView) findViewById(R.id.current_point);
        if (UserProfile.getUserProfile() != null) {
            UserProfile profile = UserProfile.getUserProfile();
            currentPoint.setText(profile.getPoints() + " pts");
            TextView username = (TextView) findViewById(R.id.drawer_username);
            username.setText(profile.getFullName());
            mProfilePicture = (RoundedImageView) findViewById(R.id.drawer_profile_pic);
            Picasso.with(this).load(profile.getPhotoUrl()).placeholder(R.drawable.icon_user).into(mProfilePicture);
        }

    }

    /* Called whenever we call invalidateOptionsMenu() */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the nav drawer is open, hide action items related to the content view
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawer);
        //menu.findItem(R.id.action_bar).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // The action bar home/up action should open or close the drawer.
        // ActionBarDrawerToggle will take care of this.
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);

    }

    private void selectItem(int position) {
        //update the main content by replacing fragments
        FragmentManager fragmentManager = getSupportFragmentManager();
        Fragment fragment = null;
        Intent intent = new Intent();
        switch (position) {
        case 0:
            fragment = new FindClinicsFragment();
            fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
            break;
        case 1:
            intent.setClass(this, RewardListActivityFragment.class);
            startActivity(intent);
            break;
        case 2:
            intent.setClass(this, PointHistoryActivityFragment.class);
            startActivity(intent);
            break;
        case 3:
            intent.setClass(this, ClinicActivityFragment.class);
            startActivity(intent);
            break;
        case 4:
            fragment = new HelpPageFragment();
            fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
            break;
        //            case 5:
        //                fragment = new HelpPageFragment();
        //                fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
        //                break;
        default:
            fragment = new TimelineFragment();
            fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
            break;
        }

        //
        //        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        HashMap<String, Object> map = getHashMapForNaviMenu(position);
        setTitle(String.valueOf(map.get(KEY_NAV_ACTION)));
        mDrawerLayout.closeDrawer(mDrawer);
    }

    public void jumpToProfile(View view) {
        Intent intent = new Intent();
        intent.setClass(this, UserEditProfileActivityFragment.class);
        startActivity(intent); // update selected item and title, then close the drawer
        mDrawerLayout.closeDrawer(mDrawer);
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
            getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        }
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public void onAttachFragment(Fragment fragment) {
        super.onAttachFragment(fragment);
        String fragmentSimpleName = fragment.getClass().getSimpleName();

        if (!fragmentSimpleName.equals("CustomDialogFragment")) {
            FragmentManager fm = getSupportFragmentManager();
            for (int i = 0; i < fm.getBackStackEntryCount(); ++i) {
                fm.popBackStack();
            }
        }
    }

    private void openCropImage(Uri photoUri) {
        FileUtil.getPath(this, photoUri);
        File imageFile = new File(FileUtil.getPath(this, photoUri));
        if (imageFile.exists()) {
            mCroppedImageUri = Uri.fromFile(getOutputPhotoFile());
            new Crop(photoUri).output(mCroppedImageUri).asSquare().start(this);
        }
    }

    private void setPhoto() {
        File imageFile = new File(FileUtil.getPath(this, mCroppedImageUri));
        if (imageFile.exists()) {
            Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
            mProfilePicture.setImageBitmap(bitmap);
            new HttpAsyncTask(this).execute();
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQ) {
            if (resultCode == RESULT_OK) {
                if (data == null) {
                    Toast.makeText(this, "Image saved successfully", Toast.LENGTH_LONG).show();
                } else {
                    fileUri = data.getData();
                    Toast.makeText(this, "Image saved successfully in: " + data.getData(), Toast.LENGTH_LONG)
                            .show();
                }
                openCropImage(fileUri);
            } else if (resultCode == RESULT_CANCELED) {
                Toast.makeText(this, "Cancelled", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Callout for image capture failed!", Toast.LENGTH_LONG).show();
            }
        } else if (requestCode == Crop.REQUEST_CROP && resultCode == RESULT_OK) {
            setPhoto();
        } else {
            if (resultCode == RESULT_OK) {
                if (null == data)
                    return;
                String path = FileUtil.getPath(this, data.getData());
                openCropImage(data.getData());
            }
        }
    }

    private HashMap<String, Object> getHashMapForNaviMenu(int position) {
        HashMap map = new HashMap<String, String>();
        switch (position) {
        case 0:
            map.put(KEY_NAV_ACTION, getResources().getString(R.string.nav_action_1));
            map.put(KEY_NAV_ACTION_DETAIL, getResources().getString(R.string.nav_action_detail_1));
            map.put(KEY_NAV_IMAGE, R.drawable.ic_doctor_24dp_gray);
            break;
        case 1:
            map.put(KEY_NAV_ACTION, getResources().getString(R.string.nav_action_2));
            map.put(KEY_NAV_ACTION_DETAIL, getResources().getString(R.string.nav_action_detail_2));
            map.put(KEY_NAV_IMAGE, R.drawable.ic_wallet_giftcard_grey600_24dp);
            break;
        case 2:
            map.put(KEY_NAV_ACTION, getResources().getString(R.string.nav_action_3));
            map.put(KEY_NAV_ACTION_DETAIL, getResources().getString(R.string.nav_action_detail_3));
            map.put(KEY_NAV_IMAGE, R.drawable.ic_local_attraction_grey600_24dp);
            break;
        case 3:
            map.put(KEY_NAV_ACTION, getResources().getString(R.string.nav_action_4));
            map.put(KEY_NAV_ACTION_DETAIL, getResources().getString(R.string.nav_action_detail_4));
            map.put(KEY_NAV_IMAGE, R.drawable.ic_event_note_grey600_24dp);

            break;
        case 4:
            map.put(KEY_NAV_ACTION, getResources().getString(R.string.nav_action_5));
            map.put(KEY_NAV_ACTION_DETAIL, getResources().getString(R.string.nav_action_detail_5));
            map.put(KEY_NAV_IMAGE, R.drawable.ic_live_help_grey600_24dp);
            break;
        default:
            map.put(KEY_NAV_ACTION, getResources().getString(R.string.nav_action_1));
            map.put(KEY_NAV_ACTION_DETAIL, getResources().getString(R.string.nav_action_detail_1));
            map.put(KEY_NAV_IMAGE, R.drawable.ic_action_picture);
            break;
        }

        return map;

    }

    public void updateProfilePhoto(final View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.string_picture).setItems(R.array.profile_photo_array,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            takePhoto(view);
                        } else {
                            getGallery(view);
                        }
                    }
                });
        builder.create();
        builder.show();
    }

    private File getOutputPhotoFile() {

        File directory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                getPackageName());

        if (!directory.exists()) {
            if (!directory.mkdirs()) {
                return null;
            }
        }

        String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss", Locale.US).format(new Date());

        return new File(directory.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
    }

    public void takePhoto(View view) {
        Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        fileUri = Uri.fromFile(getOutputPhotoFile());
        i.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        startActivityForResult(i, CAPTURE_IMAGE_ACTIVITY_REQ);
    }

    public void getGallery(View view) {
        if (Build.VERSION.SDK_INT < 19) {
            Intent intent = new Intent();
            intent.setType("image/jpeg");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Photo"), GALLERY_INTENT_CALLED);
        } else {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/jpeg");
            startActivityForResult(intent, GALLERY_KITKAT_INTENT_CALLED);
        }
    }

    @Override
    public void onTaskStarted() {
    }

    @Override
    public void onTaskFinished(AsyncTaskResponse result) {
        if (result.getResponse() == null) {
            Toast.makeText(this, getString(R.string.message_no_network_connection), Toast.LENGTH_LONG).show();
            return;
        }
        Picasso.with(this).invalidate(UserProfile.getUserProfile().getPhotoUrl());
        Picasso.with(this).load(UserProfile.getUserProfile().getPhotoUrl()).placeholder(R.drawable.icon_user)
                .into(mProfilePicture);
    }

    /* The click listner for ListView in the navigation drawer */
    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
        }
    }

    private class HttpAsyncTask extends AsyncTask<Integer, Integer, AsyncTaskResponse> {

        private final AsyncHttpTaskListener mAsyncHttpTaskListener;

        public HttpAsyncTask(AsyncHttpTaskListener listener) {
            mAsyncHttpTaskListener = listener;
        }

        @Override
        protected void onPreExecute() {
            mAsyncHttpTaskListener.onTaskStarted();
        }

        @Override
        protected AsyncTaskResponse doInBackground(Integer... params) {
            Object object = UserController.updateProfilePhoto(mContext,
                    FileUtil.getPath(mContext, mCroppedImageUri));
            return new AsyncTaskResponse(object);
        }

        @Override
        protected void onPostExecute(AsyncTaskResponse result) {
            mAsyncHttpTaskListener.onTaskFinished(result);
        }
    }

}