0

I am creating a chat app in which Users can create groups. when a users creates a group, he/she can choose a group profile image. but if i choose the image, it wont upload. what to do?

I have inspected the code, there is no error anywhere

CreateGroupActivity.java:

package com.satyamedh.chitchatmessenger;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;

import de.hdodenhof.circleimageview.CircleImageView;

public class CreateGroupActivity extends AppCompatActivity
{


    private CircleImageView circleImageView;
    private EditText editText;
    private Button buttonconf, buttoncanc;

    private Uri resultUri;
    private final static int chosenProfileImage = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_group);

        initializeFields();

        buttoncanc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent profileIntent = new Intent(CreateGroupActivity.this, MainActivity.class);
                startActivity(profileIntent);
            }
        });

        buttonconf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(editText.getText())){
                    Toast.makeText(CreateGroupActivity.this, "Please enter text..", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    DatabaseReference rootref = FirebaseDatabase.getInstance().getReference();

                    Intent settingsIntent = new Intent(CreateGroupActivity.this, chooseUserActivity.class);
                    String key = rootref.push().getKey();
                    settingsIntent.putExtra("groupKey", key);
                    settingsIntent.putExtra("groupImage", resultUri);
                    settingsIntent.putExtra("groupName", editText.getText().toString());
                    startActivity(settingsIntent);
                }
            }
        });

        circleImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent galleryIntent = new Intent();
                galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
                galleryIntent.setType("image/*");
                startActivityForResult(galleryIntent, chosenProfileImage);
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);



        if(requestCode == chosenProfileImage && resultCode == RESULT_OK && data != null)
        {
            Uri imageUri = data.getData();

            CropImage
                    .activity()
                    .setGuidelines(CropImageView.Guidelines.ON)
                    .start(this);

        }

        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
        {
            final CropImage.ActivityResult result = CropImage.getActivityResult(data);

            if(resultCode == RESULT_OK) {

                resultUri = result.getUri();

                circleImageView.setImageURI(resultUri);


            }

        }


    }

    private void initializeFields()
    {


        MobileAds.initialize(this, "ca-app-pub-3127817354023186~6842500243");
        final AdView mAdView;

        mAdView = findViewById(R.id.my_adView_createGroup);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);
        mAdView.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                // Code to be executed when an ad finishes loading.
            }

            @Override
            public void onAdFailedToLoad(int errorCode) {
                // Code to be executed when an ad request fails.
            }

            @Override
            public void onAdOpened() {
                // Code to be executed when an ad opens an overlay that
                // covers the screen.
            }

            @Override
            public void onAdClicked() {



                // Code to be executed when the user clicks on an ad.
            }

            @Override
            public void onAdLeftApplication() {
                // Code to be executed when the user has left the app.
            }

            @Override
            public void onAdClosed() {
                // Code to be executed when the user is about to return
                // to the app after tapping on an ad.
            }
        });

        circleImageView = findViewById(R.id.create_group_image);
        editText = findViewById(R.id.create_group_name);
        buttonconf = findViewById(R.id.confirm_button);
        buttoncanc = findViewById(R.id.cancel_button);


    }
}

chooseUserActivity.java:

package com.satyamedh.chitchatmessenger;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;

import java.util.HashMap;
import java.util.Objects;

import de.hdodenhof.circleimageview.CircleImageView;


/**
 * A simple {@link Fragment} subclass.
 */
public class chooseUserActivity extends AppCompatActivity {


    private RecyclerView myRecyclerList;

    private DatabaseReference ContactsRef, UsersRef;

    private String currentUID;

    private DatabaseReference groupsRef;

    private Button confirmButton;

