ca.zadrox.dota2esportticker.ui.TeamSearchActivity.java Source code

Java tutorial

Introduction

Here is the source code for ca.zadrox.dota2esportticker.ui.TeamSearchActivity.java

Source

/*
 * Copyright 2014 Nicholas Liu
 *
 * 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 ca.zadrox.dota2esportticker.ui;

import android.app.LoaderManager;
import android.app.SearchManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.nispok.snackbar.Snackbar;
import com.squareup.picasso.Picasso;

import ca.zadrox.dota2esportticker.R;
import ca.zadrox.dota2esportticker.data.MatchContract;
import ca.zadrox.dota2esportticker.service.UpdateTeamsService;
import ca.zadrox.dota2esportticker.ui.widget.BezelImageView;
import ca.zadrox.dota2esportticker.ui.widget.CheckableImageButton;
import ca.zadrox.dota2esportticker.util.TeamFavHelper;

/**
 * Created by Acco on 12/3/2014.
 */
public class TeamSearchActivity extends BaseActivity {
    private static final String TAG = TeamSearchActivity.class.getSimpleName();

    private static final String KEY_QUERY = "query";

    private SearchView mSearchView;
    private ProgressBar mProgressBar;
    private ListView mListView;
    private SearchAdapter mAdapter;

    private Handler mHandler = new Handler();

    private String mQuery = null;

    private static final String[] PROJECTION = new String[] {
            MatchContract.TeamEntry.TABLE_NAME + "." + MatchContract.TeamEntry._ID,
            MatchContract.TeamEntry.COLUMN_TEAM_NAME, MatchContract.TeamEntry.COLUMN_TEAM_LOGO_URL,
            MatchContract.TeamEntry.COLUMN_TEAM_STARRED, };

    private static final int TEAM_ID = 0;
    private static final int TEAM_NAME = 1;
    private static final int TEAM_LOGO = 2;
    private static final int TEAM_FAV = 3;

    private static final int LOADER_ID = 0;

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

        setContentView(R.layout.activity_team_search);

        final Toolbar toolbar = getActionBarToolbar();
        toolbar.setNavigationIcon(R.drawable.ic_up);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        toolbar.setTitle("");

        if (savedInstanceState != null) {
            mQuery = savedInstanceState.getString(KEY_QUERY);
            getLoaderManager().initLoader(LOADER_ID, null, mLoaderCallbacks);
        }

        mProgressBar = (ProgressBar) findViewById(R.id.progress_search);
        mListView = (ListView) findViewById(R.id.list_results);
        mAdapter = new SearchAdapter(this, null, 0);

