Android Firebase - 用户在更改子数据后自动退出

时间:2017-02-10 08:46:27

标签: android firebase firebase-realtime-database

感谢您的阅读。我正在开发MyAccountActivity,用户可以更改自己的个人资料图片。我在这里做的是当在onActivityResult()方法中完成裁剪图像时,程序将更改当前用户的图像值。当图像值改变时,onCreate()方法中的addValueEventListener将再次出现以读取该值并将该图像URL或字符串存储到Picasso中,就像我在addValueEventListener中一样。但是,应用程序只是在裁剪后自动签出。

通过打印出mImageUrl,我注意到当我成功裁剪图像时,它改变了值,但是一秒后它又回到了上一张图片,然后它将我退出。

任何人都可以帮助我吗?谢谢。

MyProfileActivity.java

public class MyProfileActivity extends AppCompatActivity
{
    /*UI*/
    private Toolbar mMyProfileToolbar;
    private TextView mAge;
    private TextView mGender;
    private TextView mReligion;
    private TextView mSports;
    private TextView mState;
    private TextView mTimeRegistered;
    private TextView mDisplayName;
    private CircleImageView mProfileImage;

    /*Firebase*/
    private DatabaseReference mDatabaseUser;
    private FirebaseUser mUser;
    private StorageReference mStorage;
    private DatabaseReference mDatabasePost;
    private StorageReference filepath;
    private DatabaseReference user_db;

    /*Other*/
    private String age;
    private String gender;
    private String religion;
    private String sports;
    private String state;
    private String timeRegistered;
    private String displayName;

    private Uri mImageUri = null;

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

        /*UI*/
        mMyProfileToolbar = (Toolbar)findViewById(R.id.activity_my_profile_toolbar);
        mProfileImage = (CircleImageView)findViewById(R.id.activity_my_profile_profile_image);
        mDisplayName = (TextView)findViewById(R.id.activity_my_profile_display_name);
        mAge = (TextView)findViewById(R.id.activity_my_profile_age);
        mGender = (TextView)findViewById(R.id.activity_my_profile_gender);
        mReligion = (TextView)findViewById(R.id.activity_my_profile_religion);
        mSports = (TextView)findViewById(R.id.activity_my_profile_sports);
        mState = (TextView)findViewById(R.id.activity_my_profile_state);
        mTimeRegistered = (TextView)findViewById(R.id.activity_my_profile_time_registered);

        /*Firebase*/
        mDatabaseUser = FirebaseDatabase.getInstance().getReference().child("User");
        mUser = FirebaseAuth.getInstance().getCurrentUser();
        mStorage = FirebaseStorage.getInstance().getReference();

        /*Function*/
        setSupportActionBar(mMyProfileToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle(null);


        mDatabaseUser.child(mUser.getUid()).addValueEventListener(new ValueEventListener()
        {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot)
            {
                System.out.println("TestUp------------------------------------at addValueEventListener");
                displayName = dataSnapshot.child("displayName").getValue().toString();
                age = dataSnapshot.child("age").getValue().toString();
                gender = dataSnapshot.child("gender").getValue().toString();
                religion = dataSnapshot.child("religion").getValue().toString();
                sports = dataSnapshot.child("sports").getValue().toString();
                state = dataSnapshot.child("state").getValue().toString();
                timeRegistered = dataSnapshot.child("timeRegistered").getValue().toString();

                mImageUri = Uri.parse(dataSnapshot.child("image").getValue().toString());
                System.out.println("TestUp------------------------------------mImageUri: " + mImageUri);

                Picasso.with(MyProfileActivity.this).load(mImageUri).into(mProfileImage);


                mDisplayName.setText(displayName);
                mAge.setText("Age: " + age);
                mGender.setText("Gender: " + gender);
                mReligion.setText("Religion: " + religion);
                mSports.setText("Sports: " + sports);
                mState.setText("State: " + state);
                mTimeRegistered.setText("Time Registered: " + timeRegistered);
            }

            @Override
            public void onCancelled(DatabaseError databaseError)
            {

            }
        });

        mProfileImage.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.setType("image/*");
                startActivityForResult(i, 1);
            }
        });
    }

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

        if(requestCode == 1 && resultCode == RESULT_OK)
        {
            mImageUri = data.getData();

            CropImage.activity(mImageUri)
                    .setGuidelines(CropImageView.Guidelines.OFF)
                    .setAspectRatio(1, 1)
                    .start(this);
        }
        if(requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
        {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);

            if(resultCode == RESULT_OK)
            {
                mImageUri = result.getUri();

                DatabaseReference user_db = mDatabaseUser.child(mUser.getUid());
                user_db.child("image").setValue(mImageUri.toString());

                System.out.println("TestDown------------------------------------user_db: " + user_db);
                System.out.println("TestDown------------------------------------mImageUri: " + mImageUri);  


            }
            else if(resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE)
            {
                System.out.println("Test9------------------------------------");
                Toast.makeText(MyProfileActivity.this, "ERROR", Toast.LENGTH_SHORT).show();
                Exception error = result.getError();
                System.out.println("Test10------------------------------------");
            }
        }
    }
}

Firebase实时数据库规则

{
"rules": {
  // User profiles are only readable/writable by the user who owns it
  ".read": true,
  ".write": true,
  "users": {
    "$UID": {
      ".read": "auth.uid == $UID",
      ".write": "auth.uid == $UID"
    }
  },

  // Posts can be read by anyone but only written by logged-in users.
  "posts": {
    ".read": true,
    ".write": "auth.uid != null",

    "$POSTID": {
      // UID must matched logged in user and is fixed once set
      "uid": {
        ".validate": "(data.exists() && data.val() == newData.val()) || newData.val() == auth.uid"
      },

      // User can only update own stars
      "stars": {
        "$UID": {
            ".validate": "auth.uid == $UID"
        }
      }
    }
  },

  // User posts can be read by anyone but only written by the user that owns it,
  // and with a matching UID
  "user-posts": {
    ".read": true,

    "$UID": {
      "$POSTID": {
        ".write": "auth.uid == $UID",
          ".validate": "data.exists() || newData.child('uid').val() == auth.uid"
      }
    }
  },


  // Comments can be read by anyone but only written by a logged in user
  "post-comments": {
    ".read": true,
    ".write": "auth.uid != null",

    "$POSTID": {
      "$COMMENTID": {
        // UID must matched logged in user and is fixed once set
        "uid": {
            ".validate": "(data.exists() && data.val() == newData.val()) || newData.val() == auth.uid"
        }
      }
    }
  }
}
}

1 个答案:

答案 0 :(得分:0)

您可以在这种情况下使用单值侦听器。在你再次打电话之前,它不会听。

ref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // Logic for success...
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

            // Logic for failure...
        }
    });
  

一次读取数据:   在某些情况下,您可能希望调用一次回调然后立即删除,例如在初始化您不希望更改的UI元素时。您可以使用addListenerForSingleValueEvent()方法来简化此方案:它会触发一次,然后不会再次触发。

original post from firebase