Search in sources :

Example 26 with User

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

the class LoginSignUpActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // the first time user open the app the default preferences must be setted up
    PreferenceManager.setDefaultValues(this, R.layout.preferences, false);
    Log.i(TAG, "onCreate");
    FirebaseUtils.getInstance().setUp();
    // getting Intent from invitation
    Intent startingIntent = getIntent();
    // prepare intent for MainActivity
    goToMain = new Intent(getApplicationContext(), MainActivity.class);
    goToMain.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
    String action = startingIntent.getAction();
    Log.d(TAG, "action " + action);
    // 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");
        goToMain.putExtra("inviterID", inviterID);
    } else
        inviterID = null;
    if (startingIntent.hasExtra("groupToBeAddedID")) {
        groupToBeAddedID = startingIntent.getStringExtra("groupToBeAddedID");
        startingIntent.removeExtra("groupToBeAddedID");
        goToMain.putExtra("groupToBeAddedID", groupToBeAddedID);
    } else
        groupToBeAddedID = null;
    // insert tabs and current fragment in the main layout
    setContentView(R.layout.activity_log_in_signup);
    // for adding custom font to the title of the app
    TextView titleTextView = (TextView) findViewById(R.id.title);
    Typeface mycustomfont = Typeface.createFromAsset(getAssets(), "fonts/Lobster-Regular.ttf");
    titleTextView.setTypeface(mycustomfont);
    // for adding custom background image
    ImageView background = (ImageView) findViewById(R.id.background);
    Glide.with(this).load(R.drawable.background).centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL).into(background);
    // findViewById(R.id.activity_log_in_signup_layout).setOnClickListener(this);
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText(R.string.login));
    tabLayout.addTab(tabLayout.newTab().setText(R.string.signup));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    viewPager = (ViewPager) findViewById(R.id.main_view_pager);
    adapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    viewPager.setCurrentItem(0);
    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            Log.d(TAG, String.valueOf(tab.getPosition()));
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
        }
    });
}
Also used : Typeface(android.graphics.Typeface) TabLayout(android.support.design.widget.TabLayout) Intent(android.content.Intent) TextView(android.widget.TextView) MainActivity(com.polito.mad17.madmax.activities.MainActivity) ImageView(android.widget.ImageView) FragmentPagerAdapter(android.support.v4.app.FragmentPagerAdapter)

Example 27 with User

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

the class SignUpFragment method sendVerificationEmail.

