com.armtimes.activities.SingleArticlePreviewActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.armtimes.activities.SingleArticlePreviewActivity.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.activities;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.ShareActionProvider;
import android.text.Html;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.armtimes.R;
import com.armtimes.database.NewsContract;
import com.armtimes.database.NewsDatabaseHelper;
import com.armtimes.dialogs.DialogSettings;
import com.armtimes.downloaders.ArticleInfo;
import com.armtimes.downloaders.SingleArticleInfoDownloader;
import com.armtimes.utils.Logger;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class SingleArticlePreviewActivity extends ActionBarActivity
        implements SingleArticleInfoDownloader.SingleArticleDownloadListener {

    private final static String TAG = SingleArticlePreviewActivity.class.getSimpleName();

    public final static String EXTRA_CATEGORY_TITLE_ID = "NEWS_CATEGORY_TITLE_ID";
    public final static String EXTRA_CATEGORY = "CATEGORY";
    public final static String EXTRA_TITLE = "NEWS_TITLE";
    public final static String EXTRA_DESCRIPTION = "NEWS_DESCRIPTION";
    public final static String EXTRA_SHORT_DESC = "NEWS_SHORT_DESC";
    public final static String EXTRA_URL = "NEWS_URL";
    public final static String EXTRA_IMAGE_PATH = "NEWS_IMAGE_PATH";
    public final static String EXTRA_IMAGE_LINK = "NEWS_IMAGE_LINK";

    private LinearLayout layoutMain;
    private ImageView imageBanner;
    private TextView textTitle;
    private TextView textDescription;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Set Activity Layout.
        setContentView(R.layout.activity_news_reader);
        // Allows 'UP' Navigation.
        final ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        // Get information from Intent.
        final Intent intent = getIntent();
        if (intent == null) {
            finish();
            return;
        }

        initControllers();
        initActionBarTitle(intent, actionBar);

        final String url = intent.getStringExtra(EXTRA_URL);
        if (url == null || url.isEmpty()) {
            Toast.makeText(getApplicationContext(), R.string.cant_show_news_data_missing, Toast.LENGTH_LONG).show();
            finish();
            return;
        }

        // Hide main layout while news are not loaded yet.
        layoutMain.setVisibility(View.INVISIBLE);

        // Create Bundle for Progress Bar which contains,
        // Progress Bar message and title.
        Bundle progressBundle = new Bundle();
        progressBundle.putInt(ProgressDialog.EXTRA_TITLE, R.string.single_news_downloading);
        progressBundle.putInt(ProgressDialog.EXTRA_MESSAGE, R.string.txt_please_wait);

        progressDialog = new ProgressDialog();
        progressDialog.setArguments(progressBundle);
        progressDialog.setCancelable(false);
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(progressDialog, null);
        ft.commitAllowingStateLoss();

        ArticleInfo articleInfo = new ArticleInfo(intent.getStringExtra(EXTRA_URL),
                intent.getStringExtra(EXTRA_DESCRIPTION), intent.getStringExtra(EXTRA_IMAGE_LINK),
                intent.getStringExtra(EXTRA_IMAGE_PATH));

        SingleArticleInfoDownloader.startDownload(getApplicationContext(), articleInfo, this);

    }

    private void initControllers() {
        layoutMain = (LinearLayout) findViewById(R.id.layoutMain);
        // Initialize Main Banner Area where Banner Image and
        // Banner Title are located.
        RelativeLayout layoutBanner = (RelativeLayout) findViewById(R.id.layoutBanner);
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        // Set Banner Layout proportion to 1/3 of screen.
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) layoutBanner.getLayoutParams();
        params.height = metrics.heightPixels / 3;
        layoutBanner.setLayoutParams(params);

        // Initialize Banner Image.
        imageBanner = (ImageView) findViewById(R.id.imageViewBanner);
        imageBanner.setScaleType(ImageView.ScaleType.CENTER);

        // Initialize Title Text View.
        textTitle = (TextView) findViewById(R.id.textViewBannerTitle);

        // Initialize Description Text View
        textDescription = (TextView) findViewById(R.id.textViewDescription);
        textDescription.setTextAppearance(getApplicationContext(),
                DialogSettings.getTextFontSize(getApplicationContext()));
        textDescription.setTextColor(Color.BLACK);
    }

    private void initActionBarTitle(final Intent intent, final ActionBar actionBar) {
        int title = R.string.app_name;
        try {
            title = intent.getIntExtra(EXTRA_CATEGORY_TITLE_ID, 0);
        } finally {
            actionBar.setTitle(Html.fromHtml("<small>" + getResources().getString(title) + "</small>"));
            actionBar.setBackgroundDrawable(new ColorDrawable(0xFFFA294C));
        }
    }

    @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_single_article_preview, menu);
        // Get the menu item.
        MenuItem menuItem = menu.findItem(R.id.menu_item_share);
        // Get the provider and hold onto it to set/change the share intent.
        ShareActionProvider shareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
        // Set share Intent.
        // Note: You can set the share Intent afterwords if you don't want to set it right now.
        Intent intent = createShareIntent();
        if (intent != null)
            shareActionProvider.setShareIntent(intent);

        // Return true to display menu
        return true;
    }

    // Create and return the Share Intent
    private Intent createShareIntent() {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        // Get Description.
        String description = getIntent().getStringExtra(EXTRA_SHORT_DESC);
        if (description == null || description.isEmpty())
            return null;

        String url = getIntent().getStringExtra(EXTRA_URL);
        if (url == null || url.isEmpty())
            return null;

        description = Html.fromHtml(description).toString();

        final String textToShare = String.format("%s... <a href=\"%s\">%s</a>", description, url,
                getString(R.string.read_more));
        shareIntent.putExtra(Intent.EXTRA_TEXT, textToShare);
        return shareIntent;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            this.finish();
            break;

        }
        return true;
    }

    @Override
    public void onSingleArticleDownloadCompleted(final ArticleInfo articleInfo) {

        if (progressDialog != null) {
            progressDialog.dismissAllowingStateLoss();
            progressDialog = null;
        }

        // Finish current activity if Description or Title
        // are missing, missing of image is not a case to
        // finish activity.
        if (articleInfo == null) {
            Toast.makeText(getApplicationContext(), R.string.cant_show_news_data_missing, Toast.LENGTH_LONG).show();
            setResult(Activity.RESULT_CANCELED);
            finish();
            return;
        }

        // Title comes from the Database and it should be there
        // as it is downloaded at first phase from RSS.
        String title = getIntent().getStringExtra(EXTRA_TITLE);
        if (title == null || title.isEmpty()) {
            Toast.makeText(getApplicationContext(), R.string.cant_show_news_data_missing, Toast.LENGTH_LONG).show();
            setResult(Activity.RESULT_CANCELED);
            finish();
            return;
        }

        String description = articleInfo.getDescription();
        if (description == null || description.isEmpty()) {
            Toast.makeText(getApplicationContext(), R.string.cant_show_news_data_missing, Toast.LENGTH_LONG).show();
            setResult(Activity.RESULT_CANCELED);
            finish();
            return;
        }

        // If news article information was successfully downloaded,
        // and shown to the user - update database by setting given
        // news item read state to TRUE.
        try {
            // Get current table name, in which information for given
            // article must be updated.
            final String table = getIntent().getStringExtra(EXTRA_CATEGORY).toUpperCase();
            // Create Database helper object.
            NewsDatabaseHelper helper = new NewsDatabaseHelper(getApplicationContext());
            SQLiteDatabase database = helper.getWritableDatabase();
            // Create data which must be updated.
            ContentValues cv = new ContentValues();
            cv.put(NewsContract.COL_NAME_NEWS_IS_READ, 1);
            // Update appropriate field in database.
            database.update(table, cv, String.format("%s=\"%s\"", NewsContract.COL_NAME_NEWS_URL, articleInfo.url),
                    null);
            // Close database
            database.close();
            helper.close();
        } catch (Exception ex) {
            Logger.e(TAG, "Exception occurs while trying to Update database!");
        }

        // Set layout Visible.
        layoutMain.setVisibility(View.VISIBLE);

        textTitle.setText(title.trim());
        textDescription.setText(Html.fromHtml(articleInfo.getDescription()));

        // Try to set image if it exists.
        InputStream is = null;
        try {
            is = new FileInputStream(new File(articleInfo.getMainImagePath()));
            imageBanner.setImageBitmap(BitmapFactory.decodeStream(is));
            imageBanner.setScaleType(ImageView.ScaleType.CENTER_CROP);
        } catch (IOException ex) {
            imageBanner.setScaleType(ImageView.ScaleType.CENTER);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException ex) {
                    Logger.e(TAG, "Error occurs while trying to close Banner Image Stream.");
                }
            }
        }

        setResult(Activity.RESULT_OK);
    }

}