Java tutorial
/* * Copyright (C) 2011 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.vanisty.ui; import java.io.File; import java.util.ArrayList; import java.util.Calendar; import android.app.Activity; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.graphics.BitmapFactory; import android.graphics.Point; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.DatePicker; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.TableRow; import android.widget.Toast; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockFragment; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.view.Window; import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache; import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator; import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.download.URLConnectionImageDownloader; import com.nostra13.universalimageloader.utils.StorageUtils; import com.socialize.Socialize; import com.socialize.api.SocializeSession; import com.socialize.error.SocializeException; import com.socialize.listener.SocializeAuthListener; import com.socialize.networks.facebook.FacebookUtils; import com.vanisty.R; import com.vanisty.event.EventManager; import com.vanisty.maps.Navigation; import com.vanisty.ui.splash.SplashLoadingActivity; import com.vanisty.utilities.FacebookSession; import com.vanisty.utilities.FontUtils; import com.vanisty.utilities.User; public class MenuActivity extends SherlockFragmentActivity implements ActionBar.TabListener, AnimationLayout.Listener { public static ArrayList<SherlockFragment> fragments = new ArrayList<SherlockFragment>(); private boolean useLogo = true; private boolean showHomeUp = false; EventManager em; GridFragment grid; MapFragment map; FriendsEventsFragment friends; EventlistContainerFragment evlist_container; FragmentTransaction ft; ActionBar ab; ActionBar.Tab tab1; ActionBar.Tab tab2; ActionBar.Tab tab3; ActionBar.Tab tab4; ActionBar.Tab tab5; ImageLoader imageLoader; User user = User.getInstance(); protected AnimationLayout mLayout; MenuItem refresh; String displayedDate = "Today"; //List Fragments: //EventlistFragment eventlistFragment = EventlistFragment.getInstance(getEventManager().getBufferedEvents(), getEventManager().getCompleteEvents()); //EventlistFragment eventlistFragment; //DatePicker Stuff static int pYear; static int pMonth; static int pDay; /** This integer will uniquely define the dialog to be used for displaying date picker.*/ static final int DATE_DIALOG_ID = 0; /** Callback received when the user "picks" a date in the dialog */ private DatePickerDialog.OnDateSetListener pDateSetListener = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { pYear = year; pMonth = monthOfYear; pDay = dayOfMonth; /* if (evlist_time != null) { evlist_time.changeDate(); displayedDate = pDay + "." + pMonth + "." + pYear; listPagerAdapter.notifyDataSetChanged(); } */ //updateDisplay(); //displayToast(); } }; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Initialize socialize //Socialize.onCreate(this, savedInstanceState); Socialize.initAsync(this); connectSocialize(); //ConfigUtils.getConfig(this).setProperty(SocializeConfig.SOCIALIZE_EVENTS_AUTH_ENABLED, "false"); //ConfigUtils.getConfig(this).setProperty(SocializeConfig.SOCIALIZE_EVENTS_SHARE_ENABLED, "false"); //Request Progress Spinner for ActionBar must be done first requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.menu_activity); //Sidebar stuff mLayout = (AnimationLayout) findViewById(R.id.root); mLayout.setListener(this); mLayout.closeSidebar(); TableRow settings = (TableRow) findViewById(R.id.settings); settings.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { user.showUserSettings(MenuActivity.this); } }); TableRow userEvents = (TableRow) findViewById(R.id.sideEvents); userEvents.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showUserActivity("events"); } }); TableRow userLocations = (TableRow) findViewById(R.id.sideLocations); userLocations.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showUserActivity("locations"); } }); TableRow userAddress = (TableRow) findViewById(R.id.sideCity); userAddress.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showAdressChangeDialog(); } }); //Temporary set current location to home location. overwritten when Location listener gets result try { user.getCurrentLocation().setCity(user.getHomeLocation().getCity()); user.getCurrentLocation().setCountry(user.getHomeLocation().getCountry()); } catch (Exception ex) { ex.printStackTrace(); } //Get Location Data Async. There may be no result Navigation.getGpsData(this); //Navigation.getGpsData(this); //Apply roboto font to all view children FontUtils.setRobotoFont(this.getApplicationContext(), findViewById(R.id.root)); //initialize image loader initializeImageLoader(); ab = getSupportActionBar(); BitmapDrawable background = new BitmapDrawable( BitmapFactory.decodeResource(getResources(), R.drawable.ab_solid_vanisty)); ab.setBackgroundDrawable(background); //Set Progress Spinner visibility false after ActionBar was created showProgress(false); // set defaults for logo & home up ab.setDisplayHomeAsUpEnabled(showHomeUp); ab.setLogo(R.drawable.logo_white); ab.setDisplayUseLogoEnabled(useLogo); //set up tabs tab1 = ab.newTab().setTabListener(this); tab1.setIcon(R.drawable.list); ab.addTab(tab1); tab5 = ab.newTab().setTabListener(this); tab5.setIcon(R.drawable.friends); ab.addTab(tab5); tab2 = ab.newTab().setTabListener(this); tab2.setIcon(R.drawable.discover); ab.addTab(tab2); tab3 = ab.newTab().setTabListener(this); tab3.setIcon(R.drawable.compass); ab.addTab(tab3); tab4 = ab.newTab().setTabListener(this); tab4.setIcon(R.drawable.users); ab.addTab(tab4); // default to tab navigation showTabsNav(); em = getEventManager(); showEventlistContainerFragment(); //showGridFragment(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK)) { finish(); } return super.onKeyDown(keyCode, event); } @Override protected void onPause() { super.onPause(); Socialize.onPause(this); } @Override protected void onResume() { super.onResume(); Socialize.onResume(this); } @Override protected void onRestart() { super.onRestart(); } void connectSocialize() { // The "this" argument refers to the current Activity FacebookUtils.link(this, FacebookSession.getSession().getAccessToken(), true, new SocializeAuthListener() { @Override public void onCancel() { // The user cancelled the operation. } @Override public void onAuthSuccess(SocializeSession session) { try { } catch (Exception ex) { } } @Override public void onAuthFail(SocializeException error) { // Handle error } @Override public void onError(SocializeException error) { // Handle error } }); } /* * initializes a singleton instance of the global image loader and sets configurations */ public void initializeImageLoader() { File cacheDir = StorageUtils.getOwnCacheDirectory(getApplicationContext(), "Eventproject/Cache"); // Get singletone instance of ImageLoader imageLoader = ImageLoader.getInstance(); // Create configuration for ImageLoader (all options are optional, use only those you really want to customize) ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()) .memoryCacheExtraOptions(480, 800) // max width, max height .threadPoolSize(3).threadPriority(Thread.NORM_PRIORITY - 1).denyCacheImageMultipleSizesInMemory() .offOutOfMemoryHandling().memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) // You can pass your own memory cache implementation .discCache(new UnlimitedDiscCache(cacheDir)) // You can pass your own disc cache implementation .discCacheFileNameGenerator(new HashCodeFileNameGenerator()) .imageDownloader(new URLConnectionImageDownloader(8 * 1000, 20 * 1000)) // connectTimeout (8 s), readTimeout (20 s) .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) //.enableLogging() .build(); // Initialize ImageLoader with created configuration. Do it once on Application start. imageLoader.init(config); } public void showProgress(boolean showprogress) { getSherlock().setProgressBarIndeterminateVisibility(showprogress); } public void showGridFragment() { mLayout.closeSidebar(); //mViewPager.setVisibility(View.GONE); if (refresh != null) refresh.setVisible(true); if (grid == null) grid = GridFragment.getInstance(getEventManager().getBufferedDiscoverEvents(), getEventManager().getCompleteDiscoverEvents()); ft = getSupportFragmentManager().beginTransaction(); ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out); // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack ft.replace(R.id.animation_layout_content, grid); ft.addToBackStack(null); ab.selectTab(tab2); // Commit the transaction ft.commit(); } public void showFriendsEventsFragment() { mLayout.closeSidebar(); //mViewPager.setVisibility(View.GONE); if (refresh != null) refresh.setVisible(false); if (friends == null) friends = FriendsEventsFragment.getInstance(getEventManager().getBufferedFriendEvents(), getEventManager().getCompleteFriendEvents()); ft = getSupportFragmentManager().beginTransaction(); ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out); // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack ft.replace(R.id.animation_layout_content, friends); ft.addToBackStack(null); ab.selectTab(tab5); // Commit the transaction ft.commit(); } public void showEventlistContainerFragment() { mLayout.closeSidebar(); //mViewPager.setVisibility(View.GONE); if (refresh != null) refresh.setVisible(false); if (evlist_container == null) evlist_container = new EventlistContainerFragment(); ft = getSupportFragmentManager().beginTransaction(); ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out); // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack ft.replace(R.id.animation_layout_content, evlist_container); ft.addToBackStack(null); ab.selectTab(tab1); // Commit the transaction ft.commit(); } public void showMapFragment() { mLayout.closeSidebar(); //mViewPager.setVisibility(View.GONE); if (refresh != null) refresh.setVisible(false); if (map == null) map = new MapFragment(); ft = getSupportFragmentManager().beginTransaction(); ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out); // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack ft.replace(R.id.animation_layout_content, map); ft.addToBackStack(null); ab.selectTab(tab3); // Commit the transaction ft.commit(); } public void showDatePicker() { /* * shows a date picker dialog * protected Dialog onCreateDialog(int id) is called * */ /** Get the current date */ final Calendar cal = Calendar.getInstance(); pYear = cal.get(Calendar.YEAR); pMonth = cal.get(Calendar.MONTH); pDay = cal.get(Calendar.DAY_OF_MONTH); //show Dialog showDialog(DATE_DIALOG_ID); //Callback must be handled via Listener Variable pDateSetListener } public void showUrbanTalk(String cityname) { mLayout.closeSidebar(); //mViewPager.setVisibility(View.GONE); if (refresh != null) refresh.setVisible(false); UrbanTalkSplashFragment urban = new UrbanTalkSplashFragment(); Bundle bundle = new Bundle(); bundle.putString("cityname", cityname); urban.setArguments(bundle); ft = getSupportFragmentManager().beginTransaction(); ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out); // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack ft.replace(R.id.animation_layout_content, urban); ft.addToBackStack(null); ab.selectTab(tab4); // Commit the transaction ft.commit(); } public void showUserActivity(String type) { mLayout.closeSidebar(); Intent openUserActivity = new Intent(this, UserActivity.class); openUserActivity.putExtra("type", type); this.startActivity(openUserActivity); } public EventManager getEventManager() { if (em == null) em = EventManager.getInstance(); return em; } @Override public boolean onCreateOptionsMenu(Menu menu) { getSupportMenuInflater().inflate(R.menu.main_menu, menu); refresh = (MenuItem) menu.findItem(R.id.refresh); refresh.setVisible(false); /* // set up a listener for the refresh item final MenuItem refresh = (MenuItem) menu.findItem(R.id.menu_refresh); refresh.setOnMenuItemClickListener(new OnMenuItemClickListener() { // on selecting show progress spinner for 1s public boolean onMenuItemClick(MenuItem item) { // item.setActionView(R.layout.progress_action); handler.postDelayed(new Runnable() { public void run() { refresh.setActionView(null); } }, 1000); return false; } }); */ return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // TODO handle clicking the app icon/logo return false; case R.id.city: // show user home //showUserActivity(); onClickContentButton(this.getCurrentFocus()); return true; case R.id.refresh: // reload stuff if (ab.getSelectedTab() == tab2) { grid.reloadStuff(); } return true; default: return super.onOptionsItemSelected(item); } } private void showTabsNav() { ActionBar ab = getSupportActionBar(); if (ab.getNavigationMode() != ActionBar.NAVIGATION_MODE_TABS) { ab.setDisplayShowTitleEnabled(false); ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); } } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) { // FIXME add a proper implementation, for now just rotate the left // fragment //rotateLeftFrag(); //if (tab == tab1) showEventlistFragment(); if (tab == tab1) showEventlistContainerFragment(); else if (tab == tab2) { showGridFragment(); } else if (tab == tab3) { //Point p = new Point(30,30); //showPopup(this, p); showMapFragment(); } else if (tab == tab4) { showUrbanTalk(user.getHomeLocation().getCity()); } else if (tab == tab5) { showFriendsEventsFragment(); } } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) { // FIXME implement this } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) { // FIXME implement this } // The method that displays the popup. private void showPopup(final Activity context, Point p) { int popupWidth = 200; int popupHeight = 150; // Inflate the popup_layout.xml LinearLayout viewGroup = (LinearLayout) context.findViewById(R.id.popup); LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View layout = layoutInflater.inflate(R.layout.popup_layout, viewGroup); // Creating the PopupWindow final PopupWindow popup = new PopupWindow(context); popup.setContentView(layout); popup.setWidth(popupWidth); popup.setHeight(popupHeight); popup.setFocusable(true); // Some offset to align the popup a bit to the right, and a bit down, relative to button's position. int OFFSET_X = 30; int OFFSET_Y = 30; // Clear the default translucent background popup.setBackgroundDrawable(new BitmapDrawable()); // Displaying the popup at the specified location, + offsets. popup.showAtLocation(layout, Gravity.NO_GRAVITY, p.x + OFFSET_X, p.y + OFFSET_Y); // Getting a reference to Close button, and close the popup when clicked. Button close = (Button) layout.findViewById(R.id.close); close.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { popup.dismiss(); } }); } /** Create a new dialog for date picker */ @Override protected Dialog onCreateDialog(int id) { switch (id) { case DATE_DIALOG_ID: return new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay); } return null; } public void logout() { Thread t = new Thread(new Runnable() { @Override public void run() { try { FacebookSession.logout(MenuActivity.this); Toast t1 = Toast.makeText(getApplicationContext(), "Logout successful", Toast.LENGTH_LONG); t1.show(); Intent i = new Intent(MenuActivity.this, SplashLoadingActivity.class); startActivity(i); finish(); } catch (Exception ex) { Toast t1 = Toast.makeText(getApplicationContext(), "Logout not successful", Toast.LENGTH_LONG); t1.show(); ex.printStackTrace(); } } }); t.run(); } void reloadStuff() { } void showAdressChangeDialog() { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); Fragment prev = getSupportFragmentManager().findFragmentByTag("adressdialog"); if (prev != null) { ft.remove(prev); } ft.addToBackStack(null); // Create and show the dialog. CityChangeDialogFragment newFragment = new CityChangeDialogFragment(); newFragment.show(ft, "adressdialog"); } //Sidebar Stuff public void onClickContentButton(View v) { //ab.hide(); mLayout.toggleSidebar(); } @Override public void onBackPressed() { if (mLayout.isOpening()) { mLayout.closeSidebar(); } else { finish(); } } /* Callback of AnimationLayout.Listener to monitor status of Sidebar */ @Override public void onSidebarOpened() { } /* Callback of AnimationLayout.Listener to monitor status of Sidebar */ @Override public void onSidebarClosed() { //ab.show(); } /* Callback of AnimationLayout.Listener to monitor status of Sidebar */ @Override public boolean onContentTouchedWhenOpening() { // the content area is touched when sidebar opening, close sidebar mLayout.closeSidebar(); return true; } }