de.kaidev.vertretungsplanapp.MainActivity.java Source code

Java tutorial

Introduction

Here is the source code for de.kaidev.vertretungsplanapp.MainActivity.java

Source

package de.kaidev.vertretungsplanapp;

import android.*;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.FileProvider;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.text.util.Linkify;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.WindowManager;

import com.h6ah4i.android.tablayouthelper.TabLayoutHelper;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.single.DialogOnDeniedPermissionListener;
import com.karumi.dexter.listener.single.CompositePermissionListener;
import com.karumi.dexter.listener.single.EmptyPermissionListener;

import org.json.JSONException;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import de.kaidev.dialogfragmentlibrary.BuilderDialogFragment;
import de.kaidev.dialogfragmentlibrary.DialogBuilder;
import de.kaidev.githubupdatelibrary.DownloadProgress;
import de.kaidev.githubupdatelibrary.GithubUpdateFragment;
import de.kaidev.vertretungsplanapp.data.Tag;
import de.kaidev.vertretungsplanapp.dialogs.DownloadDialogFragment;
import de.psdev.licensesdialog.LicensesDialogFragment;

public class MainActivity extends AppCompatActivity
        implements SwipeRefreshLayout.OnRefreshListener, DownloadDataFragment.DownloadDataCallbacks,
        GithubUpdateFragment.UpdateCallbacks, BuilderDialogFragment.ListItemListener,
        BuilderDialogFragment.ButtonListener, NavigationView.OnNavigationItemSelectedListener {

    private static final String FRAGMENT_DEFAULT = "0FRAGMENT";
    private static final String FRAGMENT_LINK = "1FRAGMENT";
    private static final String FRAGMENT_BER = "2FRAGMENT";
    private static final String FRAGMENT_KLASSE = "3FRAGMENT";
    private static final String FRAGMENT_CUSTOM = "4FRAGMENT";
    private static final String FRAGMENT_CHECK = "5FRAGMENT";
    private static final String FRAGMENT_DOWNLOAD = "6FRAGMENT";

    Tag heute;
    Tag morgen;
    ViewPager mPager = null;
    TabLayout mTabs;

    public SwipeRefreshLayout getSwipeRefreshLayout() {
        return mSwipeRefreshLayout;
    }

    SwipeRefreshLayout mSwipeRefreshLayout;

    NavigationView mDrawer;
    DrawerLayout mDrawerLayout;

    CharSequence title;

    boolean refresh = false;

    DownloadDataFragment downloadDataFragment;
    GithubUpdateFragment updateFragment;

    DownloadDialogFragment updateDialogFragment;

    static boolean mReceiverRegistered;

    static public boolean isReceiverRegistered() {
        return mReceiverRegistered;
    }

    @Override
    protected void onStop() {
        super.onStop();
        downloadDataFragment.cancel();
    }

    @Override
    protected void onPause() {
        unregisterReceiver(receiver);
        mReceiverRegistered = false;
        super.onPause();
    }

    public void onResume() {
        final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

        super.onResume();

        registerReceiver(receiver, new IntentFilter("de.kaidev.vertretungsplanapp.gcm"));
        mReceiverRegistered = true;

        if (refresh) {
            title = sharedPreferences.getString("klasse", "5A");
            if (title.equals("Benutzerdefiniert")) {
                title = sharedPreferences.getString("class", "5A") + " (Benutzerdefiniert)";
            }
            getSupportActionBar().setTitle(title);
            refreshFragments();
        }
        File f001 = getFileStreamPath("001");
        File fnoti001 = getFileStreamPath("noti001");
        File f002 = getFileStreamPath("002");
        File fnoti002 = getFileStreamPath("noti002");

        boolean r = false;
        if (f001.lastModified() < fnoti001.lastModified()) {
            boolean delete = f001.delete();
            boolean rename = fnoti001.renameTo(f001);
            try {
                heute = Tag.getFromFile("001", this);
                r = true;
            } catch (IOException | JSONException e) {
                e.printStackTrace();
            }
        }
        if (f002.lastModified() < fnoti002.lastModified()) {
            boolean delete = f002.delete();
            boolean rename = fnoti002.renameTo(f002);
            try {
                morgen = Tag.getFromFile("002", this);
                r = true;
            } catch (IOException | JSONException e) {
                e.printStackTrace();
            }
        }
        if (r)
            refreshFragmentsTest();

        if (getSupportFragmentManager().findFragmentByTag(FRAGMENT_CHECK) == null
                && NetworkUtils.networkAvailable(this)
                && PreferenceManager.getDefaultSharedPreferences(this).getBoolean("auto_update", true)) {

            updateFragment.startCheck(MyApplication.GITHUB_API_URL);
        }

        Fragment f = getSupportFragmentManager().findFragmentByTag(FRAGMENT_DOWNLOAD);
        if (f != null) {
            updateDialogFragment = (DownloadDialogFragment) f;
        }

        ContentFragment activeFragment = ((MyFragmentAdapter) mPager.getAdapter())
                .getRegisteredFragment(mPager.getCurrentItem());
        if (activeFragment == null)
            return;
        LinearLayoutManager manager = ((LinearLayoutManager) activeFragment.getRecyclerView().getLayoutManager());
        if (manager == null)
            return;
        mSwipeRefreshLayout.setEnabled(manager.findFirstCompletelyVisibleItemPosition() == 0
                || activeFragment.getRecyclerView().getAdapter().getItemCount() == 0);
    }

    SharedPreferences.OnSharedPreferenceChangeListener mainSharedPreferencesListener = (sharedPreferences, key) -> {
        if (TextUtils.isDigitsOnly(key) || key.equals("class"))
            refresh = true;
    };

    SharedPreferences.OnSharedPreferenceChangeListener lehrerSharedPreferencesListener = (sharedPreferences,
            key) -> refresh = true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

        checkDB();
        sharedPreferences.registerOnSharedPreferenceChangeListener(mainSharedPreferencesListener);
        getSharedPreferences("lehrer", MODE_PRIVATE)
                .registerOnSharedPreferenceChangeListener(lehrerSharedPreferencesListener);

        setContentView(R.layout.activity_main);

        title = sharedPreferences.getString("klasse", "5A");
        if (title.equals("Benutzerdefiniert")) {
            title = sharedPreferences.getString("class", "5A") + " (Benutzerdefiniert)";
        }

        final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle(title);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);

        mPager = (ViewPager) findViewById(R.id.pager);
        mTabs = (TabLayout) findViewById(R.id.tabs);
        mDrawer = (NavigationView) findViewById(R.id.main_naviagtion_view);
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.refresh);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        FragmentManager fragmentManager = getSupportFragmentManager();

        downloadDataFragment = (DownloadDataFragment) fragmentManager.findFragmentByTag("DownloadDataFragment");

        if (downloadDataFragment == null) {
            downloadDataFragment = new DownloadDataFragment();
            fragmentManager.beginTransaction().add(downloadDataFragment, "DownloadDataFragment").commit();
        } else {
            mSwipeRefreshLayout.post(() -> mSwipeRefreshLayout.setRefreshing(downloadDataFragment.isRunning()));
        }

        updateFragment = (GithubUpdateFragment) fragmentManager.findFragmentByTag("UpdateFragment");

        if (updateFragment == null) {
            updateFragment = new GithubUpdateFragment();
            fragmentManager.beginTransaction().add(updateFragment, "UpdateFragment").commit();
        }

        try {
            heute = Tag.getFromFile("001", this);
            morgen = Tag.getFromFile("002", this);
        } catch (Exception e) {
            heute = new Tag();
            morgen = new Tag();
            e.printStackTrace();
            if (NetworkUtils.networkAvailable(this)) {
                downloadDataFragment.start();
                mSwipeRefreshLayout.post(() -> mSwipeRefreshLayout.setRefreshing(downloadDataFragment.isRunning()));
            }
        }
        mSwipeRefreshLayout.setOnRefreshListener(this);
        refreshFragmentsInit();

        mTabs.setTabTextColors(Color.parseColor("#b4ffffff"), Color.parseColor("#ffffff"));
        TabLayoutHelper tabLayoutHelper = new TabLayoutHelper(mTabs, mPager);
        tabLayoutHelper.updateAllTabs();
        mTabs.setupWithViewPager(mPager);
        mPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int ignored) {
                invalidateOptionsMenu();
                ContentFragment activeFragment = ((MyFragmentAdapter) mPager.getAdapter())
                        .getRegisteredFragment(mPager.getCurrentItem());
                if (activeFragment == null)
                    return;
                LinearLayoutManager manager = (LinearLayoutManager) activeFragment.getRecyclerView()
                        .getLayoutManager();
                if (manager == null)
                    return;
                mSwipeRefreshLayout.setEnabled(manager.findFirstCompletelyVisibleItemPosition() == 0
                        || activeFragment.getRecyclerView().getAdapter().getItemCount() == 0);
            }
        });

        ContentFragment activeFragment = ((MyFragmentAdapter) mPager.getAdapter())
                .getRegisteredFragment(mPager.getCurrentItem());
        if (!(activeFragment == null)) {
            LinearLayoutManager manager = (LinearLayoutManager) activeFragment.getRecyclerView().getLayoutManager();
            if (!(manager == null)) {
                mSwipeRefreshLayout.setEnabled(manager.findFirstCompletelyVisibleItemPosition() == 0
                        || activeFragment.getRecyclerView().getAdapter().getItemCount() == 0);
            }
        }

        mDrawer.setNavigationItemSelectedListener(this);
        mPager.setOnTouchListener((v, event) -> {
            mSwipeRefreshLayout.setEnabled(event.getAction() == MotionEvent.ACTION_UP);
            return false;
        });

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        GCMManager.registerGCM(this, false);
    }

    @Override
    public void downloadDataOnPreExecute() {
    }

    @Override
    public void downloadDataOnPostExecute(Tag[] data) {
        if (data != null) {
            heute = data[0];
            morgen = data[1];
            refreshFragments();
        }
        invalidateOptionsMenu();
        mSwipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void downloadDataOnCancelled() {
        Snackbar.make(findViewById(android.R.id.content), "Aktualisieren fehlgeschlagen", Snackbar.LENGTH_LONG)
                .show();
        mSwipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void checkPreExecute() {

    }

    @Override
    public void checkException() {

    }

    @Override
    public void checkClearUI() {

    }

    @Override
    public void checkPostExecute(boolean needUpdate, String remoteVersion, String name, String link) {
        if (needUpdate) {
            Bundle args = new Bundle();
            args.putString("link", link);
            args.putString("version", remoteVersion);

            BuilderDialogFragment
                    .newInstance(
                            new DialogBuilder().setMessage(name).setTitle("Update auf Version " + remoteVersion)
                                    .setNegativeButton("Abbrechen").setPositiveButton("Update"),
                            args)
                    .show(getSupportFragmentManager(), FRAGMENT_CHECK);
        }
    }

    @Override
    public void downloadPreExecute() {
        updateDialogFragment = DownloadDialogFragment.newInstance();
        updateDialogFragment.show(getSupportFragmentManager(), FRAGMENT_DOWNLOAD);
    }

    @Override
    public void downloadProgressUpdate(DownloadProgress progress) {
        if (updateDialogFragment != null) {
            switch (progress.status) {
            case DownloadStart:
                updateDialogFragment.setIndeterminate(false);
                updateDialogFragment.showLabelMinmax(true);
                updateDialogFragment.setMessage("Download...");
                updateDialogFragment.setMax(progress.max);
                break;
            case DownloadRunning:
                updateDialogFragment.setProgress(progress.progress);
                break;
            case DownloadFinished:
                updateDialogFragment.setIndeterminate(true);
                updateDialogFragment.showLabelMinmax(false);
                updateDialogFragment.setMessage("Starte Installation");
            }
        }
    }

    @Override
    public void downloadException() {
        downloadClearUI();
        Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "Download fehlgeschlagen",
                Snackbar.LENGTH_LONG);
        if (NetworkUtils.networkAvailable(this))
            snackbar.setAction("Erneut versuchen", v -> updateFragment.startCheck(MyApplication.GITHUB_API_URL));
        snackbar.show();
    }

    @Override
    public void downloadClearUI() {
        if (updateDialogFragment != null) {
            updateDialogFragment.dismissAllowingStateLoss();
            updateDialogFragment = null;
        }
    }

    @Override
    public void downloadPostExecute(File result) {
        downloadClearUI();
        startActivity(new Intent(Intent.ACTION_VIEW).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                .setDataAndType(
                        FileProvider.getUriForFile(this, "de.kaidev.vertretungsplanapp.file_provider", result),
                        "application/vnd.android.package-archive")
                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
    }

    private void checkDB() {
        String[] xmlShort = getResources().getStringArray(R.array.lehrer);
        final HashMap<String, String> xmlMap = new HashMap<>();
        for (String lehrer : xmlShort) {
            String[] split = lehrer.split("\\|", 2);
            xmlMap.put(split[1].toUpperCase(), split[0]);
        }

        SharedPreferences lehrer = getSharedPreferences("lehrer", MODE_PRIVATE);
        SharedPreferences.Editor editor = lehrer.edit();

        for (HashMap.Entry<String, String> entry : xmlMap.entrySet()) {
            String key = entry.getKey();
            if (lehrer.contains(key))
                editor.remove(key);
        }

        editor.apply();
    }

    public void refreshFragmentsInit() {
        mPager.setAdapter(new MyFragmentAdapter(getSupportFragmentManager(), heute.getKlassePrefs(this),
                heute.getDate(), morgen.getKlassePrefs(this), morgen.getDate()));
    }

    public void refreshFragments() {
        ((MyFragmentAdapter) mPager.getAdapter()).setData(heute.getKlassePrefs(this), heute.getDate(),
                morgen.getKlassePrefs(this), morgen.getDate());
    }

    public void refreshFragmentsTest() {
        mPager.setAdapter(new MyFragmentAdapter(getSupportFragmentManager(), heute.getKlassePrefs(this),
                heute.getDate(), morgen.getKlassePrefs(this), morgen.getDate()));
    }

    public void klasseChanged() {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        title = preferences.getString("klasse", "5A");
        if (title.equals("Benutzerdefiniert")) {
            if (!preferences.getBoolean("knowsAboutCustom", false)) {
                BuilderDialogFragment
                        .newInstance(new DialogBuilder().setTitle("Benutzerdefinierte Ansicht").setMessage(
                                "Mit der benutzerdefinierten Ansicht kannst du deinen Stundenplan eingeben, sodass nur noch "
                                        + "deine persnlichen Vertretungsstunden angezeigt werden")
                                .setNeutralButton("Jetzt einrichten").setPositiveButton("OK"))
                        .show(getSupportFragmentManager(), FRAGMENT_CUSTOM);
            }
            title = preferences.getString("class", "5A") + " (Benutzerdefiniert)";
        }
        getSupportActionBar().setTitle(title);
        refreshFragments();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem info = menu.add(0, 99, 0, "Info").setIcon(R.drawable.ic_info_outline_white_48dp);
        info.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

        int i = mPager != null ? mPager.getCurrentItem() : 0;
        String s = i == 0 ? heute.getInfo() : morgen.getInfo();

        if (!s.isEmpty()) {
            for (String t : s.split("\n")) {
                if (!t.startsWith("Abwesende") && !t.startsWith("Blockierte")) {
                    info.setIcon(R.drawable.ic_info_white_48dp);
                    break;
                }
            }
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        mDrawerLayout.closeDrawer(mDrawer);
        switch (menuItem.getItemId()) {
        case R.id.navigation_drawer_settings:
            final Intent intent = new Intent(this, SettingsActivity.class);
            startActivity(intent);
            break;
        case R.id.navigation_drawer_class:
            String[] items = getResources().getStringArray(R.array.klassen_liste);
            BuilderDialogFragment.newInstance(new DialogBuilder().setTitle("Klasse whlen").setItems(items))
                    .show(getSupportFragmentManager(), FRAGMENT_KLASSE);
            break;
        case R.id.navigation_drawer_info:
            BuilderDialogFragment
                    .newInstance(new DialogBuilder().setTitle("Info")
                            .setMessage(heute.getDate() + "\n" + heute.getInfo() + "\n\n" + morgen.getDate() + "\n"
                                    + morgen.getInfo())
                            .setPositiveButton("OK"))
                    .show(getSupportFragmentManager(), FRAGMENT_DEFAULT);
            break;
        case R.id.navigation_drawer_about:
            BuilderDialogFragment
                    .newInstance(new DialogBuilder().setTitle("ber die App")
                            .setMessage("Vielen Dank, dass du die VertretungsplanApp fr das Krupp "
                                    + "Gymnasium verwendest!\n\n"
                                    + "Falls du Anregungen oder Kritik hast, kannst du gerne eine E-Mail an "
                                    + "kai.volkenborn@krupp-gymnasium.eu schicken\n" + "\n"
                                    + "Copyright: Kai Volkenborn 2015\n" + "Version: " + MyApplication.versionName
                                    + "\n" + "\n" + "Diese App verwendet folgende Software von Drittanbietern:\n"
                                    + "ACRA, Retrolambda, Android Retrolambda Lombok, Google Gson, "
                                    + "Apache Commons IO, TabLayoutHelper, RecyclerView-FlexibleDivider, "
                                    + "Material Dialogs, Lightweight Stream API, LicensesDialog\n"
                                    + "Fr mehr Informationen klicke auf \nDrittanbieter Software\"")
                            .setLinkify(Linkify.EMAIL_ADDRESSES | Linkify.WEB_URLS).setPositiveButton("OK")
                            .setNeutralButton("Drittanbieter Software"))
                    .show(getSupportFragmentManager(), FRAGMENT_BER);
            break;
        case R.id.navigation_drawer_links:
            BuilderDialogFragment.newInstance(new DialogBuilder().setTitle(R.string.main_dialog_about_title)
                    .setMessage("Whle \"ffnen\", um den Vertretungsplan " + "im Browser zu ffnen.")
                    .setPositiveButton("ffnen")).show(getSupportFragmentManager(), FRAGMENT_LINK);
            break;
        }
        return false;
    }

    @Override
    public void onItemClick(String tag, int position, String item, AlertDialog dialog, Bundle arguments) {
        switch (tag) {
        case FRAGMENT_KLASSE:
            PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putString("klasse", item)
                    .apply();
            mDrawerLayout.closeDrawer(mDrawer);
            klasseChanged();
            break;
        }
    }

    @Override
    public void onButtonClick(String tag, int buttonType, AlertDialog dialog, Bundle args) {
        switch (tag) {
        case FRAGMENT_CUSTOM:
            if (buttonType == DialogInterface.BUTTON_NEUTRAL) {
                startActivity(new Intent(MainActivity.this, SettingsConfigCustom.class));
            }
            break;
        case FRAGMENT_BER:
            if (buttonType == DialogInterface.BUTTON_NEUTRAL) {
                try {
                    new LicensesDialogFragment.Builder(getApplication()).setNotices(R.raw.libraries)
                            .setIncludeOwnLicense(true).setUseAppCompat(true).build()
                            .show(getSupportFragmentManager(), FRAGMENT_DEFAULT);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException();
                }
            }
            break;
        case FRAGMENT_LINK:
            if (buttonType == DialogInterface.BUTTON_POSITIVE) {
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(
                        "http://krupp-gymnasium.eu/idesk/infodisplay/mods/link.local.php/panelId=19/key=9824511b14e8c3efcd5efd6e27989cba/Vertretungsplan/subst_001.htm")));
            }
            break;
        case FRAGMENT_DOWNLOAD:
            if (buttonType == DialogInterface.BUTTON_NEGATIVE) {
                updateFragment.cancelDownload();
            }
            break;
        case FRAGMENT_CHECK:
            if (buttonType == DialogInterface.BUTTON_POSITIVE) {
                updateFragment.startDownload(args.getString("link"), args.getString("version"));
            }
            break;
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            if (!mDrawerLayout.isDrawerOpen(mDrawer))
                mDrawerLayout.openDrawer(mDrawer);
            return true;
        }
        if (item.getItemId() == 99) {
            BuilderDialogFragment.newInstance(new DialogBuilder().setTitle("Info")
                    .setMessage(mPager.getCurrentItem() == 0 ? heute.getInfo() : morgen.getInfo())
                    .setPositiveButton("OK")).show(getSupportFragmentManager(), FRAGMENT_DEFAULT);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (mDrawerLayout.isDrawerOpen(mDrawer)) {
            mDrawerLayout.closeDrawer(mDrawer);
        } else {
            super.onBackPressed();
        }
    }

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            downloadDataFragment.start();
            mSwipeRefreshLayout.setRefreshing(true);
        }
    };

    @Override
    public void onRefresh() {
        if (NetworkUtils.networkAvailable(this)) {
            downloadDataFragment.start();
        } else {
            Snackbar.make(findViewById(android.R.id.content), "Kein Netzwerk verfgbar", Snackbar.LENGTH_SHORT)
                    .show();
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }
}