in.co.scsonline.rafaqatrasool.jkssbnotifier.MainActivity.java Source code

Java tutorial

Introduction

Here is the source code for in.co.scsonline.rafaqatrasool.jkssbnotifier.MainActivity.java

Source

/*
 * Copyright 2013 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 in.co.scsonline.rafaqatrasool.jkssbnotifier;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.kobakei.ratethisapp.RateThisApp;
import com.madx.updatechecker.lib.UpdateRunnable;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 * This example illustrates a common usage of the DrawerLayout widget
 * in the Android support library.
 * <p/>
 * <p>When a navigation (left) drawer is present, the host activity should detect presses of
 * the action bar's Up affordance as a signal to open and close the navigation drawer. The
 * ActionBarDrawerToggle facilitates this behavior.
 * Items within the drawer should fall into one of two categories:</p>
 * <p/>
 * <ul>
 * <li><strong>View switches</strong>. A view switch follows the same basic policies as
 * list or tab navigation in that a view switch does not create navigation history.
 * This pattern should only be used at the root activity of a task, leaving some form
 * of Up navigation active for activities further down the navigation hierarchy.</li>
 * <li><strong>Selective Up</strong>. The drawer allows the user to choose an alternate
 * parent for Up navigation. This allows a user to jump across an app's navigation
 * hierarchy at will. The application should treat this as it treats Up navigation from
 * a different task, replacing the current task stack using TaskStackBuilder or similar.
 * This is the only form of navigation drawer that should be used outside of the root
 * activity of a task.</li>
 * </ul>
 * <p/>
 * <p>Right side drawers should be used for actions, not navigation. This follows the pattern
 * established by the Action Bar that navigation should be to the left and actions to the right.
 * An action should be an operation performed on the current contents of the window,
 * for example enabling or disabling a data overlay on top of the current content.</p>
 */
