Example #1
0
  public void getUsers(final List<ParseObject> list, final int listSize, final int i) {
    size = listSize;
    if (i == listSize) {
      checkList();
    } else {
      if ((list.get(i).getString("toUser") + "").equals(currentUser.getObjectId() + "")) {
        friendid = list.get(i).getString("fromUser");
      } else {
        friendid = list.get(i).getString("toUser");
      }

      ParseQuery<ParseUser> query = ParseUser.getQuery();
      query.getInBackground(
          friendid,
          new GetCallback<ParseUser>() {

            @Override
            public void done(ParseUser arg0, ParseException arg1) {
              // Toast.makeText(Friends.this, arg0.getObjectId()+"", Toast.LENGTH_SHORT).show();
              addUser(arg0);
              getUsers(list, listSize, i + 1);
            }
          });
    }
  }
Example #2
0
  public void saveNote() {
    String titleToSave = titleEditText.getText().toString().trim();
    String contentToSave = contentEditText.getText().toString().trim();

    if (!contentToSave.isEmpty() || !titleToSave.isEmpty()) {
      if (note == null) {
        ParseObject post = new ParseObject("Post");
        post.put("title", titleToSave);
        post.put("content", contentToSave);
        post.put("author", ParseUser.getCurrentUser());
        post.saveInBackground();
        callback.onNoteAdded(titleToSave, contentToSave);
      } else {
        ParseQuery<ParseObject> query = ParseQuery.getQuery("Post");
        final String newTitleToSave = titleToSave;
        final String newContentToSave = contentToSave;
        query.getInBackground(
            note.getId(),
            new GetCallback<ParseObject>() {
              @Override
              public void done(ParseObject parseObject, ParseException e) {
                if (e == null) {
                  parseObject.put("title", newTitleToSave);
                  parseObject.put("content", newContentToSave);
                  callback.onNoteChanged(new Note(newTitleToSave, newContentToSave), note);
                  parseObject.saveInBackground();
                }
              }
            });
      }
    }
  }
Example #3
0
  private boolean displayDiscussionInfo() {

    final AlertDialog.Builder builder = new AlertDialog.Builder(DiscussionActivity.this);
    LayoutInflater inflater = DiscussionActivity.this.getLayoutInflater();
    final View v = inflater.inflate(R.layout.about_discussion, null);

    final ProgressDialog dia =
        ProgressDialog.show(DiscussionActivity.this, null, getString(R.string.alert_loading));
    dia.setCanceledOnTouchOutside(false);
    ParseQuery<Discussion> discussionQuery = Discussion.getDiscussionQuery();
    discussionQuery.getInBackground(
        discussionTableName,
        new GetCallback<Discussion>() {
          public void done(Discussion currentDiscussion, ParseException e) {
            if ((e == null) && (currentDiscussion != null)) {
              fetchDiscussionInformation(v, currentDiscussion);
            }

            dia.dismiss();
          }
        });

    builder
        .setView(v)
        .setTitle(discussionTopic + " (" + messagesList.size() + " messages)")
        .setPositiveButton(R.string.ok, null)
        .create()
        .show();

    return true;
  }
Example #4
0
  private void fetchDiscussionInformation(View v, Discussion currentDiscussion) {
    // Get the creation date of the current discussion
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm", Locale.getDefault());

    // Get the expiration and creation date of the current discussion
    TextView creationDate = (TextView) v.findViewById(R.id.about_discussion_value_creation);
    TextView expirationDate = (TextView) v.findViewById(R.id.about_discussion_value_expiration);
    TextView lastUpdateDate = (TextView) v.findViewById(R.id.about_discussion_value_update);
    creationDate.setText(sdf.format(currentDiscussion.getCreationDate()));
    expirationDate.setText(sdf.format(currentDiscussion.getExpirationDate()));
    if (lastMsgDate != null) {
      lastUpdateDate.setText(sdf.format(lastMsgDate));
    }

    // Get the owner of the current discussion
    final TextView owner = (TextView) v.findViewById(R.id.about_discussion_value_owner);
    String ownerID = currentDiscussion.getOwnerParseID();
    if (ownerID != null) {
      ParseQuery<ReliUser> userQuery = ReliUser.getReliQuery();
      userQuery.getInBackground(
          ownerID,
          new GetCallback<ReliUser>() {
            public void done(ReliUser reliUser, ParseException e) {
              if (e == null) {
                owner.setText(reliUser.getFullName());
              } else {
                owner.setText(Const.UNKNOWN_USER);
              }
            }
          });
    } else {
      owner.setText(Const.UNKNOWN_USER);
    }

    // Get the radius of the current discussion
    TextView radius = (TextView) v.findViewById(R.id.about_discussion_value_radius);
    radius.setText(Integer.toString(currentDiscussion.getRadius()) + " meters");

    // Get the tags of the current discussion
    TextView tags = (TextView) v.findViewById(R.id.about_discussion_value_tags);
    ArrayList<String> tagsIDs = currentDiscussion.getTagIDsForDiscussion();
    String tagsListAsString = "";
    String currentTagName;
    for (String tagID : tagsIDs) {
      if (MainActivity.tagsIdToTag.containsKey(tagID)) {
        currentTagName = MainActivity.tagsIdToTag.get(tagID).getTagName();
        if (currentTagName != null) {
          tagsListAsString += currentTagName + ", ";
        }
      }
    }

    // Write the tags on screen
    if (tagsListAsString.equals("")) {
      tagsListAsString = getString(R.string.no_tags);
    } else {
      tagsListAsString = tagsListAsString.substring(0, tagsListAsString.length() - 2);
    }
    tags.setText(tagsListAsString);
  }
