com.example.testtab.fragment.TwitEyesPageFragment.java Source code

Java tutorial

Introduction

Here is the source code for com.example.testtab.fragment.TwitEyesPageFragment.java

Source

/*
 * Copyright 2012 The Android Open Source Project
 *
 * 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.example.testtab.fragment;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import com.example.testtab.ImageLevelActivity;
import com.example.testtab.R;
import com.example.testtab.gallery.ImageAdapter;
import com.example.testtab.gallery.ImageBean;
import com.example.testtab.twiteyes.CIdsXmlRHandler;
import com.example.testtab.twiteyes.CImageLoadRH;
import com.example.testtab.twiteyes.CItem;
import com.example.testtab.twiteyes.CItemComparator;
import com.example.testtab.twiteyes.CUserTimelineXmlRH;
import com.example.testtab.twiteyes.Table;
import com.example.testtab.twiteyes.CIdsXmlRHandler.CIds;
import com.example.testtab.twiteyes.CIdsXmlRHandler.IdsFileIO;
import com.example.testtab.twiteyes.CImageLoadRH.ImgFileIO;
import com.example.testtab.twiteyes.CUserTimelineXmlRH.CUserTimeline;
import com.example.testtab.twiteyes.CUserTimelineXmlRH.UtlFileIO;

import static com.example.testtab.fragment.TwitEyesPageFragment.Mode.*;
import com.example.testtab.Tab3Activity;

//import android.app.Fragment;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.BounceInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

import static com.example.testtab.fragment.TwitEyesPageFragment.IMAGE_LEVEL_ACTIVITY;

/**
 * A fragment representing a single step in a wizard. The fragment shows a dummy title indicating
 * the page number, along with some dummy text.
 *
 * <p>This class is used by the {@link CardFlipActivity} and {@link
 * ScreenSlideActivity} samples.</p>
 */
public class TwitEyesPageFragment extends Fragment implements OnClickListener, OnLongClickListener {
    /**
     * The argument key for the page number this fragment represents.
     */
    public static final String ARG_PAGE = "page";

    /**
     * The fragment's page number, which is set to the argument value for {@link #ARG_PAGE}.
     */
    private int mPageNumber;

    // Common ----------------------------------------- //
    private static Context mContext;
    private static LayoutInflater mInflater;

    private ViewGroup mRootView;
    // Twit Eyes -------------------------------------- //
    // VARIABLE --------------------------------------- //
    // STATIC
    final static boolean MODE_DEBUG = false;
    final static boolean MODE_PROD = false;//true;
    final static int MENU0_ID = Menu.FIRST;
    final static int MENU1_ID = Menu.FIRST + 1;
    public static final int IMAGE_LEVEL_ACTIVITY = 2;
    public static final String TAG = "TWITEYES";
    private static final int MAX_IDS = 20; // 35;
    private static final int imageViews[] = { R.id.ImageView00, R.id.ImageView01, R.id.ImageView02,
            R.id.ImageView03, R.id.ImageView04, R.id.ImageView05, R.id.ImageView06, R.id.ImageView07,
            R.id.ImageView08, R.id.ImageView09, R.id.ImageView10, R.id.ImageView11, R.id.ImageView12,
            R.id.ImageView13, R.id.ImageView14, R.id.ImageView15 };

    enum Mode {
        MODE_OPTION, MODE_MAIN,
    }

    // INSTANCE
    private ArrayAdapter<String> mAdapter;
    private List<CItem> tweet;
    private int idsLimit;
    private DateFormat df;
    private Handler handler;
    private Calendar nowCal;
    private Calendar buildCal;
    private long lastKickedTime;
    private int lastPercent;
    private String screenName;
    private int interval;
    private boolean isSecure;
    private boolean isRunnable;
    private Mode modeState;

    /**
     * Factory method for this fragment class. Constructs a new fragment for the given page number.
     */
    public static TwitEyesPageFragment create(int pageNumber, Context context) {
        // Gallery ------------------------------------ //
        mContext = context;

        mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        TwitEyesPageFragment fragment = new TwitEyesPageFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PAGE, pageNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public TwitEyesPageFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPageNumber = getArguments().getInt(ARG_PAGE);
    }

