com.armtimes.drawer.CommonFragment.java Source code

Java tutorial

Introduction

Here is the source code for com.armtimes.drawer.CommonFragment.java

Source

/*
 * Copyright (C) 2015 Victor Apoyan.
 *
 * 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 com.armtimes.drawer;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.armtimes.R;
import com.armtimes.activities.SingleArticlePreviewActivity;
import com.armtimes.database.NewsContract;
import com.armtimes.database.NewsDatabaseHelper;
import com.armtimes.downloaders.ArticleInfoDownloaderService;
import com.armtimes.fragments.FragmentAdapter;
import com.armtimes.fragments.IFragmentListener;
import com.armtimes.parser.DownloadRssTask;
import com.armtimes.parser.IDownloadRssListener;

public class CommonFragment extends ListFragment implements IDownloadRssListener {

    public final static String EXTRA_CATEGORY = "CATEGORY_NAME";

    NewsDatabaseHelper mDatabaseHelper = null;
    DownloadRssTask mDownloadRssAsync = null;
    ProgressDialog mProgressDialog = null;
    boolean mIsTaskRunning = false;
    IFragmentListener mListener = null;
    FragmentAdapter mAdapter = null;
    String mCategory = "";
    int mCategoryTitleId = 0;
    LocalBroadcastManager mLocalBroadcastManager = null;

    // Broadcast receiver which receives events from ArtticleDownloadService
    // Every time when new portion of news were downloaded from Internet or
    // all news were downloaded.
    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                String category = intent.getStringExtra(EXTRA_CATEGORY);
                // Receive event from ArticleInfoDownloadService and update
                // ListView adapter to have last data.
                if (mAdapter != null && (category.equals(mCategory) || category.equals("all"))) {
                    final Cursor cursor = mDatabaseHelper.getCursorByTable(mCategory);
                    mAdapter.changeCursor(null);
                    mAdapter.changeCursor(cursor);
                }
            }
        }
    };

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

        // Prevent from recreating fragment instance.
        setRetainInstance(true);
        setHasOptionsMenu(true);

        // Create new broadcast receiver and register it.
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(getActivity());
        mLocalBroadcastManager.registerReceiver(mBroadcastReceiver, new IntentFilter("event-downloaded"));

        // Create new instance of database.
        mDatabaseHelper = new NewsDatabaseHelper(getActivity());

        // Create new instance of Async Task.
        mDownloadRssAsync = new DownloadRssTask(this, mDatabaseHelper);
        mDownloadRssAsync.execute(mCategory);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_common, container, false);

        mAdapter = new FragmentAdapter(getActivity(), mDatabaseHelper.getCursorByTable(mCategory));
        // Attach cursor adapter to the ListView
        setListAdapter(mAdapter);

        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (mListener != null)
            mListener.onFragmentAttached(getString(mCategoryTitleId));

        // If we are returning here from a screen orientation and the AsyncTask
        // is still working, re-create and display the progress dialog.
        if (mIsTaskRunning) {
            mProgressDialog = ProgressDialog.show(getActivity(), getString(R.string.txt_updating_news_feed),
                    getString(R.string.txt_please_wait));
            mProgressDialog.setCancelable(false);
        }
    }

    @Override
    public void onDetach() {
        mListener = null;
        // All dialogs should be closed before leaving the activity in order to avoid
        // the: Activity has leaked window com.android.internal.policy... exception
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
        super.onDetach();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        try {
            mListener = (IFragmentListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(
                    activity.toString() + " must implement OnFragmentInteractionListener Interface");
        }
    }

    @Override
    public void onDownloadRssStared() {
        mIsTaskRunning = true;
    }

    @Override
    public void onDownloadRssCompleted(int aResult) {
        // Dismiss dialog in case work is done.
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }

        if (mAdapter != null) {
            mAdapter.changeCursor(null);
            mAdapter.changeCursor(mDatabaseHelper.getCursorByTable(mCategory));
        }

        mProgressDialog = null;
        mIsTaskRunning = false;

        // Show toast message only in the case of fragment already
        // attached to it's activity;  otherwise showing toast can
        // cause application crashes.
        if (isAdded())
            Toast.makeText(getActivity(), getString(aResult), Toast.LENGTH_SHORT).show();

        // Start service which will download rest of information.
        Intent intent = new Intent(getActivity(), ArticleInfoDownloaderService.class);
        intent.putExtra(ArticleInfoDownloaderService.EXTRA_CATEGORY, mCategory);
        getActivity().startService(intent);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Refresh the news feed.
        if (item.getItemId() == R.id.action_refresh) {
            if (!mIsTaskRunning) {
                // Recreate database instance if null
                if (mDatabaseHelper == null)
                    mDatabaseHelper = new NewsDatabaseHelper(getActivity());
                // Create async task to start work.
                mDownloadRssAsync = new DownloadRssTask(this, mDatabaseHelper);
                mDownloadRssAsync.execute(mCategory);
                // Show progress dialog, if screen will be rotated this dialog will
                // be detached in onDismiss and created new on in onActivityCreated
                mProgressDialog = ProgressDialog.show(getActivity(), getString(R.string.txt_updating_news_feed),
                        getString(R.string.txt_please_wait));
                mProgressDialog.setCancelable(false);
            }

            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // Get current selected item.
        Cursor cursor = ((FragmentAdapter) l.getAdapter()).getCursor();
        cursor.moveToPosition(position);
        // Create new intent to send to News Reader Activity.
        Intent intent = new Intent(getActivity(), SingleArticlePreviewActivity.class);
        intent.putExtra(SingleArticlePreviewActivity.EXTRA_CATEGORY_TITLE_ID, mCategoryTitleId);
        intent.putExtra(SingleArticlePreviewActivity.EXTRA_TITLE,
                cursor.getString(cursor.getColumnIndexOrThrow(NewsContract.COL_NAME_NEWS_TITLE)));
        intent.putExtra(SingleArticlePreviewActivity.EXTRA_DESCRIPTION,
                cursor.getString(cursor.getColumnIndexOrThrow(NewsContract.COL_NAME_NEWS_DESC_LONG)));
        intent.putExtra(SingleArticlePreviewActivity.EXTRA_URL,
                cursor.getString(cursor.getColumnIndexOrThrow(NewsContract.COL_NAME_NEWS_URL)));
        intent.putExtra(SingleArticlePreviewActivity.EXTRA_IMAGE_PATH,
                cursor.getString(cursor.getColumnIndexOrThrow(NewsContract.COL_NAME_NEWS_MAIN_IMAGE_PATH)));
        intent.putExtra(SingleArticlePreviewActivity.EXTRA_IMAGE_LINK,
                cursor.getString(cursor.getColumnIndexOrThrow(NewsContract.COL_NAME_NEWS_IMAGE_URL)));
        intent.putExtra(SingleArticlePreviewActivity.EXTRA_SHORT_DESC,
                cursor.getString(cursor.getColumnIndexOrThrow(NewsContract.COL_NAME_NEWS_DESC_SHORT)));
        intent.putExtra(SingleArticlePreviewActivity.EXTRA_CATEGORY, mCategory);

        // Start News Reader Activity.
        startActivityForResult(intent, 0);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // Appears here when Single Article Preview activity is closed.
        // If Activity was canceled do nothing.

        // If Activity was successfully shown to the user, and data was
        // successfully updated in the database, we update adapter...
        if (resultCode == Activity.RESULT_OK) {
            if (mDatabaseHelper != null && mAdapter != null && mCategory != null && !mCategory.isEmpty()) {
                final Cursor cursor = mDatabaseHelper.getCursorByTable(mCategory);
                if (cursor != null) {
                    mAdapter.changeCursor(null);
                    mAdapter.changeCursor(cursor);
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        // Do a clean up of application, stop async tasks, dismiss
        // dialogs etc.

        // Stop asynchronous tasks.
        if (mDownloadRssAsync != null && !mDownloadRssAsync.isCancelled())
            mDownloadRssAsync.cancel(true);

        // Dismiss dialogs.
        if (mProgressDialog != null && mProgressDialog.isShowing())
            mProgressDialog.dismiss();

        // Unregister broadcast receiver
        if (mLocalBroadcastManager != null)
            mLocalBroadcastManager.unregisterReceiver(mBroadcastReceiver);

        super.onDestroy();
    }

    public static class EconomyFragment extends CommonFragment {

        public EconomyFragment() {
            mCategory = "economy";
            mCategoryTitleId = R.string.fr_name_economy;
        }
    }

    public static class PoliticsFragment extends CommonFragment {

        public PoliticsFragment() {
            mCategory = "politics";
            mCategoryTitleId = R.string.fr_name_politics;
        }
    }

    public static class WorldFragment extends CommonFragment {

        public WorldFragment() {
            mCategory = "world";
            mCategoryTitleId = R.string.fr_name_world;
        }
    }

    public static class LawFragment extends CommonFragment {

        public LawFragment() {
            mCategory = "law";
            mCategoryTitleId = R.string.fr_name_law;
        }
    }

    public static class SocietyFragment extends CommonFragment {

        public SocietyFragment() {
            mCategory = "society";
            mCategoryTitleId = R.string.fr_name_society;
        }
    }

    public static class CultureFragment extends CommonFragment {

        public CultureFragment() {
            mCategory = "culture";
            mCategoryTitleId = R.string.fr_name_culture;
        }
    }

    public static class SportFragment extends CommonFragment {

        public SportFragment() {
            mCategory = "sport";
            mCategoryTitleId = R.string.fr_name_sport;
        }
    }

}