com.raza.betternts.activities.MainActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.raza.betternts.activities.MainActivity.java

Source

/**
 * Copyright (C) 2016 Zakoota@github.com
 * <p>
 * Licensed under the
 * Creative Commons Attribution-NonCommercial-ShareAlike 4.0
 * International License Version 2.0 (the "License")
 * <p>
 * You are free to:
 * <p>
 * 1: Share  copy and redistribute the material in any medium or format
 * 2: Adapt  remix, transform, and build upon the material
 * <p>
 * The licensor cannot revoke these freedoms as long as you follow the license terms.
 * <p>
 * 1: Attribution  You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.
 * 2: NonCommercial  You may not use the material for commercial purposes.
 * 3: ShareAlike  If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original.
 * 4: No additional restrictions  You may not apply legal terms or technological measures that legally restrict others from doing anything the license permits.
 * <p>
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * https://creativecommons.org/licenses/by-nc-sa/4.0/
 */

package com.raza.betternts.activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import com.raza.betternts.R;
import com.raza.betternts.contentprovider.NTSPostsContract;
import com.raza.betternts.database.DbSchema;
import com.raza.betternts.declarations.CustomPagerAdapter;
import com.raza.betternts.declarations.Post;
import com.raza.betternts.parser.Parser;

public class MainActivity extends AppCompatActivity {

    public static void showSnackBar(String text, Activity a) {
        CoordinatorLayout cL = (CoordinatorLayout) a.findViewById(R.id.main_layout);
        Snackbar snackbar = Snackbar.make(cL, text, Snackbar.LENGTH_LONG);
        snackbar.show();
    }

    public static boolean isNetworkAvailable(Context mContext) {

        ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();

        return networkInfo != null && networkInfo.isConnected();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        buildTabs();

        refresh();

    }

    @Override
    protected void onStart() {
        super.onStart();
        removeOld();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @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.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_refresh) {

            refresh();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void buildTabs() {
        makeTabs();
    }

    private void makeTabs() {
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.addTab(tabLayout.newTab().setText("Vacancies"));
        tabLayout.addTab(tabLayout.newTab().setText("Deleted Posts"));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
        CustomPagerAdapter pagerAdapter = new CustomPagerAdapter(getSupportFragmentManager(),
                tabLayout.getTabCount());
        viewPager.setAdapter(pagerAdapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private boolean isDBEmpty() {
        Cursor c;
        boolean a = false, b = false;
        c = getContentResolver().query(NTSPostsContract.Posts.CONTENT_URI, NTSPostsContract.Posts.PROJECTION_ALL,
                null, null, null);
        if (c.getCount() <= 0) {
            a = true;
        }
        c = getContentResolver().query(NTSPostsContract.Ignored.CONTENT_URI,
                NTSPostsContract.Ignored.PROJECTION_ALL, null, null, null);
        if (c.getCount() <= 0) {
            b = true;
        }
        c.close();
        return a && b; //return true if both tables are empty
    }

    private void doInBG() {
        new AsyncTask<Void, Void, String>() {
            Parser nts = new Parser(getApplicationContext());
            ProgressDialog progressDialog;

            @Override
            protected void onPreExecute() {
                progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                progressDialog.setMessage("Reading NTS website");
                progressDialog.setCancelable(false);
                progressDialog.show();
            }

            @Override
            protected String doInBackground(Void... params) {
                return nts.readWeb();
            }

            @Override
            protected void onPostExecute(String s) {
                progressDialog.dismiss();
                s = s.replaceAll("[^0-9]", "");
                int i = Integer.parseInt(s);
                if (i == 200) {
                    nts.saveToDB();
                } else {
                    new AlertDialog.Builder(MainActivity.this).setTitle("Error!")
                            .setMessage("Failed to read NTS website. Error code: " + i)
                            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            }).show();
                }
            }
        }.execute();
    }

    private void refresh() {
        if (isNetworkAvailable(MainActivity.this)) {
            doInBG();
        } else if (isDBEmpty()) {
            new AlertDialog.Builder(MainActivity.this).setTitle("Error!")
                    .setMessage("No internet\nCheck your network settings and try again.")
                    .setPositiveButton("Settings", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                        }
                    }).setCancelable(false).show();
        } else {
            showSnackBar("No Internet Connection", MainActivity.this);
        }
    }

    private void removeOld() {
        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... params) {
                Cursor cursor = null;
                int removedOldPosts = 0;
                try {
                    //checking for expired posts in main table
                    cursor = getContentResolver().query(NTSPostsContract.Posts.CONTENT_URI,
                            NTSPostsContract.Posts.PROJECTION_ALL, null, null, null);

                    if (cursor.getCount() > 0) {
                        while (cursor.moveToNext()) {
                            String id = cursor.getString(cursor.getColumnIndex(DbSchema.COL_ID));
                            long lastDate = cursor.getLong(cursor.getColumnIndex(DbSchema.COL_LAST_DATE));
                            Post p = new Post(lastDate, 0);
                            if (p.isExpired()) {
                                Log.i(getClass().getName(), "###Expired: " + p.getSimpleLastDate());
                                removedOldPosts += getContentResolver().delete(NTSPostsContract.Posts.CONTENT_URI,
                                        DbSchema.COL_ID + " = ?", new String[] { id });
                            }
                        }
                    }

                    //checking for expired posts in ignored table
                    cursor = getContentResolver().query(NTSPostsContract.Ignored.CONTENT_URI,
                            NTSPostsContract.Ignored.PROJECTION_ALL, null, null, null);

                    if (cursor.getCount() > 0) {
                        while (cursor.moveToNext()) {
                            String id = cursor.getString(cursor.getColumnIndex(DbSchema.COL_ID));
                            long lastDate = cursor.getLong(cursor.getColumnIndex(DbSchema.COL_LAST_DATE));
                            Post p = new Post(lastDate, 0);
                            if (p.isExpired()) {
                                removedOldPosts += getContentResolver().delete(NTSPostsContract.Ignored.CONTENT_URI,
                                        DbSchema.COL_ID + " = ?", new String[] { id });
                            }
                        }
                    }
                } finally {
                    cursor.close();
                    Log.i(getClass().getName(), "Removed " + removedOldPosts + " expired database entries");
                }
                return null;
            }
        }.execute();
    }
}