me.skydeveloper.tikona.MainActivity.java Source code

Java tutorial

Introduction

Here is the source code for me.skydeveloper.tikona.MainActivity.java

Source

/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Akash Kumar
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

package me.skydeveloper.tikona;

import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;

import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
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 android.view.View;

import android.widget.TextView;
import android.widget.Toast;

import me.skydeveloper.tikona.helper.HttpManger;
import me.skydeveloper.tikona.helper.HttpRequest;

import java.net.CookieHandler;
import java.net.CookieManager;
import java.util.ArrayList;
import java.util.List;

import android.support.design.widget.TabLayout;

import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    private AlertDialog.Builder logout;

    private ProgressDialog popupLoader;

    private SharedPreferences urlPreferences;
    private SharedPreferences sessionPreferences;
    private SharedPreferences selfcarePreferences;

    private View logoutButton;

    private TextView userId;
    private TextView userName;
    DrawerLayout drawer;
    NavigationView navigationView;

    Menu navigationMenu;

    SessionTab sessionTab;

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

        //Facebook Analytics Initialization
        FacebookSdk.sdkInitialize(getApplicationContext());
        AppEventsLogger.activateApp(this);

        setContentView(R.layout.activity_main_navigation_drawer);
        //setContentView(R.layout.welcome);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        CookieHandler.setDefault(new CookieManager());

        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
                R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        View headerView = navigationView.getHeaderView(0);

        //navigationView.getMenu().clear();

        urlPreferences = getSharedPreferences("url", MODE_PRIVATE);
        sessionPreferences = getSharedPreferences("session", MODE_PRIVATE);
        selfcarePreferences = getSharedPreferences("selfcare", MODE_PRIVATE);

        navigationMenu = navigationView.getMenu();

        //Todo => Uncomment this when selfcare login is fixed
        /*if (!selfcarePreferences.getString("username", "").isEmpty() && !selfcarePreferences.getString("password", "").isEmpty()) {
        MenuItem item = navigationMenu.findItem(R.id.loggedIn);
        item.setVisible(true);
        } else {
        MenuItem item = navigationMenu.findItem(R.id.notLoggedIn);
        item.setVisible(true);
        }*/

        logout = new AlertDialog.Builder(this);
        logout.setMessage("Are you sure you want logout?").setTitle("Confirm Logout");
        logout.setPositiveButton("Logout", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //Call logout uri
                logout();
            }
        });
        logout.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //Do nothing
            }
        });

        logout.create();

        userId = (TextView) headerView.findViewById(R.id.userId);
        userName = (TextView) headerView.findViewById(R.id.name);

        userId.setText(selfcarePreferences.getString("username", "11XXXXXXXX"));
        userName.setText(selfcarePreferences.getString("user_name", "Guest User"));

        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        if (viewPager != null) {
            viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    //Log.d("onPageSelected", position + "");
                    if (position == 1) {
                        BillingTab.selfcareArray[0].setText(selfcarePreferences.getString("totalOutstanding",
                                "Selfcare login temporarily disabled"));//TODO => Show appropirate message after fixing selfcare bug

                        BillingTab.selfcareArray[1].setText(selfcarePreferences.getString("lastBillAmount", "-"));
                        BillingTab.selfcareArray[2].setText(selfcarePreferences.getString("lastBillDate", "-"));
                        BillingTab.selfcareArray[3].setText(selfcarePreferences.getString("dueDate", "-"));
                        BillingTab.selfcareArray[4]
                                .setText(selfcarePreferences.getString("lastPaymentAmount", "-"));
                        BillingTab.selfcareArray[5].setText(selfcarePreferences.getString("lastPaymentDate", "-"));

                        //BillingTab.selfcareArray[0].setText("test");
                    }

                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
        }
        setupViewPager(viewPager);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

        popupLoader = new ProgressDialog(this);

    }

    @Override
    protected void onResume() {
        super.onResume();
        AppEventsLogger.activateApp(getApplication());
    }

    @Override
    protected void onPause() {
        super.onPause();
        AppEventsLogger.deactivateApp(this);
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_activity, 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
        switch (id) {
        case R.id.action_logout:
            logout.show();
            break;
        case R.id.action_refresh:
            sessionTab.fetchSessionDetails();

            break;
        }
        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        switch (id) {
        //When user Not Logged in selfcare
        case R.id.selfcareLogin:
            Intent intent = new Intent(this, SelfcareLogin.class);
            startActivity(intent);
            break;

        //When user is logged in selfcare
        case R.id.selfcareRefresh:
            break;
        case R.id.changePassword:
            Intent intent2 = new Intent(this, SelfcareLogin.class);
            startActivity(intent2);
            break;
        case R.id.selfcareLogout:
            navigationMenu.findItem(R.id.loggedIn).setVisible(false);//HIDE LOGGED IN MENU
            navigationMenu.findItem(R.id.notLoggedIn).setVisible(true);//SHOW NOT LOGGED IN MENU

            //CLEAR USERNAME & PASSWORD FROM SHARED_PREFERENCES
            SharedPreferences.Editor selfcareEditor = selfcarePreferences.edit();
            selfcareEditor.clear();
            selfcareEditor.apply();

            //CHANGE VALUE IN TEXTVIEW
            SessionTab.remainingUsage.setText(R.string.ltvd);

            Snackbar.make(getCurrentFocus(), "Your are logged out from selfcare", Snackbar.LENGTH_LONG).show();
            break;

        //Current Session
        case R.id.force_refresh:
            sessionTab.getURLs();
            break;

        //Help Developer Menu
        case R.id.share:
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("text/plain");
            shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Tikona Session");
            shareIntent.putExtra(Intent.EXTRA_TEXT,
                    "https://play.google.com/store/apps/details?id=me.skydeveloper.tikona \n\nCheck out this Tikona session help which helps you manage your session.");
            startActivity(Intent.createChooser(shareIntent, "Share via"));
            break;
        case R.id.feedback:
            //TODO => Create a form to be filled by user before publishing for beta
            break;
        case R.id.playStore:
            final String appPackageName = getPackageName(); // getPackageName() from Context or Activity object
            try {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
            } catch (android.content.ActivityNotFoundException anfe) {
                startActivity(new Intent(Intent.ACTION_VIEW,
                        Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
            }
            break;
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new SessionTab(), "Session");
        adapter.addFragment(new BillingTab(), "Billing");
        sessionTab = (SessionTab) adapter.getItem(0);

        viewPager.setAdapter(adapter);

    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }

    //--------------------------------------------------------------------//

    /**
     * Calls Async Task to create Http Request to LOGOUT URI
     */
    protected void logout() {
        if (HttpManger.isOnline((ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE))) {
            String logout_url = urlPreferences.getString("logout_url", "");
            if (!logout_url.isEmpty()) {
                HttpRequest request = new HttpRequest();
                request.setMethod("GET");
                request.setUri(logout_url);
                Logout logout = new Logout();
                logout.execute(request);
            }
        } else {
            Toast.makeText(MainActivity.this, "Your are not connected to wifi", Toast.LENGTH_LONG).show();
            //Snackbar.make(this, "Your are not connected to wifi #3", Snackbar.LENGTH_LONG).show();
        }
    }

    /**
     *
     */
    private class Logout extends AsyncTask<HttpRequest, String, String> {
        @Override
        protected void onPreExecute() {
            popupLoader.setTitle("Please wait..");
            popupLoader.setMessage("Logging out current session");
            popupLoader.show();
            popupLoader.setCancelable(true);
        }

        @Override
        protected String doInBackground(HttpRequest... params) {
            String response = HttpManger.makeRequest(params[0]);
            Log.d("return data", response);
            return response;

        }

        @Override
        protected void onPostExecute(String s) {
            Log.d("response", s);
            if (s.length() > 2 && !s.isEmpty()) {
                //Session is logged out
                SessionTab.sessionStart.setText("-");
                SessionTab.sessionDuration.setText("-");
                SessionTab.sessionUsage.setText("-");

                Toast.makeText(MainActivity.this, "Your session has been logged out", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(MainActivity.this, "Error while logout.. Please try again later", Toast.LENGTH_LONG)
                        .show();
            }
            popupLoader.hide();
        }
    }
}