Search in sources :

Example 6 with User

use of com.polito.mad17.madmax.entities.User in project MadMax by deviz92.

the class VotersViewAdapter method onBindViewHolder.

@Override
public void onBindViewHolder(final VotersViewAdapter.ItemVotersViewHolder holder, int position) {
    if (position == (mData.size() - 1)) {
        Log.d(TAG, "item.getKey().equals(\"nullGroup\")");
        holder.nameTextView.setText("");
        holder.voteTextView.setVisibility(View.GONE);
    } else {
        Map.Entry<String, User> item = getItem(position);
        String photo = item.getValue().getProfileImage();
        if (photo != null && !photo.equals("")) {
            Glide.with(layoutInflater.getContext()).load(photo).centerCrop().bitmapTransform(new CropCircleTransformation(layoutInflater.getContext())).diskCacheStrategy(DiskCacheStrategy.ALL).into(holder.imageView);
        } else {
            Glide.with(layoutInflater.getContext()).load(R.drawable.user_default).centerCrop().bitmapTransform(new CropCircleTransformation(layoutInflater.getContext())).diskCacheStrategy(DiskCacheStrategy.ALL).into(holder.imageView);
        }
        holder.nameTextView.setText(item.getValue().getName() + " " + item.getValue().getSurname());
        Log.d(TAG, "vote " + item.getValue().getVote());
        if (item.getValue().getVote().equals("yes")) {
            holder.voteTextView.setVisibility(View.VISIBLE);
            holder.voteTextView.setBackgroundResource(R.drawable.thumb_up_teal);
        } else if (item.getValue().getVote().equals("no")) {
            holder.voteTextView.setVisibility(View.VISIBLE);
            holder.voteTextView.setBackgroundResource(R.drawable.thumb_down_amber);
        } else if (item.getValue().getVote().equals("null")) {
            holder.voteTextView.setVisibility(View.GONE);
        }
    }
}
Also used : User(com.polito.mad17.madmax.entities.User) CropCircleTransformation(com.polito.mad17.madmax.entities.CropCircleTransformation) Map(java.util.Map)

Example 7 with User

use of com.polito.mad17.madmax.entities.User in project MadMax by deviz92.

the class GroupEdit method updateGroup.

private boolean updateGroup(final Group group) {
    Log.i(TAG, "update group");
    if (!validateForm()) {
        Log.i(TAG, "submitted form is not valid");
        Toast.makeText(this, getString(R.string.invalid_form), Toast.LENGTH_SHORT).show();
        return false;
    }
    String newName = groupNameView.getText().toString();
    String newDescription = groupDescriptionView.getText().toString();
    if (!newName.isEmpty() && (group.getName() == null || !group.getName().equals(newName))) {
        group.setName(newName);
        databaseReference.child("groups").child(group.getID()).child("name").setValue(group.getName());
    }
    if (!newDescription.isEmpty() && (group.getDescription() == null || !group.getDescription().equals(newDescription))) {
        group.setDescription(newDescription);
        databaseReference.child("groups").child(group.getID()).child("description").setValue(group.getDescription());
    }
    if (IMAGE_CHANGED) {
        // for saving image
        StorageReference uGroupImageImageFilenameRef = storageReference.child("groups").child(group.getID()).child(group.getID() + "_groupImage.jpg");
        // Get the data from an ImageView as bytes
        groupImageView.setDrawingCacheEnabled(true);
        groupImageView.buildDrawingCache();
        Bitmap bitmap = groupImageView.getDrawingCache();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] data = baos.toByteArray();
        UploadTask uploadTask = uGroupImageImageFilenameRef.putBytes(data);
        uploadTask.addOnFailureListener(new OnFailureListener() {

            @Override
            public void onFailure(@NonNull Exception exception) {
                // todo Handle unsuccessful uploads
                Log.e(TAG, "image upload failed");
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {

            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
                group.setImage(taskSnapshot.getMetadata().getDownloadUrl().toString());
                databaseReference.child("groups").child(group.getID()).child("image").setValue(group.getImage());
            }
        });
    }
    // add event for GROUP_EDIT
    User currentUser = MainActivity.getCurrentUser();
    Event event = new Event(group.getID(), Event.EventType.GROUP_EDIT, currentUser.getName() + " " + currentUser.getSurname(), group.getName());
    event.setDate(new SimpleDateFormat("yyyy.MM.dd").format(new java.util.Date()));
    event.setTime(new SimpleDateFormat("HH:mm").format(new java.util.Date()));
    FirebaseUtils.getInstance().addEvent(event);
    return true;
}
Also used : User(com.polito.mad17.madmax.entities.User) StorageReference(com.google.firebase.storage.StorageReference) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Bitmap(android.graphics.Bitmap) UploadTask(com.google.firebase.storage.UploadTask) NonNull(android.support.annotation.NonNull) Event(com.polito.mad17.madmax.entities.Event) SimpleDateFormat(java.text.SimpleDateFormat) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Example 8 with User

