Search in sources :

Example 16 with ValueEventListener

use of com.google.firebase.database.ValueEventListener 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 17 with ValueEventListener

use of com.google.firebase.database.ValueEventListener 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)

Example 18 with ValueEventListener

use of com.google.firebase.database.ValueEventListener in project MadMax by deviz92.

the class ExpenseDetailActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_expense_detail);
    Intent intent = getIntent();
    groupID = intent.getStringExtra("groupID");
    userID = intent.getStringExtra("userID");
    expenseID = intent.getStringExtra("expenseID");
    fab = (FloatingActionButton) findViewById(R.id.fab);
    updateFab(0);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    toolbar.setBackgroundColor(0x0000FF00);
    // Get a support ActionBar corresponding to this toolbar
    ActionBar ab = getSupportActionBar();
    // Enable the Up button
    ab.setDisplayHomeAsUpEnabled(true);
    // insert tabs and current fragment in the main layout
    // mainView.addView(getLayoutInflater().inflate(R.layout.activity_expense_detail, null));
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText(R.string.expense_detail));
    tabLayout.addTab(tabLayout.newTab().setText(R.string.comments));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    viewPager = (ViewPager) findViewById(R.id.expense_detail_view_pager);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

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

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

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
        }
    });
    ExpenseDetailPagerAdapter adapter = new ExpenseDetailPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount(), expenseID, TAG);
    viewPager.setAdapter(adapter);
    viewPager.setCurrentItem(0);
    // Set data of upper part of Activity
    imageView = (ImageView) findViewById(R.id.img_photo);
    amountTextView = (TextView) findViewById(R.id.tv_amount);
    creatorNameTextView = (TextView) findViewById(R.id.tv_creator_name);
    expenseNameTextView = (TextView) findViewById(R.id.tv_pending_name);
    balanceTextTextView = (TextView) findViewById(R.id.tv_balance_text);
    balanceTextView = (TextView) findViewById(R.id.tv_balance);
    payExpenseButton = (Button) findViewById(R.id.btn_pay_debt);
    userImage = MainActivity.getCurrentUser().getProfileImage();
    payExpenseButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Log.d(TAG, "Clicked payButton");
            if (expenseBalance >= 0) {
                Toast.makeText(ExpenseDetailActivity.this, getString(R.string.no_debts_to_pay_for_expense), Toast.LENGTH_SHORT).show();
            } else {
                Intent intent = new Intent(ExpenseDetailActivity.this, PayExpenseActivity.class);
                intent.putExtra("groupID", groupID);
                intent.putExtra("userID", userID);
                intent.putExtra("userImage", userImage);
                intent.putExtra("debt", expenseBalance);
                intent.putExtra("expenseID", expenseID);
                intent.putExtra("expenseName", expenseName);
                intent.putExtra("expenseCurrency", currency);
                intent.putExtra("expenseImage", expensePhoto);
                startActivity(intent);
                finish();
            }
        }
    });
    // Retrieve data of this expense
    databaseReference.child("expenses").child(expenseID).addListenerForSingleValueEvent(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            expenseName = dataSnapshot.child("description").getValue(String.class);
            Double amount = dataSnapshot.child("amount").getValue(Double.class);
            currency = dataSnapshot.child("currency").getValue(String.class);
            expensePhoto = dataSnapshot.child("expensePhoto").getValue(String.class);
            expenseNameTextView.setText(expenseName);
            // .load(dataSnapshot.child("image").getValue(String.class))
            Glide.with(getApplicationContext()).load(dataSnapshot.child("expensePhoto").getValue(String.class)).placeholder(R.color.colorPrimary).centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL).into(imageView);
            DecimalFormat df = new DecimalFormat("#.##");
            amountTextView.setText(df.format(amount) + " " + currency);
            // Retrieve my balance for this expense
            Double dueImport = Double.parseDouble(String.valueOf(dataSnapshot.child("participants").child(userID).child("fraction").getValue())) * dataSnapshot.child("amount").getValue(Double.class);
            Double alreadyPaid = dataSnapshot.child("participants").child(userID).child("alreadyPaid").getValue(Double.class);
            expenseBalance = alreadyPaid - dueImport;
            expenseBalance = Math.floor(expenseBalance * 100) / 100;
            if (expenseBalance > 0) {
                balanceTextTextView.setText("For this expense you should receive");
                balanceTextView.setText(expenseBalance.toString() + " " + currency);
            } else if (expenseBalance < 0) {
                balanceTextTextView.setText("For this expense you should pay");
                Double absBalance = abs(expenseBalance);
                balanceTextView.setText(absBalance.toString() + " " + currency);
            } else if (expenseBalance == 0) {
                balanceTextTextView.setText("For this expense you have no debts");
                balanceTextView.setText("0" + " " + currency);
            }
            // Retrieve name and surname of creator
            String creatorID = dataSnapshot.child("creatorID").getValue(String.class);
            databaseReference.child("users").child(creatorID).addListenerForSingleValueEvent(new ValueEventListener() {

                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    String name = dataSnapshot.child("name").getValue(String.class);
                    String surname = dataSnapshot.child("surname").getValue(String.class);
                    creatorNameTextView.setText(name + " " + surname);
                }

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

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}
Also used : DecimalFormat(java.text.DecimalFormat) ExpenseDetailPagerAdapter(com.polito.mad17.madmax.activities.ExpenseDetailPagerAdapter) Intent(android.content.Intent) DataSnapshot(com.google.firebase.database.DataSnapshot) ImageView(android.widget.ImageView) View(android.view.View) TextView(android.widget.TextView) DatabaseError(com.google.firebase.database.DatabaseError) TabLayout(android.support.design.widget.TabLayout) ValueEventListener(com.google.firebase.database.ValueEventListener) ActionBar(android.support.v7.app.ActionBar)

