Android Open Source - opentraining Create Exercise Activity






From Project

Back to project page opentraining.

License

The source code is released under:

GNU General Public License

If you think the Android project opentraining listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

/**
 * //from   w  w w  .  ja va  2 s  .  c o m
 * This is OpenTraining, an Android application for planning your your fitness training.
 * Copyright (C) 2012-2014 Christian Skubich
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

package de.skubware.opentraining.activity.create_exercise;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

import android.support.v4.app.FragmentTransaction;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.Fragment;

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;


import de.skubware.opentraining.R;
import de.skubware.opentraining.activity.create_exercise.ExerciseImageListAdapter.ImageData;
import de.skubware.opentraining.basic.ExerciseType;
import de.skubware.opentraining.basic.License;
import de.skubware.opentraining.basic.Muscle;
import de.skubware.opentraining.basic.SportsEquipment;
import de.skubware.opentraining.basic.ExerciseType.ExerciseSource;
import de.skubware.opentraining.db.Cache;
import de.skubware.opentraining.db.DataProvider;
import de.skubware.opentraining.db.IDataProvider;
import android.widget.Toast;


/**
 * An activity for creating new {@link ExerciseType}s.
 * 
 */
public class CreateExerciseActivity extends ActionBarActivity implements
    ActionBar.TabListener {
  /** Tag for logging*/
  private final String TAG = "CreateExerciseActivity";
  
  /** Static String for preferences. */
  public final static String PREFERENCE_SHOW_SWIPE_TO_DISMISS_ADVISE = "SHOW_SWIPE_TO_DISMISS_ADVISE";

  
  /**
   * The {@link android.support.v4.view.PagerAdapter} that will provide
   * fragments for each of the sections. We use a
   * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
   * will keep every loaded fragment in memory. If this becomes too memory
   * intensive, it may be best to switch to a
   * {@link android.support.v4.app.FragmentStatePagerAdapter}.
   */
  SectionsPagerAdapter mSectionsPagerAdapter;

  /**
   * The {@link ViewPager} that will host the section contents.
   */
  ViewPager mViewPager;


  /** Static int for onActivityResult */
  static final int TAKE_PICTURE = 447;
  
  /** Static int for onActivityResult */
  static final int CHOSE_PICTURE = 555;
  
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_create_exercise);

    // Set up the action bar.
    final ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the app.
    mSectionsPagerAdapter = new SectionsPagerAdapter(
        getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setOffscreenPageLimit(mSectionsPagerAdapter.getCount());    
    mViewPager.setAdapter(mSectionsPagerAdapter);

    // When swiping between different sections, select the corresponding
    // tab. We can also use ActionBar.Tab#select() to do this if we have
    // a reference to the Tab.
    mViewPager
        .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
          @Override
          public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
          }
        });

    // For each of the sections in the app, add a tab to the action bar.
    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
      // Create a tab with text corresponding to the page title defined by
      // the adapter. Also specify this Activity object, which implements
      // the TabListener interface, as the callback (listener) for when
      // this tab is selected.
      actionBar.addTab(actionBar.newTab()
          .setText(mSectionsPagerAdapter.getPageTitle(i))
          .setTabListener(this));
    }
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_create_exercise, menu);
    

    // configure menu_create_exercise_info
    MenuItem menu_create_exercise_info = (MenuItem) menu.findItem(R.id.menuitem_create_exercise_info);
    menu_create_exercise_info.setOnMenuItemClickListener(new OnMenuItemClickListener() {
      public boolean onMenuItemClick(MenuItem item) {
        AlertDialog.Builder builder = new AlertDialog.Builder(CreateExerciseActivity.this);
        builder.setTitle(getString(R.string.title_about_creating_exercise));
        builder.setMessage(getString(R.string.text_about_creating_exercise));
        
        builder.create().show();


        return true;
      }
    });
    

    return true;
  }
  
  @Override
  public void onDestroy(){
    super.onDestroy();
    
    // clean up images
    ImageFragment imageFragment = (ImageFragment) mSectionsPagerAdapter.getItem(2);
    List<ImageData> images = imageFragment.getImages();
    IDataProvider dataProvider = new DataProvider(this);
    Cache.INSTANCE.updateCache(this);

    for(ImageData image:images){
      // remove not used/referenced images
      dataProvider.deleteCustomImage(image.name, true);
    }
    
  }

  @Override
  public void onTabSelected(ActionBar.Tab tab,
      FragmentTransaction fragmentTransaction) {
    mViewPager.setCurrentItem(tab.getPosition());
  }

  @Override
  public void onTabUnselected(ActionBar.Tab tab,
      FragmentTransaction fragmentTransaction) {
  }

  @Override
  public void onTabReselected(ActionBar.Tab tab,
      FragmentTransaction fragmentTransaction) {
  }

  private static String makeFragmentName(int viewId, int index) {
       return "android:switcher:" + viewId + ":" + index;
  }
  
  /** Saves the created exercise. */
  @SuppressWarnings("unchecked")
  private void saveExercise(){
    NameFragment nameFragment = (NameFragment)  getSupportFragmentManager().findFragmentByTag(makeFragmentName(R.id.pager,0));//  mSectionsPagerAdapter.getItem(0);
    DescriptionFragment descriptionFragment = (DescriptionFragment) getSupportFragmentManager().findFragmentByTag(makeFragmentName(R.id.pager,1));
    ImageFragment imageFragment = (ImageFragment) getSupportFragmentManager().findFragmentByTag(makeFragmentName(R.id.pager,2));
    SimpleDataFragment<Muscle> muscleDataFragment = (SpinnerDataFragment<Muscle>) getSupportFragmentManager().findFragmentByTag(makeFragmentName(R.id.pager,3));
    EquipmentDataFragment equipmentDataFragment = (EquipmentDataFragment) getSupportFragmentManager().findFragmentByTag(makeFragmentName(R.id.pager,4));

    DataProvider dataProvider = new DataProvider(this);

    
    // handle names
    Map<Locale, String> translationMap = nameFragment.getTranslationMap();
    
    if(translationMap.isEmpty()){
      Log.v(TAG, "User did not enter an exercise name.");
      Toast.makeText(this, getString(R.string.provide_name), Toast.LENGTH_LONG).show();
      
      return;
    }
    
    
    // handle description
    String description = descriptionFragment.getExerciseDescription();
      
    // handle muscle
    SortedSet<Muscle> muscleList = new TreeSet<Muscle>(muscleDataFragment.getChosenObjects());

    // handle equipment
    SortedSet<SportsEquipment> equipmentList = new TreeSet<SportsEquipment>(equipmentDataFragment.getChosenObjects());

    // save image
    List<ImageData> imageDataList = imageFragment.getImages();
    List<File> imageList = new ArrayList<File>();
    Map<File, License> imageLicenseMap = new HashMap<File, License>();
    for(ImageData image:imageDataList){
      File f = new File(image.name);
      imageList.add(f);
      imageLicenseMap.put(f, image.imageLicense);
    }

    
    ExerciseType.Builder exerciseBuilder = new ExerciseType.Builder(translationMap.values().iterator().next(), ExerciseSource.CUSTOM).description(description).translationMap(translationMap).activatedMuscles(muscleList).neededTools(equipmentList).imagePath(imageList).imageLicenseMap(imageLicenseMap);
    ExerciseType ex = exerciseBuilder.build();
    
    // save exercise
    boolean succ = dataProvider.saveCustomExercise(ex);
    
    
    if(!succ){
      Toast.makeText(this, getString(R.string.could_not_save_exercise), Toast.LENGTH_LONG).show();
    }else{
      Toast.makeText(this, getString(R.string.exercise_saved), Toast.LENGTH_LONG).show();
      finish();
    }
  }
  
  /**
   * Show Dialog when user wants to go back.
   */
  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
      AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
      dialogBuilder.setTitle(getString(R.string.save_exercise))
      .setMessage(getString(R.string.should_exercise_be_saved))
      .setNegativeButton(getString(R.string.discard_exercise), new OnClickListener(){
        @Override
        public void onClick(DialogInterface dialog, int which) {
          dialog.dismiss();
          finish();
        }
      })
      .setNeutralButton(getString(R.string.cancel), new OnClickListener(){
        @Override
        public void onClick(DialogInterface dialog, int which) {
          dialog.dismiss();
        }
      })      
      .setPositiveButton(getString(R.string.save), new OnClickListener(){
        @Override
        public void onClick(DialogInterface dialog, int which) {
          saveExercise();
        }
      }).create().show();      
    }
    return super.onKeyDown(keyCode, event);
  }


  
  
  /**
   * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
   * one of the sections/tabs/pages.
   */
  public class SectionsPagerAdapter extends FragmentPagerAdapter {
    
    public SectionsPagerAdapter(FragmentManager fm) {
      super(fm);
    }

    @Override
    public Fragment getItem(int position) {

      switch (position) {
      case 0:
        return new NameFragment();
      case 1:
        return new DescriptionFragment();
      case 2:  
        return new ImageFragment();
      case 3:  
        return new MuscleDataFragment();
      case 4:
        return new EquipmentDataFragment();
      }
      
      throw new IllegalStateException("No fragment for position: " + position);
    }

    @Override
    public int getCount() {
      return 5;
    }

    @Override
    public CharSequence getPageTitle(int position) {
      switch (position) {
      case 0:
        return getString(R.string.title_name_fragment).toUpperCase(Locale.GERMANY);
      case 1:
        return getString(R.string.title_description_fragment).toUpperCase(Locale.GERMANY);
      case 2:  
        return getString(R.string.title_image_fragment).toUpperCase(Locale.GERMANY);
      case 3:  
        return getString(R.string.title_muscle_data_fragment).toUpperCase(Locale.GERMANY);
      case 4:
        return getString(R.string.title_equipment_data_fragment).toUpperCase(Locale.GERMANY);
      }  
      return null;
    }
  }


  /**
   * Shows a toast message that explains "swipe-to-dismiss".
   */
  public void swipeToDismissAdvise(){
    Toast.makeText(this, getString(R.string.swipe_to_dismiss_advise), Toast.LENGTH_LONG).show();
  }
  
}