use of com.polito.mad17.madmax.entities.User in project MadMax by deviz92.

the class GroupEdit method onCreate.

@Override
@TargetApi(23)
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.edit_group);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    groupNameView = (EditText) this.findViewById(R.id.group_name);
    groupDescriptionView = (EditText) this.findViewById(R.id.group_description);
    groupImageView = (ImageView) this.findViewById(R.id.group_image);
    saveButton = (Button) this.findViewById(R.id.btn_save);
    final Intent intent = getIntent();
    final String groupID = intent.getStringExtra("groupID");
    Log.d("DAVIDE", "da GroupEdit: " + groupID);
    databaseReference.child("groups").child(groupID).addListenerForSingleValueEvent(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            group = new Group();
            group.setID(dataSnapshot.getKey());
            group.setName(dataSnapshot.child("name").getValue(String.class));
            group.setDescription(dataSnapshot.child("description").getValue(String.class));
            group.setImage(dataSnapshot.child("image").getValue(String.class));
            groupNameView.setText(group.getName());
            groupDescriptionView.setText(group.getDescription());
            // progressDialog = new ProgressDialog(ProfileEdit.this);
            String groupImage = group.getImage();
            if (groupImage != null && !groupImage.equals("noImage")) {
                // Loading image
                Glide.with(getApplicationContext()).load(groupImage).centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL).into(groupImageView);
            } else {
                // Loading image
                Glide.with(getApplicationContext()).load(R.drawable.group_default).centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL).into(groupImageView);
            }
            groupImageView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Log.i(TAG, "image clicked");
                    if (MainActivity.shouldAskPermission()) {
                        String[] perms = { "android.permission.READ_EXTERNAL_STORAGE" };
                        int permsRequestCode = 200;
                        requestPermissions(perms, permsRequestCode);
                    }
                    // allow to the user the choose image
                    Intent intent = new Intent();
                    // Show only images, no videos or anything else
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    // Always show the chooser (if there are multiple options available)
                    startActivityForResult(Intent.createChooser(intent, "Select picture"), PICK_IMAGE_REQUEST);
                // now see onActivityResult
                }
            });
            saveButton.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Log.i(TAG, "save clicked");
                    if (updateGroup(group)) {
                        Toast.makeText(GroupEdit.this, getString(R.string.saved), Toast.LENGTH_SHORT).show();
                        Intent i = new Intent(getApplicationContext(), GroupDetailActivity.class);
                        i.putExtra("groupID", groupID);
                        i.putExtra("userID", MainActivity.getCurrentUID());
                        startActivity(i);
                        finish();
                    }
                }
            });
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.w(TAG, databaseError.getMessage());
        }
    });
}
Also used : Group(com.polito.mad17.madmax.entities.Group) DatabaseError(com.google.firebase.database.DatabaseError) Intent(android.content.Intent) ValueEventListener(com.google.firebase.database.ValueEventListener) DataSnapshot(com.google.firebase.database.DataSnapshot) ImageView(android.widget.ImageView) View(android.view.View) TargetApi(android.annotation.TargetApi)