Example #5
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_item_display);
    if (savedInstanceState == null) {
      Bundle extras = getIntent().getExtras();
      if (extras == null) {
        itemId = null;
      } else {
        itemId = extras.getString("itemId");
      }
    } else {
      itemId = (String) savedInstanceState.getSerializable("itemId");
    }

    if (savedInstanceState == null) {
      Bundle extras = getIntent().getExtras();
      if (extras == null) {
        imageNum = 0;
      } else {
        imageNum = extras.getInt("imageNum");
      }
    } else {
      imageNum = (int) savedInstanceState.getSerializable("imageNum");
    }

    if (savedInstanceState == null) {
      Bundle extras = getIntent().getExtras();
      if (extras == null) {
        userId = null;
      } else {
        userId = extras.getString("userId");
      }
    } else {
      userId = (String) savedInstanceState.getSerializable("userId");
    }

    ParseQuery<ParseObject> query = ParseQuery.getQuery("Item");
    query.getInBackground(
        itemId,
        new GetCallback<ParseObject>() {
          public void done(ParseObject object, ParseException e) {
            if (e == null) {

              if (object.has("itemImage0")) {
                ImageView displayImage = (ImageView) findViewById(R.id.imageDisplay);
                ParseFile image = object.getParseFile("itemImage0");
                try {
                  byte[] imageData = image.getData();
                  Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
                  displayImage.setImageBitmap(bitmap);
                } catch (ParseException e1) {
                  e1.printStackTrace();
                }
              }
            } else {
            }
          }
        });
  }
 private void inviteSelectedPlayers(
     final String gameId, final List<ParseUser> selectedPlayersList) {
   final ParseQuery<ParseObject> query = ParseQuery.getQuery("gameInfo");
   query.getInBackground(
       gameId,
       new GetCallback<ParseObject>() {
         public void done(final ParseObject game, final ParseException e) {
           if (e == null) {
             for (final ParseUser invitee : selectedPlayersList) {
               // see https://parse.com/questions/push-notifications-on-android-to-specific-users
               ParsePush parsePush = new ParsePush();
               ParseQuery<ParseInstallation> pQuery = ParseInstallation.getQuery();
               pQuery.whereEqualTo("username", invitee);
               parsePush.setQuery(pQuery);
               parsePush.setMessage(
                   "You've been invited to play scavenger hunt: "
                       + game.getString("gameName")
                       + ", by "
                       + ParseUser.getCurrentUser().getString("username"));
               parsePush.sendInBackground();
             }
           }
         }
       });
 }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_status_detail_view);

    mStatus = (TextView) findViewById(R.id.statusDetailView);

    // get intent that status detail
    Intent intent = getIntent();
    status = intent.getStringExtra("objectID");

    ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Status");

    query.getInBackground(
        status,
        new GetCallback<ParseObject>() {
          @Override
          public void done(ParseObject parseObject, ParseException e) {
            if (e == null) {
              // success
              String userStatus = parseObject.getString("newStatus");
              mStatus.setText(userStatus);
            } else {
              // there was a problem, advice user

            }
          }
        });
  }
Example #8
0
  public void moreImageFunction(View view) {

    ParseQuery<ParseObject> query = ParseQuery.getQuery("Item");
    query.getInBackground(
        itemId,
        new GetCallback<ParseObject>() {
          public void done(ParseObject object, ParseException e) {
            if (e == null) {
              imageNum = next(imageNum);
              String item = "itemImage" + imageNum;
              if (object.has(item)) {
                ImageView displayImage = (ImageView) findViewById(R.id.imageDisplay);
                ParseFile image = object.getParseFile(item);
                try {
                  byte[] imageData = image.getData();
                  Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
                  displayImage.setImageBitmap(bitmap);
                } catch (ParseException e1) {
                  e1.printStackTrace();
                }
              }
            } else {
            }
          }
        });
  }
 private void updateHomeServiceRequestStatus(final ParseUser attendedBy) {
   ParseQuery<ParseObject> query = ParseQuery.getQuery("HomeServiceRequest");
   query.getInBackground(
       requestId,
       new GetCallback<ParseObject>() {
         @Override
         public void done(ParseObject parseObject, ParseException e) {
           progressBar.setVisibility(View.GONE);
           orderSent.setVisibility(View.VISIBLE);
           if (e == null && parseObject != null) {
             parseObject.put("status", HomeServiceRequestStatus.ASIGNADO.getValue());
             parseObject.put(
                 "attendedBy",
                 attendedBy); // TODO if the current user is admin, he can choose an employee to
                              // attend the request
             Date dateForService = stringToDate(date);
             if (dateForService != null) {
               parseObject.put("dateForService", dateForService);
             }
             parseObject.saveInBackground(
                 new SaveCallback() {
                   @Override
                   public void done(ParseException e) {
                     if (e == null) { // el status se actulizó, mandamos el push al cliente
                       sendPushToClient(
                           date, userId, name, imageUrl, problemDesc, attendedBy.getUsername());
                       if (hasEmployee) { // y al empleado
                         sendPushToEmployee(requestId, employeeId);
                       }
                       notificationSent = true;
                     } else {
                       // no se actualizó
                       Log.e("ERROR: ", e.getMessage());
                       TextView textViewOrderSent =
                           (TextView) orderSent.findViewById(R.id.textview_notification);
                       if (textViewOrderSent != null) {
                         textViewOrderSent.setText(
                             getResources().getString(R.string.order_not_sent));
                       }
                     }
                   }
                 });
           } else {
             // TODO mostrar mensaje de error en el textview
             Log.e("ERROR: ", e != null ? e.getMessage() : null);
             TextView textViewOrderSent =
                 (TextView) orderSent.findViewById(R.id.textview_notification);
             if (textViewOrderSent != null) {
               textViewOrderSent.setText(getResources().getString(R.string.request_not_updated));
             }
           }
         }
       });
 }
