firebase中的数据未更新(Android)

时间:2017-06-06 20:44:08

标签: android firebase firebase-realtime-database

数据未在FireBase中更新它会长时间保持加载但不会更新(Android应用程序) 在一个屏幕中我保留了一个从图库中选择的图像按钮剩余的两个是编辑文本按钮一个是标题字段而另一个是描述字段然后在单击发布按钮之后它应该发布图像以及标题,描述字段但是在点击之后发布后不断发布

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

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.auth.FirebaseUser;
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;

public class PostActivity extends AppCompatActivity {
    private ImageButton mSelectImage;
    private EditText mPostTitle;
    private EditText mPostDesc;
    private Button mSubmitBtn;
    private Uri mImageUri = null;
    private StorageReference mStorage;
    private ProgressDialog mProgress;
    private DatabaseReference mDatabase;
    private FirebaseAuth mAuth;
    private FirebaseUser mCurrentUser;
    private DatabaseReference mDatabaseUser;

    private static final int GALLERY_REQUEST = 1;

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

        mStorage = FirebaseStorage.getInstance().getReference();
        mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");

        mSelectImage = (ImageButton) findViewById(R.id.imageSelect);

        mPostTitle = (EditText) findViewById(R.id.titleField);
        mPostDesc = (EditText) findViewById(R.id.descField);
        mSubmitBtn = (Button) findViewById(R.id.submitBtn);
        mProgress = new ProgressDialog(this);

        mAuth = FirebaseAuth.getInstance();
        mCurrentUser = mAuth.getCurrentUser();
        mDatabaseUser = FirebaseDatabase.getInstance().getReference().child("Users").child(mCurrentUser.getUid());

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

                Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
                galleryIntent.setType("image/*");
                startActivityForResult(galleryIntent, GALLERY_REQUEST);
            }
        });

        mSubmitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startPosting();
            }
        });
    }

    private void startPosting() {

        //Get values from title and description
        mProgress.setMessage("Uploading to DB...");

        final String title_val = mPostTitle.getText().toString().trim();
        final String desc_val = mPostDesc.getText().toString().trim();

        if (!TextUtils.isEmpty(title_val) && !TextUtils.isEmpty(desc_val) && mImageUri != null) {
            //start uploading to DB
            //authenticate before letting upload(not in this app)
            mProgress.show();

            StorageReference filePath = mStorage.child("Blog_Images").child(mImageUri.getLastPathSegment());

            filePath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @SuppressWarnings("VisibleForTests")
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                    final Uri downloadUrl = taskSnapshot.getDownloadUrl();

                    final DatabaseReference newPost = mDatabase.push();//push creates unique random ID(no overwriting)

                    if(mDatabaseUser != null) {
                        mDatabaseUser.addValueEventListener(new ValueEventListener() {
                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {

                                newPost.child("title").setValue(title_val);
                                newPost.child("desc").setValue(desc_val);
                                newPost.child("image").setValue(downloadUrl.toString());
                                newPost.child("uid").setValue(mCurrentUser.getUid());
                                newPost.child("username").setValue(dataSnapshot.child("name").getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {
                                        if (task.isSuccessful()) {

                                            startActivity(new Intent(PostActivity.this, MainActivity.class));
                                        }
                                    }
                                });

                            }

                            @Override
                            public void onCancelled(DatabaseError databaseError) {

                            }
                        });
                    }

                    mProgress.dismiss();

                    startActivity(new Intent(PostActivity.this, MainActivity.class));

                }
            });

        }
    }

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

        if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK) {

            mImageUri = data.getData();
            mSelectImage.setImageURI(mImageUri);

        }
    }
}    

2 个答案:

答案 0 :(得分:0)

首先删除if(mDatabaseUser != null) {..},然后删除mDatabaseUser.addValueEventListener(new ValueEventListener() {..},而不是mDatabaseUser.child(mCurrentUser.getUid()).addValueEventListener(new ValueEventListener() {...},请执行以下操作:.child(mCurrentUser.getUid())从您的mDatabaseUser = FirebaseDatabase.getInstance().getReference().child("Users").child(mCurrentUser.getUid());顶部移除startActivity(new Intent(PostActivity.this, MainActivity.class));后代码。

而且第二个values[0] = values[1]也不是必需的。

答案 1 :(得分:0)

我没有仔细查看您发布的所有代码,可能完全不了解您的处理过程。有两件事可能会导致您描述的一些问题。

在FirebaseHelper中,onChildChanged()方法调用fetchData(),它将更改的部分详细信息添加到数组列表中。您不应该更新现有的部分细节而不是再次添加它们吗?此外,在onChildRemoved()中,不会从数组列表中删除节详细信息。他们不需要被移除吗?

在CustomAdapter中,按钮的单击侦听器添加匿名ValueEventListeners。因为它们是匿名的,所以当不再需要它们时,您无法删除它们。添加了addValueEventListener()的ValueEventListeners在删除之前保持活动状态。如果您的目标是获取数据一次,请使用addListenerForSingleValueEvent()。

fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
    note.setTitle(titleTextView.getText().toString());
    note.setDescription(descriptionTextView.getText().toString());
    database.child("notes").child(note.getUid()).setValue(note);
    finish();
}
});