Java Source Code List

at.technikum.mti.fancycoverflow.FancyCoverFlowAdapter.java
at.technikum.mti.fancycoverflow.FancyCoverFlowItemWrapper.java
at.technikum.mti.fancycoverflow.FancyCoverFlow.java
de.skubware.opentraining.activity.ChangeLogDialog.java
de.skubware.opentraining.activity.DisclaimerDialog.java
de.skubware.opentraining.activity.MainActivity.java
de.skubware.opentraining.activity.NavigationGalleryAdapter.java
de.skubware.opentraining.activity.SelectWorkoutDialogFragment.java
de.skubware.opentraining.activity.WhatsNewDialog.java
de.skubware.opentraining.activity.acra.ACRACrashReportMailer.java
de.skubware.opentraining.activity.acra.ACRAFeedbackMailer.java
de.skubware.opentraining.activity.acra.OpenTrainingApplication.java
de.skubware.opentraining.activity.acra.RequestExerciseUpdate.java
de.skubware.opentraining.activity.create_exercise.CreateExerciseActivity.java
de.skubware.opentraining.activity.create_exercise.CustomSpinner.java
de.skubware.opentraining.activity.create_exercise.DescriptionFragment.java
de.skubware.opentraining.activity.create_exercise.EditImageMetadataDialog.java
de.skubware.opentraining.activity.create_exercise.EquipmentDataFragment.java
de.skubware.opentraining.activity.create_exercise.ExerciseImageListAdapter.java
de.skubware.opentraining.activity.create_exercise.ImageFragment.java
de.skubware.opentraining.activity.create_exercise.MuscleDataFragment.java
de.skubware.opentraining.activity.create_exercise.NameFragment.java
de.skubware.opentraining.activity.create_exercise.SimpleDataFragment.java
de.skubware.opentraining.activity.create_exercise.SpinnerDataFragment.java
de.skubware.opentraining.activity.create_workout.DialogFilterMusclesAndEquipment.java
de.skubware.opentraining.activity.create_workout.DialogWorkoutOverviewFragment.java
de.skubware.opentraining.activity.create_workout.ExerciseDetailOnGestureListener.java
de.skubware.opentraining.activity.create_workout.ExerciseTypeDetailActivity.java
de.skubware.opentraining.activity.create_workout.ExerciseTypeDetailFragment.java
de.skubware.opentraining.activity.create_workout.ExerciseTypeListActivity.java
de.skubware.opentraining.activity.create_workout.ExerciseTypeListAdapter.java
de.skubware.opentraining.activity.create_workout.ExerciseTypeListFragment.java
de.skubware.opentraining.activity.create_workout.SelectMuscleDialog.java
de.skubware.opentraining.activity.create_workout.SendExerciseFeedbackDialogFragment.java
de.skubware.opentraining.activity.create_workout.upload_exercise.ExerciseImage.java
de.skubware.opentraining.activity.create_workout.upload_exercise.UploadExerciseAsyncTask.java
de.skubware.opentraining.activity.create_workout.upload_exercise.UploadExerciseImagesAsyncTask.java
de.skubware.opentraining.activity.create_workout.upload_exercise.WgerRestService.java
de.skubware.opentraining.activity.manage_workouts.RenameWorkoutDialogFragment.java
de.skubware.opentraining.activity.manage_workouts.WorkoutDetailActivity.java
de.skubware.opentraining.activity.manage_workouts.WorkoutDetailFragment.java
de.skubware.opentraining.activity.manage_workouts.WorkoutListActivity.java
de.skubware.opentraining.activity.manage_workouts.WorkoutListFragment.java
de.skubware.opentraining.activity.settings.LicenseDialog.java
de.skubware.opentraining.activity.settings.SettingsActivity.java
de.skubware.opentraining.activity.settings.sync.OpenTrainingSyncResultReceiver.java
de.skubware.opentraining.activity.settings.sync.OpenTrainingSyncService.java
de.skubware.opentraining.activity.settings.sync.RestClient.java
de.skubware.opentraining.activity.settings.sync.SyncFinishedDialog.java
de.skubware.opentraining.activity.settings.sync.WgerImageDownloader.java
de.skubware.opentraining.activity.settings.sync.WgerJSONParser.java
de.skubware.opentraining.activity.start_training.DialogFragmentAddEntry.java
de.skubware.opentraining.activity.start_training.DialogFragmentTrainingEntryTable.java
de.skubware.opentraining.activity.start_training.FExDetailActivity.java
de.skubware.opentraining.activity.start_training.FExDetailFragment.java
de.skubware.opentraining.activity.start_training.FExListActivity.java
de.skubware.opentraining.activity.start_training.FExListAdapter.java
de.skubware.opentraining.activity.start_training.FExListFragment.java
de.skubware.opentraining.activity.start_training.RecoveryTimerManager.java
de.skubware.opentraining.activity.start_training.SwipeDismissListViewTouchListener.java
de.skubware.opentraining.activity.start_training.SwipeDismissTouchListener.java
de.skubware.opentraining.activity.start_training.TrainingEntryListAdapter.java
de.skubware.opentraining.basic.ActivationLevel.java
de.skubware.opentraining.basic.ExerciseTag.java
de.skubware.opentraining.basic.ExerciseType.java
de.skubware.opentraining.basic.FSet.java
de.skubware.opentraining.basic.FitnessExercise.java
de.skubware.opentraining.basic.IExercise.java
de.skubware.opentraining.basic.License.java
de.skubware.opentraining.basic.Muscle.java
de.skubware.opentraining.basic.SportsEquipment.java
de.skubware.opentraining.basic.TrainingEntry.java
de.skubware.opentraining.basic.Translatable.java
de.skubware.opentraining.basic.Workout.java
de.skubware.opentraining.db.Cache.java
de.skubware.opentraining.db.DataHelper.java
de.skubware.opentraining.db.DataProvider.java
de.skubware.opentraining.db.IDataProvider.java
de.skubware.opentraining.db.parser.AbstractJSONParser.java
de.skubware.opentraining.db.parser.ExerciseTagJSONParser.java
de.skubware.opentraining.db.parser.ExerciseTypeXMLParser.java
de.skubware.opentraining.db.parser.IParser.java
de.skubware.opentraining.db.parser.MuscleJSONParser.java
de.skubware.opentraining.db.parser.SportsEquipmentJSONParser.java
de.skubware.opentraining.db.parser.WorkoutXMLParser.java
de.skubware.opentraining.db.parser.XMLSaver.java
de.skubware.opentraining.db.rest.ExerciseImageGSONSerializer.java
de.skubware.opentraining.db.rest.ExerciseTypeGSONSerializer.java
de.skubware.opentraining.db.rest.LanguageGSONDeserializer.java
de.skubware.opentraining.db.rest.MuscleGSONDeserializer.java
de.skubware.opentraining.db.rest.ServerModel.java
de.skubware.opentraining.db.rest.SportsEquipmentGSONDeserializer.java
de.skubware.opentraining.exporter.HTMLExporter.java
de.skubware.opentraining.exporter.LaTeXExporter.java
de.skubware.opentraining.exporter.WorkoutExporter.java