Example #10
0
 public void getInBackground(String objectId, final shared.baas.GetCallback<T> callback) {
   pq.getInBackground(
       objectId,
       new GetCallback() {
         @Override
         public void done(ParseObject o, ParseException e) {
           if (e == null) callback.done(facade.wrap(o));
           else callback.error(e);
         }
       });
 }
Example #11
0
 public static void getQuestion(String objectId) {
   ParseQuery<ParseObject> query = ParseQuery.getQuery(Common.OBJECT_POST);
   query.getInBackground(
       objectId,
       new GetCallback<ParseObject>() {
         @Override
         public void done(ParseObject question, ParseException e) {
           if (e == null) {
             EventBus.getDefault().post(new QuestionEvent(Arrays.asList(question)));
           }
         }
       });
 }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_actividad);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    final ProgressDialog mDialog = new ProgressDialog(this, ProgressDialog.STYLE_SPINNER);
    mDialog.setMessage("Cargando Evento");
    mDialog.show();

    String objectId = getIntent().getStringExtra("objectId");
    ParseQuery<ParseObject> query = ParseQuery.getQuery("Actividad");
    query.getInBackground(
        objectId,
        new GetCallback<ParseObject>() {
          @Override
          public void done(ParseObject actividad, ParseException arg1) {
            mDialog.dismiss();
            if (arg1 == null) {

              String banner = actividad.getParseFile("BannerActividad").getUrl();
              String detalle = actividad.getString("Detalle");
              Date date = actividad.getDate("InicioDate");
              String nombre = actividad.getString("NombreActividad");
              int prioridad = actividad.getInt("Prioridad");
              String contenedor = actividad.getString("contenedor");
              String objectId = actividad.getString("objectId");
              Actividad a =
                  new Actividad(banner, detalle, date, nombre, prioridad, contenedor, objectId);
              float h =
                  TypedValue.applyDimension(
                      TypedValue.COMPLEX_UNIT_DIP, 180, getResources().getDisplayMetrics());
              float w =
                  TypedValue.applyDimension(
                      TypedValue.COMPLEX_UNIT_DIP, 180, getResources().getDisplayMetrics());
              FotosFragment.imageDownloader.forceDownload(
                  banner, (ImageView) findViewById(R.id.banner), (int) w, (int) h);
              //					((ImageView) findViewById(R.id.banner)).setImageBitmap(a.banner);
              ((TextView) findViewById(R.id.textView1)).setText(a.contenedor);
              ((TextView) findViewById(R.id.textView2)).setText(a.nombre);
              ((TextView) findViewById(R.id.textView3)).setText(a.detalle);
              getSupportActionBar().setTitle(nombre);
            } else {
              Toast.makeText(getApplicationContext(), "Error de conexión", Toast.LENGTH_LONG)
                  .show();
              arg1.printStackTrace();
            }
          }
        });
  }
Example #13
0
 private void saveDiscussionObject() {
   if (discussionTableName != null) {
     ParseQuery<Discussion> discussionQuery = Discussion.getDiscussionQuery();
     discussionQuery.getInBackground(
         discussionTableName,
         new GetCallback<Discussion>() {
           public void done(Discussion returnedDiscussion, ParseException e) {
             if (e == null) {
               discussionObject = returnedDiscussion;
             }
           }
         });
   }
 }
    @Override
    protected Void doInBackground(Void... params) {
      // Create the array
      /* mItems = new ArrayList<Leader>();
      try {
          ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Point");
          query.include("User");
          query.orderByDescending("pointslead");
          ob = query.find();
          final Leader map = new Leader();

          for (final ParseObject img : ob) {
              Log.e("1", img.getInt("pointslead") + "");
              map.setpLead(img.getInt("pointslead"));*/

      ParseQuery<ParseUser> queryuser = ParseUser.getQuery();
      queryuser.getInBackground(
          g,
          new GetCallback<ParseUser>() {
            public void done(ParseUser object, ParseException e) {
              if (e == null) {
                Log.e("--:--", "-- yes --");
                name = object.getUsername();
                url = object.getParseFile("img").getUrl();
                idobj = object.getObjectId();

                Log.e("--:--", name);
                Log.e("--:--", url);
                Log.e("--:--", idobj);
                map.setUsername(name);
                map.setUrl(url);
                if (ParseUser.getCurrentUser().getObjectId().equals(idobj)) {
                  map.setMe(true);
                } else {
                  map.setMe(false);
                }
                mItems.add(map);

              } else {
                Log.e("Error", e.getMessage());
              }
            }
          });

      return null;
    }