    /**
     * Returns the page number represented by this fragment object.
     */
    public int getPageNumber() {
        return mPageNumber;
    }

    // TwitEyes --------------------------------------- //
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        /*        // Inflate the layout containing a title and body text.
                ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_screen_slide_page, container, false);
                // Set the title view to show the page number.
                ((TextView) rootView.findViewById(android.R.id.text1)).setText(getString(R.string.title_template_step, mPageNumber + 10));
        */
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.tw_main, container, false);

        // TwitEyes OnCreate -------------------------- //
        //        this.mImageView = (ImageView)rootView.findViewById(R.id.image_view);
        // LIST VIEW
        mAdapter = new ArrayAdapter<String>(mContext, R.layout.tw_list_row, new ArrayList<String>());
        //        setListAdapter(mAdapter);

        // INSTANCE
        this.tweet = new ArrayList<CItem>();
        this.idsLimit = 0;
        this.df = new SimpleDateFormat("EEE MMM dd HH:mm:ss ZZZZZ yyyy", Locale.ENGLISH);
        this.handler = new Handler();
        this.lastKickedTime = 0;
        this.lastPercent = 0;
        this.screenName = "";
        this.interval = 0;
        this.isSecure = true;
        this.isRunnable = true;
        modeState = MODE_MAIN;

        // LISTENER
        for (int i = 0; i < imageViews.length; i++) {
            ImageButton iButton = (ImageButton) rootView.findViewById(imageViews[i]);
            iButton.setOnClickListener(this);
            iButton.setOnLongClickListener(this);
        }

        // LOAD SAVE.DAT
        loadGame();

        // OPTION
        //        if (this.screenName.equals("")) kickImageLevelActivity();
        if (this.screenName.equals(""))
            ((Tab3Activity) mContext).kickImageLevelActivity();
        this.mRootView = rootView;
        // TwitEyes OnCreate -------------------------- //

        return rootView;
    }

    @Override
    public void onStop() {
        super.onStop();
        saveGame();
    }

    private void kickAction(boolean isFromOption) {
        if (modeState == MODE_MAIN) {
            // CLEAR PROGRESS
            showProgressBar(0);

            if (!this.screenName.equals(""))
                kickIdsXML(isFromOption);
            else
                showWarning(Table.WARN_USERNAME);
            //         kickIdsXML(isFromOption);//test
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        kickAction(false);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    public boolean onLongClick(View v) {
        for (int i = 0; i < imageViews.length; i++) {
            if (v.getId() == imageViews[i]) {
                //             setUserId(i);
                break;
            }
        }
        return false;
    }

    public void onClick(View v) {
        for (int i = 0; i < imageViews.length; i++) {
            if (v.getId() == imageViews[i]) {
                //             getTweet(i);
                break;
            }
        }
    }

    public synchronized void endImgLoad(ImgFileIO status, String resMessage, final Bitmap bitmap, final int index,
            final int fresh) {
        showErrorLog("endImageLoad : index : " + index + " ---- //");
        boolean isContinue = true;
        switch (status) {
        case InterruptError:
            toastFormThread(Table.ERROR_INTERRUPTED + " while loading image.");
            isContinue = false;
            break;
        case HttpCodeError:
            toastFormThread(Table.ERROR_HTTP_CODE + " while loading image. Http Response: " + resMessage);
            isContinue = false;
            break;
        case FileMalformedError:
            toastFormThread(Table.ERROR_MALFORMED_URL + " while loading image.");
            isContinue = false;
            break;
        case ClientProtocolError:
            toastFormThread(Table.ERROR_CLIENT_PROTOCOL + " while loading image.");
            isContinue = false;
            break;
        case FileIOError:
            toastFormThread(Table.ERROR_IO + " while loading image.");
            isContinue = false;
            break;
        case FileCloserror:
            toastFormThread(Table.ERROR_FILE_CLOSE + " while loading image.");
            isContinue = false;
        }
        if (!isContinue)
            return;
        if (bitmap == null) {
            toastFormThread(Table.ERROR_IMAGE_NULL + " while loading image. Http Response: " + resMessage + " (No. "
                    + index + ")");
            //return;
        }

        // CONTINUE
        this.handler.post(new Runnable() {
            public void run() {
                ImageButton image = (ImageButton) mRootView.findViewById(imageViews[index]);
                image.setImageBitmap(bitmap);

                if (bitmap != null) {
                    AnimationSet set = new AnimationSet(true);

                    AlphaAnimation alpha;
                    switch (fresh) {
                    case 1:
                    case 2:
                        alpha = new AlphaAnimation(0.0f, 0.8f);
                        break;
                    case 3:
                    case 4:
                        alpha = new AlphaAnimation(0.0f, 0.6f);
                        break;
                    case 5:
                    case 6:
                        alpha = new AlphaAnimation(0.0f, 0.4f);
                        break;
                    case 7:
                        alpha = new AlphaAnimation(0.0f, 0.2f);
                        break;
                    default:
                        alpha = new AlphaAnimation(0.0f, 1.0f);
                    }
                    set.addAnimation(alpha);
                    set.setDuration(500);
                    set.setFillAfter(true);

                    image.startAnimation(set);
                }
            }
        });
    }

    // IDS -------------------------------------------- //
    public void showProgressBar(int percent) {
        TextView textLayer = (TextView) this.mRootView.findViewById(R.id.progress_bar);
        AnimationSet set = new AnimationSet(true);

        // ALPHA
        AlphaAnimation alpha;
        switch (percent) {
        case 100:
            alpha = new AlphaAnimation(1.0f, 0.0f);
            break;
        case 0:
            alpha = new AlphaAnimation(0.0f, 1.0f);
            break;
        default:
            alpha = new AlphaAnimation(0.8f, 1.0f);
        }
        alpha.setDuration(500);

        TranslateAnimation translate;
        float toX = ((float) percent - 100.0f) / 100.0f;
        float fromX = toX - 0.1f;
        translate = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, fromX, Animation.RELATIVE_TO_PARENT, toX,
                Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f);
        translate.setDuration(500);
        translate.setInterpolator(new BounceInterpolator());

        set.addAnimation(alpha);
        set.addAnimation(translate);
        //         set.setDuration(500);
        set.setFillBefore(true);
        set.setFillAfter(true);

        textLayer.startAnimation(set);
    }

    public void progressFromThread(final int size, final int limit) {
        int rate;
        if (limit <= 0)
            rate = 10;
        else
            rate = (int) (size * 10 / limit);

        if (rate < 0)
            rate = 0;
        else if (rate > 10)
            rate = 10;

        final int percent = rate * 10;
        if (percent != this.lastPercent) {
            this.lastPercent = percent;
            this.handler.post(new Runnable() {
                public void run() {
                    showProgressBar(percent);
                }
            });
        }
    }

    // USER TIME LINE ----------------------------------//
    private boolean isKick(long now, long build) { // 10X: MORE THAN 10X MINUTES PASSED
        int passed;
        if (build > (now - 600)) {
            passed = 0; // 0 - 9
        } else if (build > (now - 1200)) {
            passed = 1; // 10 - 19
        } else if (build > (now - 1800)) {
            passed = 2; // 20 - 29  
        } else {
            passed = 3; // 30 -
        }

        if (passed > this.interval)
            return true;
        else
            return false;
    }

    private int calcFresh(long now, long build) { // X: MORE THAN X DAY PASSED
        if (build > (now - 86400)) {
            return 0;
        } else if (build > (now - 172800)) {
            return 1;
        } else if (build > (now - 259200)) {
            return 2;
        } else if (build > (now - 345600)) {
            return 3;
        } else if (build > (now - 432000)) {
            return 4;
        } else if (build > (now - 518400)) {
            return 5;
        } else if (build > (now - 604800)) {
            return 6;
        }
        return 7;
    }

    private Date str2Date(String str) {
        Date rtn;
        try {
            rtn = df.parse(str);
        } catch (java.text.ParseException e) {
            rtn = null;
        }
        return rtn;
    }

    public synchronized void endUtlXML(UtlFileIO status, String resMessage, final List<CUserTimeline> messageList,
            final int index, final String user_id) {
        boolean isContinue = true;
        switch (status) {
        case InterruptError:
            toastFormThread(Table.ERROR_INTERRUPTED + " while retrieving a tweet. (No. " + index + ")");
            isContinue = false;
            break;
        case HttpCodeError:
            toastFormThread(Table.ERROR_HTTP_CODE + " while retrieving a tweet. Http Response: " + resMessage
                    + "(No. " + index + ")");
            isContinue = false;
            break;
        case FileMalformedError:
            toastFormThread(Table.ERROR_MALFORMED_URL + " while retrieving a tweet. (No. " + index + ")");
            isContinue = false;
            break;
        case FileStateError:
            toastFormThread(Table.ERROR_ILLEGAL_STATE + " while retrieving a tweet. (No. " + index + ")");
            isContinue = false;
            break;
        case ClientProtocolError:
            toastFormThread(Table.ERROR_CLIENT_PROTOCOL + " while retrieving a tweet. (No. " + index + ")");
            isContinue = false;
            break;
        case FileIOError:
            toastFormThread(Table.ERROR_IO + " while retrieving a tweet. (No. " + index + ")");
            isContinue = false;
            break;
        case FileSAXError:
            toastFormThread(Table.ERROR_SAX + " while retrieving a tweet. (No. " + index + ")");
            isContinue = false;
            break;
        case FileCloserror:
            toastFormThread(Table.ERROR_FILE_CLOSE + " while retrieving a tweet. (No. " + index + ")");
            isContinue = false;
        }
        if (isContinue) {
            if (messageList == null) {
                toastFormThread(Table.ERROR_UTL_NULL + " (No. " + index + " with null)");
                isContinue = false;
            } else if (messageList.size() <= 0) {
                toastFormThread(Table.ERROR_UTL_NULL + " (No. " + index + " 0 tweet)");
                isContinue = false;
            }
        }

        // CONTINUE ----------------------------------- //
        if (isContinue) {
            // CALC FRESH
            Date build = str2Date(messageList.get(0).getDate());
            int fresh = 7;
            if (build != null) {
                buildCal.setTime(build);
                fresh = calcFresh(nowCal.getTimeInMillis() / 1000, buildCal.getTimeInMillis() / 1000);
            }

            String text = messageList.get(0).getText();
            String img = messageList.get(0).getImage(); //+"?time="+nowCal.getTimeInMillis();MAKE INSTANCE IN EVERY CONNECTION

            // PUT CITEM INTO LIST
            tweet.add(new CItem(index, fresh, text, img, user_id));
        }

        // KICK IMAGE REQUEST ------------------------- //
        if (!isContinue)
            this.idsLimit--;

        // PROGRESS END
        progressFromThread(tweet.size(), this.idsLimit);

        if ((tweet.size() >= this.idsLimit) && (this.idsLimit > 0)) {
            // SORT
            Collections.sort(tweet, new CItemComparator());

            // KICK IMAGELOAD
            kickImageLoad();

            // ENABLE OPTION
            this.isRunnable = true;
        }
    }

    private void kickImageLoad() {
        int viewsLimit = imageViews.length;
        if (viewsLimit > this.tweet.size())
            viewsLimit = this.tweet.size();
        for (int i = 0; i < viewsLimit; i++) {
            CItem nm = tweet.get(i);
            if (!nm.isLoad()) {
                nm.setLoad(true);
                CImageLoadRH imgLoad = new CImageLoadRH(this, nm.getImage(), i, nm.getFresh());
                imgLoad.start();
            }
        }
    }

    public void clearWarning() {
        TextView textLayer = (TextView) this.mRootView.findViewById(R.id.text_id);
        textLayer.setText("");
    }

    public void showWarning(String str) {
        // CLEAR (Warn) & TWEET
        clearTweet();

        TextView textLayer = (TextView) this.mRootView.findViewById(R.id.text_id);
        textLayer.setText(str);
    }

    public void toastFormThread(final String str) {
        this.handler.post(new Runnable() {
            public void run() {
                showWarning(str);
            }
        });
    }

    public synchronized void endIdsXML(IdsFileIO status, String resMessage, final List<CIds> messageList) {
        boolean isContinue = true;
        switch (status) {
        case InterruptError:
            toastFormThread(Table.ERROR_INTERRUPTED + " while searching friends.");
            isContinue = false;
            break;
        case HttpCodeError:
            if (resMessage.equalsIgnoreCase("not found")) {
                toastFormThread(
                        Table.ERROR_IDS_NOT_FOUND + " while searching friends. Http Response: " + resMessage);
            } else {
                toastFormThread(Table.ERROR_HTTP_CODE + " while searching friends. Http Response: " + resMessage);
            }
            isContinue = false;
            break;
        case FileMalformedError:
            toastFormThread(Table.ERROR_MALFORMED_URL + " while searching friends.");
            isContinue = false;
            break;
        case FileStateError:
            toastFormThread(Table.ERROR_ILLEGAL_STATE + " while searching friends.");
            isContinue = false;
            break;
        case ClientProtocolError:
            toastFormThread(Table.ERROR_CLIENT_PROTOCOL + " while searching friends.");
            isContinue = false;
            break;
        case FileIOError:
            toastFormThread(Table.ERROR_IO + " while searching friends.");
            isContinue = false;
            break;
        case FileSAXError:
            toastFormThread(Table.ERROR_SAX + " while searching friends.");
            isContinue = false;
            break;
        case FileCloserror:
            toastFormThread(Table.ERROR_FILE_CLOSE + " while searching friends.");
            isContinue = false;
        }
        if (isContinue) {
            if (messageList == null) {
                toastFormThread(Table.ERROR_IDS_NULL + " (null)");
                isContinue = false;
            }
            if (messageList.size() <= 0) {
                toastFormThread(Table.ERROR_IDS_NULL + " (0 friend)");
                isContinue = false;
            }
        }
        if (!isContinue) {
            // ENABLE OPTION
            this.isRunnable = true;

            // RESET LAST KICKED TIME
            this.lastKickedTime = 0;

            return;
        }

        // SHUFFLE
        Collections.shuffle(messageList);
        this.idsLimit = messageList.size();
        if (this.idsLimit > MAX_IDS)
            this.idsLimit = MAX_IDS;

        // KICK UTL REQUEST
        for (int i = 0; i < this.idsLimit; i++) {
            String id = messageList.get(i).getId();
            // OFTEN ERROR ?id="+id+"&count=2" 
            // NO IMG URL ?trim_user=true&id="+id
            // HUGE BUT NO ERROR ?id="+id
            String dstUrl;
            if (MODE_PROD) { // PROD
                if (this.isSecure)
                    dstUrl = "https://api.twitter.com/1/statuses/user_timeline.xml?user_id=" + id + "&count=1";
                else
                    dstUrl = "http://api.twitter.com/1/statuses/user_timeline.xml?user_id=" + id + "&count=1";
            } else { // DEMO
                if (this.isSecure)
                    dstUrl = "https://watasama.com/twiteyes/statuses/user_timeline" + i + ".xml";
                else
                    dstUrl = "http://watasama.com/twiteyes/statuses/user_timeline" + i + ".xml";
            }

            CUserTimelineXmlRH utlXml = new CUserTimelineXmlRH(this, dstUrl, i, id);
            utlXml.start();
        }
    }

    // EVENT ------------------------------------------ //
    private void kickIdsXML(boolean isFromOption) {
        // RESET CALENDAR 
        this.nowCal = Calendar.getInstance(Locale.ENGLISH);
        this.buildCal = Calendar.getInstance(Locale.ENGLISH);

        long nowTime = nowCal.getTimeInMillis() / 1000;
        //      this.lastKickedTime = 0;                  // DEMO
        if (isKick(nowTime, this.lastKickedTime)) {
            this.lastKickedTime = nowTime;
            this.lastPercent = 0;
        } else {
            // KICK IMAGELOAD
            //         kickImageLoad();

            // SHOW WARN
            if (isFromOption)
                showWarning(Table.WARN_INTERVAL);

            return;
        }

        // DISABLE OPTION
        this.isRunnable = false;

        // CLEAR WARNING
        clearWarning();

        // CLEAR TWEET
        clearTweet();

        // CLEAR IMAGE
        for (int i = 0; i < imageViews.length; i++) {
            ImageButton iButton = (ImageButton) this.mRootView.findViewById(imageViews[i]);
            iButton.setImageBitmap(null);
        }

        // CLEAR ITEM
        this.tweet.clear();

        // KICK IDS REQUEST
        String dstUrl;
        if (MODE_PROD) { // PROD
            if (this.isSecure)
                dstUrl = "https://api.twitter.com/1/friends/ids.xml?id=" + this.screenName + "&cursor=-1";
            else
                dstUrl = "http://api.twitter.com/1/friends/ids.xml?id=" + this.screenName + "&cursor=-1";
        } else { // DEMO
            if (this.isSecure)
                dstUrl = "https://watasama.com/twiteyes/friends/ids.xml";
            else
                dstUrl = "http://watasama.com/twiteyes/friends/ids.xml";
        }

        CIdsXmlRHandler idsXml = new CIdsXmlRHandler(this, dstUrl);
        idsXml.start();

    }

    public void clearTweet() {
        this.mAdapter.clear();
    }

    public void showTweet(final String str) {
        // CLEAR WARN & TWEET
        clearWarning();
        clearTweet();

        CharSequence styledText = Html.fromHtml(str);
        String text = styledText.toString();
        mAdapter.add(text);
    }

    private void getTweet(int key) {
        if (tweet.size() > key) {
            CItem nm = tweet.get(key);
            showTweet(nm.getText());
        }
    }

    // SET USER_IDAVE --------------------------------- //
    private void setUserId(int key) {
        if (tweet.size() > key) {
            CItem nm = tweet.get(key);
            this.screenName = nm.getUserId();
            Toast.makeText(this.mContext, "The user has changed.", Toast.LENGTH_SHORT).show();
        }
    }

    // SAVE LOAD -------------------------------------- //
    public void saveGame() {
        if (modeState == MODE_OPTION)
            return;

        int intSecure = (this.isSecure) ? 1 : 0;
        StringBuilder sb = new StringBuilder(Long.toString(this.lastKickedTime) + "<>" + urlEncode(this.screenName)
                + "<>" + this.interval + "<>" + intSecure + "<<>>");

        int viewsLimit = imageViews.length;
        if (viewsLimit > tweet.size())
            viewsLimit = tweet.size();
        for (int i = 0; i < viewsLimit; i++) {
            CItem nm = tweet.get(i);
            sb.append(Integer.toString(nm.getIndex()) + "<>" + nm.getFresh() + "<>" + urlEncode(nm.getText()) + "<>"
                    + urlEncode(nm.getImage()) + "<>" + urlEncode(nm.getUserId()) + "<<>>");

        }

        String str = sb.substring(0, sb.length() - 4);
        if (save("save.dat", str)) {
            showToast("Save has done to save.dat.");
        } else {
            showToast("Save has not done.");
        }
    }

    public boolean setData(String str) {
        String[] rows = str.split("<<>>");
        if (rows.length == 0)
            return false;

        String[] headCols = rows[0].split("<>");
        if (rows.length == 1) {
            this.screenName = urlDecode(headCols[1]);
            this.interval = Integer.parseInt(headCols[2]);
            this.isSecure = (Integer.parseInt(headCols[3]) == 1) ? true : false;

            return false;
        }

        boolean isContinue = true;

        this.lastKickedTime = Long.parseLong(headCols[0]);
        this.screenName = urlDecode(headCols[1]);
        this.interval = Integer.parseInt(headCols[2]);
        this.isSecure = (Integer.parseInt(headCols[3]) == 1) ? true : false;

        // CONTINUE
        if (isContinue) {
            int viewsLimit = imageViews.length;
            if (viewsLimit > (rows.length - 1))
                viewsLimit = rows.length - 1;
            for (int i = 0; i < viewsLimit; i++) {
                String[] cols = rows[i + 1].split("<>");
                if (cols.length < 4)
                    continue;

                int index = Integer.parseInt(cols[0]);
                int fresh = Integer.parseInt(cols[1]);
                String text = urlDecode(cols[2]);
                String img = urlDecode(cols[3]);
                String user_id = urlDecode(cols[4]);

                // PUT CITEM INTO LIST
                tweet.add(new CItem(index, fresh, text, img, user_id));

            }

        }

        return isContinue;
    }

    public void loadGame() {
        if (load("save.dat")) {
            showToast("Load has done from save.dat.");
        } else {
            showToast("Load has not done.");
        }
    }

    // SAVE LOAD PRIMITIVE
    public boolean save(String name, String data) {
        try {
            OutputStream out = this.mContext.openFileOutput(name, this.mContext.MODE_PRIVATE);
            PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, "UTF-8"));
            writer.append(data);
            writer.close();
        } catch (IOException e) {
            return false;
        }
        return true;
    }

    public boolean load(String name) {
        InputStream in;
        try {
            in = this.mContext.openFileInput(name);
        } catch (FileNotFoundException e) {
            return false;
        }
        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String s;
            while ((s = reader.readLine()) != null) {
                sb.append(s);
            }
            String str = sb.substring(0, sb.length());
            boolean rtn = setData(str);
            reader.close();

            return rtn;
        } catch (IOException e) {
            return false;
        }
    }

    // OPTION MENU ------------------------------------ //
    public boolean isSaveOK() {
        return this.isRunnable;
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        //       boolean result = super.onCreateOptionsMenu(menu);

        // OPTION
        MenuItem item0 = menu.add(0, MENU0_ID, Menu.NONE, R.string.menu0);
        item0.setIcon(R.drawable.home);

        // REFRESH
        MenuItem item1 = menu.add(0, MENU1_ID, Menu.NONE, R.string.menu1);
        item1.setIcon(R.drawable.cancel);
        //       return result;
        return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case MENU0_ID:
            if (isSaveOK()) {
                kickImageLevelActivity();
            }
            return true;
        case MENU1_ID:
            if (isSaveOK()) {
                kickAction(true);
            }
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    // IMAGE LEVEL ACTIVITY --------------------------- //
    private void setOutput(Intent data) {
        // TEXT OUTPUT
        this.screenName = data.getExtras().getString(ImageLevelActivity.TEXT_OUTPUT);
        if (this.screenName == null)
            this.screenName = "";

        // INT OUTPUT
        this.interval = data.getExtras().getInt(ImageLevelActivity.INT_OUTPUT, 0);

        // BOOLEAN OUTPUT
        this.isSecure = data.getExtras().getBoolean(ImageLevelActivity.BOOLEAN_OUTPUT, true);
    }

    public void tell(String str) {
        Toast.makeText(this.mContext, "return " + str, Toast.LENGTH_SHORT).show();
    }

    private void kickImageLevelActivity() {
        modeState = MODE_OPTION;
        Intent intent = new Intent(this.mContext, ImageLevelActivity.class);
        intent.putExtra(ImageLevelActivity.TEXT_INPUT, this.screenName);
        intent.putExtra(ImageLevelActivity.INT_INPUT, this.interval);
        intent.putExtra(ImageLevelActivity.BOOLEAN_INPUT, this.isSecure);

        startActivityForResult(intent, IMAGE_LEVEL_ACTIVITY);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == IMAGE_LEVEL_ACTIVITY) {
            if (resultCode != Activity.RESULT_OK) {
                Toast.makeText(this.mContext, "Canceled.", Toast.LENGTH_SHORT).show();
            } else {
                setOutput(data);
                int intSecure = (this.isSecure) ? 1 : 0;
                Toast.makeText(this.mContext, "Saved.", Toast.LENGTH_SHORT).show();
                showToast("sName " + this.screenName + " iT " + this.interval + " iS " + intSecure);
            }
            modeState = MODE_MAIN;
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    // COMMON ----------------------------------------- //
    public void showErrorLog(String str) {
        if (MODE_DEBUG)
            Log.e(TAG, str);
    }

    public void showToast(String str) {
        if (MODE_DEBUG)
            Toast.makeText(this.mContext, str, Toast.LENGTH_SHORT).show();
    }

    private String getFromArray(String string, int index) {
        String[] strings = string.split(" ");
        return strings[index];
    }

    private String urlEncode(String str) {
        if (str.length() == 0)
            return "";

        String inText;
        try {
            inText = URLEncoder.encode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            inText = "";
        }
        return inText;
    }

    private String urlDecode(String str) {
        if (str.length() == 0)
            return "";

        String inText;
        try {
            inText = URLDecoder.decode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            inText = "";
        }
        return inText;
    }

}