        mListView.setAdapter(mAdapter);

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putString(KEY_QUERY, mSearchView.getQuery().toString());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.team_search, menu);
        MenuItem searchItem = menu.findItem(R.id.action_search);
        Toolbar.LayoutParams params = new Toolbar.LayoutParams(Toolbar.LayoutParams.MATCH_PARENT,
                Toolbar.LayoutParams.MATCH_PARENT);

        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        mSearchView = (SearchView) searchItem.getActionView();
        mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

        mSearchView.setLayoutParams(params);
        mSearchView.setMaxWidth(getResources().getDisplayMetrics().widthPixels);

        mSearchView.setIconifiedByDefault(false);
        mSearchView.setQueryHint("Search");

        ImageView magImage = (ImageView) mSearchView.findViewById(R.id.search_mag_icon);
        magImage.setLayoutParams(new LinearLayout.LayoutParams(0, 0));

        final EditText editText = (AutoCompleteTextView) mSearchView.findViewById(R.id.search_src_text);
        editText.setHintTextColor(getResources().getColor(R.color.theme_primary_light));

        if (mQuery != null) {
            mSearchView.setQuery(mQuery, false);
        } else {
            mSearchView.requestFocus();
        }

        mSearchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
            @Override
            public boolean onSuggestionSelect(int i) {
                return onSuggestionClick(i);
            }

            @Override
            public boolean onSuggestionClick(int i) {
                Cursor c = (Cursor) mSearchView.getSuggestionsAdapter().getItem(i);
                mSearchView.setQuery(c.getString(1), true);
                mSearchView.clearFocus();

                return true;
            }
        });

        return true;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        Intent searchIntent = new Intent(UpdateTeamsService.ACTION_UPDATE_SEARCHED_TEAMS, null, this,
                UpdateTeamsService.class);

        searchIntent.putExtra(UpdateTeamsService.EXTRA_SEARCH_NAME, intent.getStringExtra(SearchManager.QUERY));

        mQuery = intent.getStringExtra(SearchManager.QUERY);

        startService(searchIntent);

    }

    @Override
    protected void onPause() {
        super.onPause();

        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
        localBroadcastManager.unregisterReceiver(mSearchReceiver);
    }

    @Override
    protected void onResume() {
        super.onResume();

        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UpdateTeamsService.STATUS_COMPLETED);
        intentFilter.addAction(UpdateTeamsService.STATUS_ERROR);
        intentFilter.addAction(UpdateTeamsService.STATUS_NO_CONNECTIVITY);
        intentFilter.addAction(UpdateTeamsService.STATUS_UPDATING);

        localBroadcastManager.registerReceiver(mSearchReceiver, intentFilter);
    }

    private BroadcastReceiver mSearchReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (action.equals(UpdateTeamsService.STATUS_COMPLETED)) {
                //showSnackbar("Finished search");
                mProgressBar.setVisibility(View.GONE);
                loadResultsFromDB();
            } else if (action.equals(UpdateTeamsService.STATUS_ERROR)) {
                showSnackbar("Error occurred - local results shown");
                mProgressBar.setVisibility(View.GONE);
                loadResultsFromDB();
            } else if (action.equals(UpdateTeamsService.STATUS_NO_CONNECTIVITY)) {
                showSnackbar("No connection - local results shown");
                mProgressBar.setVisibility(View.GONE);
                loadResultsFromDB();
            } else if (action.equals(UpdateTeamsService.STATUS_UPDATING)) {
                //showSnackbar("Searching");
                mProgressBar.setVisibility(View.VISIBLE);
            }
        }
    };

    private void showSnackbar(String text) {
        Snackbar.with(this).text(text).duration(Snackbar.SnackbarDuration.LENGTH_SHORT).show(this);
    }

    private void loadResultsFromDB() {
        getLoaderManager().restartLoader(LOADER_ID, null, mLoaderCallbacks);
    }

    private LoaderManager.LoaderCallbacks<Cursor> mLoaderCallbacks = new LoaderManager.LoaderCallbacks<Cursor>() {
        @Override
        public Loader<Cursor> onCreateLoader(int id, Bundle args) {

            String sortOrder = MatchContract.TeamEntry.COLUMN_TEAM_NAME + " ASC";

            return new CursorLoader(getApplicationContext(), MatchContract.TeamEntry.CONTENT_URI, PROJECTION,
                    MatchContract.TeamEntry.COLUMN_TEAM_NAME + " LIKE '%" + mQuery + "%'", null, sortOrder);
        }

        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
            mAdapter.swapCursor(data);
        }

        @Override
        public void onLoaderReset(Loader<Cursor> loader) {
            mAdapter.swapCursor(null);
        }
    };

    private class SearchAdapter extends CursorAdapter {

        private LayoutInflater mInflater = null;

        public SearchAdapter(Context context, Cursor c, int flags) {
            super(context, c, flags);

            mInflater = LayoutInflater.from(context);
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            View mView = mInflater.inflate(R.layout.listitem_team, parent, false);
            return mView;
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            String teamName = cursor.getString(TEAM_NAME);
            String teamLogo = cursor.getString(TEAM_LOGO);
            final long teamId = cursor.getLong(TEAM_ID);
            boolean teamFav = cursor.getInt(TEAM_FAV) > 0;

            TopTeamViewBinder vb = (TopTeamViewBinder) view.getTag();

            if (vb == null) {
                vb = new TopTeamViewBinder();
                vb.mTeamLogo = (BezelImageView) view.findViewById(R.id.listitem_team_logo);
                vb.mTeamName = (TextView) view.findViewById(R.id.listitem_team_name);
                vb.mTeamRank = (TextView) view.findViewById(R.id.listitem_team_rank);
                vb.mTeamFav = (CheckableImageButton) view.findViewById(R.id.listitem_team_fav);
                view.setTag(vb);
            }

            Picasso.with(context).load(teamLogo).into(vb.mTeamLogo);
            vb.mTeamName.setText(teamName);
            vb.mTeamRank.setVisibility(View.GONE);

            if (teamFav) {
                vb.mTeamFav.setImageResource(R.drawable.ic_starred_v16);
                vb.mTeamFav.setChecked(true);
            } else {
                vb.mTeamFav.setImageResource(R.drawable.ic_unstarred_v16);
                vb.mTeamFav.setChecked(false);
            }

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    CheckableImageButton imageButton = ((TopTeamViewBinder) v.getTag()).mTeamFav;

                    imageButton.toggle();

                    TeamFavHelper.setTeamStarred(getApplicationContext(), teamId, imageButton.isChecked());

                    if (imageButton.isChecked()) {
                        imageButton.setImageResource(R.drawable.ic_starred_v16);
                    } else {
                        imageButton.setImageResource(R.drawable.ic_unstarred_v16);
                    }
                }
            });

        }

        private class TopTeamViewBinder {
            public BezelImageView mTeamLogo;
            public TextView mTeamName;
            public TextView mTeamRank;
            public CheckableImageButton mTeamFav;
        }
    }
}