Example #15
0
 private void deleteNote(final Note note) {
   Log.d(LOG_TAG, "delete note: " + note);
   ParseQuery<ParseObject> query = ParseQuery.getQuery("Post");
   query.getInBackground(
       note.getId(),
       new GetCallback<ParseObject>() {
         @Override
         public void done(ParseObject parseObject, ParseException e) {
           if (e == null) {
             Log.d(LOG_TAG, "note deleted");
             parseObject.deleteInBackground();
             if (notesAdapter.getItemCount() == 0) {
               showEmptyView();
             }
           }
         }
       });
 }
  /**
   * Method called by the update button. Open the NewDietActivity with the selected diet in order to
   * edit them.
   */
  public void update(View v) {
    final String objectId = (String) v.getTag();
    Log.d("TAG: objectId", objectId);

    ParseQuery<Diet> query = ParseQuery.getQuery("Diet");
    query.whereEqualTo("user", ParseUser.getCurrentUser());
    query.getInBackground(
        objectId,
        new GetCallback<Diet>() {
          @Override
          public void done(Diet diet, final ParseException exception) {
            if (exception == null) { // found diet
              Intent intent = new Intent(DietActivity.this, NewDietActivity.class);
              intent.putExtra("diet", objectId);
              startActivity(intent);
            } else if (exception != null) {
              Log.d(
                  "FitAssistant",
                  "Error finding diet with id " + objectId + ": " + exception.getMessage());
            }
          }
        });
  }
Example #17
0
  private void editSegment(final String name, final double distance, final double cost) {

    ParseQuery<Segment> query = ParseQuery.getQuery("Segments");

    query.getInBackground(
        segment_id,
        new GetCallback<Segment>() {
          @Override
          public void done(Segment object, ParseException e) {

            if (e == null) {
              object.setName(name);
              object.setDistance(distance);
              object.setCost(cost);
              object.setCalendarID(sharedPreferences.getString("calendarID", ""));
              object.saveInBackground();

              setResult(1);
              finish();
            }
          }
        });
  }
  /** Method called by the delete button. Delete the selected diet. */
  public void delete(View v) {
    final String objectId = (String) v.getTag();
    Log.d("TAG: objectId", objectId);

    final ProgressDialog dialog = new ProgressDialog(this);
    final Dialog error_dialog = new Dialog(this, "No connection detected", "ok");
    dialog.setTitle("Deleting diet");
    dialog.show();
    ParseQuery<Diet> query = ParseQuery.getQuery("Diet");
    query.whereEqualTo("user", ParseUser.getCurrentUser());
    query.getInBackground(
        objectId,
        new GetCallback<Diet>() {
          @Override
          public void done(Diet diet, final ParseException exception) {
            if (exception == null) { // found diets

              ParseQuery<Meal> query = ParseQuery.getQuery("Meal");
              query.whereEqualTo("user", ParseUser.getCurrentUser());
              query.whereEqualTo("dietId", diet.getObjectId());
              try {
                List<Meal> meals = query.find();
                ParseObject.deleteAll(meals);
                diet.delete();
                dialog.dismiss();
                initialize();
              } catch (ParseException e) {
                Log.d("FitAssistant", "Error deleting diet" + e.getMessage());
              }
            } else if (exception != null) {
              Log.d(
                  "FitAssistant",
                  "Error finding diet with id " + objectId + ": " + exception.getMessage());
            }
          }
        });
  }
  public void deleteCheckedItems() {
    int sizeAdapter = adapter.getCount();
    for (int i = sizeAdapter - 1; i >= 0; i--) {

      View view = gv.getChildAt(i);

      CheckBox cv = (CheckBox) view.findViewById(R.id.gallery_checkBox_item);
      if (cv.isChecked()) {
        ParseQuery<ParseObject> query = ParseQuery.getQuery("Gallery");
        query.getInBackground(
            STgallery.getInstance().get(i).id,
            new GetCallback<ParseObject>() {
              public void done(ParseObject galleryPic, ParseException e) {
                if (e == null) {
                  // delete from server
                  try {
                    galleryPic.delete();
                  } catch (ParseException e1) {
                    e1.printStackTrace();
                  }
                  galleryPic.saveInBackground();
                } else {
                  Toast.makeText(
                          GalleryActivity.this,
                          getResources().getString(R.string.please_check_internet_connection),
                          Toast.LENGTH_LONG)
                      .show();
                  e.printStackTrace();
                }
              }
            });
        STgallery.getInstance().remove(i);
      }
      adapter.notifyDataSetChanged();
    }
    Toast.makeText(getApplicationContext(), "Selected Items Cleared", Toast.LENGTH_SHORT).show();
  }
