net.niyonkuru.koodroid.MainActivity.java Source code

Java tutorial

Introduction

Here is the source code for net.niyonkuru.koodroid.MainActivity.java

Source

/*
 * Copyright 2012 Mike Niyonkuru
 *
 * 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 net.niyonkuru.koodroid;

import android.content.ContentValues;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.SimpleOnPageChangeListener;
import android.support.v4.widget.SimpleCursorAdapter;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Toast;

import java.util.ArrayList;

import net.niyonkuru.koodroid.adapter.PagesAdapter;
import net.niyonkuru.koodroid.provider.AccountContract.Subscribers;
import net.niyonkuru.koodroid.provider.SettingsContract.Settings;
import net.niyonkuru.koodroid.ui.DetailFragment;
import net.niyonkuru.koodroid.ui.OverviewFragment;
import net.niyonkuru.koodroid.ui.UsageFragment;
import net.niyonkuru.koodroid.util.Config;
import net.niyonkuru.koodroid.util.IntentUtils;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;

import com.viewpagerindicator.TitlePageIndicator;

import static net.niyonkuru.koodroid.BuildConfig.DEBUG;

/**
 * This activity is the main portal to the application.
 */
public class MainActivity extends SherlockFragmentActivity
        implements LoaderManager.LoaderCallbacks<Cursor>, OverviewFragment.CallBack, UsageFragment.CallBack {
    private static final String TAG = "MainActivity";

    private SimpleCursorAdapter mAdapter;

    private ArrayList<Subscriber> mSubscribers;

    private PagesAdapter mPagesAdapter;

    private Handler mHandler;

    private boolean mDualPaneMode;

    private boolean mPortraitMode;

    private boolean mDetailsMode;

    private int mWhat;

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        Window window = getWindow();
        window.setFormat(PixelFormat.RGBA_8888);
    }

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

        mHandler = new Handler();

        Settings settings = App.getSettings();

        int selectedPage = settings.page();
        String subscriber = settings.preferredSubscriber();
        String email = settings.email();

        loadPages(selectedPage, subscriber, email);

        mAdapter = new SimpleCursorAdapter(this, R.layout.spinner_item, null,
                new String[] { Subscribers.SUBSCRIBER_ID }, new int[] { android.R.id.text1 }, 0);
        mAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item);

        getSupportLoaderManager().initLoader(0, null, this);

        View detailsFrame = findViewById(R.id.details);
        mDualPaneMode = detailsFrame != null;

        Configuration configuration = getResources().getConfiguration();
        mPortraitMode = configuration.orientation == Configuration.ORIENTATION_PORTRAIT;

        if (savedInstanceState != null && savedInstanceState.getBoolean("details_mode")) {
            showDetails(savedInstanceState.getInt("what"), subscriber);
        }
    }

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

        mHandler.removeCallbacks(mLoginAction);
    }

    @Override
    public void onBackPressed() {
        if (mDetailsMode) {
            getSupportFragmentManager().popBackStack();

            if (mPortraitMode) {
                findViewById(R.id.content).setVisibility(View.VISIBLE);
            }
            findViewById(R.id.details).setVisibility(View.GONE);

            if (mSubscribers.size() > 1) {
                ActionBar actionBar = getSupportActionBar();
                actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
                actionBar.setDisplayHomeAsUpEnabled(false);
                actionBar.setTitle(R.string.app_name);
            }

            mDetailsMode = false;
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        savedInstanceState.putBoolean("details_mode", mDetailsMode);
        savedInstanceState.putInt("what", mWhat);

        super.onSaveInstanceState(savedInstanceState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        mDetailsMode = savedInstanceState.getBoolean("details_mode");
        mWhat = savedInstanceState.getInt("what");

        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.menu.app_menu_items, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();

        if (itemId == android.R.id.home) {
            onBackPressed();
            return true;
        } else if (itemId == R.id.menu_share) {
            IntentUtils.share(this);
            return true;
        } else if (itemId == R.id.menu_settings) {
            startActivity(new Intent(this, SettingsActivity.class));
            return true;
        } else if (itemId == R.id.menu_help) {
            Uri uri = Uri.parse(getString(R.string.help_video));
            startActivity(new Intent(Intent.ACTION_VIEW, uri));
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onLoginRequired() {
        long duration = DateUtils.SECOND_IN_MILLIS * 5;

        Toast.makeText(this, getString(R.string.service_error_session, duration / 1000), Toast.LENGTH_SHORT).show();

        mHandler.postDelayed(mLoginAction, duration);
    }

    private void loadPages(int currentPage, String subscriber, String email) {
        FragmentManager fm = getSupportFragmentManager();
        String[] titles = getResources().getStringArray(R.array.page_titles);

        mPagesAdapter = new PagesAdapter(fm, titles, email, subscriber);

        ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
        pager.setAdapter(mPagesAdapter);

        TitlePageIndicator indicator = (TitlePageIndicator) findViewById(R.id.indicator);
        indicator.setViewPager(pager);
        indicator.setCurrentItem(currentPage);
        indicator.setOnPageChangeListener(new SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                ContentValues values = new ContentValues(1);
                values.put(Settings.PAGE, position);
                getContentResolver().insert(Settings.CONTENT_URI, values);
            }
        });
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        String selection = Subscribers.SUBSCRIBER_EMAIL + "='" + App.getSettings().email() + "'";
        CursorLoader loader = new CursorLoader(this, Subscribers.CONTENT_URI, SubscribersQuery.PROJECTION,
                selection, null, Subscribers.DEFAULT_SORT);
        loader.setUpdateThrottle(DateUtils.SECOND_IN_MILLIS);

        return loader;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        /* only display dropdown navigation for users with more than 1 phone */
        if (data.getCount() <= 1)
            return;

        mSubscribers = new ArrayList<Subscriber>(data.getCount());

        while (data.moveToNext()) { /* cache subscriber list information */
            Subscriber s = new Subscriber();
            s._id = data.getString(SubscribersQuery.SUBSCRIBER_ID);
            s.switcher = data.getString(SubscribersQuery.SUBSCRIBER_SWITCHER);

            if (s.switcher == null) {
                s.switcher = buildSwitcherUrl(s._id, data);
            }

            mSubscribers.add(s);
        }
        mAdapter.swapCursor(data);

        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        int subscriberIndex = App.getSettings().subscriberIndex();

        actionBar.setListNavigationCallbacks(mAdapter, new CallBack(subscriberIndex));
        actionBar.setSelectedNavigationItem(subscriberIndex);
    }

    /**
     * Build the switcher url manually based on another subscriber's by replacing the last param.
     */
    private String buildSwitcherUrl(String subscriberId, Cursor data) {
        String url = null;

        if (data.moveToNext()) {
            url = data.getString(SubscribersQuery.SUBSCRIBER_SWITCHER);

            if (url != null) {
                // replace the last param with this subscriber
                url = url.substring(0, url.lastIndexOf('=') + 1) + subscriberId;
            }

            data.moveToPrevious();
        }

        return url;
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        mAdapter.changeCursor(null);
    }

    @Override
    public void onShowDataTransactions(String subscriber) {
        showDetails(DetailFragment.DATA_DETAIL, subscriber);
    }

    @Override
    public void onShowTabTransactions(String subscriber) {
        showDetails(DetailFragment.TAB_DETAIL, subscriber);
    }

    /**
     * Show a detail fragment for a requested item
     *
     * @param what       - the item requested
     * @param subscriber - the owner of the item
     */
    private void showDetails(int what, String subscriber) {
        if (DEBUG)
            Log.d(TAG, "showing what: " + what + " subscriber: " + subscriber);

        if (mDualPaneMode) {
            DetailFragment details = getDetailFragment();

            if (details == null || !details.equals(what, subscriber)) {
                /* Make new fragment to show details on this selection. */
                details = DetailFragment.newInstance(what, subscriber);
            }

            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

            if (details.isAdded()) {
                ft.show(details);
            } else {
                ft.replace(R.id.details, details);
            }
            ft.addToBackStack("details").commit();

            if (mPortraitMode) {
                findViewById(R.id.content).setVisibility(View.GONE);
            }
            findViewById(R.id.details).setVisibility(View.VISIBLE);

            mWhat = what;
            mDetailsMode = true;

        } else {
            Intent i = new Intent(this, DetailActivity.class);
            i.putExtra("what", what);
            i.putExtra("subscriber", subscriber);
            startActivity(i);
        }
    }

    private DetailFragment getDetailFragment() {
        return (DetailFragment) getSupportFragmentManager().findFragmentById(R.id.details);
    }

    private final Runnable mLoginAction = new Runnable() {
        @Override
        public void run() {
            IntentUtils.actionOpenLogin(MainActivity.this);
        }
    };

    private class CallBack implements ActionBar.OnNavigationListener {
        private int mSelectedNavigationItem;

        public CallBack(int itemPosition) {
            mSelectedNavigationItem = itemPosition;
        }

        @Override
        public boolean onNavigationItemSelected(int itemPosition, long itemId) {
            if (itemPosition == mSelectedNavigationItem || itemPosition >= mSubscribers.size())
                return true;

            Subscriber subscriber = mSubscribers.get(itemPosition);

            if (DEBUG)
                Log.d(TAG, "switching to: " + subscriber._id);

            if (mDetailsMode) {
                showDetails(mWhat, subscriber._id);
            }

            Toast.makeText(MainActivity.this, getString(R.string.toast_switching_start, subscriber._id),
                    Toast.LENGTH_LONG).show();

            ContentValues values = new ContentValues(1);
            values.put(Settings.NAVIGATION_URL, Config.INTERNAL_URL + subscriber.switcher);
            values.put(Settings.PREFERRED_SUBSCRIBER, subscriber._id);
            values.put(Settings.SUBSCRIBER_INDEX, itemPosition);
            getContentResolver().insert(Settings.CONTENT_URI, values);

            mPagesAdapter.switchSubscriber(subscriber._id);

            mSelectedNavigationItem = itemPosition;

            return true;
        }
    }

    /**
     * {@link Subscribers} query parameters
     */
    public interface SubscribersQuery {
        String[] PROJECTION = { Subscribers._ID, Subscribers.SUBSCRIBER_ID, Subscribers.SUBSCRIBER_SWITCHER };

        int SUBSCRIBER_ID = 1;
        int SUBSCRIBER_SWITCHER = 2;
    }

    /*
      * this stores cached information about a subscriber, so we don't have to query every time
      */
    static class Subscriber {
        String _id;
        String switcher;
    }
}