private void sendVerificationEmail() {
    Log.i(TAG, "sendVerificationEmail");
    final FirebaseUser user = auth.getCurrentUser();
    if (user == null) {
        Log.e(TAG, "Error while retriving current user from db");
        Toast.makeText(getContext(), getString(R.string.error_user_db), Toast.LENGTH_LONG).show();
        return;
    }
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this.getContext());
    String defaultCurrency = sharedPref.getString(SettingsFragment.DEFAULT_CURRENCY, "");
    String UID = user.getUid();
    final User u = new User(UID, usernameView.getText().toString(), nameView.getText().toString(), surnameView.getText().toString(), emailView.getText().toString(), passwordView.getText().toString(), "", defaultCurrency);
    progressDialog.setMessage("Sending email verification, please wait...");
    progressDialog.show();
    // inserimento dell'utente a db (tranne la foto)
    HashMap<String, String> newUserEntry = new HashMap<>();
    newUserEntry.put("email", u.getEmail());
    newUserEntry.put("password", u.getPassword());
    newUserEntry.put("name", u.getName());
    newUserEntry.put("surname", u.getSurname());
    newUserEntry.put("username", u.getUsername());
    databaseReference.child("users").child(u.getID()).setValue(newUserEntry);
    Log.i(TAG, "new user sent into db");
    // for saving image
    if (imageSetted) {
        StorageReference uProfileImageFilenameRef = storageReference.child("users").child(UID).child(UID + "_profileImage.jpg");
        // Get the data from an ImageView as bytes
        profileImageView.setDrawingCacheEnabled(true);
        profileImageView.buildDrawingCache();
        Bitmap bitmap = profileImageView.getDrawingCache();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] data = baos.toByteArray();
        UploadTask uploadTask = uProfileImageFilenameRef.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.
                // inserimento della foto a db
                u.setProfileImage(taskSnapshot.getMetadata().getDownloadUrl().toString());
                databaseReference.child("users").child(u.getID()).child("image").setValue(u.getProfileImage());
                user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {

                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        progressDialog.dismiss();
                        if (task.isSuccessful()) {
                            Log.i(TAG, "verification email successfully sent");
                            Toast.makeText(getContext(), R.string.emailVerification_text, Toast.LENGTH_LONG).show();
                        } else {
                            databaseReference.child("users").child(u.getID()).removeValue();
                            user.delete();
                            Log.d(TAG, "user deleted from db");
                            Log.e(TAG, "verification email not sent, exception: " + task.getException());
                        }
                        onClickSignUpInterface.itemClicked(SignUpFragment.class.getSimpleName(), "1");
                    }
                });
            }
        });
    } else {
        user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {

            @Override
            public void onComplete(@NonNull Task<Void> task) {
                progressDialog.dismiss();
                if (task.isSuccessful()) {
                    Log.i(TAG, "verification email successful sent");
                    Toast.makeText(getContext(), R.string.emailVerification_text, Toast.LENGTH_LONG).show();
                } else {
                    databaseReference.child("users").child(u.getID()).removeValue();
                    user.delete();
                    Log.d(TAG, "user deleted from db");
                    Log.e(TAG, "verification email not sent, exception: " + task.getException());
                }
                onClickSignUpInterface.itemClicked(SignUpFragment.class.getSimpleName(), "1");
            }
        });
    }
}
Also used : Task(com.google.android.gms.tasks.Task) UploadTask(com.google.firebase.storage.UploadTask) User(com.polito.mad17.madmax.entities.User) FirebaseUser(com.google.firebase.auth.FirebaseUser) StorageReference(com.google.firebase.storage.StorageReference) SharedPreferences(android.content.SharedPreferences) HashMap(java.util.HashMap) FirebaseUser(com.google.firebase.auth.FirebaseUser) ByteArrayOutputStream(java.io.ByteArrayOutputStream) FirebaseAuthWeakPasswordException(com.google.firebase.auth.FirebaseAuthWeakPasswordException) FirebaseAuthUserCollisionException(com.google.firebase.auth.FirebaseAuthUserCollisionException) IOException(java.io.IOException) Bitmap(android.graphics.Bitmap) UploadTask(com.google.firebase.storage.UploadTask) OnCompleteListener(com.google.android.gms.tasks.OnCompleteListener) NonNull(android.support.annotation.NonNull) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Example 28 with User

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

the class FriendsFragment method getUserAndGroupBalance.