public class MainActivity extends ActionBarActivity
        implements FragmentManager.OnBackStackChangedListener, NotificationsFragment.readCounterListener {
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    private String[] navigationTitles;
    private int[] icons = { R.drawable.ic_notification_grey, R.drawable.ic_selection_grey, R.drawable.ic_r_r_grey,
            R.drawable.ic_office_order_grey, R.drawable.ic_jobs_grey, R.drawable.ic_login_grey,
            R.drawable.ic_syallabus_grey, R.drawable.ic_about_us_grey };
    private int[] iconsSelected = { R.drawable.ic_notification_selected, R.drawable.ic_selection_selected,
            R.drawable.ic_r_r_selected, R.drawable.ic_office_order_selected, R.drawable.ic_jobs_selected,
            R.drawable.ic_login_selected, R.drawable.ic_syallabus_selected, R.drawable.ic_about_us_selected };

    AlarmReceiver alarm = new AlarmReceiver();

    private ArrayList<Integer> notificationsCount;

    ArrayAdapter<String> drawerListAdapter;
    //Contsructor to pass the context to make toast when in fetchdata function doc return null exception
    Parser obj = new Parser(this);

    //Tracker for analytics
    // private Tracker mTracker;

    @Override
    protected void onStart() {
        super.onStart();
        /*TODO-Optimise this code below for better performance
        * frequent database query is not good and find a way to Use notifyDataSetChanged to reflect
        * notification count in a better way*/
        notificationsCount = new ArrayList<>();
        DbManage dbManage = new DbManage(this);
        try {
            dbManage.open();

            if (dbManage.getNotificationsCount("no", "notifications") != 0) //check if the method worked to return any count
                notificationsCount.add(dbManage.getNotificationsCount("no", "notifications")); //add the counts in the array and add 0 for the rest
            else
                notificationsCount.add(0);

            if (dbManage.getNotificationsCount("no", "selections") != 0)
                notificationsCount.add(dbManage.getNotificationsCount("no", "selections"));
            else
                notificationsCount.add(0);

            if (dbManage.getNotificationsCount("no", "releaseRecommendations") != 0)
                notificationsCount.add(dbManage.getNotificationsCount("no", "releaseRecommendations"));
            else
                notificationsCount.add(0);

            if (dbManage.getNotificationsCount("no", "officeOrders") != 0)
                notificationsCount.add(dbManage.getNotificationsCount("no", "officeOrders"));
            else
                notificationsCount.add(0);

        } catch (SQLException e) {
            e.printStackTrace();
        }

        dbManage.close();

        //Monitor launch times and interval from installation
        RateThisApp.onStart(this);
        //if the criteria is satisfied the dialog will show up
        RateThisApp.showRateDialogIfNeeded(this);

    }

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

        //ads code start
        AdView mAdView = (AdView) findViewById(R.id.adView);
        if (ConnectionUtils.isOnline(MainActivity.this)) {

            mAdView = (AdView) findViewById(R.id.adView);
            AdRequest adRequest = new AdRequest.Builder().build();
            mAdView.loadAd(adRequest);

        } else {
            mAdView.setVisibility(View.GONE);
        }
        //ads code end

        //callback for rate this app dialog
        RateThisApp.Config config = new RateThisApp.Config(3, 3);
        RateThisApp.init(config);

        /*//analytics code start
        // Obtain the shared Tracker instance.
        Analytics application = (Analytics) getApplication();
        mTracker = application.getDefaultTracker();
        //analytics code end*/

        //background update check code start
        new UpdateRunnable(this, new Handler()).start();//using https://github.com/danielemaddaluno/Android-Update-Checker/
        //background update check code end

        PreferenceManager.setDefaultValues(this, R.xml.settings, false);//set the default values that are provided in xml

        mTitle = mDrawerTitle = getTitle();
        navigationTitles = getResources().getStringArray(R.array.navigation_titles_array);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);
        mDrawerList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

        // set a custom shadow that overlays the main content when the drawer opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        // set up the drawer's list view with items and click listener
        drawerListAdapter = new MyListAdapter();
        mDrawerList.setAdapter(drawerListAdapter);

        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        // enable ActionBar app icon to behave as action to toggle nav drawer
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().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 */
                R.string.drawer_open, /* "open drawer" description for accessibility */
                R.string.drawer_close /* "close drawer" description for accessibility */
        ) {
            public void onDrawerClosed(View view) {
                getSupportActionBar().setTitle(mTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            public void onDrawerOpened(View drawerView) {
                getSupportActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
                drawerListAdapter.notifyDataSetChanged();//refresh the drawer list
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

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

    private class MyListAdapter extends ArrayAdapter<String> {

        public MyListAdapter() {
            super(MainActivity.this, R.layout.drawer_list_item, android.R.id.text1, navigationTitles);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = super.getView(position, convertView, parent);
            ImageView icon = (ImageView) v.findViewById(R.id.row_icon);
            TextView countTextView = (TextView) v.findViewById(R.id.notification_count);

            if (!notificationsCount.isEmpty() && position < 4) {

                if (notificationsCount.get(position) != 0) {
                    String count = "";
                    count = String.valueOf(notificationsCount.get(position));
                    countTextView.setText(count);
                    countTextView.setBackgroundResource(R.drawable.badge_circle);
                } else {
                    countTextView.setText("");
                    countTextView.setBackgroundResource(0);
                }
            }

            if (mDrawerList.isItemChecked(position)) {
                icon.setImageResource(iconsSelected[position]);
            } else {
                icon.setImageResource(icons[position]);
            }

            return v;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    /* 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(mDrawerList);
         menu.findItem(R.id.action_websearch).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;
        }
        // Handle action buttons
        switch (item.getItemId()) {

        case R.id.app_settings:
            Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
            startActivity(intent);
            return true;
        case R.id.check_update:
            new UpdateRunnable(this, new Handler()).force(true).start();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onBackPressed() {

        /*if(getSupportFragmentManager().getBackStackEntryCount()==0) {
        setTitle(navigationTitles[0]); //When backstack is empty then set title to first title
        mDrawerList.setItemChecked(0, true); //highlight the first item.
        }*/
        if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
            mDrawerLayout.closeDrawer(GravityCompat.START);

        } else {

            if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
                super.onBackPressed();
                setTitle(navigationTitles[0]); //When backstack has  one entry then set title to first title as its not updated by onBackStackChanged Listener
                mDrawerList.setItemChecked(0, true); //highlight the first item.
            } else
                super.onBackPressed();//Default behaviour of exiting the app.
        }

    }

    @Override
    public void onBackStackChanged() {
        //called when the BackStack changes
        //retrieve the current fragment on stack top use its tag to determine the title
        int position;
        int count = getSupportFragmentManager().getBackStackEntryCount();
        if (count > 0) {
            position = Integer.parseInt(getSupportFragmentManager().getBackStackEntryAt(count - 1).getName());
            setTitle(navigationTitles[position]);
            mDrawerList.setItemChecked(position, true);//update the selected item in drawer
        }

    }

    @Override
    public void readCount(int count, String Table) {
        //depending upon the table name decrease the corresponding count
        switch (Table) {
        case "notifications":
            if (notificationsCount.get(0) != 0)
                notificationsCount.set(0, notificationsCount.get(0) - count);
            break;
        case "selections":
            if (notificationsCount.get(1) != 0)
                notificationsCount.set(1, notificationsCount.get(1) - count);
            break;
        case "releaseRecommendations":
            if (notificationsCount.get(2) != 0)
                notificationsCount.set(2, notificationsCount.get(2) - count);
            break;
        case "officeOrders":
            if (notificationsCount.get(3) != 0)
                notificationsCount.set(3, notificationsCount.get(3) - count);
            break;
        default:
            break;
        }
    }

    /* 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 void selectItem(int position) {
        // update the main content by replacing fragments

        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.addOnBackStackChangedListener(this);//change listener to update the title

        //raaf begin
        if (position == 0) {
            Fragment fragment = new NotificationsFragment();
            Bundle args = new Bundle();
            args.putString("table_name", getResources().getStringArray(R.array.table_names)[position]);
            args.putString("div_id", getResources().getStringArray(R.array.div_ids)[position]);
            fragment.setArguments(args);
            //FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
        } else if (position == 4) {
            Fragment webViewFragment = new JobsFragment();
            Bundle args = new Bundle();
            args.putString("base_url", "http://www.jkssb.nic.in/Pages/Applicant/Jobs.aspx");
            webViewFragment.setArguments(args);
            //FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.content_frame, webViewFragment)
                    .addToBackStack("" + position).commit();

        } else if (position == 5) {

            Fragment webViewFragment = new LoginFragment();
            Bundle args = new Bundle();
            args.putString("base_url", "http://www.jkssb.nic.in/Pages/login.aspx");
            webViewFragment.setArguments(args);
            //FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.content_frame, webViewFragment)
                    .addToBackStack("" + position).commit();

        } else if (position == 6) {
            Fragment syllabusFragment = new SyllabusFragment();
            //FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.content_frame, syllabusFragment)
                    .addToBackStack("" + position).commit();

        } else if (position == 7) {
            Fragment aboutFragment = new AboutFragment();
            //FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.content_frame, aboutFragment)
                    .addToBackStack("" + position).commit();
        } else {
            Fragment fragment = new NotificationsFragment();
            Bundle args = new Bundle();
            args.putString("table_name", getResources().getStringArray(R.array.table_names)[position]);
            args.putString("div_id", getResources().getStringArray(R.array.div_ids)[position]);
            fragment.setArguments(args);
            fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).addToBackStack("" + position)
                    .commit();

        }
        //raaf end

        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        setTitle(navigationTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    }

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

    /**
     * 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 toggles
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onResume() {
        super.onResume();

        //Run just once
        //Start the notification alarm when run for the first time
        SharedPreferences pref = this.getSharedPreferences(this.getPackageName(), this.MODE_PRIVATE);
        if (pref.getBoolean("alarmFlag", true)) { //IF alarm is not set (when run for first time) as this
            //shared pref doesn't exist so supply default value "true"
            Log.d("RUNNING ALARM FOR IST", "TIME--DEFAULT VALUE");
            alarm.setAlarm(this);
            SharedPreferences.Editor edit = pref.edit();
            edit.putBoolean("alarmFlag", false);//set shared preference to false so it doesnt get executed the next time
            edit.commit();
        }

        //End Run just once

        /* //test to send analytics data of activity
         // [START screen_view_hit]
         mTracker.setScreenName("MainActivity");
         mTracker.send(new HitBuilders.ScreenViewBuilder().build());
         // [END screen_view_hit]*/
    }

}