Example 19 with ValueEventListener

use of com.google.firebase.database.ValueEventListener in project MadMax by deviz92.

the class ExpenseDetailFragment method onCreateView.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    Log.i(TAG, "onCreateView");
    setInterface((OnItemClickInterface) getActivity());
    // Read expenseID from ExpenseDetailPagerAdapter
    Bundle b = this.getArguments();
    expenseID = b.getString("expenseID");
    final View view = inflater.inflate(R.layout.skeleton_list, container, false);
    RecyclerView.ItemDecoration divider = new InsetDivider.Builder(getContext()).orientation(InsetDivider.VERTICAL_LIST).dividerHeight(getResources().getDimensionPixelSize(R.dimen.divider_height)).color(ContextCompat.getColor(getContext(), R.color.colorDivider)).insets(getResources().getDimensionPixelSize(R.dimen.divider_inset), 0).overlay(true).build();
    recyclerView = (RecyclerView) view.findViewById(R.id.rv_skeleton);
    layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.addItemDecoration(divider);
    participantsViewAdapter = new ParticipantsViewAdapter(this.getContext(), this, participants);
    recyclerView.setAdapter(participantsViewAdapter);
    // Ascolto i participants alla spesa
    databaseReference.child("expenses").child(expenseID).addListenerForSingleValueEvent(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // Per ogni participant
            for (DataSnapshot participantSnap : dataSnapshot.child("participants").getChildren()) {
                Double alreadyPaid = participantSnap.child("alreadyPaid").getValue(Double.class);
                Double dueImport = alreadyPaid - participantSnap.child("fraction").getValue(Double.class) * dataSnapshot.child("amount").getValue(Double.class);
                String currency = dataSnapshot.child("currency").getValue(String.class);
                User u = new User();
                u.setAlreadyPaid(alreadyPaid);
                u.setDueImport(dueImport);
                u.setExpenseCurrency(currency);
                String participantID = participantSnap.getKey();
                FirebaseUtils.getInstance().getParticipantName(participantID, participants, participantsViewAdapter, u);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.w(TAG, databaseError.toException());
        }
    });
    return view;
}
Also used : User(com.polito.mad17.madmax.entities.User) Bundle(android.os.Bundle) LinearLayoutManager(android.support.v7.widget.LinearLayoutManager) DataSnapshot(com.google.firebase.database.DataSnapshot) View(android.view.View) RecyclerView(android.support.v7.widget.RecyclerView) DatabaseError(com.google.firebase.database.DatabaseError) RecyclerView(android.support.v7.widget.RecyclerView) ValueEventListener(com.google.firebase.database.ValueEventListener)

Example 20 with ValueEventListener

use of com.google.firebase.database.ValueEventListener in project MadMax by deviz92.

the class ExpenseEdit method onCreate.

