com.example.amand.mobileprogrammingfitnessapp.LoggedActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.example.amand.mobileprogrammingfitnessapp.LoggedActivity.java

Source

package com.example.amand.mobileprogrammingfitnessapp;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.amand.mobileprogrammingfitnessapp.Fragments.ExerciseFrag;
import com.example.amand.mobileprogrammingfitnessapp.Fragments.GymFrag;
import com.example.amand.mobileprogrammingfitnessapp.Fragments.HealthFrag;
import com.example.amand.mobileprogrammingfitnessapp.Fragments.LocationFunctions1;
import com.example.amand.mobileprogrammingfitnessapp.Fragments.NutritionFrag;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.util.ArrayList;

import de.hdodenhof.circleimageview.CircleImageView;

public class LoggedActivity extends AppCompatActivity {

    //Defined a wide range of varriables
    // the toolbar, that is used to replace the actionbar
    private Toolbar toolbar;
    // the navigation view, a reference to naviagtion view
    private NavigationView navigationView;
    // the drawer layout
    private DrawerLayout drawerLayout;
    // alert dialog to display about information
    private AlertDialog.Builder dialog;
    // the menu item gym icon, for displaying the menu icon when the gym fragment is loaded
    private MenuItem itemGym;
    // The setting icon, this is added, because this options is not available because the user has not logged in
    // This is only possible, due to the test option i created for bobby, without the need of logging in
    private MenuItem SettingIcon;
    // two boolean options, else false or show
    private boolean show = false;
    private boolean setting = true;
    // reference to the view header, to allow texts and imageview to be changed
    private View header;
    // these are textviews of the headers
    private TextView username;
    private TextView namee;
    private Database database;
    // the background reference
    private RelativeLayout naviagtionbackground;
    // reference to the circle imageview
    private CircleImageView circle;
    // byte array of the bytes of the image that is used to be decoded
    private byte[] decode;
    public String temp;
    // these are not used, but are involved in decoding byte into an object
    private Object o;
    private byte[] objectDdecode;
    // the current frame layout that is used to display fragment
    private FrameLayout frame;
    // reference for the window that is used to change the status bar colour
    private Window window;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_logged);

        // toolbar reference, and is used to instantiate the toolbar
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitleTextColor(0xFFFFFFFF);
        setSupportActionBar(toolbar);
        // this sets the toolbar colour and replaces the action bar, although this activity has style
        // of no actionbar

        // dialog is instantiated, and is set up with appropriate message, that is displayed when the user
        // presses the about icon
        dialog = new AlertDialog.Builder(this);
        dialog.setTitle("About");
        dialog.setMessage("This appliation was developed for Mobile & Ubiquitous Computing. This application"
                + "is a fitness app and composed of contents, such as nutrition, health, exercises and gym facilities."
                + "The gym facilities provides numerous features, such as displaying gyms near you"
                + System.lineSeparator()
                + "The application makes use of a circular Imageview that under apache 2.0 Licencing"
                + "http://www.apache.org/licenses/LICENSE-2.0.txt");

        // Reference to the database object, which is used to recieve users information
        database = new Database(getApplicationContext(), null, null, 1);
        // reference to the navogationn view that consists of navigation header and items
        navigationView = (NavigationView) findViewById(R.id.navigation_view);
        // the first fragment is loaded
        switchFragment(1);
        toolbar.setTitle("Nutrition");
        // the references to textviews and circle imageview to change the details of the navigation drawer
        header = navigationView.getHeaderView(0);
        circle = (CircleImageView) header.findViewById(R.id.profile_image);
        namee = (TextView) header.findViewById(R.id.fullnameheader);
        username = (TextView) header.findViewById(R.id.usernameheader);
        naviagtionbackground = (RelativeLayout) header.findViewById(R.id.navbackground);
        // reference to the drawerlayout
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
        // reference to framelayout
        frame = (FrameLayout) findViewById(R.id.Screen);
        // the decode stream
        decode = new byte[100];
        // this gets the information that is passed in from the register screen. The data is the username, and
        //is needed when using the database methods
        // if the data recieved is null, then the visabilty of the setting icon is false
        Intent intt = getIntent();
        temp = intt.getStringExtra("key");
        if (temp == null) {
            setting = false;
        }

        //Two methods are called, when the oncreate method has ran, the first method is responsible
        //in displaying the users detail in the navigation drawer, takes the username as parameters
        // Likewise the loadpreference method, loads the preference of each user
        setNavigationDetails(temp);
        loadpreferences(temp);
        //      //  database.loadPreferenes(temp);
        //        objectDdecode = database.loadPreferenes(temp);
        //        Toast.makeText(getApplicationContext(),"done" +database.loadPreferenes(temp).toString(),Toast.LENGTH_LONG).show();
        //        Toast.makeText(getApplicationContext(),objectDdecode.toString(),Toast.LENGTH_LONG).show();

        // the naviagtion view is set with item click listener. This listens to the click of items that are
        // present in the application
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

            // this method is responosble for dealing with the menu items that have been clicked.
            public boolean onNavigationItemSelected(MenuItem menuItem) {
                // checks if the item has been selected, if its not selected set to false
                // else make it true to indicate its been checked
                if (menuItem.isChecked())
                    menuItem.setChecked(false);
                else
                    menuItem.setChecked(true);
                //closes the naviagtion drawer once checked
                drawerLayout.closeDrawers();

                //switch condidtion to assess what action is performed once the item has been  checked
                switch (menuItem.getItemId()) {
                // the nutrition fragment is selected, if the gym icon is showing, it will disappear
                // the toolbar text is also set to nutrition
                case R.id.nutritionF:
                    switchFragment(1);
                    show = false;
                    // reloads the option menu
                    invalidateOptionsMenu();
                    toolbar.setTitle("Nutrition");
                    return true;

                // the health fragment is selected, if the gym icon is showing, it will disappear
                // the toolbar text is also set to Health
                case R.id.HealthF:
                    switchFragment(3);
                    toolbar.setTitle("Health");
                    show = false;
                    // reloads the option menu
                    invalidateOptionsMenu();
                    return true;
                // the exercie fragment is selected, if the gym icon is showing, it will disappear
                // the toolbar text is also set to Exercise
                case R.id.ExerciseF:
                    Toast.makeText(getApplicationContext(), "Exercise", Toast.LENGTH_SHORT).show();
                    switchFragment(2);
                    toolbar.setTitle("Exercises");
                    show = false;
                    // reloads the option menu
                    invalidateOptionsMenu();
                    return true;
                // the gym fragment is selected, if the gym icon is not showing, it will appear
                // the toolbar text is also set to gym
                case R.id.GymF:
                    Toast.makeText(getApplicationContext(), "Gym Selected", Toast.LENGTH_SHORT).show();
                    switchFragment(4);
                    toolbar.setTitle("Gym Facilities");
                    show = true;
                    // reloads the option menu, to show the gym action icon
                    invalidateOptionsMenu();
                    return true;
                // the logout item would just be intent back to the login screen.
                // to ensure user cannot travel back, the finish method is called to delete activity off the
                // stack
                case R.id.logoffF:
                    Intent intt = new Intent(getApplicationContext(), LoginScreen.class);
                    startActivity(intt);
                    finish();
                    return true;
                // by default, even though this shouldnt happen, a toast message is presented to the user
                default:
                    Toast.makeText(getApplicationContext(),
                            "Somethings Wrong, please contact amandeep for more detail", Toast.LENGTH_SHORT).show();
                    return true;

                }
            }
        });
        //Syncs the actionbartoggle to sync in with the toolbar
        new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.opendrawer, R.string.closedrawer)
                .syncState();

    }

    // this method creates the option menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.actionbarfunctions, menu);
        // the menuitem are set up
        // reference to the menu item, gym icon and setting are made, this is because the
        // the icon visibilty depends on the users action
        itemGym = menu.findItem(R.id.LocGym);
        SettingIcon = menu.findItem(R.id.Usetting);
        itemGym.setVisible(show);
        SettingIcon.setVisible(setting);
        return true;
    }

    // this method is responsoble  to deal with the icons that have been clicked
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
        // increase about icon, then the dialog will appear
        case R.id.about:
            dialog.show();
            dialog.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            return true;
        //increase the setting icon a new intent to the setting activity, while sending the username as
        // extra
        case R.id.Usetting:
            Intent intt = new Intent(getApplicationContext(), SettinhUserPrefs.class);
            intt.putExtra("key", temp);
            startActivity(intt);
            return true;
        // The gym icon, do nothing, this icon is set to invisible, and can only be instantiated from gym fragment
        case R.id.LocGym:
            return false;
        }
        return super.onOptionsItemSelected(item);

    }

    // this method is called and is responsible for switching the fragement, the frame layout is replaced
    // by the fragmenet, depending on what position of item has been clicked
    public void switchFragment(int number) {

        switch (number) {
        case 1:
            NutritionFrag fragment = new NutritionFrag();
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.Screen, fragment);
            transaction.commit();
            break;
        case 2:

            ExerciseFrag fragment2 = new ExerciseFrag();
            FragmentTransaction transaction1 = getSupportFragmentManager().beginTransaction();
            transaction1.replace(R.id.Screen, fragment2);
            transaction1.commit();
            break;
        case 3:
            HealthFrag fragment3 = new HealthFrag();
            FragmentTransaction transaction2 = getSupportFragmentManager().beginTransaction();
            transaction2.replace(R.id.Screen, fragment3);
            transaction2.commit();
            break;
        case 4:
            GymFrag fragment4 = new GymFrag();
            FragmentTransaction transaction3 = getSupportFragmentManager().beginTransaction();
            transaction3.replace(R.id.Screen, fragment4);
            transaction3.commit();
            break;

        }

    }

    // the set navigation method is used to set the details of the user, this takes string as parameters
    // this string should be the username
    public void setNavigationDetails(String currentUser) {
        String temp2 = database.getfirstName(currentUser);
        String temp3 = database.getSurname(currentUser);
        // the firstname and second name is obtained by calling the database methods, these methods take
        // string username as parameters. The database method, finds the details in the database depending on the
        // username. The details are then stored and set on the navigation header textviews.

        username.setText(currentUser);
        namee.setText(temp2 + " " + temp3);
        // the same is applied with the image. The methodd returns byte array that is decoded into an image
        // and is set on the circular imageview
        decode = database.getImage(currentUser);

        Bitmap image = BitmapFactory.decodeByteArray(decode, 0, decode.length);
        circle.setImageBitmap(image);
        Bundle bundle = new Bundle();
        bundle.putString("key", currentUser);
        GymFrag frag = new GymFrag();
        frag.setArguments(bundle);

    }

    // the load preferences method is also loaded, on create, and involves loaded the users preferences
    // if they exist. This takes the users username, to identify the preference.
    public void loadpreferences(String currentuser) {
        // this involves to see whenever the user's preference file exista
        File f = new File("/data/data/" + getPackageName() + "/shared_prefs/" + currentuser + ".xml");

        //if the preference file exists, the preferences will be recieved.
        if (f.exists()) {
            Toast.makeText(getApplicationContext(), "Loaded user's current preference", Toast.LENGTH_LONG).show();
            //the preferences are loaded, the preference will be loaded, is essentially the name of the
            // users username
            SharedPreferences preferences = getSharedPreferences(currentuser, Context.MODE_PRIVATE);
            // Colours are obtained from the preferences, if it is unable to be obtained, a default value
            // of zero is given
            int red = preferences.getInt("Red", 0);
            int green = preferences.getInt("Green", 0);
            int blue = preferences.getInt("Blue", 0);
            // the naviagtion background is also obtained.
            String backgroundd = preferences.getString("background", "background");

            int header = getApplicationContext().getResources().getIdentifier(backgroundd, "drawable",
                    getPackageName());
            frame.setBackgroundColor(Color.rgb(red, green, blue));
            window = this.getWindow();
            window.setStatusBarColor(Color.rgb(red, green, blue));
            toolbar.setBackgroundColor(Color.rgb(red, green, blue));

            naviagtionbackground.setBackgroundResource(header);
            // sets the users details bassed on preferences
        }

        // this method is not being used and involves decoding objects that are stored in the users database

        //        byte[] perference = new byte[100];
        //        objectDdecode = database.loadPreferenes(currentuser);
        //        ByteArrayInputStream inputStream = new ByteArrayInputStream(objectDdecode);
        //        Toast.makeText(getApplicationContext(),objectDdecode.toString(),Toast.LENGTH_LONG).show();
        ////perference = database.loadPreferenes(currentuser);
        //        SharedPreferences preference = getSharedPreferences("userdesign",Context.MODE_PRIVATE);
        //
        //
        //        String aman = preference.getString("red","");
        //        Toast.makeText(getApplicationContext(),aman,Toast.LENGTH_LONG).show();
        //
        //        ObjectInputStream inputStream1 = null;
        //        try {
        //            inputStream1 = new ObjectInputStream(inputStream);
        //             o = inputStream1.readObject();
        //
        //        } catch (IOException e) {
        //            e.printStackTrace();
        //        } catch (ClassNotFoundException e) {
        //            e.printStackTrace();
        //        }
        //        SharedPreferences demo = (SharedPreferences) o ;
        //        demo = getPreferences(Context.MODE_PRIVATE);
        //       // Toast.makeText(getApplicationContext(),demo.toString(),Toast.LENGTH_LONG).show();
        //
        //        Toast.makeText(getApplicationContext(),"got your preference" ,Toast.LENGTH_LONG).show();
    }
    // else nothing is displayed.

}