a.dev.mobile.thread.MainActivity.java Source code

Java tutorial

Introduction

Here is the source code for a.dev.mobile.thread.MainActivity.java

Source

package a.dev.mobile.thread;

import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Point;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

import a.dev.mobile.thread.isoThread.IsoFragment;
import a.dev.mobile.thread.navigator.NavigationAdapter;
import a.dev.mobile.thread.navigator.NavigationList;
import a.dev.mobile.thread.navigator.drawerListArray;
import a.dev.mobile.thread.unThread.UnFragment;
import a.dev.mobile.thread.utils.ExternalDbOpenHelper;
import a.dev.mobile.thread.view.ProgressBarCircular;
import me.drakeet.materialdialog.MaterialDialog;

public class MainActivity extends AppCompatActivity
        implements UnFragment.OnIdFragSelectedListenerUN, IsoFragment.OnIdFragSelectedListenerFromISO {
    private static int mLastPosition;
    private ListView listDrawer;
    private NavigationAdapter navigationAdapter;
    private ExternalDbOpenHelper dbOpenHelper;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;
    private CharSequence mDrawerTitle;
    private CharSequence mTitle;

    private InterstitialAd mInterstitialAd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Create the InterstitialAd and set the adUnitId (defined in values/strings.xml).

        mLastPosition = loadIntFromFile();

        progressBarCircular = (ProgressBarCircular) findViewById(R.id.progress);
        listDrawer = (ListView) findViewById(R.id.left_drawer);
        //allocate nav_header
        if (listDrawer != null) {
            List<Integer> listHeader = new ArrayList<Integer>();
            listHeader.add(0);
            listHeader.add(2);
            navigationAdapter = new NavigationAdapter(this, NavigationList.getNavigatorAdapter(this, listHeader));

        }
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        if (toolbar != null)
            setSupportActionBar(toolbar);

        //create  nav_header and fotter
        LayoutInflater inflater = getLayoutInflater();
        ViewGroup header = (ViewGroup) inflater.inflate(R.layout.nav_header, listDrawer, false);
        ViewGroup footer = (ViewGroup) inflater.inflate(R.layout.nav_footer, listDrawer, false);

        //add nav_header and fotter
        listDrawer.addHeaderView(header, null, false); // true = clickable
        listDrawer.addFooterView(footer, null, true);

        // Set the adapter for the list view
        assert listDrawer != null;
        listDrawer.setAdapter(navigationAdapter);
        /***/

        // Set the list's click listener
        listDrawer.setOnItemClickListener(new DrawerItemClickListener());

        mTitle = mDrawerTitle = getTitle();
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
                mDrawerLayout, /* DrawerLayout object */
                toolbar, /* nav drawer icon to replace 'Up' caret */
                R.string.drawer_open, /* "open drawer" description */
                R.string.drawer_close /* "close drawer" description */
        ) {

            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                getSupportActionBar().setTitle(mTitle);
            }

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                getSupportActionBar().setTitle(mDrawerTitle);
            }
        };

        // Set the drawer toggle as the DrawerListener
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        //Set width of drawer
        DrawerLayout.LayoutParams layoutParams = (DrawerLayout.LayoutParams) listDrawer.getLayoutParams();
        layoutParams.width = calculateDrawerWidth();
        listDrawer.setLayoutParams(layoutParams);

        if (savedInstanceState != null) {

            setTitleFragments(mLastPosition);
            navigationAdapter.resetarCheck();
            navigationAdapter.setChecked(mLastPosition, true);
        } else {

            if (UnFragment.idUnItemFrag == UnFragment.UN_DIAMETER_ID
                    || IsoFragment.idIsoItemFrag == IsoFragment.ISO_DIAMETER_ID) {
                CopyDataBase copyDataBase = new CopyDataBase();
                copyDataBase.execute();
            }
        }
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        mInterstitialAd = newInterstitialAd();
        loadInterstitial();
    }

    private InterstitialAd newInterstitialAd() {
        InterstitialAd interstitialAd = new InterstitialAd(this);
        interstitialAd.setAdUnitId(getString(R.string.interstitial_ad_unit_id));
        interstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                //                mNextLevelButton.setEnabled(true);

            }

            @Override
            public void onAdFailedToLoad(int errorCode) {
                //                mNextLevelButton.setEnabled(true);
            }

            @Override
            public void onAdClosed() {
                // Proceed to the next level.
                goToNextLevel();
            }
        });
        return interstitialAd;

    }

    private void showInterstitial() {
        // Show the ad if it's ready. Otherwise toast and reload the ad.
        if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
            mInterstitialAd.show();
        } else {
            //Toast.makeText(this, "Ad did not load", Toast.LENGTH_SHORT).show();
            goToNextLevel();
        }
    }

    private void loadInterstitial() {
        // Disable the next level button and load the ad.
        AdRequest adRequest = new AdRequest.Builder().setRequestAgent("android_studio:ad_template").build();
        mInterstitialAd.loadAd(adRequest);
    }

    private void goToNextLevel() {
        // Show the next level and reload the ad to prepare for the level after.

        mInterstitialAd = newInterstitialAd();
        loadInterstitial();
    }

    @Override
    public void onBackPressed() {
        Log.d("TEXT", "** " + mLastPosition);
        if (mLastPosition != AppConst.ISO_THREAD) {
            switch (UnFragment.idUnItemFrag) {
            case UnFragment.UN_DIAMETER_ID:

                exitFromApp();
                break;
            case UnFragment.UN_TOLERANCE_ID:
                setUnFragment(UnFragment.UN_DIAMETER_ID);
                break;
            case UnFragment.UN_INFO_ID:
                setUnFragment(UnFragment.UN_TOLERANCE_ID);
                break;

            }
            Log.d("TEXT", "-- " + UnFragment.idUnItemFrag);
        } else {
            switch (IsoFragment.idIsoItemFrag) {
            case IsoFragment.ISO_DIAMETER_ID:

                exitFromApp();
                break;
            case IsoFragment.ISO_PITCH_ID:
                setIsoFragment(IsoFragment.ISO_DIAMETER_ID);
                break;
            case IsoFragment.ISO_TOLERANCE_ID:

                setIsoFragment(IsoFragment.ISO_PITCH_ID);
                break;

            case IsoFragment.ISO_INFO_ID:

                setIsoFragment(IsoFragment.ISO_TOLERANCE_ID);
                break;

            }

        }

    }

    //    ------------------------------------
    Fragment fragment;

    FragmentManager fragmentManager;

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

    private Handler mHandler = new Handler();

    private void setFragmentDrawer(int position) {
        fragment = null;
        fragmentManager = getSupportFragmentManager();

        switch (position) {
        case AppConst.ISO_THREAD:
            fragment = new IsoFragment().newInstance(IsoFragment.ISO_DIAMETER_ID);
            break;
        case AppConst.UNC_THREAD:
            fragment = new UnFragment().newInstance(UnFragment.UN_DIAMETER_ID, position);
            break;
        case AppConst.UN_THREAD:
            fragment = new UnFragment().newInstance(UnFragment.UN_DIAMETER_ID, position);
            break;
        case AppConst.UNEF_THREAD:
            fragment = new UnFragment().newInstance(UnFragment.UN_DIAMETER_ID, position);
            break;
        case AppConst.UNF_THREAD:
            fragment = new UnFragment().newInstance(UnFragment.UN_DIAMETER_ID, position);
            break;
        case AppConst.UNS_THREAD:
            fragment = new UnFragment().newInstance(UnFragment.UN_DIAMETER_ID, position);
            break;
        case AppConst.ALL_UN_THREAD:
            fragment = new UnFragment().newInstance(UnFragment.UN_DIAMETER_ID, position);
            break;

        }
        if (fragment != null) {
            setTitleFragments(mLastPosition);
            navigationAdapter.resetarCheck();
            navigationAdapter.setChecked(position, true);
            fragmentManager.beginTransaction().replace(R.id.main_content, fragment).commit();
        }

        listDrawer.setItemChecked(position, true);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mDrawerLayout.closeDrawer(listDrawer);
            }
        }, 200);

    }

    /* 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(listDrawer);
        //menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);

    }

    private void setUnFragment(int idNextFrag) {
        UnFragment unFragment = null;
        fragmentManager = getSupportFragmentManager();

        unFragment = new UnFragment().newInstance(idNextFrag, mLastPosition);

        if (unFragment != null) {
            fragmentManager.beginTransaction().replace(R.id.main_content, unFragment).commit();
        }
    }

    private void setIsoFragment(int idNextFrag) {
        IsoFragment isoFragment = null;
        fragmentManager = getSupportFragmentManager();

        isoFragment = new IsoFragment().newInstance(idNextFrag);

        if (isoFragment != null) {
            fragmentManager.beginTransaction().replace(R.id.main_content, isoFragment).commit();
        }

    }

    private static long back_pressed;

    private void exitFromApp() {
        if (back_pressed + 3000 > System.currentTimeMillis()) {
            super.onBackPressed();
        } else {
            Toast.makeText(getBaseContext(), getString(R.string.post_to_exit, Toast.LENGTH_SHORT),
                    Toast.LENGTH_SHORT).show();
        }
        back_pressed = System.currentTimeMillis();
    }

    private void setTitleFragments(int position) {
        getSupportActionBar().setSubtitle((drawerListArray.getAbrThread(this, position) + " / "
                + drawerListArray.getNameThread(this, position)));
    }

    public int calculateDrawerWidth() {
        // Calculate ActionBar height
        TypedValue tv = new TypedValue();
        int actionBarHeight = 0;
        if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
            actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
        }
        Display display = getWindowManager().getDefaultDisplay();
        int width;

        if (android.os.Build.VERSION.SDK_INT >= 13) {
            Point size = new Point();
            display.getSize(size);
            width = size.x;

        } else {
            width = display.getWidth(); // deprecated

        }
        return width - actionBarHeight;
    }

    /*from fragment*/
    @Override
    public void callbackFromUN(int idItemFrag) {
        setUnFragment(idItemFrag);

        int random = r.nextInt(10);

        if (random < 6)
            showInterstitial();
        Log.d("ttt", "random1 " + random);
    }

    Random r = new Random();

    @Override
    public void callbackFromISO(int idItemFrag) {
        setIsoFragment(idItemFrag);
        int random = r.nextInt(10);
        loadInterstitial();

        //1 = 10%
        if (random < 3)
            showInterstitial();
        Log.d("ttt", "random2 " + random);
    }

    /**
     * ********
     */
    public void clickOpen(View view) {

        WebView webView = new WebView(this);
        webView.loadUrl("file:///android_asset/licenses.html");
        new AlertDialog.Builder(this).setTitle(R.string.dialog_licenses_notice_title).setView(webView)
                .setCancelable(true).show();

    }

    public void clickAbout(View view) {
        startDialogAbout();
    }

    private void startDialogAbout() {
        // Get app version
        PackageManager pm = getPackageManager();
        String packageName = getPackageName();
        String versionName;
        try {
            PackageInfo info = pm.getPackageInfo(packageName, 0);
            versionName = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            versionName = "N/A";
        }
        final MaterialDialog materialDialog = new MaterialDialog(this);
        materialDialog.setBackgroundResource(R.color.background_nav);
        materialDialog.setTitle(Html.fromHtml(getString(R.string.app_name_and_version, versionName)));
        materialDialog.setMessage(
                Html.fromHtml(getString(R.string.about_body, Calendar.getInstance().get(Calendar.YEAR))));
        materialDialog.setCanceledOnTouchOutside(true);

        materialDialog.show();
    }

    private ProgressBarCircular progressBarCircular;

    class CopyDataBase extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressBarCircular.setVisibility(View.VISIBLE);
        }

        @Override
        protected Void doInBackground(Void... params) {
            dbOpenHelper = new ExternalDbOpenHelper(MainActivity.this);
            SQLiteDatabase mySQLiteDatabase = dbOpenHelper.openDataBase();

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            if (dbOpenHelper != null)
                dbOpenHelper.close();
            if (dbOpenHelper != null)
                dbOpenHelper.close();

            if (progressBarCircular != null)
                progressBarCircular.setVisibility(View.GONE);

            setFragmentDrawer(mLastPosition);
        }
    }

    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int posicao, long id) {
            mLastPosition = posicao - 1;
            setFragmentDrawer(mLastPosition);

            saveIntInFile(mLastPosition);

        }
    }

    private void saveIntInFile(int value) {
        SharedPreferences sharedPreferences;
        sharedPreferences = getSharedPreferences(AppConst.SHARED_PREFERENCES, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt(AppConst.PREF_ISO_OR_UN, value);
        editor.apply();
    }

    private int loadIntFromFile() {
        SharedPreferences sharedPreferences;
        int i = 1;
        sharedPreferences = getSharedPreferences(AppConst.SHARED_PREFERENCES, Context.MODE_PRIVATE);
        if (sharedPreferences.contains(AppConst.PREF_ISO_OR_UN)) {
            i = sharedPreferences.getInt(AppConst.PREF_ISO_OR_UN, i);
        }
        return i;
    }

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

        saveIntInFile(mLastPosition);

    }
}