Example #20
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_event);

    InternetConnectionService service = new InternetConnectionService(AddEventActivity.this);
    if (!service.isInternetConnection()) {
      ModalService.ShowNoConnetionError(AddEventActivity.this);
      return;
    }

    tbStartDate = (TextView) findViewById(R.id.tbStartDate);
    tbEndDate = (TextView) findViewById(R.id.tbEndDate);
    tbStartTime = (TextView) findViewById(R.id.tbStartTime);
    tbEndTime = (TextView) findViewById(R.id.tbEndTime);
    btnAddFriends = (TextView) findViewById(R.id.btnFriends);
    btnSaveEvent = (TextView) findViewById(R.id.btnSave);
    tbTitle = (TextView) findViewById(R.id.tbEventTitle);
    tbPlace = (TextView) findViewById(R.id.tbPlace);
    tbDesc = (TextView) findViewById(R.id.tbDesc);

    addedUsers = new ArrayList<>();
    endDate = new LocalDate();
    startDate = new LocalDate();
    startTime = new LocalTime();
    endTime = new LocalTime();

    String eventId = getIntent().getStringExtra("eventId");
    if (eventId != null) {
      final ProgressDialog dlg = new ProgressDialog(AddEventActivity.this);
      dlg.setTitle("Please wait.");
      dlg.setMessage("Searching event.  Please wait.");
      dlg.show();

      ParseQuery<ParseEvent> query = ParseQuery.getQuery("Event");
      query.getInBackground(
          eventId,
          new GetCallback<ParseEvent>() {
            @Override
            public void done(ParseEvent object, ParseException e) {
              if (e == null) {
                loadedEvent = object;

                tbTitle.setText(loadedEvent.getTitle());
                tbPlace.setText(loadedEvent.getPlace());
                tbDesc.setText(loadedEvent.getDescription());

                endDate = loadedEvent.getEndDate().toLocalDate();
                startDate = loadedEvent.getStartDate().toLocalDate();
                startTime = loadedEvent.getEndDate().toLocalTime();
                endTime = loadedEvent.getEndDate().toLocalTime();

                btnSaveEvent.setText("SAVE EVENT");

                try {
                  addedUsers = loadedEvent.getUsers();
                } catch (ParseException e1) {
                  ModalService.ShowErrorModal(
                      "Error occured while proceding users!", AddEventActivity.this);
                  finish();
                }
                dlg.dismiss();
              } else {
                dlg.dismiss();
                ModalService.ShowErrorModal("There is no such event!", AddEventActivity.this);
                finish();
              }
            }
          });
    }

    tbStartDate.setText(startDate.toString("dd/MM/yyyy"));
    tbEndDate.setText(endDate.toString("dd/MM/yyyy"));
    tbStartTime.setText(startTime.toString("HH:mm"));
    tbEndTime.setText(endTime.toString("HH:mm"));

    setOnClickListeners();
  }