@Override
@TargetApi(23)
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.edit_expense);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    expenseImageView = (ImageView) this.findViewById(R.id.expense_image);
    expenseBillView = (ImageView) this.findViewById(R.id.expense_bill);
    expenseDescriptionView = (EditText) this.findViewById(R.id.expense_description);
    expenseAmountView = (EditText) this.findViewById(R.id.expense_amount);
    expenseCurrencyView = (Spinner) this.findViewById(R.id.expense_currency);
    saveButton = (Button) this.findViewById(R.id.btn_save);
    // creating spinner for currencies
    final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.currencies, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    expenseCurrencyView.setAdapter(adapter);
    Intent intent = getIntent();
    String expenseID = intent.getStringExtra("expenseID");
    if (intent.getStringExtra("EXPENSE_TYPE").equals("EXPENSE_EDIT")) {
        EXPENSE_TYPE = Event.EventType.EXPENSE_EDIT;
        expense_type = "expenses";
    } else {
        EXPENSE_TYPE = Event.EventType.PENDING_EXPENSE_EDIT;
        expense_type = "proposedExpenses";
    }
    databaseReference.child(expense_type).child(expenseID).addListenerForSingleValueEvent(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            expense = new Expense();
            expense.setID(dataSnapshot.getKey());
            expense.setDescription(dataSnapshot.child("description").getValue(String.class));
            expense.setCurrency(dataSnapshot.child("currency").getValue(String.class));
            expense.setExpensePhoto(dataSnapshot.child("expensePhoto").getValue(String.class));
            expense.setBillPhoto(dataSnapshot.child("billPhoto").getValue(String.class));
            final String groupID = dataSnapshot.child("groupID").getValue(String.class);
            expenseDescriptionView.setText(expense.getDescription());
            if (EXPENSE_TYPE.equals(Event.EventType.PENDING_EXPENSE_EDIT)) {
                expense.setAmount(dataSnapshot.child("amount").getValue(Double.class));
                expenseAmountView.setText(String.valueOf(expense.getAmount()));
            }
            // set the defaultCurrency value for the spinner based on the user preferences
            int spinnerPosition = adapter.getPosition(expense.getCurrency());
            expenseCurrencyView.setSelection(spinnerPosition);
            // progressDialog = new ProgressDialog(ProfileEdit.this);
            // loading expense photo (if present)
            String expenseImage = expense.getExpensePhoto();
            if (expenseImage != null && !expenseImage.equals("")) {
                // Loading image
                Glide.with(getApplicationContext()).load(expenseImage).centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL).into(expenseImageView);
            } else {
                // Loading image
                expenseImageView.setImageResource(R.drawable.add_photo);
            /* Glide.with(getApplicationContext()).load(R.drawable.add_photo)
                            .centerCrop()
                            //.bitmapTransform(new CropCircleTransformation(this))
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .into(expenseImageView);*/
            }
            expenseImageView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Log.i(TAG, "expense 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
                }
            });
            // loading expense bill (if present)
            String expenseBill = expense.getBillPhoto();
            if (expenseBill != null && !expenseBill.equals("")) {
                // Loading image
                Glide.with(getApplicationContext()).load(expenseBill).centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL).into(expenseBillView);
            } else {
                // Loading image
                expenseImageView.setImageResource(R.drawable.add_photo);
            /*Glide.with(getApplicationContext()).load(R.drawable.add_photo)
                            .centerCrop()
                            //.bitmapTransform(new CropCircleTransformation(this))
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .into(expenseBillView);*/
            }
            expenseBillView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Log.i(TAG, "expense bill 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_BILL_REQUEST);
                // now see onActivityResult
                }
            });
            saveButton.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Log.i(TAG, "save clicked");
                    if (updateExpense(expense)) {
                        Toast.makeText(ExpenseEdit.this, getString(R.string.saved), Toast.LENGTH_SHORT).show();
                        Intent intent;
                        if (EXPENSE_TYPE.equals(Event.EventType.EXPENSE_EDIT)) {
                            intent = new Intent(getApplicationContext(), ExpenseDetailActivity.class);
                            intent.putExtra("groupID", expense.getGroupID());
                            intent.putExtra("expenseID", expense.getID());
                            intent.putExtra("userID", MainActivity.getCurrentUser().getID());
                        } else {
                            intent = new Intent(getApplicationContext(), MainActivity.class);
                            intent.putExtra("currentFragment", 2);
                        }
                        startActivity(intent);
                        finish();
                    }
                }
            });
        }

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

Aggregations

DataSnapshot (com.google.firebase.database.DataSnapshot)44 DatabaseError (com.google.firebase.database.DatabaseError)44 ValueEventListener (com.google.firebase.database.ValueEventListener)44 View (android.view.View)19 LinearLayoutManager (android.support.v7.widget.LinearLayoutManager)12 RecyclerView (android.support.v7.widget.RecyclerView)12 User (com.polito.mad17.madmax.entities.User)12 Intent (android.content.Intent)11 Bundle (android.os.Bundle)10 DatabaseReference (com.google.firebase.database.DatabaseReference)9 TextView (android.widget.TextView)7 ImageView (android.widget.ImageView)6 Event (com.polito.mad17.madmax.entities.Event)5 SimpleDateFormat (java.text.SimpleDateFormat)5 HashMap (java.util.HashMap)4 TabLayout (android.support.design.widget.TabLayout)3 Query (com.google.firebase.database.Query)3 ArrayList (java.util.ArrayList)3 TargetApi (android.annotation.TargetApi)2 SharedPreferences (android.content.SharedPreferences)2