Java tutorial
/* * * * Copyright 2015 Van Shu * * * * 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.mobimvp.cliques.ui; import android.accounts.Account; import android.accounts.AccountManager; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ArgbEvaluator; import android.animation.ObjectAnimator; import android.animation.TypeEvaluator; import android.animation.ValueAnimator; import android.content.Intent; import android.graphics.Color; import android.graphics.Rect; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.provider.Settings; import android.support.v4.view.ViewCompat; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.animation.DecelerateInterpolator; import android.widget.AbsListView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.NetworkError; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.ServerError; import com.android.volley.TimeoutError; import com.android.volley.VolleyError; import com.google.android.gms.auth.GoogleAuthUtil; import com.mobimvp.cliques.R; import com.mobimvp.cliques.service.RequestManager; import com.mobimvp.cliques.ui.widgets.MultiSwipeRefreshLayout; import com.mobimvp.cliques.ui.widgets.ScrimInsetsScrollView; import com.mobimvp.cliques.util.AnalyticsManager; import com.mobimvp.cliques.util.HelpUtils; import com.mobimvp.cliques.util.LUtils; import com.mobimvp.cliques.util.RecentTasksStyler; import com.mobimvp.cliques.util.UIUtils; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import static com.mobimvp.cliques.util.LogUtils.LOGD; import static com.mobimvp.cliques.util.LogUtils.LOGW; import static com.mobimvp.cliques.util.LogUtils.makeLogTag; /** * A base activity that handles common functionality in the app. This includes the * navigation drawer, login and authentication, Action Bar tweaks, amongst others. */ public abstract class BaseActivity extends ActionBarActivity implements MultiSwipeRefreshLayout.CanChildScrollUpCallback { private static final String TAG = makeLogTag(BaseActivity.class); // Navigation drawer: private DrawerLayout mDrawerLayout; // Helper methods for L APIs private LUtils mLUtils; private ObjectAnimator mStatusBarColorAnimator; private ViewGroup mDrawerItemsListContainer; private Handler mHandler; // When set, these components will be shown/hidden in sync with the action bar // to implement the "quick recall" effect (the Action Bar and the header views disappear // when you scroll down a list, and reappear quickly when you scroll up). private ArrayList<View> mHideableHeaderViews = new ArrayList<>(); // Durations for certain animations we use: private static final int HEADER_HIDE_ANIM_DURATION = 300; protected static final int NAVDRAWER_ITEM_HOME = 0; protected static final int NAVDRAWER_ITEM_SHOTS = 1; protected static final int NAVDRAWER_ITEM_MY_PROFILE = 2; protected static final int NAVDRAWER_ITEM_SETTINGS = 6; protected static final int NAVDRAWER_ITEM_INVALID = -1; protected static final int NAVDRAWER_ITEM_SEPARATOR = -2; protected static final int NAVDRAWER_ITEM_SEPARATOR_SPECIAL = -3; private static final int[] NAVDRAWER_TITLE_RES_ID = new int[] { R.string.navdrawer_item_home, R.string.navdrawer_item_shots, R.string.navdrawer_item_my_profile, R.string.navdrawer_item_social, R.string.navdrawer_item_video_library, R.string.navdrawer_item_sign_in, R.string.navdrawer_item_settings, R.string.navdrawer_item_experts_directory, R.string.navdrawer_item_people_ive_met }; // icons for navdrawer items (indices must correspond to above array) private static final int[] NAVDRAWER_ICON_RES_ID = new int[] { R.drawable.ic_launcher, R.drawable.ic_launcher, R.drawable.ic_launcher, R.drawable.ic_launcher, R.drawable.ic_launcher, 0, // Sign in R.drawable.ic_drawer_settings, R.drawable.ic_launcher, R.drawable.ic_launcher, }; // delay to launch nav drawer item, to allow close animation to play private static final int NAVDRAWER_LAUNCH_DELAY = 250; // fade in and fade out durations for the main content when switching between // different Activities of the app through the Nav Drawer private static final int MAIN_CONTENT_FADEOUT_DURATION = 150; private static final int MAIN_CONTENT_FADEIN_DURATION = 250; private ArrayList<Integer> mNavDrawerItems = new ArrayList<>(); // views that correspond to each navdrawer item, null if not yet created private View[] mNavDrawerItemViews = null; // SwipeRefreshLayout allows the user to swipe the screen down to trigger a manual refresh private SwipeRefreshLayout mSwipeRefreshLayout; // Primary toolbar and drawer toggle private Toolbar mActionBarToolbar; // variables that control the Action Bar auto hide behavior (aka "quick recall") private boolean mActionBarAutoHideEnabled = false; private int mActionBarAutoHideSensivity = 0; private int mActionBarAutoHideMinY = 0; private int mActionBarAutoHideSignal = 0; private boolean mActionBarShown = true; // A Runnable that we should execute when the navigation drawer finishes its closing animation private Runnable mDeferredOnDrawerClosedRunnable; private int mThemedStatusBarColor; private int mNormalStatusBarColor; private int mProgressBarTopWhenActionBarShown; private static final TypeEvaluator ARGB_EVALUATOR = new ArgbEvaluator(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); AnalyticsManager.initializeAnalyticsTracker(getApplicationContext()); RecentTasksStyler.styleRecentTasksEntry(this); mHandler = new Handler(); ActionBar ab = getSupportActionBar(); if (ab != null) { ab.setDisplayHomeAsUpEnabled(true); } mLUtils = LUtils.getInstance(this); mThemedStatusBarColor = getResources().getColor(R.color.theme_primary_dark); mNormalStatusBarColor = mThemedStatusBarColor; } private void trySetupSwipeRefresh() { mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout); if (mSwipeRefreshLayout != null) { mSwipeRefreshLayout.setColorSchemeResources(R.color.refresh_progress_1, R.color.refresh_progress_2, R.color.refresh_progress_3); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { requestDataRefresh(); } }); if (mSwipeRefreshLayout instanceof MultiSwipeRefreshLayout) { MultiSwipeRefreshLayout mswrl = (MultiSwipeRefreshLayout) mSwipeRefreshLayout; mswrl.setCanChildScrollUpCallback(this); } } } protected void setProgressBarTopWhenActionBarShown(int progressBarTopWhenActionBarShown) { mProgressBarTopWhenActionBarShown = progressBarTopWhenActionBarShown; updateSwipeRefreshProgressBarTop(); } private void updateSwipeRefreshProgressBarTop() { if (mSwipeRefreshLayout == null) { return; } int progressBarStartMargin = getResources() .getDimensionPixelSize(R.dimen.swipe_refresh_progress_bar_start_margin); int progressBarEndMargin = getResources() .getDimensionPixelSize(R.dimen.swipe_refresh_progress_bar_end_margin); int top = mActionBarShown ? mProgressBarTopWhenActionBarShown : 0; mSwipeRefreshLayout.setProgressViewOffset(false, top + progressBarStartMargin, top + progressBarEndMargin); } /** * Returns the navigation drawer item that corresponds to this Activity. Subclasses * of BaseActivity override this to indicate what nav drawer item corresponds to them * Return NAVDRAWER_ITEM_INVALID to mean that this Activity should not have a Nav Drawer. */ protected int getSelfNavDrawerItem() { return NAVDRAWER_ITEM_INVALID; } /** * Sets up the navigation drawer as appropriate. Note that the nav drawer will be * different depending on whether the attendee indicated that they are attending the * event on-site vs. attending remotely. */ private void setupNavDrawer() { // What nav drawer item should be selected? int selfItem = getSelfNavDrawerItem(); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); if (mDrawerLayout == null) { return; } mDrawerLayout.setStatusBarBackgroundColor(getResources().getColor(R.color.theme_primary_dark)); ScrimInsetsScrollView navDrawer = (ScrimInsetsScrollView) mDrawerLayout.findViewById(R.id.navdrawer); if (selfItem == NAVDRAWER_ITEM_INVALID) { // do not show a nav drawer if (navDrawer != null) { ((ViewGroup) navDrawer.getParent()).removeView(navDrawer); } mDrawerLayout = null; return; } if (navDrawer != null) { final View chosenAccountContentView = findViewById(R.id.chosen_account_content_view); final View chosenAccountView = findViewById(R.id.chosen_account_view); final int navDrawerChosenAccountHeight = getResources() .getDimensionPixelSize(R.dimen.navdrawer_chosen_account_height); navDrawer.setOnInsetsCallback(new ScrimInsetsScrollView.OnInsetsCallback() { @Override public void onInsetsChanged(Rect insets) { ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) chosenAccountContentView .getLayoutParams(); lp.topMargin = insets.top; chosenAccountContentView.setLayoutParams(lp); ViewGroup.LayoutParams lp2 = chosenAccountView.getLayoutParams(); lp2.height = navDrawerChosenAccountHeight + insets.top; chosenAccountView.setLayoutParams(lp2); } }); } if (mActionBarToolbar != null) { mActionBarToolbar.setNavigationIcon(R.drawable.ic_drawer); mActionBarToolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mDrawerLayout.openDrawer(Gravity.START); } }); } mDrawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() { @Override public void onDrawerClosed(View drawerView) { // run deferred action, if we have one if (mDeferredOnDrawerClosedRunnable != null) { mDeferredOnDrawerClosedRunnable.run(); mDeferredOnDrawerClosedRunnable = null; } onNavDrawerStateChanged(false, false); } @Override public void onDrawerOpened(View drawerView) { onNavDrawerStateChanged(true, false); } @Override public void onDrawerStateChanged(int newState) { onNavDrawerStateChanged(isNavDrawerOpen(), newState != DrawerLayout.STATE_IDLE); } @Override public void onDrawerSlide(View drawerView, float slideOffset) { onNavDrawerSlide(slideOffset); } }); mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.START); // populate the nav drawer with the correct items populateNavDrawer(); } @Override public void setContentView(int layoutResID) { super.setContentView(layoutResID); getActionBarToolbar(); } // Subclasses can override this for custom behavior protected void onNavDrawerStateChanged(boolean isOpen, boolean isAnimating) { if (mActionBarAutoHideEnabled && isOpen) { autoShowOrHideActionBar(true); } } protected void onNavDrawerSlide(float offset) { } protected boolean isNavDrawerOpen() { return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(Gravity.START); } protected void closeNavDrawer() { if (mDrawerLayout != null) { mDrawerLayout.closeDrawer(Gravity.START); } } /** Populates the navigation drawer with the appropriate items. */ private void populateNavDrawer() { mNavDrawerItems.clear(); mNavDrawerItems.add(NAVDRAWER_ITEM_HOME); mNavDrawerItems.add(NAVDRAWER_ITEM_SHOTS); mNavDrawerItems.add(NAVDRAWER_ITEM_MY_PROFILE); mNavDrawerItems.add(NAVDRAWER_ITEM_SEPARATOR); mNavDrawerItems.add(NAVDRAWER_ITEM_SETTINGS); createNavDrawerItems(); } @Override public void onBackPressed() { if (isNavDrawerOpen()) { closeNavDrawer(); } else { super.onBackPressed(); } } private void createNavDrawerItems() { mDrawerItemsListContainer = (ViewGroup) findViewById(R.id.navdrawer_items_list); if (mDrawerItemsListContainer == null) { return; } mNavDrawerItemViews = new View[mNavDrawerItems.size()]; mDrawerItemsListContainer.removeAllViews(); int i = 0; for (int itemId : mNavDrawerItems) { mNavDrawerItemViews[i] = makeNavDrawerItem(itemId, mDrawerItemsListContainer); mDrawerItemsListContainer.addView(mNavDrawerItemViews[i]); ++i; } } /** * Sets up the given navdrawer item's appearance to the selected state. Note: this could * also be accomplished (perhaps more cleanly) with state-based layouts. */ private void setSelectedNavDrawerItem(int itemId) { if (mNavDrawerItemViews != null) { for (int i = 0; i < mNavDrawerItemViews.length; i++) { if (i < mNavDrawerItems.size()) { int thisItemId = mNavDrawerItems.get(i); formatNavDrawerItem(mNavDrawerItemViews[i], thisItemId, itemId == thisItemId); } } } } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); setupNavDrawer(); trySetupSwipeRefresh(); updateSwipeRefreshProgressBarTop(); View mainContent = findViewById(R.id.main_content); if (mainContent != null) { mainContent.setAlpha(0); mainContent.animate().alpha(1).setDuration(MAIN_CONTENT_FADEIN_DURATION); } else { LOGW(TAG, "No view with ID main_content to fade in."); } } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.menu_about: HelpUtils.showAbout(this); return true; } return super.onOptionsItemSelected(item); } protected void requestDataRefresh() { } private void goToNavDrawerItem(int item) { Intent intent; switch (item) { case NAVDRAWER_ITEM_HOME: intent = new Intent(this, HomeActivity.class); startActivity(intent); finish(); break; case NAVDRAWER_ITEM_SHOTS: intent = new Intent(this, ShotsActivity.class); startActivity(intent); finish(); break; case NAVDRAWER_ITEM_MY_PROFILE: intent = new Intent(this, ProfileActivity.class); startActivity(intent); break; case NAVDRAWER_ITEM_SETTINGS: intent = new Intent(this, SettingsActivity.class); startActivity(intent); break; } } private void onNavDrawerItemClicked(final int itemId) { if (itemId == getSelfNavDrawerItem()) { mDrawerLayout.closeDrawer(Gravity.START); return; } if (isSpecialItem(itemId)) { goToNavDrawerItem(itemId); } else { // launch the target Activity after a short delay, to allow the close animation to play mHandler.postDelayed(new Runnable() { @Override public void run() { goToNavDrawerItem(itemId); } }, NAVDRAWER_LAUNCH_DELAY); // change the active item on the list so the user can see the item changed setSelectedNavDrawerItem(itemId); // fade out the main content View mainContent = findViewById(R.id.main_content); if (mainContent != null) { mainContent.animate().alpha(0).setDuration(MAIN_CONTENT_FADEOUT_DURATION); } } mDrawerLayout.closeDrawer(Gravity.START); } @Override protected void onResume() { super.onResume(); } @Override protected void onPause() { super.onPause(); } /** * Converts an intent into a {@link Bundle} suitable for use as fragment arguments. */ public static Bundle intentToFragmentArguments(Intent intent) { Bundle arguments = new Bundle(); if (intent == null) { return arguments; } final Uri data = intent.getData(); if (data != null) { arguments.putParcelable("_uri", data); } final Bundle extras = intent.getExtras(); if (extras != null) { arguments.putAll(intent.getExtras()); } return arguments; } @Override public void onStart() { super.onStart(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { } @Override public void onStop() { super.onStop(); } /** * Initializes the Action Bar auto-hide (aka Quick Recall) effect. */ private void initActionBarAutoHide() { mActionBarAutoHideEnabled = true; mActionBarAutoHideMinY = getResources().getDimensionPixelSize(R.dimen.action_bar_auto_hide_min_y); mActionBarAutoHideSensivity = getResources().getDimensionPixelSize(R.dimen.action_bar_auto_hide_sensivity); } /** * Indicates that the main content has scrolled (for the purposes of showing/hiding * the action bar for the "action bar auto hide" effect). currentY and deltaY may be exact * (if the underlying view supports it) or may be approximate indications: * deltaY may be INT_MAX to mean "scrolled forward indeterminately" and INT_MIN to mean * "scrolled backward indeterminately". currentY may be 0 to mean "somewhere close to the * start of the list" and INT_MAX to mean "we don't know, but not at the start of the list" */ private void onMainContentScrolled(int currentY, int deltaY) { if (deltaY > mActionBarAutoHideSensivity) { deltaY = mActionBarAutoHideSensivity; } else if (deltaY < -mActionBarAutoHideSensivity) { deltaY = -mActionBarAutoHideSensivity; } if (Math.signum(deltaY) * Math.signum(mActionBarAutoHideSignal) < 0) { // deltaY is a motion opposite to the accumulated signal, so reset signal mActionBarAutoHideSignal = deltaY; } else { // add to accumulated signal mActionBarAutoHideSignal += deltaY; } boolean shouldShow = currentY < mActionBarAutoHideMinY || (mActionBarAutoHideSignal <= -mActionBarAutoHideSensivity); autoShowOrHideActionBar(shouldShow); } protected Toolbar getActionBarToolbar() { if (mActionBarToolbar == null) { mActionBarToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar); if (mActionBarToolbar != null) { setSupportActionBar(mActionBarToolbar); } } return mActionBarToolbar; } protected void autoShowOrHideActionBar(boolean show) { if (show == mActionBarShown) { return; } mActionBarShown = show; onActionBarAutoShowOrHide(show); } protected void enableActionBarAutoHide(final ListView listView) { initActionBarAutoHide(); listView.setOnScrollListener(new AbsListView.OnScrollListener() { final static int ITEMS_THRESHOLD = 3; int lastFvi = 0; @Override public void onScrollStateChanged(AbsListView view, int scrollState) { } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { onMainContentScrolled(firstVisibleItem <= ITEMS_THRESHOLD ? 0 : Integer.MAX_VALUE, lastFvi - firstVisibleItem > 0 ? Integer.MIN_VALUE : lastFvi == firstVisibleItem ? 0 : Integer.MAX_VALUE); lastFvi = firstVisibleItem; } }); } private View makeNavDrawerItem(final int itemId, ViewGroup container) { boolean selected = getSelfNavDrawerItem() == itemId; int layoutToInflate = 0; if (itemId == NAVDRAWER_ITEM_SEPARATOR) { layoutToInflate = R.layout.navdrawer_separator; } else if (itemId == NAVDRAWER_ITEM_SEPARATOR_SPECIAL) { layoutToInflate = R.layout.navdrawer_separator; } else { layoutToInflate = R.layout.navdrawer_item; } View view = getLayoutInflater().inflate(layoutToInflate, container, false); if (isSeparator(itemId)) { // we are done UIUtils.setAccessibilityIgnore(view); return view; } ImageView iconView = (ImageView) view.findViewById(R.id.icon); TextView titleView = (TextView) view.findViewById(R.id.title); int iconId = itemId >= 0 && itemId < NAVDRAWER_ICON_RES_ID.length ? NAVDRAWER_ICON_RES_ID[itemId] : 0; int titleId = itemId >= 0 && itemId < NAVDRAWER_TITLE_RES_ID.length ? NAVDRAWER_TITLE_RES_ID[itemId] : 0; // set icon and text iconView.setVisibility(iconId > 0 ? View.VISIBLE : View.GONE); if (iconId > 0) { iconView.setImageResource(iconId); } titleView.setText(getString(titleId)); formatNavDrawerItem(view, itemId, selected); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onNavDrawerItemClicked(itemId); } }); return view; } private boolean isSpecialItem(int itemId) { return itemId == NAVDRAWER_ITEM_SETTINGS || itemId == NAVDRAWER_ITEM_MY_PROFILE; } private boolean isSeparator(int itemId) { return itemId == NAVDRAWER_ITEM_SEPARATOR || itemId == NAVDRAWER_ITEM_SEPARATOR_SPECIAL; } private void formatNavDrawerItem(View view, int itemId, boolean selected) { if (isSeparator(itemId)) { // not applicable return; } ImageView iconView = (ImageView) view.findViewById(R.id.icon); TextView titleView = (TextView) view.findViewById(R.id.title); if (selected) { view.setBackgroundResource(R.drawable.selected_navdrawer_item_background); } // configure its appearance according to whether or not it's selected titleView.setTextColor(selected ? getResources().getColor(R.color.navdrawer_text_color_selected) : getResources().getColor(R.color.navdrawer_text_color)); iconView.setColorFilter(selected ? getResources().getColor(R.color.navdrawer_icon_tint_selected) : getResources().getColor(R.color.navdrawer_icon_tint)); } @Override protected void onDestroy() { super.onDestroy(); } protected void onRefreshingStateChanged(boolean refreshing) { if (mSwipeRefreshLayout != null) { mSwipeRefreshLayout.setRefreshing(refreshing); } } protected void enableDisableSwipeRefresh(boolean enable) { if (mSwipeRefreshLayout != null) { mSwipeRefreshLayout.setEnabled(enable); } } protected void registerHideableHeaderView(View hideableHeaderView) { if (!mHideableHeaderViews.contains(hideableHeaderView)) { mHideableHeaderViews.add(hideableHeaderView); } } protected void deregisterHideableHeaderView(View hideableHeaderView) { if (mHideableHeaderViews.contains(hideableHeaderView)) { mHideableHeaderViews.remove(hideableHeaderView); } } public LUtils getLUtils() { return mLUtils; } public int getThemedStatusBarColor() { return mThemedStatusBarColor; } public void setNormalStatusBarColor(int color) { mNormalStatusBarColor = color; if (mDrawerLayout != null) { mDrawerLayout.setStatusBarBackgroundColor(mNormalStatusBarColor); } } protected void onActionBarAutoShowOrHide(boolean shown) { if (mStatusBarColorAnimator != null) { mStatusBarColorAnimator.cancel(); } mStatusBarColorAnimator = ObjectAnimator .ofInt((mDrawerLayout != null) ? mDrawerLayout : mLUtils, (mDrawerLayout != null) ? "statusBarBackgroundColor" : "statusBarColor", shown ? Color.BLACK : mNormalStatusBarColor, shown ? mNormalStatusBarColor : Color.BLACK) .setDuration(250); if (mDrawerLayout != null) { mStatusBarColorAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { ViewCompat.postInvalidateOnAnimation(mDrawerLayout); } }); } mStatusBarColorAnimator.setEvaluator(ARGB_EVALUATOR); mStatusBarColorAnimator.start(); updateSwipeRefreshProgressBarTop(); for (View view : mHideableHeaderViews) { if (shown) { view.animate().translationY(0).alpha(1).setDuration(HEADER_HIDE_ANIM_DURATION) .setInterpolator(new DecelerateInterpolator()); } else { view.animate().translationY(-view.getBottom()).alpha(0).setDuration(HEADER_HIDE_ANIM_DURATION) .setInterpolator(new DecelerateInterpolator()); } } } @Override public boolean canSwipeRefreshChildScrollUp() { return false; } public Response.ErrorListener errorListener = new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if (error instanceof ParseError) { Toast.makeText(getApplicationContext(), "Parsing error " + error.getMessage(), Toast.LENGTH_SHORT) .show(); } else if (error instanceof NetworkError) { Toast.makeText(getApplicationContext(), "Check your connection and try again " + error.getMessage(), Toast.LENGTH_SHORT).show(); } else if (error instanceof ServerError) { try { Toast.makeText(getApplicationContext(), "Server error.Response code is : " + error.networkResponse.statusCode + ", : " + new String(error.networkResponse.data, "UTF-8"), Toast.LENGTH_SHORT).show(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else if (error instanceof TimeoutError) { Toast.makeText(getApplicationContext(), "Connection times out and try again", Toast.LENGTH_SHORT) .show(); } else { Toast.makeText(getApplicationContext(), "Unknown error " + error.getMessage(), Toast.LENGTH_SHORT) .show(); } } }; protected void addRequest(Request request) { RequestManager.addRequest(request, this); } }