Android Open Source - PlayTogether Match Activity






From Project

Back to project page PlayTogether.

License

The source code is released under:

This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a co...

If you think the Android project PlayTogether 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

package com.rockylearnstodevelop.playtogether;
/*from  www  .  j  a  v  a 2  s .c  o m*/
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import com.squareup.picasso.Picasso;

public class MatchActivity extends Activity {

  protected List<ParseObject> mActivities = new ArrayList<ParseObject>();
  protected List<ParseObject> mUserInfo = new ArrayList<ParseObject>();
  protected Set<String> matchUserNames = new HashSet<String>(); //match UserloginID
  
  //Store the information: key-userId, value-(objectId, name, time, skillLevel)
  protected Map<String, List<String[]>> matchActivityData = new HashMap<String, List<String[]>>();
  
  protected List<String> names = new ArrayList<String>();
  protected List<String> activityObjectId = new ArrayList<String>();
  
  protected String selectedSport;
  protected String selectedTime;
  protected String selectedLevel;
  protected String randomName;
  protected String randomActivityObjectId;
  
  private String currentUserId; 
  private String currentUserName; 
  private ParseUser mCurrentUser;
  private ParseUser matchUser;
  private int i = 0;
  
  private static final String TAG = MatchActivity.class.getSimpleName();