Example 9 with User

use of com.polito.mad17.madmax.entities.User in project MadMax by deviz92.

the class MainActivity method onStart.

@Override
protected void onStart() {
    super.onStart();
    Log.i(TAG, "onStart");
    startingIntent = getIntent();
    currentFragment = startingIntent.getIntExtra("currentFragment", 1);
    // start declaration of a listener on all the current user data -> attached in onStart()
    currentUserListener = new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Log.d(TAG, "onDataChange currentUserref");
            if (currentUser == null) {
                // makeText(MainActivity.this, "Ricreato user", Toast.LENGTH_SHORT).show(); // todo: di debug, da rimuovere
                currentUser = new User();
            }
            currentUser.setID(currentUID);
            currentUser.setName(dataSnapshot.child("name").getValue(String.class));
            currentUser.setSurname(dataSnapshot.child("surname").getValue(String.class));
            currentUser.setUsername(dataSnapshot.child("username").getValue(String.class));
            currentUser.setProfileImage(dataSnapshot.child("image").getValue(String.class));
            currentUser.setEmail(dataSnapshot.child("email").getValue(String.class));
            currentUser.setPassword(dataSnapshot.child("password").getValue(String.class));
            Log.d(TAG, "taken basic data of currentUser " + currentUser.toString());
            // get user friends's IDs
            if (dataSnapshot.child("friends").hasChildren())
                for (DataSnapshot friend : dataSnapshot.child("friends").getChildren()) {
                    if (!friend.hasChild("deleted") || !friend.child("deleted").getValue(Boolean.class))
                        currentUser.getUserFriends().put(friend.getKey(), null);
                }
            // get user groups's IDs
            if (dataSnapshot.child("groups").hasChildren())
                for (DataSnapshot group : dataSnapshot.child("groups").getChildren()) {
                    if (group.getValue(Boolean.class))
                        currentUser.getUserGroups().put(group.getKey(), null);
                }
            Log.d(TAG, "Taken friends and groups, now creating the adapter");
            if (currentFragment != null) {
                viewPager.setCurrentItem(currentFragment);
                updateFab(currentFragment);
            } else {
                viewPager.setCurrentItem(1);
                updateFab(1);
            }
            // load nav menu header data for the current user
            loadNavHeader();
            Log.d(TAG, "logged user name: " + currentUser.getName());
            Log.d(TAG, "logged user surname: " + currentUser.getSurname());
            Uri data = startingIntent.getData();
            if (data != null) {
                inviterID = data.getQueryParameter("inviterID");
                groupToBeAddedID = data.getQueryParameter("groupToBeAddedID");
            } else {
                // retrieving data from the intent inviterID & groupToBeAddedID as the group ID where to add the current user
                if (startingIntent.hasExtra("inviterID")) {
                    // to be used to set the current user as friend of the inviter
                    Log.d(TAG, "there is an invite");
                    inviterID = startingIntent.getStringExtra("inviterID");
                    startingIntent.removeExtra("inviterID");
                }
                if (startingIntent.hasExtra("groupToBeAddedID")) {
                    groupToBeAddedID = startingIntent.getStringExtra("groupToBeAddedID");
                    startingIntent.removeExtra("groupToBeAddedID");
                }
            }
            // control if user that requires the friendship is already a friend
            if (inviterID != null) {
                if (!currentUser.getUserFriends().containsKey(inviterID)) {
                    FirebaseUtils.getInstance().addFriend(inviterID);
                    inviterID = null;
                    makeText(MainActivity.this, getString(R.string.new_friend), Toast.LENGTH_LONG).show();
                }
            /*else
                        makeText(MainActivity.this, getString(R.string.already_friends), Toast.LENGTH_LONG).show();*/
            }
            // control if user is already part of requested group
            if (groupToBeAddedID != null) {
                if (!currentUser.getUserGroups().containsKey(groupToBeAddedID)) {
                    // currentUser.joinGroup(groupToBeAddedID); //todo usare questa? non aggiorna il numero dei membri
                    currentUser.getUserGroups().put(groupToBeAddedID, null);
                    FirebaseUtils.getInstance().joinGroupFirebase(currentUID, groupToBeAddedID);
                    groupToBeAddedID = null;
                    makeText(MainActivity.this, getString(R.string.join_group), Toast.LENGTH_LONG).show();
                }
            // else
            // makeText(MainActivity.this, getString(R.string.already_in_group) + "\""+currentUser.getUserGroups().get(groupToBeAddedID).getName()+"\"", Toast.LENGTH_LONG).show();
            }
            if (startingIntent.hasExtra("notificationTitle")) {
                Intent notificationIntent = null;
                switch(startingIntent.getStringExtra("notificationTitle")) {
                    case "notification_invite":
                        if (startingIntent.hasExtra("groupID")) {
                            notificationIntent = new Intent(getApplicationContext(), GroupDetailActivity.class);
                            notificationIntent.putExtra("groupID", startingIntent.getStringExtra("groupID"));
                        }
                        break;
                    case "notification_expense_added":
                        if (startingIntent.hasExtra("groupID")) {
                            notificationIntent = new Intent(getApplicationContext(), ExpenseDetailActivity.class);
                            notificationIntent.putExtra("groupID", startingIntent.getStringExtra("groupID"));
                            if (startingIntent.hasExtra("expenseID")) {
                                notificationIntent.putExtra("expenseID", startingIntent.getStringExtra("expenseID"));
                            }
                        }
                        break;
                    case "notification_expense_removed":
                        if (startingIntent.hasExtra("groupID")) {
                            notificationIntent = new Intent(getApplicationContext(), GroupDetailActivity.class);
                            notificationIntent.putExtra("groupID", startingIntent.getStringExtra("groupID"));
                        }
                        break;
                    case "notification_proposalExpense_added":
                        if (startingIntent.hasExtra("expenseID")) {
                            notificationIntent = new Intent(getApplicationContext(), PendingExpenseDetailActivity.class);
                            notificationIntent.putExtra("expenseID", startingIntent.getStringExtra("expenseID"));
                        }
                        break;
                }
                if (notificationIntent != null) {
                    notificationIntent.putExtra("userID", currentUID);
                    startingIntent.removeExtra("notificationTitle");
                    startActivityForResult(notificationIntent, REQUEST_NOTIFICATION);
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            // TODO: come gestire?
            Log.d(TAG, "getting current user failed");
        }
    };
    // end of listener declaration on all the current user data
    authListener = new FirebaseAuth.AuthStateListener() {

        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            Log.d(TAG, "onAuthStateChanged");
            currentFirebaseUser = firebaseAuth.getCurrentUser();
            if (currentFirebaseUser != null && currentFirebaseUser.isEmailVerified()) {
                // getting reference to the user from db
                currentUID = currentFirebaseUser.getUid();
                currentUserRef = usersRef.child(currentUID);
                // take refreshed toked and save it to use FCM
                currentUserRef.child("token").setValue(FirebaseInstanceId.getInstance().getToken());
                Log.d(TAG, "device token: " + FirebaseInstanceId.getInstance().getToken());
                // attach a listener on all the current user data
                currentUserRef.addValueEventListener(currentUserListener);
            } else {
                Log.d(TAG, "current user is null, so go to login activity");
                Intent goToLogin = new Intent(getApplicationContext(), LoginSignUpActivity.class);
                // currentUser = null;
                startActivity(goToLogin);
                auth.removeAuthStateListener(authListener);
                finish();
            }
        }
    };
    // attach the listener to the FirebaseAuth instance
    auth.addAuthStateListener(authListener);
}
Also used : User(com.polito.mad17.madmax.entities.User) FirebaseUser(com.google.firebase.auth.FirebaseUser) DatabaseError(com.google.firebase.database.DatabaseError) LoginSignUpActivity(com.polito.mad17.madmax.activities.login.LoginSignUpActivity) Intent(android.content.Intent) ValueEventListener(com.google.firebase.database.ValueEventListener) DataSnapshot(com.google.firebase.database.DataSnapshot) Uri(android.net.Uri) FirebaseAuth(com.google.firebase.auth.FirebaseAuth)

