yet.another.hackernews.reader.HackernewsFragment.java Source code

Java tutorial

Introduction

Here is the source code for yet.another.hackernews.reader.HackernewsFragment.java

Source

/*******************************************************************************
 * Copyright 2012 Niklas Ekman
 *
 *    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 yet.another.hackernews.reader;

import java.util.ArrayList;
import java.util.Calendar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import yet.another.hackernews.reader.data.News;
import yet.another.hackernews.reader.functions.DownloadText;
import yet.another.hackernews.reader.functions.DownloadText.OnDownloadTextListener;
import yet.another.hackernews.reader.functions.NewsAdapter;
import yet.another.hackernews.reader.functions.ProgressFragment.OnProgressListener;
import yet.another.hackernews.reader.utils.MyDialogUtils;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;

public class HackernewsFragment extends SherlockFragment
        implements OnDownloadTextListener, OnItemClickListener, OnProgressListener {

    private static NewsAdapter adapter;

    protected DownloadText dl;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return inflater.inflate(R.layout.layout_hackernews, container, false);
    }

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

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

        if (adapter == null) {
            adapter = new NewsAdapter(getSherlockActivity(), R.layout.list_news, new ArrayList<News>(0));
        } else {
            if (!adapter.isEmpty()) {
                adapter.clear();
            }
        }

        final ListView newsList = (ListView) getSherlockActivity().findViewById(R.id.hackernews_list);

        newsList.setAdapter(adapter);
        newsList.setOnItemClickListener(this);
    }

    protected void updateList(String URL, boolean forceUpdate) {

        MyDialogUtils.newDialog(this, getString(R.string.loading_title), null);
        MyDialogUtils.show(getSherlockActivity().getSupportFragmentManager());

        dl = new DownloadText(getSherlockActivity());
        dl.setOnDownloadTextListener(this);

        dl.forceUpdate(forceUpdate);
        dl.execute(URL);
    }

    @Override
    public void onFinished(int id, String text) {
        MyDialogUtils.hideDialog();

        if (text == null) {
            Toast.makeText(getSherlockActivity().getApplicationContext(), R.string.no_cache, Toast.LENGTH_SHORT)
                    .show();
            ((HackernewsActivity) getSherlockActivity()).handleError();
            return;
        }

        try {
            final JSONObject results = new JSONObject(text);
            final JSONArray theNews = results.getJSONArray("items");

            final int length = theNews.length();

            for (int i = 0; i < length; i++) {
                adapter.add(new News(theNews.getJSONObject(i)));
            }

        } catch (JSONException e) {
        }

        adapter.notifyDataSetChanged();

        new Timestamp(this).parse(id);

        dl = null;
    }

    @Override
    public void onError(int error) {
        MyDialogUtils.hideDialog();

        Toast.makeText(getSherlockActivity().getApplicationContext(), R.string.error, Toast.LENGTH_LONG).show();

    }

    @Override
    public void onCancel() {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View v, int pos, long id) {
        final News news = (News) parent.getAdapter().getItem(pos);

        if (news.getTitle().equals("More")) {
            return;
        }

        final int screenLayout = getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK;

        switch (screenLayout) {

        case Configuration.SCREENLAYOUT_SIZE_XLARGE:

            final FragmentManager fManager = getSherlockActivity().getSupportFragmentManager();
            final ViewFragment fragment = (ViewFragment) fManager.findFragmentById(R.id.fragment_view);

            if (fragment != null) {
                ViewFragment.setNews(news);
                fragment.update(null);
                v.setEnabled(true);
            }

            break;
        default:

            Bundle sendArgs = new Bundle();
            sendArgs.putString("NewsObject", news.toString());

            Intent browser = new Intent(getSherlockActivity(), ViewActivity.class);
            browser.putExtras(sendArgs);
            startActivity(browser);

            break;
        }
    }

    @Override
    public void OnProgressCancel() {
        if (dl != null && dl.getStatus() == AsyncTask.Status.RUNNING) {
            dl.cancel(true);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        OnProgressCancel();
    }

    private class Timestamp {

        final SherlockFragment fragment;
        final TextView timestamp;

        public Timestamp(SherlockFragment fragment) {
            this.fragment = fragment;

            timestamp = (TextView) fragment.getSherlockActivity().findViewById(R.id.hackernews_timestamp);
        }

        public void parse(int id) {

            SharedPreferences prefs = fragment.getSherlockActivity().getSharedPreferences(DownloadText.CACHE,
                    Context.MODE_PRIVATE);

            String date = String.valueOf(prefs.getInt(DownloadText.CACHE_LAST_DATE + id, 0));

            final long lastUpdateTime = prefs.getLong(DownloadText.CACHE_LAST_TIME + id, 0);

            if (date.equals("0") || lastUpdateTime == 0) {
                set(null, null, null);
                return;
            }

            final Calendar cal = Calendar.getInstance();
            cal.setTimeInMillis(lastUpdateTime);

            String hour = String.valueOf(cal.get(Calendar.HOUR_OF_DAY));
            String minute = String.valueOf(cal.get(Calendar.MINUTE));

            if (minute.length() <= 1) {
                minute = "0" + minute;
            }

            if (hour.length() <= 1) {
                hour = "0" + hour;
            }

            set(date, hour, minute);
        }

        private void set(String date, String hour, String minute) {
            timestamp.setText(fragment.getString(R.string.cache_timestamp));

            if (date == null) {
                timestamp.append(": N/A");
            } else {
                timestamp.append(": " + date + " - " + hour + ":" + minute);
            }
        }
    }

}