  protected ImageView mPhoto;
  protected TextView mName;
  protected TextView mAge;
  protected TextView mSport;
  protected TextView mLevel;
  protected TextView mTime;
  protected TextView mGender;
  protected Button mNext;
  protected Button mPlay;
  
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.activity_match);
    // Show the Up button in the action bar.
    setupActionBar();
    
    Intent intent = getIntent();
    selectedSport = intent.getExtras().getString(ParseConstants.KEY_SPORT);
    selectedTime = intent.getExtras().getString(ParseConstants.KEY_TIME);
    selectedLevel = intent.getExtras().getString(ParseConstants.KEY_LEVEL);

    mPhoto = (ImageView) findViewById(R.id.userPhoto);
    mName = (TextView) findViewById(R.id.userName);
    mAge = (TextView) findViewById(R.id.userAge);
    mSport = (TextView) findViewById(R.id.sportName);
    mLevel = (TextView) findViewById(R.id.sportLevel);
    mTime = (TextView) findViewById(R.id.sportTime);
    mGender = (TextView) findViewById(R.id.gender);
    mNext = (Button) findViewById(R.id.nextUser);
    mPlay = (Button) findViewById(R.id.playButton);
    
    mNext.setOnClickListener(new View.OnClickListener() {
      
      @Override
      public void onClick(View arg0) {        
        findNextMatch();
      }
    });
    
    mPlay.setOnClickListener(new View.OnClickListener() {
      
      @Override
      public void onClick(View v) {
        if(randomName != null){
          Toast.makeText(MatchActivity.this, R.string.request_toast, Toast.LENGTH_LONG).show();
          ParseObject request = createRequest();
          send(request);
        }
        else{
          //no match
          Toast.makeText(MatchActivity.this, R.string.no_match, Toast.LENGTH_LONG).show();
          Log.d(TAG, "no match");
        }  
      }
    });
  }

  @Override
  protected void onResume() {
    super.onResume();
    setProgressBarIndeterminateVisibility(true);
    mCurrentUser = ParseUser.getCurrentUser();
    currentUserId = mCurrentUser.getObjectId();
    currentUserName = mCurrentUser.getUsername();
    queryForActivities();
  }
  
  private void findNextMatch() {
    if(names.size() > 0){
      if(i < names.size()){
        randomActivityObjectId = activityObjectId.get(i);
        randomName = names.get(i++);
      }
      else{
        i = 0;
        randomActivityObjectId = activityObjectId.get(i);
        randomName = names.get(i++);
      }

      //get the match user name
      String userName = randomName;
      Log.d(TAG, "randomActivityObjectId: " + randomActivityObjectId);
      //use the match user name to query for UserInfo
      queryForUserInfo(userName);
      mName.setText(userName);
      mSport.setText(selectedSport);
      mLevel.setText(selectedLevel);
      mTime.setText(selectedTime);
    }
    else{
      Toast.makeText(MatchActivity.this, "no Match", Toast.LENGTH_LONG).show();
      Log.d(TAG, "no match");
    }
  }
    
  private void queryForUserInfo(String userName) {
    // if there is a match
    ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(ParseConstants.CLASS_USERINFO);
    query.whereEqualTo(ParseConstants.KEY_USERNAME, userName);
    query.findInBackground(new FindCallback<ParseObject>() {
      @Override
      public void done(List<ParseObject> userInfo, ParseException e) {
        setProgressBarIndeterminateVisibility(false);
         if (e == null) {
           //test how many UserInfo was found
           mUserInfo = userInfo;
               Log.d("UserInfo", "Retrieved " + mUserInfo.size() + " UserInfo");
               ParseObject mInfo = mUserInfo.get(0);
               String gender = mInfo.getString(ParseConstants.KEY_GENDER);
               String birthday = mInfo.getString(ParseConstants.KEY_BIRTHDAY);
               String weChatId = mInfo.getString(ParseConstants.KEY_WECHATID);
               //get the photo
               ParseFile file = mInfo.getParseFile(ParseConstants.KEY_FILE);
               Uri fileUri = Uri.parse(file.getUrl());
               Picasso.with(MatchActivity.this).load(fileUri.toString()).into(mPhoto);
               mGender.setText(gender);
               mAge.setText(getAgeFromDate(birthday));
         } else {
                  Log.d(TAG, "Match UserInfo error: " + e.getMessage());
           }
      }
    });
  }
  
  protected void send(ParseObject request) {
    request.saveInBackground(new SaveCallback() {
      
      @Override
      public void done(ParseException e) {
        if(e == null){
          Toast.makeText(MatchActivity.this, R.string.request_sent_successful, Toast.LENGTH_LONG).show();
        }
        else{
          Log.d(TAG, "request failed to send out");
        }
      }
    });
  }


  protected ParseObject createRequest() {
    ParseObject mRequest = new ParseObject(ParseConstants.CLASS_ACTIVITYREQUEST);
    mRequest.put(ParseConstants.KEY_SENDERID, currentUserId);
    mRequest.put(ParseConstants.KEY_SENDERNAME, currentUserName);
    mRequest.put(ParseConstants.KEY_ACTIVITYID, randomActivityObjectId);
    mRequest.put(ParseConstants.KEY_RECIPIENTNAME, randomName);
    mRequest.put(ParseConstants.KEY_SPORT, selectedSport);
    mRequest.put(ParseConstants.KEY_LEVEL, selectedLevel);
    mRequest.put(ParseConstants.KEY_TIME, selectedTime);
    
    return mRequest;
  }

  private void queryForActivities() {  
    // if there is a match
    ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(ParseConstants.CLASS_SPORTACTIVITY);
    query.whereEqualTo(ParseConstants.KEY_SPORT, selectedSport);
    //Reorder the result according to the time users shake the phone
    query.addDescendingOrder(ParseConstants.KEY_CREATEDAT);
    query.findInBackground(new FindCallback<ParseObject>() {
        public void done(List<ParseObject> sportActivities, ParseException e) {
            if (e == null) {
              //test how many times the user upload the SportPreference
                Log.d("sport", "Retrieved " + sportActivities.size() + " sports");
                mActivities = sportActivities;
                
                retrieveMatchData();
                matchResult();
            
                testResult();
                
            } else {
                Log.d(TAG, "Match error: " + e.getMessage());
            }
        }
    });
  }
  
  private void retrieveMatchData() {
    String userId;
    String userName;
        String[] data;
        //retrieve the userIds from the list
        for(ParseObject activity: mActivities){
          userId = activity.getString(ParseConstants.KEY_USERID);
          userName = activity.getString(ParseConstants.KEY_USERNAME);
          data = new String[]{activity.getString(ParseConstants.KEY_USERNAME),
              activity.getString(ParseConstants.KEY_TIME),
              activity.getString(ParseConstants.KEY_LEVEL),
              activity.getObjectId(),
              activity.getString(ParseConstants.KEY_ALONE)};
          List<String[]> activityData = new ArrayList<String[]>();
          //the Id of the user himself should not be include
          if(!userId.equals(currentUserId)){
            //no duplicate userNames
            if(!matchUserNames.contains(userName)){
              matchUserNames.add(userName);
              activityData.add(data);
              matchActivityData.put(userName, activityData);
            }
            else{
              matchActivityData.get(userName).add(data);
            }
          }
        }
  }
  
  protected void matchResult() {
    //time & skill match
    List<String[]> matchActivites = new ArrayList<String[]>();
    if(matchActivityData.size() > 0){
      Collection<List<String[]>> acitivitiesLists = matchActivityData.values(); 
      for(List<String[]> activitiesList: acitivitiesLists){
        for(String[] activity: activitiesList){
          if(activity[1].equals(selectedTime)){
            if(activity[2].equals(selectedLevel)){
              matchActivites.add(activity);
            }
          }
        }
      }
      if(matchActivites.size() > 0){
        for(String[] activity: matchActivites){
          if(!names.contains(activity[0])){
            names.add(activity[0]);
            activityObjectId.add(activity[3]);
          }
        }
          
        randomActivityObjectId = activityObjectId.get(i);
        Log.d(TAG, "activityObjectIds has " + activityObjectId.size() + " ids");
        Log.d(TAG, "randomActivityObjectId: " + randomActivityObjectId);
        randomName = names.get(i++);
        
        //get the match user name
        String userName = randomName;
        //use the match user name to query for UserInfo
        queryForUserInfo(userName);
        mName.setText(userName);
        mSport.setText(selectedSport);
        mLevel.setText(selectedLevel);
        mTime.setText(selectedTime);
      }else{
        //no match
        Toast.makeText(MatchActivity.this, R.string.no_match, Toast.LENGTH_LONG).show();
        Log.d(TAG, "no match");
      }
    }
    else{
      //no match
      Toast.makeText(MatchActivity.this, R.string.no_match, Toast.LENGTH_LONG).show();
      Log.d(TAG, "no match");
    }
  }  

  private void testResult() {
    //check how many users wanna play this sport
        Log.d("matchUserIds", "has: " + matchUserNames.size() + " ids");
        Log.d("matchActivityData", "has: " + matchActivityData.size() + " data");
        if(matchUserNames.size() > 0){
          for(String name: matchUserNames){
              if(matchActivityData.size() > 0){
                List<String[]> test_activityData = matchActivityData.get(name);
                Log.d(TAG, name + " has " + test_activityData.size() + " activities");
                for(String[] data: test_activityData){
                  StringBuilder builder = new StringBuilder();
                  for(String string: data){
                    builder.append(string + " ");
                  }
                  Log.d("activity data: ", builder.toString());
                }
              }
            }
        }
  }

  public String getAgeFromDate(String date) {
    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
      Date birthday = null;
    try {
      birthday = formatter.parse(date);
    } catch (java.text.ParseException e) {
      e.printStackTrace();
    }
    
    Integer age = 0;
    if(birthday != null){
        Calendar a = getCalendar(birthday);
        Calendar b = Calendar.getInstance();
        age = b.get(Calendar.YEAR) - a.get(Calendar.YEAR);
        if (a.get(Calendar.MONTH) > b.get(Calendar.MONTH) || 
            (a.get(Calendar.MONTH) == b.get(Calendar.MONTH) && a.get(Calendar.DATE) > b.get(Calendar.DATE))) {
          age--;
        }
        Log.d(TAG, "Age: " + age.toString());
        return age.toString();
      }
    else{
      Log.d(TAG, "error birthday!");
      return "0";
    }
  }

  private Calendar getCalendar(Date date) {
      Calendar cal = Calendar.getInstance(Locale.US);
      cal.setTime(date);
      return cal;
  }
  
  /**
   * Set up the {@link android.app.ActionBar}.
   */
  private void setupActionBar() {

    getActionBar().setDisplayHomeAsUpEnabled(true);

  }

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

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
      // This ID represents the Home or Up button. In the case of this
      // activity, the Up button is shown. Use NavUtils to allow users
      // to navigate up one level in the application structure. For
      // more details, see the Navigation pattern on Android Design:
      //
      // http://developer.android.com/design/patterns/navigation.html#up-vs-back
      //
      NavUtils.navigateUpFromSameTask(this);
      return true;
    }
    return super.onOptionsItemSelected(item);
  }

}




Java Source Code List

com.rockylearnstodevelop.playtogether.ActivitiesFragment.java
com.rockylearnstodevelop.playtogether.ActivityAdapter.java
com.rockylearnstodevelop.playtogether.FileHelper.java
com.rockylearnstodevelop.playtogether.ImageResizer.java
com.rockylearnstodevelop.playtogether.LoginActivity.java
com.rockylearnstodevelop.playtogether.MainActivity.java
com.rockylearnstodevelop.playtogether.MatchActivity.java
com.rockylearnstodevelop.playtogether.NoMatchActivity.java
com.rockylearnstodevelop.playtogether.ParseConstants.java
com.rockylearnstodevelop.playtogether.PlayWithMe2Application.java
com.rockylearnstodevelop.playtogether.RequestAdapter.java
com.rockylearnstodevelop.playtogether.RequestFragment.java
com.rockylearnstodevelop.playtogether.SectionsPagerAdapter.java
com.rockylearnstodevelop.playtogether.SignupActivity.java
com.rockylearnstodevelop.playtogether.UserInfoActivity.java
com.rockylearnstodevelop.playtogether.WannaPlayFragment.java