    private String downloadUrl       ;







    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_choose_user);


        super.onCreate(savedInstanceState);
        initializeFields();


    }

    private void initializeFields()
    {
        myRecyclerList = findViewById(R.id.users_choser_group);
        myRecyclerList.setLayoutManager(new LinearLayoutManager(chooseUserActivity.this));
        FirebaseAuth mAuth = FirebaseAuth.getInstance();
        currentUID = mAuth.getCurrentUser().getUid();

        ContactsRef = FirebaseDatabase.getInstance().getReference().child("Contacts").child(currentUID);
        UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");

        confirmButton = findViewById(R.id.confirm_group);

        MobileAds.initialize(this, "ca-app-pub-3127817354023186~6842500243");

        final AdView mAdView;

        mAdView = findViewById(R.id.choose_user_adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);
        mAdView.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                // Code to be executed when an ad finishes loading.
            }

            @Override
            public void onAdFailedToLoad(int errorCode) {
                // Code to be executed when an ad request fails.
            }

            @Override
            public void onAdOpened() {
                // Code to be executed when an ad opens an overlay that
                // covers the screen.
            }

            @Override
            public void onAdClicked() {



                // Code to be executed when the user clicks on an ad.
            }

            @Override
            public void onAdLeftApplication() {
                // Code to be executed when the user has left the app.
            }

            @Override
            public void onAdClosed() {
                // Code to be executed when the user is about to return
                // to the app after tapping on an ad.
            }
        });

        Toolbar toolbar = findViewById(R.id.users_chosers_toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setTitle("Choose users to be in " + getIntent().getExtras().get("groupName").toString());



    }

    @Override
    protected void onStart() {
        super.onStart();


        FirebaseRecyclerOptions<Contacts> options =
                new FirebaseRecyclerOptions.Builder<Contacts>()
                        .setQuery(ContactsRef, Contacts.class)
                        .build()
                ;



        FirebaseRecyclerAdapter<Contacts, ChatsViewHolder>
                adapter = new
                FirebaseRecyclerAdapter <Contacts, ChatsViewHolder>(options) {
                    @Override
                    protected void onBindViewHolder(@NonNull final ChatsViewHolder holder, final int position, @NonNull Contacts model)
                    {
                        final String string = getRef(position).getKey();

                        final String[] image = {"default_image"};




                        UsersRef
                                .child(string)
                                .addValueEventListener(new ValueEventListener() {
                                    @SuppressLint("SetTextI18n")
                                    @Override
                                    public void onDataChange(@NonNull final DataSnapshot dataSnapshot)
                                    {



                                        if (dataSnapshot.exists())
                                        {
                                            if (dataSnapshot.hasChild("image"))
                                            {
                                                image[0] = dataSnapshot.child("image").getValue().toString();
                                                Picasso.get().load(image[0]).placeholder(R.drawable.profile_image).into(holder.profileImageView);
                                            }
                                            final String name = dataSnapshot.child("name").getValue().toString();

                                            holder.Username.setText(name);

                                            holder.Userstatus.setText("Last seen: \n");

                                            if(dataSnapshot.child("userState").hasChild("state"))
                                            {
                                                String date  = dataSnapshot.child("userState").child("date").getValue().toString();
                                                String state  = dataSnapshot.child("userState").child("state").getValue().toString();
                                                String time  = dataSnapshot.child("userState").child("time").getValue().toString();

                                                if(Objects.equals(state, "online"))
                                                {
                                                    holder.Userstatus.setText(getString(R.string.Online));
                                                }
                                                else
                                                {
                                                    holder.Userstatus.setText(getString(R.string.last_seen) + time + " " + date);
                                                }


                                            }
                                            else
                                            {
                                                holder.Userstatus.setText("Offline");
                                            }


                                            final HashMap<String, Object>  hashMap = new HashMap<>();



                                            holder.itemView.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v)
                                                {
                                                    if (!hashMap.containsKey(getRef(position).getKey())) {

                                                        holder.itemView.setPadding(15, 15, 15, 15);


                                                        holder.IsUserInGroup.setVisibility(View.VISIBLE);

                                                        if (hashMap.isEmpty()) {
                                                            hashMap.put(currentUID, "admin");
                                                        }
                                                        hashMap.put(getRef(position).getKey(), "non-admin");
                                                    }

                                                    else {
                                                        holder.itemView.setPadding(0, 0, 0, 0);

                                                        if (hashMap.size() == 1)
                                                        {
                                                            hashMap.remove(currentUID, "admin");
                                                        }
                                                        holder.IsUserInGroup.setVisibility(View.INVISIBLE);

                                                        hashMap.remove(getRef(position).getKey(), "non-admin");

                                                    }

                                                    groupsRef = FirebaseDatabase.getInstance().getReference().child("Groups").child(getIntent().getExtras().get("groupKey").toString());



                                                }
                                            });

                                            confirmButton.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v)
                                                {

                                                    final StorageReference ProfileImagesRef;
                                                    ProfileImagesRef = FirebaseStorage.getInstance().getReference().child("Groups profile images");

                                                    final StorageReference ref = ProfileImagesRef.child(getIntent().getExtras().get("groupKey").toString() + ".jpg");



                                                    ref.putFile((Uri) getIntent().getExtras().get("groupImage"))
                                                            .addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                                                                @Override
                                                                public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {


                                                                    ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                                                        @Override
                                                                        public void onSuccess(Uri uri)
                                                                        {
                                                                            Toast.makeText(chooseUserActivity.this, uri.toString(), Toast.LENGTH_SHORT).show();
                                                                            downloadUrl = uri.toString();


                                                                        }
                                                                    });


                                                                }



                                                            });

                                                    groupsRef = FirebaseDatabase.getInstance().getReference().child("Groups").child(getIntent().getExtras().get("groupKey").toString());

                                                    groupsRef.child("Users").updateChildren(hashMap);

                                                    groupsRef.child("Messages").setValue("");

                                                    groupsRef.child("Group info").child("group name").setValue(getIntent().getExtras().get("groupName").toString());

                                                    groupsRef.child("Group info").child("group image").setValue(downloadUrl);

                                                    Toast.makeText(chooseUserActivity.this, "Group created successfully", Toast.LENGTH_SHORT).show();

                                                    Intent settingsIntent = new Intent(chooseUserActivity.this, MainActivity.class);
                                                    settingsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                                    startActivity(settingsIntent);
                                                    finish();


                                                }
                                            });

                                        }



                                    }

                                    @Override
                                    public void onCancelled(@NonNull DatabaseError databaseError) {

                                    }
                                });



                    }

                    @NonNull
                    @Override
                    public ChatsViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i)
                    {
                        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.users_display_layout, viewGroup, false);

                        return new ChatsViewHolder(view);

                    }
                };

        myRecyclerList.setAdapter(adapter);
        adapter.startListening();



    }


    public static class ChatsViewHolder extends RecyclerView.ViewHolder
    {

        CircleImageView profileImageView;
        TextView Username, Userstatus;
        CheckBox IsUserInGroup;

         ChatsViewHolder(@NonNull View itemView)
        {
            super(itemView);

            profileImageView = itemView.findViewById(R.id.users_profile_image);
            Username = itemView.findViewById(R.id.users_name);
            Userstatus = itemView.findViewById(R.id.users_status);
            IsUserInGroup = itemView.findViewById(R.id.IsUserInGroup);


        }


    }


}