Example #21
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ajout_membre);
    context = this;
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setTitle("Ajouter un membre");
    mMembre = (AutoCompleteTextView) findViewById(R.id.membre);
    tontineId = getIntent().getExtras().getString("TONTINE_ID");
    thisuser = ParseUser.getCurrentUser();
    date = DateFormat.getDateTimeInstance().format(new Date());

    if (NetworkUtil.getConnectivityStatus(this) == TYPE_NOT_CONNECTED) {
      Toast.makeText(this, R.string.no_internet, Toast.LENGTH_SHORT).show();
    } else {
      ParseQuery<Tontine> tontineQuery = ParseQuery.getQuery(Tontine.class);
      tontineQuery.getInBackground(
          tontineId,
          new GetCallback<Tontine>() {
            @Override
            public void done(Tontine tontine, ParseException e) {
              if (e == null) {
                /*thistontine = tontine;
                ParseQuery<Membre> membreQuery = ParseQuery.getQuery(Membre.class);
                membreQuery.whereEqualTo("tontine", tontine);
                membreQuery.findInBackground(new FindCallback<Membre>() {
                    @Override
                    public void done(List<Membre> membreList, ParseException e) {
                        if ((e == null) && (membreList.size() >= 0)) {
                            ParseQuery<ParseUser> userParseQuery = ParseQuery.getQuery(ParseUser.class);
                            userParseQuery.whereNotContainedIn("objectId", membreList);
                            userParseQuery.findInBackground(new FindCallback<ParseUser>() {
                                @Override
                                public void done(List<ParseUser> users, ParseException e) {
                                    if (e == null) {
                                        for (ParseUser user : users) {
                                            //membreList.add(membre.getAdherant());
                                            membres.add(user.getUsername());
                                        }
                                    } else {
                                        Log.d("users", "empty");
                                    }
                                }
                            });
                        }
                    }
                });*/
                thistontine = tontine;
                ParseQuery<Membre> membreQuery = ParseQuery.getQuery(Membre.class);
                membreQuery.whereNotEqualTo("tontine", tontine);
                membreQuery.findInBackground(
                    new FindCallback<Membre>() {
                      @Override
                      public void done(List<Membre> membreList, ParseException e) {
                        if ((e == null) && (membreList.size() >= 0)) {
                          for (Membre membre : membreList) {
                            ParseUser user = membre.getAdherant();
                            user.fetchIfNeededInBackground(
                                new GetCallback<ParseUser>() {
                                  @Override
                                  public void done(ParseUser parseObject, ParseException e) {

                                    membres.add(parseObject.getUsername());
                                  }
                                });
                          }
                        }
                      }
                    });
              }
            }
          });
    }

    ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, membres);
    mMembre.setAdapter(adapter);
    mMembre.setThreshold(1);
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Initialize the count for the objects that will be accessed from the query
    count = 0;

    // Get the bundle from the previous activity from the profile name
    restaurant = getIntent().getExtras();
    resName = restaurant.getString("profileName");
    // resID = "KM9nKPYUob";
    resID = restaurant.getString("resID");
    if (resID == null) {
      resID = "KM9nKPYUob";
    }
    // resID = "pGohUeer8T";

    // Set the layout as the restaurant profile activity layout
    setContentView(R.layout.activity_restaurant_profile);

    // Set the LinearLayout for reviews
    final LinearLayout review = (LinearLayout) findViewById(R.id.reviewsList);

    // Set the name of the restaurant
    TextView profileName = (TextView) findViewById(R.id.profileName);
    // Get the name of the restaurant from the query to set
    profileName.setText(resName);

    // Set the profile Picture of the restaurant
    ImageView profilePicture = (ImageView) findViewById(R.id.profileIcon);
    Bitmap b = (Bitmap) restaurant.getParcelable("image");
    profilePicture.setImageBitmap(b);

    // Query for the restaurant object
    query = ParseQuery.getQuery("RestaurantObject");
    query.getInBackground(
        resID,
        new GetCallback<ParseObject>() {
          @Override
          public void done(ParseObject object, com.parse.ParseException e) {
            if (e == null) {
              res = object;
              // Set up reviews
              reviews = res.getJSONArray("reviewList");
              // Set up pictures
              parsePics = res.getJSONArray("pictureList");

              // Set rating to Google's rating
              RatingBar stars = (RatingBar) findViewById(R.id.ratingStars);
              Double ratingDbl = (Double) restaurant.get("Rating");
              if (ratingDbl == null) {
                ratingDbl = 3.0;
              }
              String ratingStr = ratingDbl.toString();
              stars.setRating(Float.parseFloat(ratingStr));

              // Set up link for website
              TextView textView = (TextView) findViewById(R.id.website);
              textView.setClickable(true);
              textView.setMovementMethod(LinkMovementMethod.getInstance());
              String text = "<a href='" + restaurant.getString("Website") + "'> Website </a>";
              // String text = "<a href='google.com'> Website </a>";
              textView.setText(Html.fromHtml(text));

              // Set up phone number
              final TextView phoneNum = (TextView) findViewById(R.id.phone);
              phoneNum.setClickable(true);
              phoneNum.setText(restaurant.getString("PhoneNumber"));
              // phoneNum.setText("<a href='+tel:+510-378-3326)'> 510-378-3326 </a>");

              phoneNum.setOnClickListener(
                  new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                      // TODO Auto-generated method stub
                      String phone_no = (phoneNum.getText().toString().replaceAll("-", ""));
                      Intent callIntent = new Intent(Intent.ACTION_DIAL);
                      callIntent.setData(Uri.parse("tel:" + phone_no));
                      startActivity(callIntent);
                    }
                  });

              // Set up link to menu activity
              TextView menuButton = (TextView) findViewById(R.id.menuChange);
              menuButton.setOnClickListener(
                  new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                      Intent i = new Intent(getApplicationContext(), RestaurantMenu.class);
                      startActivity(i);
                      setContentView(R.layout.content_base);
                    }
                  });

              // Set Hours of the restaurant
              TextView hours = (TextView) findViewById(R.id.hours);
              hours.setText(restaurant.getString("Hours"));

              // Set Location of the restaurant
              TextView location = (TextView) findViewById(R.id.location);
              location.setText(restaurant.getString("Address"));

              // Add pictures to the scroll view
              LinearLayout restaurantPics = (LinearLayout) findViewById(R.id.restaurantPics);
              for (int i = 0; parsePics != null && !parsePics.isNull(i); i++) {
                try {
                  query = ParseQuery.getQuery("ImageUpload");
                  query.whereEqualTo("objectId", parsePics.get(i).toString());
                  ParseObject pictureObj = query.getFirst();
                  ParseFile fileObject = pictureObj.getParseFile("ImageFile");
                  fileObject.getDataInBackground(
                      new GetDataCallback() {

                        @Override
                        public void done(byte[] data, com.parse.ParseException e) {
                          if (e == null) {

                            Log.d("test", "We've got data in data.");
                            // Decode the Byte[] into
                            // Bitmap
                            final float scale = getResources().getDisplayMetrics().density;
                            int pixels = (int) (100 * scale + 0.5f);

                            Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);

                            float ratio = (float) bmp.getHeight() / (float) bmp.getWidth();

                            Bitmap scaled =
                                Bitmap.createScaledBitmap(
                                    bmp,
                                    (int) ((150 * scale + 0.5f) * 1 / ratio),
                                    (int) (150 * scale + 0.5f),
                                    false);
                            bmp.recycle();

                            Log.i("This is the bitmap", bmp.toString());

                            LinearLayout scrollPics =
                                (LinearLayout) findViewById(R.id.restaurantPics);
                            // Get the ImageView from
                            // main.xml

                            ImageButton image =
                                (ImageButton) new ImageButton(scrollPics.getContext());
                            // Set the Bitmap into the
                            // ImageView
                            image.setImageBitmap(scaled);
                            image.setScaleType(ImageView.ScaleType.CENTER_CROP);

                            image.setLayoutParams(new ViewGroup.LayoutParams(pixels, pixels));

                            scrollPics.addView(image);
                          } else {
                            Log.d("test", "There was a problem downloading the data.");
                          }
                        }
                      });
                  // restaurantPics.addView(foodPic);
                } catch (JSONException ex) {
                  ex.printStackTrace();
                } catch (com.parse.ParseException ex) {
                  ex.printStackTrace();
                }
              }

              // Show user reviews

              for (int j = count;
                  count < j + 5 && reviews != null && !reviews.isNull(reviews.length() - count - 1);
                  count++) {
                // The following lines of code is what will go into the for loop after we have data
                // to use
                // in the data base

                // TODO: figure out how to properly load reviews in background thread in correct
                // order
                // trying to make it load faster
                /*query = ParseQuery.getQuery("UserReview");
                try {
                    query.getInBackground(reviews.get(reviews.length() - count - 1).toString(), new GetCallback<ParseObject>() {
                        @Override
                        public void done(ParseObject object, com.parse.ParseException e) {
                            reviewObj = object;
                            if (object != null) {
                                Log.i("This is the Stuff in", reviewObj.get("Review").toString());
                                final TextView author = new TextView(getApplicationContext());

                                // get username
                                ParseQuery<ParseUser> userQuery = ParseUser.getQuery();
                                userQuery.getInBackground(reviewObj.get("UserID").toString(), new GetCallback<ParseUser>() {
                                    @Override
                                    public void done(ParseUser object, com.parse.ParseException e) {
                                        if (e == null) {
                                            author.setText(object.getUsername());
                                        }
                                        else {
                                            author.setText("Anonymous User");
                                        }

                                        // Setting up the rating bar for the rating
                                        RatingBar authorRating = new RatingBar(getApplicationContext(), null, android.R.attr.ratingBarStyleSmall);
                                        authorRating.setNumStars(5);
                                        authorRating.setStepSize((float) 0.5);
                                        authorRating.setIsIndicator(true);
                                        authorRating.setRating(Float.parseFloat(reviewObj.get("Rating").toString()));
                                        authorRating.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                                        review.addView(authorRating);

                                        // get the review
                                        TextView authorReview = new TextView(getApplicationContext());
                                        authorReview.setText(reviewObj.get("Review").toString());
                                        review.addView(authorReview);

                                        author.setTypeface(Typeface.DEFAULT_BOLD);
                                        review.addView(author);
                                    }
                                });
                            }
                        }
                    });

                } catch (JSONException ex) {
                    ex.printStackTrace();
                }*/

                try {
                  query = ParseQuery.getQuery("UserReview");
                  query.whereEqualTo(
                      "objectId", reviews.get(reviews.length() - count - 1).toString());
                  ParseObject reviewObj =
                      query.get(reviews.get(reviews.length() - count - 1).toString());

                  Log.i("This is the Stuff in", reviewObj.get("Review").toString());

                  LinearLayout review = (LinearLayout) findViewById(R.id.reviewsList);

                  ParseQuery<ParseUser> userQuery = ParseUser.getQuery();
                  userQuery.whereEqualTo("objectId", reviewObj.get("UserID").toString());
                  TextView author = new TextView(getApplicationContext());

                  if (userQuery.count() == 0) {
                    author.setText("Anonymous User");
                  } else {
                    ParseUser userObj = userQuery.getFirst();
                    author.setText(userObj.getUsername().toString());
                  }

                  author.setTextColor(Color.DKGRAY);
                  author.setTypeface(Typeface.DEFAULT_BOLD);

                  review.addView(author);

                  query = ParseQuery.getQuery("UserReview");
                  query.whereEqualTo(
                      "objectId", reviews.get(reviews.length() - count - 1).toString());

                  // Setting up the rating bar for the rating
                  RatingBar authorRating =
                      new RatingBar(
                          getApplicationContext(), null, android.R.attr.ratingBarStyleSmall);
                  authorRating.setNumStars(5);
                  authorRating.setStepSize((float) 0.1);
                  authorRating.setIsIndicator(true);
                  authorRating.setRating(Float.parseFloat(reviewObj.get("Rating").toString()));
                  authorRating.setLayoutParams(
                      new AbsListView.LayoutParams(
                          AbsListView.LayoutParams.WRAP_CONTENT,
                          ViewGroup.LayoutParams.WRAP_CONTENT));
                  review.addView(authorRating);

                  TextView authorReview = new TextView(getApplicationContext());
                  authorReview.setText(reviewObj.get("Review").toString());
                  authorReview.setTextColor(Color.DKGRAY);
                  review.addView(authorReview);

                } catch (JSONException ex) {
                  ex.printStackTrace();

                } catch (com.parse.ParseException ex) {
                  ex.printStackTrace();
                }
              }

              Button more = new Button(getApplicationContext());
              more.setText("more");
              more.setOnClickListener(
                  new View.OnClickListener() {
                    public void onClick(View v) {
                      if (reviews == null || reviews.isNull(reviews.length() - count - 1)) {
                        Toast.makeText(
                                getApplicationContext(), "No More Reviews!", Toast.LENGTH_SHORT)
                            .show();
                        return;
                      }
                      // Set ratings for the restaurant
                      for (int j = count;
                          count < j + 5
                              && reviews != null
                              && !reviews.isNull(reviews.length() - count - 1);
                          count++) {
                        // The following lines of code is what will go into the for loop after we
                        // have data to use
                        // in the data base

                        try {
                          query = ParseQuery.getQuery("UserReview");
                          query.whereEqualTo(
                              "objectId", reviews.get(reviews.length() - count - 1).toString());
                          ParseObject reviewObj =
                              query.get(reviews.get(reviews.length() - count - 1).toString());

                          Log.i("This is the Stuff in", reviewObj.get("Review").toString());

                          LinearLayout review = (LinearLayout) findViewById(R.id.reviewsList);

                          ParseQuery<ParseUser> userQuery = ParseUser.getQuery();
                          userQuery.whereEqualTo("objectId", reviewObj.get("UserID").toString());
                          TextView author = new TextView(v.getContext());

                          if (userQuery.count() == 0) {
                            author.setText("Anonymous User");
                          } else {
                            ParseUser userObj = userQuery.getFirst();
                            author.setText(userObj.getUsername().toString());
                          }

                          author.setTextColor(Color.DKGRAY);
                          author.setTypeface(Typeface.DEFAULT_BOLD);

                          review.addView(author);

                          query = ParseQuery.getQuery("UserReview");
                          query.whereEqualTo(
                              "objectId", reviews.get(reviews.length() - count - 1).toString());
                          // Setting up the rating bar for the rating
                          RatingBar authorRating =
                              new RatingBar(
                                  v.getContext(), null, android.R.attr.ratingBarStyleSmall);
                          authorRating.setNumStars(5);
                          authorRating.setStepSize((float) 0.1);
                          authorRating.setIsIndicator(true);
                          authorRating.setRating(
                              Float.parseFloat(reviewObj.get("Rating").toString()));
                          authorRating.setLayoutParams(
                              new AbsListView.LayoutParams(
                                  AbsListView.LayoutParams.WRAP_CONTENT,
                                  ViewGroup.LayoutParams.WRAP_CONTENT));

                          review.addView(authorRating);

                          // Set the review
                          TextView authorReview = new TextView(v.getContext());
                          authorReview.setText(reviewObj.get("Review").toString());

                          authorReview.setTextColor(Color.DKGRAY);
                          review.addView(authorReview);

                        } catch (JSONException e) {
                          e.printStackTrace();

                        } catch (com.parse.ParseException e) {
                          e.printStackTrace();
                        }
                      }
                    }
                  });

              LinearLayout outerLayout = (LinearLayout) findViewById(R.id.profileOuterLinearLayout);
              outerLayout.addView(more);
            }
          }
        });

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
  }