Example 10 with User

use of com.polito.mad17.madmax.entities.User in project MadMax by deviz92.

the class ChooseGroupActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.d(TAG, "onCreate");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_choose_group);
    RecyclerView.ItemDecoration divider = new InsetDivider.Builder(this).orientation(InsetDivider.VERTICAL_LIST).dividerHeight(getResources().getDimensionPixelSize(R.dimen.divider_height)).color(getResources().getColor(R.color.colorDivider)).insets(getResources().getDimensionPixelSize(R.dimen.divider_inset), 0).overlay(true).build();
    recyclerView = (RecyclerView) findViewById(R.id.rv_skeleton);
    layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.addItemDecoration(divider);
    groupsViewAdapter = new GroupsViewAdapter(getBaseContext(), this, groups, ChooseGroupActivity.TAG);
    recyclerView.setAdapter(groupsViewAdapter);
    // Ascolto i gruppi dello user
    databaseReference.child("users").child(MainActivity.getCurrentUID()).child("groups").addListenerForSingleValueEvent(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // Per ogni gruppo dello user
            for (DataSnapshot groupSnapshot : dataSnapshot.getChildren()) {
                // Se il gruppo è true, ossia è ancora tra quelli dello user
                if (groupSnapshot.getValue(Boolean.class))
                    FirebaseUtils.getInstance().getGroup(groupSnapshot.getKey(), groups, groupsViewAdapter);
                else {
                    // tolgo il gruppo da quelli che verranno stampati, così lo vedo sparire realtime
                    groups.remove(groupSnapshot.getKey());
                    groupsViewAdapter.update(groups);
                    groupsViewAdapter.notifyDataSetChanged();
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.w(TAG, databaseError.toException());
        }
    });
}
Also used : GroupsViewAdapter(com.polito.mad17.madmax.activities.groups.GroupsViewAdapter) DatabaseError(com.google.firebase.database.DatabaseError) RecyclerView(android.support.v7.widget.RecyclerView) ValueEventListener(com.google.firebase.database.ValueEventListener) LinearLayoutManager(android.support.v7.widget.LinearLayoutManager) DataSnapshot(com.google.firebase.database.DataSnapshot)

Aggregations

User (com.polito.mad17.madmax.entities.User)27 Intent (android.content.Intent)17 DataSnapshot (com.google.firebase.database.DataSnapshot)16 DatabaseError (com.google.firebase.database.DatabaseError)16 ValueEventListener (com.google.firebase.database.ValueEventListener)16 Event (com.polito.mad17.madmax.entities.Event)15 SimpleDateFormat (java.text.SimpleDateFormat)14 View (android.view.View)8 HashMap (java.util.HashMap)8 Map (java.util.Map)8 ImageView (android.widget.ImageView)6 CropCircleTransformation (com.polito.mad17.madmax.entities.CropCircleTransformation)6 Bitmap (android.graphics.Bitmap)4 NonNull (android.support.annotation.NonNull)4 LinearLayoutManager (android.support.v7.widget.LinearLayoutManager)4 RecyclerView (android.support.v7.widget.RecyclerView)4 StorageReference (com.google.firebase.storage.StorageReference)4 UploadTask (com.google.firebase.storage.UploadTask)4 Group (com.polito.mad17.madmax.entities.Group)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4