com.jwork.dhammapada.ChapterFragment.java Source code

Java tutorial

Introduction

Here is the source code for com.jwork.dhammapada.ChapterFragment.java

Source

/* ========================================================================
 * Copyright 2013 Jimmy Halim
 * Licensed under the Creative Commons Attribution-NonCommercial 3.0 license 
 * You may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://creativecommons.org/licenses/by-nc/3.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.jwork.dhammapada;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.jwork.dhammapada.controller.DhammapadaController;
import com.jwork.dhammapada.model.Chapter;
import com.jwork.dhammapada.model.DhammapadaContentProvider;
import com.jwork.dhammapada.model.DhammapadaContentProvider.TableChapter;
import com.jwork.dhammapada.utility.LogUtility;

public class ChapterFragment extends ListFragment implements LoaderCallbacks<Cursor>, OnClickListener {

    private LogUtility log = LogUtility.getInstance();

    private SimpleCursorAdapter mAdapter;
    private Controller controller;
    private View view;

    private static int LOADER_CHAPTER = 1;
    private static String[] LOADER_CHAPTER_PROJECTION = new String[] { DhammapadaContentProvider.TableChapter.ID,
            DhammapadaContentProvider.TableChapter.NO, DhammapadaContentProvider.TableChapter.TOTAL,
            DhammapadaContentProvider.TableChapter.START, DhammapadaContentProvider.TableChapter.END,
            DhammapadaContentProvider.TableChapter.TITLE_PALI, DhammapadaContentProvider.TableChapter.TITLE_ENG,
            DhammapadaContentProvider.TableChapter.TITLE_ID };

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        log.v(this, "onActivityCreated()");
        super.onActivityCreated(savedInstanceState);

        mAdapter = new CustomAdapter(getActivity(), R.layout.chapter_item, null,
                new String[] { DhammapadaContentProvider.TableChapter.TITLE_PALI,
                        DhammapadaContentProvider.TableChapter.TITLE_ID,
                        DhammapadaContentProvider.TableChapter.TITLE_ENG },
                new int[] { R.id.chapterItemPali, R.id.chapterItemId, R.id.chapterItemEng }, 0);
        setListAdapter(mAdapter);

        controller = new DhammapadaController(getActivity(), null);

        Bundle bundle = new Bundle();
        getLoaderManager().initLoader(LOADER_CHAPTER, bundle, this);

    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        log.d(this, "onCreateView()");

        view = inflater.inflate(R.layout.chapter_list, container, false);
        if (view == null) {
            log.w(this, "Problem inflating view, returned null");
            return null;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            final android.widget.SearchView svSearch = (android.widget.SearchView) view
                    .findViewById(R.id.sv_search);
            svSearch.setOnQueryTextListener(new android.widget.SearchView.OnQueryTextListener() {

                @Override
                public boolean onQueryTextSubmit(String query) {
                    InputMethodManager imm = (InputMethodManager) getActivity()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(svSearch.getWindowToken(), 0);
                    search(query);
                    return true;
                }

                @Override
                public boolean onQueryTextChange(String newText) {
                    return false;
                }
            });
        } else {
            ImageButton btnSearch = (ImageButton) view.findViewById(R.id.button_search);
            btnSearch.setOnClickListener(this);
            //           txtSearch = (EditText)view.findViewById(R.id.text_search);
            //           txtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            //              @Override
            //              public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            //                 if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            //                    search(v.getText());
            //                    return true;
            //                 }
            //                 return false;
            //              }
            //           });
        }
        return view;
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        log.v(this, "onCreateLoader(id:" + id + ")");
        Uri baseUri;
        baseUri = DhammapadaContentProvider.getChapterUri();
        return new CursorLoader(getActivity(), baseUri, LOADER_CHAPTER_PROJECTION, null, null, null);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        log.v(this, "onLoadFinished(data:" + data.getCount() + ")");
        mAdapter.swapCursor(data);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        log.v(this, "onLoaderReset()");
        mAdapter.swapCursor(null);
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        log.v(this, "onListItemClick(pos:" + position + "|id:" + id);
        Message message = Message.obtain();
        message.what = Constant.WHAT_SELECT_CHAPTER;
        message.obj = v.getTag();
        controller.executeMessage(message);
    }

    public static Fragment newInstance() {
        return new ChapterFragment();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
        //      SearchView searchView = new SearchView(getSherlockActivity().getSupportActionBar().getThemedContext());
        //        searchView.setQueryHint("Search for sutta");
        //        searchView.setOnQueryTextListener(this);
        //        searchView.setOnSuggestionListener(this);

        //        searchView.setSuggestionsAdapter(mSuggestionsAdapter);

        //        menu.add("Search")
        //            .setIcon(R.drawable.abs__ic_search)
        //            .setActionView(searchView)
        //            .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);

        //      SubMenu subMenu = menu.addSubMenu(Menu.NONE, 99, 99, null);
        //      
        //      inflater.inflate(R.menu.submenu_chapter, subMenu);
        //
        //       MenuItem subMenuItem = subMenu.getItem();
        //       subMenuItem.setIcon(R.drawable.ic_action_overflow);
        //       subMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        log.v(this, "onOptionsItemSelected(" + item.getItemId() + ")");
        switch (item.getItemId()) {
        case R.id.action_search:
            //         Toast.makeText(getActivity(), "Search", Toast.LENGTH_SHORT).show();
            break;
        case R.id.action_settings:
            Toast.makeText(getActivity(), "Setting", Toast.LENGTH_SHORT).show();
            break;
        case R.id.action_about:
            Toast.makeText(getActivity(), "About", Toast.LENGTH_SHORT).show();
            break;
        case 99:
            break;
        default:
            //         Toast.makeText(getActivity(), "Unknown", Toast.LENGTH_SHORT).show();
            break;
        }
        return true;
    }

    private static class CustomAdapter extends SimpleCursorAdapter {

        private LayoutInflater layoutInflater;
        private int layout;
        private Typeface tf;

        public CustomAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
            super(context, layout, c, from, to, flags);
            layoutInflater = LayoutInflater.from(context);
            this.layout = layout;
            tf = Typeface.createFromAsset(context.getAssets(), "fonts/arlrdbd.ttf");
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            View view = layoutInflater.inflate(layout, parent, false);

            Chapter holder = new Chapter();
            holder.setNo(cursor.getInt(cursor.getColumnIndex(TableChapter.NO)));
            holder.setStart(cursor.getInt(cursor.getColumnIndex(TableChapter.START)));
            holder.setEnd(cursor.getInt(cursor.getColumnIndex(TableChapter.END)));
            holder.setTotal(cursor.getInt(cursor.getColumnIndex(TableChapter.TOTAL)));
            holder.setTitlePali(cursor.getString(cursor.getColumnIndex(TableChapter.TITLE_PALI)));
            holder.setTitleEng(cursor.getString(cursor.getColumnIndex(TableChapter.TITLE_ENG)));
            holder.setTitleId(cursor.getString(cursor.getColumnIndex(TableChapter.TITLE_ID)));
            view.setTag(holder);

            return view;
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            Chapter holder = (Chapter) view.getTag();

            holder.setNo(cursor.getInt(cursor.getColumnIndex(TableChapter.NO)));
            holder.setStart(cursor.getInt(cursor.getColumnIndex(TableChapter.START)));
            holder.setEnd(cursor.getInt(cursor.getColumnIndex(TableChapter.END)));
            holder.setTotal(cursor.getInt(cursor.getColumnIndex(TableChapter.TOTAL)));
            holder.setTitlePali(cursor.getString(cursor.getColumnIndex(TableChapter.TITLE_PALI)));
            holder.setTitleEng(cursor.getString(cursor.getColumnIndex(TableChapter.TITLE_ENG)));
            holder.setTitleId(cursor.getString(cursor.getColumnIndex(TableChapter.TITLE_ID)));
            view.setTag(holder);

            TextView txtViewPali = (TextView) view.findViewById(R.id.chapterItemPali);
            TextView txtViewEng = (TextView) view.findViewById(R.id.chapterItemEng);
            TextView txtViewId = (TextView) view.findViewById(R.id.chapterItemId);

            txtViewPali.setTypeface(tf);
            txtViewEng.setTypeface(tf);
            txtViewId.setTypeface(tf);

            txtViewPali.setText(holder.getTitlePali());
            txtViewEng.setText(holder.getTitleEng());
            txtViewId.setText(holder.getTitleId());
        }

    }

    @Override
    public void onClick(View view) {
        log.v(this, "onClick(" + view.getId() + ")");

        //      if (view == btnSearch) {
        //         btnSearch.setVisibility(View.INVISIBLE);
        //         txtSearch.setVisibility(View.VISIBLE);
        //         txtSearch.requestFocus();
        //         InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        //         imm.showSoftInput(txtSearch, InputMethodManager.SHOW_IMPLICIT);
        //      }

        final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());

        alert.setTitle(getString(R.string.search));

        // Set an EditText view to get user input 
        final EditText input = new EditText(getActivity());
        alert.setView(input);

        alert.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                search(input.getText().toString());
            }
        });

        alert.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                dialog.dismiss();
            }
        });

        alert.show();
    }

    private void search(CharSequence query) {
        Message message = Message.obtain();
        message.what = Constant.WHAT_SEARCH_VERSE;
        message.obj = query;
        controller.executeMessage(message);
    }

    //   @Override
    //   public boolean onQueryTextSubmit(String query) {
    //      log.v(this, "onQueryTextSubmit("+query+")");
    //      Message message = Message.obtain();
    //      message.what = Constant.WHAT_SEARCH_VERSE;
    //      message.obj = query;
    //      controller.executeMessage(message);
    //      return false;
    //   }
    //
    //   @Override
    //   public boolean onQueryTextChange(String newText) {
    //      return false;
    //   }

}