Example #23
0
  @Nullable
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View v = inflater.inflate(R.layout.screen_newpolicy, null);
    mRecyclerView = (RecyclerView) v.findViewById(R.id.uploadsListview);
    mAddUpload = (ImageButton) v.findViewById(R.id.addUpload);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(v.getContext()));
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    ParseObject.registerSubclass(Upload.class);
    ParseObject.registerSubclass(Policy.class);
    ParseUser.registerSubclass(Client.class);

    clients = (Spinner) v.findViewById(R.id.clientSpinner);
    description = (EditText) v.findViewById(R.id.description);
    cost = (EditText) v.findViewById(R.id.cost);
    address = (EditText) v.findViewById(R.id.address);
    city = (EditText) v.findViewById(R.id.city);
    zip = (EditText) v.findViewById(R.id.zip);
    states = (Spinner) v.findViewById(R.id.states);

    allClients = new ArrayList<>();
    thisUploads = new ArrayList<>();
    newUploads = new ArrayList<>();

    final ParseQuery<Client> getClients = ParseQuery.getQuery(Client.class);
    final ParseQuery<Policy> getPolicy = ParseQuery.getQuery(Policy.class);
    bundle = this.getArguments();
    if (bundle != null)
      if (bundle.getString("policyID") != null)
        getPolicy.getInBackground(
            bundle.getString("policyID"),
            new GetCallback<Policy>() {

              public void done(Policy p, ParseException e) {
                currentPolicy = new Policy();
                currentPolicy = p;
                description.setText(p.getDescription());
                cost.setText(p.getCost().toString());
                address.setText(p.getAddress());
                city.setText(p.getCity());
                zip.setText(p.getZip().toString());
                states.setSelection(((ArrayAdapter) states.getAdapter()).getPosition(p.getState()));
                Thread t = new Thread(new LoadUploads(v.getContext()));
                t.start();
              }
            });

    if (bundle != null)
      if (bundle.getString("clientID") != null) clientID = bundle.getString("clientID");

    getClients.whereEqualTo("accountType", "Client");
    getClients.whereEqualTo("AgentID", ParseUser.getCurrentUser().getObjectId());
    getClients.findInBackground(
        new FindCallback<Client>() {
          @Override
          public void done(List<Client> list, ParseException e) {
            allClients.addAll(list);
            ArrayList<String> clientNames = new ArrayList<String>();
            for (Client c : list) clientNames.add(c.getUserName());
            clientNameAdapter =
                new ArrayAdapter<String>(
                    getActivity(), android.R.layout.simple_spinner_item, clientNames);
            clients.setAdapter(clientNameAdapter);
            if (bundle != null)
              if (bundle.getString("clientName") != null) {
                clients.setSelection(
                    ((ArrayAdapter) clients.getAdapter())
                        .getPosition(bundle.getString("clientName")));
                clients.setEnabled(false);
                clients.setClickable(false);
              }
          }
        });

    mAddUpload.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            Intent intent = new Intent();
            intent.setType("image/*,video/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            // Always show the chooser (if there are multiple options available)
            startActivityForResult(
                Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
          }
        });

    ItemTouchHelper helper =
        new ItemTouchHelper(
            new ItemTouchHelper.SimpleCallback(
                ItemTouchHelper.UP
                    | ItemTouchHelper.DOWN
                    | ItemTouchHelper.START
                    | ItemTouchHelper.END,
                ItemTouchHelper.START | ItemTouchHelper.END) {
              @Override
              public boolean onMove(
                  RecyclerView recyclerView,
                  RecyclerView.ViewHolder viewHolder,
                  RecyclerView.ViewHolder target) {
                adapter.notifyItemMoved(
                    viewHolder.getAdapterPosition(), target.getAdapterPosition());
                return true;
              }

              @Override
              public void onSwiped(RecyclerView.ViewHolder viewHolder, int i) {
                thisUploads.remove(viewHolder.getAdapterPosition());
                adapter.notifyItemRemoved(viewHolder.getAdapterPosition());
              }
            });
    helper.attachToRecyclerView(mRecyclerView);
    return v;
  }