// Retrieve balance of userID toward groupID
void getUserAndGroupBalance(final String userID, final String name, final String surname, final String profileImage, final String groupID) {
    // key = currency
    // value = balance for that currency
    final HashMap<String, Double> totBalances = new HashMap<>();
    totBalances.clear();
    // retrieve data of group
    // final HashMap<String, Double> totalBalance = new HashMap<>();
    // totalBalance.put(userID,0d);
    totBalance = 0d;
    groupListener = databaseReference.child("groups").child(groupID).addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(final DataSnapshot groupDataSnapshot) {
            totBalances.clear();
            // totalBalance.put(userID,0d);
            if (!listenedGroups.contains(groupID))
                listenedGroups.add(groupID);
            final String groupName = groupDataSnapshot.child("name").getValue(String.class);
            final Boolean deleted = groupDataSnapshot.child("deleted").getValue(Boolean.class);
            if (deleted != null) {
                final User u = new User();
                u.setName(name);
                u.setSurname(surname);
                u.setProfileImage(profileImage);
                u.setBalancesWithGroup(totBalances);
                // Metto subito user nella lista, con bilanci inizialmente a zero
                if (!deleted && groupDataSnapshot.child("members").hasChild(MainActivity.getCurrentUID()) && !groupDataSnapshot.child("members").child(MainActivity.getCurrentUID()).child("deleted").getValue(Boolean.class)) {
                    friends.put(userID, u);
                } else {
                    friends.remove(userID);
                }
                friendsViewAdapter.update(friends);
                friendsViewAdapter.notifyDataSetChanged();
                // Se gruppo ha almeno una spesa
                if (groupDataSnapshot.child("expenses").getChildrenCount() > 0) {
                    for (DataSnapshot groupExpenseSnapshot : groupDataSnapshot.child("expenses").getChildren()) {
                        // Contribuiscono al bilancio solo le spese non eliminate dal gruppo
                        if (groupExpenseSnapshot.getValue(Boolean.class) == true) {
                            // Adesso sono sicuro che la spesa non è stata eliminata
                            // Ascolto la singola spesa del gruppo
                            String expenseID = groupExpenseSnapshot.getKey();
                            databaseReference.child("expenses").child(expenseID).addListenerForSingleValueEvent(new ValueEventListener() {

                                @Override
                                public void onDataChange(DataSnapshot dataSnapshot) {
                                    // dice se user contribuisce o no a quella spesa
                                    Boolean involved = false;
                                    for (DataSnapshot participantSnapshot : dataSnapshot.child("participants").getChildren()) {
                                        // todo poi gestire caso in cui utente viene tolto dai participant alla spesa
                                        if (participantSnapshot.getKey().equals(userID))
                                            involved = true;
                                    }
                                    // se user ha partecipato alla spesa
                                    if (involved) {
                                        // balance = credito/debito dello user per quella spesa
                                        for (DataSnapshot d : dataSnapshot.child("participants").getChildren()) {
                                            Log.d(TAG, "PartCampo " + d.getKey() + ": " + d.getValue());
                                        }
                                        Double alreadyPaid = dataSnapshot.child("participants").child(userID).child("alreadyPaid").getValue(Double.class);
                                        Double fraction = dataSnapshot.child("participants").child(userID).child("fraction").getValue(Double.class);
                                        Double balance = null;
                                        String currency = null;
                                        if (fraction != null) {
                                            Log.d(TAG, "Fraction: " + fraction);
                                            Double amount = dataSnapshot.child("amount").getValue(Double.class);
                                            if (amount != null) {
                                                Double dueImport = fraction * amount;
                                                balance = alreadyPaid - dueImport;
                                                currency = dataSnapshot.child("currency").getValue(String.class);
                                            // se user per quella spesa ha già pagato più soldi della sua quota, il balance è positivo
                                            }
                                        }
                                        if (balance != null && currency != null) {
                                            // current balance for that currency
                                            Double temp = totBalances.get(currency);
                                            // update balance for that currency
                                            if (temp != null) {
                                                totBalances.put(currency, temp + balance);
                                                Log.d(TAG, "Actual debt for " + groupName + ": " + totBalances.get(currency) + " " + currency);
                                            } else {
                                                totBalances.put(currency, balance);
                                                Log.d(TAG, "Actual debt for " + groupName + ": " + totBalances.get(currency) + " " + currency);
                                            }
                                        // se user per quella spesa ha già pagato più soldi della sua quota, il balance è positivo
                                        // Double currentBalance = totBalances.get(userID);
                                        // totBalances.put(userID, currentBalance+balance);
                                        }
                                    }
                                    // u.setBalanceWithGroup(totalBalance.get(userID));
                                    u.setBalancesWithGroup(totBalances);
                                    u.setName(name);
                                    u.setSurname(surname);
                                    u.setProfileImage(profileImage);
                                    // se il gruppo non è deleted e io faccio ancora parte del gruppo
                                    if (!deleted && groupDataSnapshot.child("members").hasChild(MainActivity.getCurrentUID()) && !groupDataSnapshot.child("members").child(MainActivity.getCurrentUID()).child("deleted").getValue(Boolean.class)) {
                                        friends.put(userID, u);
                                    } else {
                                        friends.remove(userID);
                                    }
                                    friendsViewAdapter.update(friends);
                                    friendsViewAdapter.notifyDataSetChanged();
                                }

                                @Override
                                public void onCancelled(DatabaseError databaseError) {
                                }
                            });
                        }
                    }
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}
Also used : User(com.polito.mad17.madmax.entities.User) DatabaseError(com.google.firebase.database.DatabaseError) HashMap(java.util.HashMap) ValueEventListener(com.google.firebase.database.ValueEventListener) DataSnapshot(com.google.firebase.database.DataSnapshot)

Example 29 with User

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

the class FriendsViewAdapter method onBindViewHolder.

@Override
public void onBindViewHolder(final ItemFriendsViewHolder holder, int position) {
    Log.d(TAG, "isGroupDetail " + isGroupDetail);
    if (position == (mData.size() - 1)) {
        Log.d(TAG, "item.getKey().equals(\"nullGroup\")");
        holder.nameTextView.setText("");
        holder.balanceTextView.setText("");
        holder.balanceTextTextView.setText("");
    } else {
        Map.Entry<String, User> item = getItem(position);
        Log.d(TAG, item.getKey() + " " + item.getValue().getName() + " " + item.getValue().getProfileImage());
        if (isGroupDetail)
            holder.balanceLayout.setVisibility(View.VISIBLE);
        else
            holder.balanceLayout.setVisibility(View.GONE);
        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());
        // Double balance = item.getValue().getBalanceWithGroup();
        totBalances = item.getValue().getBalancesWithGroup();
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
        String defaultCurrency = sharedPref.getString(SettingsFragment.DEFAULT_CURRENCY, "");
        Boolean multipleCurrencies = false;
        Double shownBal;
        String shownCurr;
        if (totBalances != null && !totBalances.isEmpty()) {
            if (!totBalances.isEmpty()) {
                // If there is more than one currency
                if (totBalances.size() > 1) {
                    multipleCurrencies = true;
                } else // If there is just one currency
                {
                    multipleCurrencies = false;
                }
                if (totBalances.containsKey(defaultCurrency)) {
                    shownBal = totBalances.get(defaultCurrency);
                    shownCurr = defaultCurrency;
                } else {
                    shownCurr = (String) totBalances.keySet().toArray()[0];
                    shownBal = totBalances.get(shownCurr);
                }
                // Print balance
                if (shownBal > 0) {
                    if (isGroupDetail) {
                        holder.balanceTextTextView.setText(R.string.should_receive_from_the_group);
                    } else {
                        holder.balanceTextTextView.setText(R.string.you_should_receive);
                    }
                    holder.balanceTextTextView.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));
                    if (multipleCurrencies)
                        holder.balanceTextView.setText(df.format(shownBal) + " " + shownCurr + "*");
                    else
                        holder.balanceTextView.setText(df.format(shownBal) + " " + shownCurr);
                    holder.balanceTextView.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));
                } else if (shownBal < 0) {
                    if (isGroupDetail) {
                        holder.balanceTextTextView.setText(R.string.owes_to_the_group);
                    } else {
                        holder.balanceTextTextView.setText(R.string.you_owe);
                    }
                    holder.balanceTextTextView.setTextColor(ContextCompat.getColor(context, R.color.colorPrimaryDark));
                    if (multipleCurrencies)
                        holder.balanceTextView.setText(df.format(Math.abs(shownBal)) + " " + shownCurr + "*");
                    else
                        holder.balanceTextView.setText(df.format(Math.abs(shownBal)) + " " + shownCurr);
                    holder.balanceTextView.setTextColor(ContextCompat.getColor(context, R.color.colorPrimaryDark));
                } else if (shownBal == 0) {
                    holder.balanceTextTextView.setText(R.string.no_debts);
                    holder.balanceTextTextView.setTextColor(ContextCompat.getColor(context, R.color.colorSecondaryText));
                    holder.balanceTextView.setText("0 " + defaultCurrency);
                    holder.balanceTextView.setTextColor(ContextCompat.getColor(context, R.color.colorSecondaryText));
                }
            }
        } else // If there are no balances in the map
        {
            holder.balanceTextTextView.setText(R.string.no_debts);
            holder.balanceTextTextView.setTextColor(ContextCompat.getColor(context, R.color.colorSecondaryText));
            holder.balanceTextView.setText("0 " + defaultCurrency);
            holder.balanceTextView.setTextColor(ContextCompat.getColor(context, R.color.colorSecondaryText));
        }
    // todo fin qui
    /*if (balance != null)
            {
                DecimalFormat df = new DecimalFormat("#.##");
                if (balance > 0) {
                    holder.balanceTextTextView.setText(R.string.should_receive_from_the_group);
                    holder.balanceTextTextView.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));

                    //todo mettere valuta
                    String balanceText = df.format(Math.abs(balance)) + " €";
                    holder.balanceTextView.setText(balanceText);
                    holder.balanceTextView.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));

                }
                else
                {
                    if (balance < 0) {
                        holder.balanceTextTextView.setText(R.string.owes_to_the_group);
                        holder.balanceTextTextView.setTextColor(ContextCompat.getColor(context, R.color.colorPrimaryDark));
                        //todo mettere valuta
                        String balanceText = df.format(Math.abs(balance)) + " €";
                        holder.balanceTextView.setText(balanceText);
                        holder.balanceTextView.setTextColor(ContextCompat.getColor(context, R.color.colorPrimaryDark));
                    } else {
                        holder.balanceTextTextView.setText(R.string.no_debts);
                        holder.balanceTextTextView.setTextColor(ContextCompat.getColor(context, R.color.colorSecondaryText));
                        //todo mettere valuta
                        holder.balanceTextView.setText("0 €");
                    }
                    //holder.balanceTextView.setVisibility(View.GONE);
                }
            }

            else if (balance == null)
            {
                holder.balanceTextView.setVisibility(View.GONE);
                holder.balanceTextTextView.setVisibility(View.GONE);

            }*/
    }
}
Also used : User(com.polito.mad17.madmax.entities.User) SharedPreferences(android.content.SharedPreferences) CropCircleTransformation(com.polito.mad17.madmax.entities.CropCircleTransformation) HashMap(java.util.HashMap) Map(java.util.Map)

Example 30 with User

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

the class NewMemberActivity method onActivityResult.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.i(TAG, "onActivityResult: requestCode=" + requestCode + ", resultCode=" + resultCode);
    if (requestCode == MainActivity.REQUEST_INVITE_GROUP) {
        if (resultCode == RESULT_OK) {
            // Get the invitation IDs of all sent messages
            String[] ids = AppInviteInvitation.getInvitationIds(resultCode, data);
            for (String id : ids) {
                Log.i(TAG, "onActivityResult: sent invitation " + id);
            }
            // add event for FRIEND_GROUP_INVITE
            User currentUser = MainActivity.getCurrentUser();
            Event event = new Event(groupID, Event.EventType.FRIEND_GROUP_INVITE, currentUser.getName() + " " + currentUser.getSurname());
            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);
        } else {
            // Sending failed or it was canceled, show failure message to the user
            Log.e(TAG, "onActivityResult: failed sent");
        // Toast.makeText(this, "Unable to send invitation", Toast.LENGTH_SHORT).show();
        }
    }
}
Also used : User(com.polito.mad17.madmax.entities.User) Event(com.polito.mad17.madmax.entities.Event) SimpleDateFormat(java.text.SimpleDateFormat)

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