Can anyone help me please?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
satyamedh
  • 47
  • 1
  • 12
  • 1
    If you encounter problems, it's best to create a [MCVE](https://stackoverflow.com/help/mcve) when posting a question. You posted over 550 lines of code for this issue. That's a lot for people to parse and try to debug online. – Alex Mamo May 28 '19 at 12:43
  • Sorry, it will upload the file but will not get the download URL – satyamedh May 28 '19 at 13:26
  • Check **[this](https://stackoverflow.com/questions/53299915/how-to-get-offline-uploaded-file-download-url-in-firebase/53300660#53300660)** out. – Alex Mamo May 28 '19 at 13:28
  • @AlexMamo yes, it worked, but CreateGroupActivity wont put it in intent and thus it wont be saved in database. – satyamedh May 28 '19 at 13:39
  • Please read [how to create a minimal, complete, verifiable example](http://stackoverflow.com/help/mcve), as there is simply too much code here to efficiently help you. Also note that "it will upload the file but will not get the download URL" is unclear and conflicts with your original "if i choose the image, it wont upload" statement. If you debug your code, what specific line doesn't give the result that you expect it to give? – Frank van Puffelen May 28 '19 at 13:45
  • I fixed it by moving `groupsRef.child("Group info").child("group image").setValue(uri.toString());` into the OnCompleteListner – satyamedh May 28 '19 at 14:15
  • into ` ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener()` – satyamedh May 29 '19 at 06:55

1 Answers1

0

I fixed it by moving the code in the on success listener itself

satyamedh
  • 47
  • 1
  • 12