我正在创建一个聊天应用程序,用户可以在其中创建群组。用户创建群组时,他/她可以选择一个群组个人资料图像。但是,如果我选择图片,它将不会上传。该怎么办?
我已经检查过代码,任何地方都没有错误
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);
}
}
}
有人可以帮我吗?
答案 0 :(得分:0)
我通过移动on成功侦听器本身中的代码来修复它