В этом действии пользователи загружают изображение и описание после загрузки сообщения, отправленного пользователем в Основное действие, но когда я нажимаю кнопку загрузки, он продолжает бесконечную oop и перезагружается снова и снова, и когда я закрываю приложение и перезапустите снова, он работает нормально. Он хранит информацию в базе данных firebase. Вот код этого пакета действий com.codewithosama.socialapp;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import com.google.android.gms.tasks.Continuation;
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 java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
public class ProjectActivity extends AppCompatActivity {
private Toolbar mToolbar;
private ImageButton selectProjectImage;
private Button uploadProjectButton;
private EditText projectDescription;
private static final int gallery_pick=1;
private Uri imageUri;
private String description;
private ProgressDialog loadingBar;
// URL of String
private String downloadUrl;
//Date and Time
private String saveCurrentDate , saveCurrentTime , projectRandomName;
private long countProjects=0;
// Firebase
private StorageReference projectImagesRefernce;
private DatabaseReference usersRef , projectRef;
private FirebaseAuth mAuth;
private String currentUserId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_project);
//Firebase
projectImagesRefernce = FirebaseStorage.getInstance().getReference();
usersRef = FirebaseDatabase.getInstance().getReference().child("Users");
projectRef = FirebaseDatabase.getInstance().getReference().child("Projects");
mAuth = FirebaseAuth.getInstance();
currentUserId = mAuth.getCurrentUser().getUid();
selectProjectImage=(ImageButton)findViewById(R.id.select_project_image);
uploadProjectButton =(Button)findViewById(R.id.upload_project_btn);
projectDescription=(EditText)findViewById(R.id.project_description);
loadingBar = new ProgressDialog(this);
mToolbar = (Toolbar) findViewById(R.id.update_project_page_toolbar);
setSupportActionBar(mToolbar);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP)
{
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
// getSupportActionBar().setHomeButtonEnabled(true);
}
else
{
getActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
//getActionBar().setHomeButtonEnabled(true);
}
getSupportActionBar().setTitle("Upload Project");
selectProjectImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openGalley();
}
});
uploadProjectButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
validateProjectInfo();
}
});
}
private void validateProjectInfo()
{
description = projectDescription.getText().toString();
if(imageUri==null)
{
Toast.makeText(this, "Please select project Image", Toast.LENGTH_SHORT).show();
}
else if (TextUtils.isEmpty(description))
{
Toast.makeText(this, "Please provide description of project", Toast.LENGTH_SHORT).show();
}
else
{
loadingBar.setTitle("Adding new Project");
loadingBar.setMessage("Please wait ...");
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
storingImageToFirebaseStorage();
}
}
private void storingImageToFirebaseStorage()
{
// For Date
Calendar calForData = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMM-yyyy");
saveCurrentDate = currentDate.format(calForData.getTime());
// For Time
Calendar calForTime = Calendar.getInstance();
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm");
saveCurrentTime = currentTime.format(calForTime.getTime());
final StorageReference filepath = projectImagesRefernce.child("project images").child(imageUri.getLastPathSegment()
+projectRandomName + ".jpg");
// Random Name
projectRandomName=saveCurrentDate + saveCurrentTime;
filepath.putFile(imageUri).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
@Override
public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()){
throw task.getException();
}
return filepath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downUri = task.getResult();
Toast.makeText(ProjectActivity.this, "Profile Image stored successfully to Firebase storage...", Toast.LENGTH_SHORT).show();
downloadUrl = downUri.toString();
savingProjectInformationToDatabase();
}
else
{
String message = task.getException().getMessage();
Toast.makeText(ProjectActivity.this, "Error occured: " + message, Toast.LENGTH_SHORT).show();
}
}
});
//
// filepath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
// @Override
// public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
// filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
// @Override
// public void onSuccess(Uri uri) {
// downloadUrl = uri.toString();
// Toast.makeText(ProjectActivity.this,"Image uploaded",Toast.LENGTH_SHORT).show();
//
// savingProjectInformationToDatabase();
// }
// });
// }
// });
}
private void savingProjectInformationToDatabase()
{
projectRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{
if(dataSnapshot.exists())
{
countProjects =dataSnapshot.getChildrenCount();
}
else
{
countProjects=0;
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
usersRef.child(currentUserId).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{
if(dataSnapshot.exists())
{
String userFullName = dataSnapshot.child("fullName").getValue().toString();
String userProfileImage = dataSnapshot.child("profile image").getValue().toString();
HashMap projectMap = new HashMap();
projectMap.put("uid" ,currentUserId);
projectMap.put("date" ,saveCurrentDate);
projectMap.put("time" ,saveCurrentTime);
projectMap.put("description" ,description);
projectMap.put("projectImageUrl" ,downloadUrl);
projectMap.put("profileimage" ,userProfileImage);
projectMap.put("fullname" ,userFullName);
projectMap.put("counter",countProjects);
projectRef.child(currentUserId+projectRandomName).updateChildren(projectMap).addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task)
{
if (task.isSuccessful())
{
Toast.makeText(ProjectActivity.this, "Project is updated successfull", Toast.LENGTH_SHORT).show();
sendUserToMainActivity();
loadingBar.dismiss();
}
else
{
String message = task.getException().toString();
Toast.makeText(ProjectActivity.this, "Error Occured :" +message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError)
{
}
});
}
private void openGalley()
{
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent ,gallery_pick);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==gallery_pick && resultCode==RESULT_OK && data != null)
{
imageUri = data.getData();
selectProjectImage.setImageURI(imageUri);
}
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item)
{
int id = item.getItemId();
if(id == android.R.id.home)
{
sendUserToMainActivity();
}
return super.onOptionsItemSelected(item);
}
private void sendUserToMainActivity()
{
Intent mainIntent = new Intent(ProjectActivity.this, MainActivity.class);
startActivity(mainIntent);
Log.d("main_activity", "This is working ");
}
}
Эти строки появляются снова и снова в Logcat
2020-07-27 12:09:42.770 2626-5215/? I/ActivityManager: START u0 {cmp=com.codewithosama.socialapp/.MainActivity} from uid 10174
2020-07-27 12:09:42.771 2626-5215/? W/ActivityManager: startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { cmp=com.codewithosama.socialapp/.MainActivity }
2020-07-27 12:09:42.812 2626-3376/? W/NotificationService: Toast already killed. pkg=com.codewithosama.socialapp callback=android.app.ITransientNotification$Stub$Proxy@851e89a
2020-07-27 12:09:42.917 6802-6802/com.codewithosama.socialapp W/ActionBarDrawerToggle: DrawerToggle may not show up because NavigationIcon is not visible. You may need to call actionbar.setDisplayHomeAsUpEnabled(true);
2020-07-27 12:09:42.978 818-818/? D/SurfaceFlinger: duplicate layer name: changing com.codewithosama.socialapp/com.codewithosama.socialapp.MainActivity to com.codewithosama.socialapp/com.codewithosama.socialapp.MainActivity#1
2020-07-27 12:09:43.033 2626-3045/? I/ActivityManager: START u0 {act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10200000 cmp=com.android.launcher3/.CustomizationPanelLauncher (has extras)} from uid 1000
2020-07-27 12:09:43.042 3274-3274/? I/GoogleInputMethod: onFinishInput() : Dummy InputConnection bound
2020-07-27 12:09:43.042 3274-3274/? I/GoogleInputMethod: onStartInput() : Dummy InputConnection bound
Когда я ввожу Log в sendUserToMainActivity, это происходит снова и снова .. Я поставил точку останова на sendUserToMainActivity, и это повторялось снова и снова
sendUserToMainActivity:301, ProjectActivity (com.codewithosama.socialapp)
access$900:40, ProjectActivity (com.codewithosama.socialapp)
onComplete:239, ProjectActivity$6$1 (com.codewithosama.socialapp)
run:4, zzj (com.google.android.gms.tasks)
handleCallback:790, Handler (android.os)
dispatchMessage:99, Handler (android.os)
loop:164, Looper (android.os)
main:6626, ActivityThread (android.app)
invoke:-1, Method (java.lang.reflect)
run:438, RuntimeInit$MethodAndArgsCaller (com.android.internal.os)
Спасибо adanvce за помощь. Я стараюсь подробно описать свою проблему, но если вам нужны дополнительные подробности, вы можете спросить меня