Strange behaviour of Firebase RecyclerView

Here is code for when the Firebase RecyclerView is set, here RecyclerView is used to show a different type of post like events, discussion, requirement, etc. for events a different linear-layout is shown to the user. but this event is displayed in the posts which do not have that data. This same error is seen in the images too. the posts which don’t have image also shows images from other posts.

    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(layoutManager);
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DATE, -30);

    adapter = new FirebaseRecyclerAdapter<Post, PostAdapterViewHolder>(Post.class, R.layout.post_list_item, PostAdapterViewHolder.class, databaseReference.orderByChild("timestamp").startAt(calendar.getTimeInMillis()).endAt(System.currentTimeMillis())) {
        public void populateViewHolder(final PostAdapterViewHolder postAdapterViewHolder, final Post post, final int position) {
            final String key = this.getRef(position).getKey();
            Log.d("whatiskey",""+key);

            documentref.child(key).addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    String value=String.valueOf(dataSnapshot.child("documentUrl").getValue());


                   if(value.equals(null)||value.equals("null"))
                   {
                       postAdapterViewHolder.removedocumentimage();
                   }
                   else
                   {
                       getFileName(value);
                       postAdapterViewHolder.setDocumentimage();
                   }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

            postAdapterViewHolder.setKey(key);
            postAdapterViewHolder.setContext(getActivity().getApplicationContext());
            postAdapterViewHolder.setCommunityId(CommunityId);
            postAdapterViewHolder.setDescription(post.getText(),post.getType());
            postAdapterViewHolder.setUser(post.getCreator());
            postAdapterViewHolder.setTime(post.getTimestamp());
            postAdapterViewHolder.setImage(post.getImageUrl(),post.getType());
            postAdapterViewHolder.setType(post.getType());
            postAdapterViewHolder.postdata(key,CommunityId);
            postAdapterViewHolder.setLike(post.getLikesCount());
            postAdapterViewHolder.setBookmark();
            postAdapterViewHolder.time.setVisibility(View.INVISIBLE);
            postAdapterViewHolder.activitybar.setVisibility(View.GONE);
            postAdapterViewHolder.setReadMark();
        }
    };
    recyclerView.setAdapter(adapter);

here is the recyclerview’s layout for every views:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/swiplayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="3dp"
android:background="@drawable/recycler_bg"
android:orientation="horizontal"
app:cardElevation="2dp">

<TextView
    android:id="@+id/title"
    android:layout_width="7dp"
    android:layout_height="match_parent"
    android:background="@drawable/blueside" />

<LinearLayout
    android:background="?android:attr/selectableItemBackground"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:id="@+id/head"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_centerVertical="true"
            android:layout_marginBottom="5dp"
            android:layout_marginLeft="15dp"
            android:scaleType="fitXY"
            android:src="@drawable/user" />

        <LinearLayout
            android:id="@+id/linearLayout2"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginBottom="5dp"
            android:layout_marginLeft="10dp"
            android:layout_toEndOf="@+id/imageView2"
            android:layout_toRightOf="@+id/imageView2"
            android:orientation="vertical">

            <TextView
                android:id="@+id/username"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:gravity="start"
                android:text="User Name"
                android:textColor="#485866"
                android:textSize="14sp"
              />

            <TextView
                android:id="@+id/designation"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:text="Role"
                android:textSize="12sp" />

        </LinearLayout>

        <LinearLayout
            android:layout_marginTop="10dp"
            android:id="@+id/linearLayout3"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignBottom="@+id/linearLayout2"
            android:layout_marginEnd="11dp"
            android:layout_marginRight="11dp"
            android:layout_toLeftOf="@+id/bookmark"
            android:layout_toStartOf="@+id/bookmark"
            android:gravity="end"
            android:orientation="vertical">

            <TextView
                android:id="@+id/tag"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="11dp"
                android:layout_marginRight="11dp"
                android:background="@drawable/bluebutton"
                android:gravity="center"
                android:layout_gravity="center_vertical"
                android:paddingLeft="10dp"
                android:paddingRight="10dp"
                android:text="Post type"
                android:textColor="@color/white"
                android:textSize="6pt" />

            <TextView
                android:id="@+id/date"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginEnd="15dp"
                android:layout_marginRight="15dp"
                android:gravity="end"
                android:text="Time"
                android:textSize="5pt"
                android:visibility="invisible" />
        </LinearLayout>
        <ImageView
            android:id="@+id/bookmark"
            android:layout_width="25dp"
            android:layout_height="40dp"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_gravity="center"
            android:layout_marginEnd="14dp"
            android:layout_marginRight="14dp"
            android:layout_marginTop="3dp"
            android:layout_weight="1"
            android:src="@drawable/fav_clicked_change" />

    </RelativeLayout>
    <LinearLayout
        android:id="@+id/documenttext"
        android:layout_width="match_parent"
        android:paddingRight="10dp"
        android:layout_height="30dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:background="@drawable/grayrect"
        android:orientation="horizontal"
        android:layout_gravity="center"
        android:gravity="center">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.3"
            app:srcCompat="@drawable/darkattachment"
            android:padding="5dp"/>
        <TextView
            android:id="@+id/docname"
            android:layout_weight="0.5"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
                android:gravity="center_vertical"
            android:text="Document Attached"/>

    </LinearLayout>

    <LinearLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/description"
            android:layout_width="0dp"
            android:autoLink="web|email|phone"
            android:layout_height="wrap_content"
            android:layout_marginBottom="5dp"
            android:layout_marginEnd="5dp"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="5dp"
            android:layout_marginStart="15dp"
            android:layout_marginTop="5dp"
            android:layout_weight="3.8"
            android:gravity="start"
            android:maxLines="10"
            android:textColor="@color/grey"
            android:textSize="6pt" />

        <ImageView
            android:id="@+id/imageview"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_gravity="center"
            android:layout_marginBottom="5dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:scaleType="fitCenter"
            app:srcCompat="@drawable/ic_launcher_background"
            android:transitionName="simple_activity_transition"
            android:visibility="gone"
            tools:ignore="UnusedAttribute" />

    </LinearLayout>

    <LinearLayout
        android:background="@drawable/graybutton"
        android:id="@+id/eventLayout"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="10dp"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:orientation="vertical"
            android:layout_marginTop="3dp"
            android:layout_marginBottom="3dp"
            android:gravity="center"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:layout_marginRight="5dp"
                android:visibility="gone"
                android:id="@+id/event_image"
                android:layout_gravity="center"
                android:layout_width="150dp"
                android:layout_height="100dp" />

            <TextView
                android:textColor="@color/grey"
                android:layout_marginTop="3dp"
                android:gravity="center"
                android:layout_marginRight="5dp"
                android:id="@+id/post_eventName"
                android:textSize="17sp"
                android:textStyle="bold"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Name"/>

            <LinearLayout
                android:padding="3dp"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:gravity="center"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <ImageView
                    android:layout_width="25dp"
                    android:layout_height="20dp"
                    app:srcCompat="@drawable/locationpin"/>

                <TextView
                    android:paddingLeft="10dp"
                    android:layout_gravity="center"
                    android:id="@+id/post_eventVenue"
                    android:textSize="16sp"
                    android:textStyle="bold"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Venue"/>

            </LinearLayout>

        </LinearLayout>

        <LinearLayout
            android:layout_marginBottom="5dp"
            android:weightSum="2"
            android:layout_marginLeft="20dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:text="Event timings"
                android:layout_width="wrap_content"
                android:layout_marginRight="5dp"
                android:layout_height="wrap_content"
                android:id="@+id/post_event_timings" />

        </LinearLayout>

        <TextView
            android:id="@+id/event_description"
            android:layout_width="match_parent"
            android:autoLink="web|email|phone"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:layout_marginEnd="5dp"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="5dp"
            android:layout_marginStart="15dp"
            android:layout_marginTop="5dp"
            android:layout_weight="3.8"
            android:gravity="start"
            android:text="This is some random text"
            android:maxLines="10"
            android:textColor="@color/grey"
            android:textSize="6pt" />

        <LinearLayout
            android:id="@+id/post_feedback_box"
            android:layout_marginTop="5dp"
            android:layout_marginBottom="10dp"
            android:weightSum="3"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:background="@drawable/bluecurve"
                android:id="@+id/post_eventNo"
                android:textColor="@color/white"
                android:layout_weight="1"
                android:text="No"
                android:gravity="center"
                android:layout_width="wrap_content"
                android:layout_height="30dp" />

            <TextView
                android:layout_marginLeft="5dp"
                android:background="@drawable/bluecurve"
                android:id="@+id/post_eventMaybe"
                android:textColor="@color/white"
                android:layout_weight="1"
                android:text="Maybe"
                android:gravity="center"
                android:layout_width="wrap_content"
                android:layout_height="30dp" />

            <TextView
                android:layout_marginLeft="5dp"
                android:layout_width="wrap_content"
                android:background="@drawable/bluecurve"
                android:id="@+id/post_eventYes"
                android:textColor="@color/white"
                android:text="Yes"
                android:layout_weight="1"
                android:gravity="center"
                android:layout_height="30dp" />

        </LinearLayout>

    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:layout_marginTop="2dp"
            android:layout_marginBottom="3dp"
            android:layout_alignParentEnd="true"
            android:id="@+id/readMark"
            android:layout_marginRight="14dp"
            android:layout_width="9dp"
            android:layout_height="9dp"
            app:srcCompat="@drawable/orangecircle"
            android:layout_alignParentRight="true" />

    </RelativeLayout>

    <LinearLayout
        android:id="@+id/activitybar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="3">


        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center">

            <ImageView
                android:id="@+id/like"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:src="@drawable/emptyup" />

            <TextView
                android:id="@+id/likecount"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:gravity="center"
                android:text="0"
                android:textSize="8pt" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="2dp"
            android:layout_weight="1"
            android:gravity="center">

            <ImageView
                android:layout_width="25dp"
                android:layout_height="19dp"
                android:src="@drawable/chat" />

            <TextView
                android:layout_width="30dp"
                android:layout_height="30dp"

                android:gravity="center"
                android:text="0"
                android:textSize="8pt" />

        </LinearLayout>


        <ImageView
            android:id="@+id/sharebutton"
            android:layout_width="20dp"
            android:layout_height="18dp"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:src="@drawable/share" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="10dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/userdata"
            android:layout_width="2dp"
            android:layout_height="10dp"
            android:gravity="center"
            android:textColor="@color/white" />

        <TextView
            android:id="@+id/postdata"
            android:layout_width="match_parent"
            android:layout_height="10dp"
            android:gravity="center"
            android:textColor="@color/white"
            android:textSize="5pt" />

    </LinearLayout>

</LinearLayout>

and Inside PopulateviewGolder of the recyclerview I do this for events:

 if (type.contentEquals("Requirement")) {

        tag.setText("Requirement");
        title.setBackgroundResource(R.drawable.yellowside);
        tag.setBackgroundResource(R.drawable.yellowbutton);

    } else if (type.contentEquals("Offerings")) {

        tag.setText("Offering");
        title.setBackgroundResource(R.drawable.greenside);
        tag.setBackgroundResource(R.drawable.greenbutton);

    } else if (type.contentEquals("Question")) {

        tag.setText("Question");
        title.setBackgroundResource(R.drawable.blueside);
        tag.setBackgroundResource(R.drawable.bluebutton);

    } else if (type.contentEquals("Announcement")) {

        tag.setText("Announcement");
        title.setBackgroundResource(R.drawable.redside);
        tag.setBackgroundResource(R.drawable.redbutton);

    } else if (type.contentEquals("JLT")) {

        tag.setText("JLT");
        title.setBackgroundResource(R.drawable.blueside);
        tag.setBackgroundResource(R.drawable.bluebutton);

    } else if (type.contentEquals("Event")) {

        tag.setText("Event");
        eventLayout.setVisibility(View.VISIBLE);
        setEvent(key);
        title.setBackgroundResource(R.drawable.redside);
        tag.setBackgroundResource(R.drawable.redbutton);

    } else {

        tag.setText("Discussion");
        title.setBackgroundResource(R.drawable.blueside);
        tag.setBackgroundResource(R.drawable.bluebutton);

    }

the function of setting event data is:

eventName = itemView.findViewById(R.id.post_eventName);
    eventVenue = itemView.findViewById(R.id.post_eventVenue);
    eventTimings = itemView.findViewById(R.id.post_event_timings);

    DatabaseReference eventDBrefence = FirebaseDatabase.getInstance().getReference().child("Posts").child(CommunityId).child("posts").child(key).child("eventDetails");
    eventDBrefence.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Event event = dataSnapshot.getValue(Event.class);
            eventName.setText(event.getEventName());
            if (event.getFromDate().equals(event.getToDate())) {
                eventTimings.setText("At " + event.getFromDate() + " from " + event.getFromTime() + " to " + event.getToTime());
            } else {
                eventTimings.setText("From " + event.getFromDate() + " at " + event.getFromTime() + " to " + event.getToDate() + " at " + event.getToTime());
            }
            eventVenue.setText(event.getEventVenue());
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

How to pass value from firebase database ValueEventListener? [duplicate]

This question already has an answer here:

im quiet new in firebase database and android, I am create a method to count total size of db children, but it always return 0 when accessed outside onDataChange method, here my code

private int getChildSize() {
 final List<String> keys = new ArrayList<>();
 DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("profiles");
    ref.orderByChild("phoneNumber")
            .equalTo(phoneNumber)
            .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    for(DataSnapshot item : dataSnapshot.getChildren()){
                        keys.add(item.getKey());

                        Log.d(TAG, "onDataChange: " + keys.size()); // more than 0
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

 return keys.size(); // return 0;
}

any ideas?

File Upload in reactjs

I wanted to upload file using reactjs and store that file in firebase storage after that i want to access that document in my ionic application.
I have uploaded the file and successfully save it in firebase storage,but filename is remains undefined. I also wanted to save that file name and path in the database.
here is my code

   handleSubmitFirebase(event) {
    //alert('A push was submitted: ' + this.state.value);
    alert(JSON.parse(event));
    var docInfo = {
        title: this.docnm.value,
        path: this.docfile.value,
        date: this.docdt.value,
        unm: this.unm.value,
        D_id: DbConfig.database()
            .ref("documents")
            .push(docInfo).key
    }; //documents info

    DbConfig.database()
        .ref("documents")
        .push(docInfo);
    this.docnm.value = ""; // <- clear the input
    alert("Successfully Added");


}

handlePdfUploadStart() { this.setState({ isUploading: true, progress: 0 }); }
handlePdfProgress(progress) { this.setState({ progress }); }
handlePdfUploadError(error) {
    this.setState({ isUploading: false });
    console.error(error);
}
handlePdfUploadSuccess(filename) {
    alert(filename);
    this.setState({ avatar: filename, progress: 100, isUploading: false });
    DbConfig.storage().ref('upload/').child(filename).getDownloadURL().then(url => this.setState({ avatarURL: url }));
}

render() {
    return (
        <div className="content">
            <NavBar></NavBar>
            <div className="row">
                <div className="col-md-10">
                    <div className="card">
                        <div className="card-header card-header-icon" data-background-color="rose">
                            <i className="material-icons">account_balance</i>
                        </div>
                        <div className="card-content">
                            <h4 className="card-title">Add Document</h4>
                            <form onSubmit={this.handleSubmitFirebase}>
                                <div className="form-group label-floating is-empty">
                                    <label className="control-label">Document Name</label>
                                    <input type="text" className="form-control" ref={el => (this.docnm = el)} onChange={this.handleChange} />
                                    <span className="material-input"></span></div>
                                <div className="form-group label-floating is-empty">
                                    <label className="control-label">User Name</label>
                                    <input type="text" className="form-control" ref={el => (this.unm = el)} onChange={this.handleChange} />
                                    <span className="material-input"></span></div>
                                <div className="form-group label-floating is-empty">
                                    <label className="control-label">Date</label>
                                    <input type="date" className="form-control" ref={el => (this.docdt = el)} onChange={this.handleChange} />
                                    <span className="material-input"></span></div>
                                <div className="form-group  label-floating is-empty">
                                    <label className="control-label">Document</label>
                                    <FileUploader
                                        accept="pdf,doc/*"
                                        name="avatar"
                                        ref={el => (this.docfile = el)}
                                        filename={file => alert(this.docfile.value + file.name.split('.')[1])}
                                        storageRef={DbConfig.storage().ref('upload/')}
                                        onUploadStart={this.handlePdfUploadStart}
                                        onUploadError={this.handlePdfUploadError}
                                        onUploadSuccess={this.handlePdfUploadSuccess}
                                        onProgress={this.handlePdfProgress}
                                    />
                                    <span className="material-input"></span></div>

                                <button type="submit" className="btn btn-fill btn-rose submit_btn">Submit</button>
                            </form>
                        </div>
                    </div>
                </div>

            </div>
        </div>
    )
}

Pulling Marker Data From db Updating Multiple Marker Position

I am pulling marker data from database puting it into HashMap then placing them on map. The problem is how do I update positions of markers when their positions change ? Below code is adding new marker when position changes as expected.How do i know that marker is already existing so I need to update its position or remove then add again to new position ?

mydb.child("map").child("players").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            HashMap<String,AvatarObject> players= new HashMap();
            for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
                players.put(childSnapshot.getKey(), childSnapshot.getValue(AvatarObject.class));
            }
            players.remove(username); //nevermind this
            for (Map.Entry<String, AvatarObject> entry : players.entrySet()) {
                Log.d("asd","Key = " + entry.getKey() + ", Latitude = " + entry.getValue().getLatitude()+"Longitude = " + entry.getValue().getLongitude());

                 googleMap.addMarker(new MarkerOptions().position(
                        new LatLng(entry.getValue().getLatitude(),entry.getValue().getLatitude()))
                        .title(entry.getValue().getAvatar()));
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    });

There are 2 markers in db.This is log output:

Key = yunus, Latitude = 51.890214Longitude = 29.377358
Key = lastpeony, Latitude = 50.8901758Longitude = 28.377297

how to use firebasedatabase transactions?

I want to use firebase database transaction in my react native app. I want to update the users count whenever the user is added in database

here is the code I’m using

let dbCountPath = "/DatabaseUsersCount/" + "count"

    dbCountPath.transaction(function (current_value) {
      return (current_value || 0) + 1;
    });

I’m getting error of transaction is not exists ? how can we solve this issue ?

Writing data to Firebase, Android

I have an App which uses Firebase and it uses ‘push’ to write a record. My problem is with updating the content of that record. Any help very welcome. I am using Firebase Authentication email/password and that works fine. I also have my database in a Java Class which also works fine. In onCreate method I have the data referenced:

 databasePropertyData FirebaseDatabase.getInstance().getReference("users");

Using a button I can create a new record with it’s unique identifier, which is what I want:

    String ownerId = databasePropertyData.push().getKey();
    PropertyData propertyData = new PropertyData(ownerId, ownerName, name);
    databasePropertyData.child(ownerId).setValue(propertyData);

This code works fine and creates a record with the user id just as I want.

However, I now want to update that particular record and that is where the problems lies. The code I have used (and a myriad variations) sets up a new record rather than updating the existing data. This is one example of my failed experimentation:

   String ownerId = databasePropertyData.getKey();
   databasePropertyData.child(ownerId).setValue(name,ownerName);

Any help would be much appreciated.

File Upload in reactjs

I wanted to upload file using reactjs and store that file in firebase storage after that i want to access that document in my ionic application.
I have uploaded the file and successfully save it in firebase storage,but filename is remains undefined. I also wanted to save that file name and path in the database.
here is my code

   handleSubmitFirebase(event) {
    //alert('A push was submitted: ' + this.state.value);
    alert(JSON.parse(event));
    var docInfo = {
        title: this.docnm.value,
        path: this.docfile.value,
        date: this.docdt.value,
        unm: this.unm.value,
        D_id: DbConfig.database()
            .ref("documents")
            .push(docInfo).key
    }; //documents info

    DbConfig.database()
        .ref("documents")
        .push(docInfo);
    this.docnm.value = ""; // <- clear the input
    alert("Successfully Added");


}

handlePdfUploadStart() { this.setState({ isUploading: true, progress: 0 }); }
handlePdfProgress(progress) { this.setState({ progress }); }
handlePdfUploadError(error) {
    this.setState({ isUploading: false });
    console.error(error);
}
handlePdfUploadSuccess(filename) {
    alert(filename);
    this.setState({ avatar: filename, progress: 100, isUploading: false });
    DbConfig.storage().ref('upload/').child(filename).getDownloadURL().then(url => this.setState({ avatarURL: url }));
}

render() {
    return (
        <div className="content">
            <NavBar></NavBar>
            <div className="row">
                <div className="col-md-10">
                    <div className="card">
                        <div className="card-header card-header-icon" data-background-color="rose">
                            <i className="material-icons">account_balance</i>
                        </div>
                        <div className="card-content">
                            <h4 className="card-title">Add Document</h4>
                            <form onSubmit={this.handleSubmitFirebase}>
                                <div className="form-group label-floating is-empty">
                                    <label className="control-label">Document Name</label>
                                    <input type="text" className="form-control" ref={el => (this.docnm = el)} onChange={this.handleChange} />
                                    <span className="material-input"></span></div>
                                <div className="form-group label-floating is-empty">
                                    <label className="control-label">User Name</label>
                                    <input type="text" className="form-control" ref={el => (this.unm = el)} onChange={this.handleChange} />
                                    <span className="material-input"></span></div>
                                <div className="form-group label-floating is-empty">
                                    <label className="control-label">Date</label>
                                    <input type="date" className="form-control" ref={el => (this.docdt = el)} onChange={this.handleChange} />
                                    <span className="material-input"></span></div>
                                <div className="form-group  label-floating is-empty">
                                    <label className="control-label">Document</label>
                                    <FileUploader
                                        accept="pdf,doc/*"
                                        name="avatar"
                                        ref={el => (this.docfile = el)}
                                        filename={file => alert(this.docfile.value + file.name.split('.')[1])}
                                        storageRef={DbConfig.storage().ref('upload/')}
                                        onUploadStart={this.handlePdfUploadStart}
                                        onUploadError={this.handlePdfUploadError}
                                        onUploadSuccess={this.handlePdfUploadSuccess}
                                        onProgress={this.handlePdfProgress}
                                    />
                                    <span className="material-input"></span></div>

                                <button type="submit" className="btn btn-fill btn-rose submit_btn">Submit</button>
                            </form>
                        </div>
                    </div>
                </div>

            </div>
        </div>
    )
}

Encrypted Password doesn’t match at login from firebase database using AES algorithm

I have been trying to register a new user. At the time of the registration I encrypted the password in the Firebase Database using AES.The Algorithm.password encryption is succesfully. But when I am trying to login the user with the email id and the password, the passwords which I entered in
the registration form are not matching. Instead the password matches with the encryption string which is stored in the firebase database.

Register Activity

  public class RegisterActivity extends AppCompatActivity implements
  View.OnClickListener {

    private static final String TAG = "MAGIC";
    Firebase mref= null;
    private User user;
    private EditText name;
    private EditText phoneNumber;
    private EditText email;
    private EditText password;
    private EditText address;
    private Button register;
    private FirebaseAuth mAuth;
    private ProgressDialog mProgressDialog;

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

    Firebase.setAndroidContext(this);
    mAuth = FirebaseAuth.getInstance();
}

    @Override
    protected void onStart() {
    super.onStart();
    name = (EditText) findViewById(R.id.edit_text_username);
    phoneNumber = (EditText) findViewById(R.id.edit_text_phone_number);
    email = (EditText) findViewById(R.id.edit_text_new_email);
    password = (EditText) findViewById(R.id.edit_text_new_password);
    address = (EditText) findViewById(R.id.edit_text_address);
    register = (Button) findViewById(R.id.button_register);

    register.setOnClickListener(this);
}
    @Override
    public void onStop() {
    super.onStop();
}

    //This method sets up a new User by fetching the user entered details.
    protected void setUpUser() {
    user = new User();
    user.setName(name.getText().toString().trim());
    user.setPhoneNumber(phoneNumber.getText().toString().trim());
    user.setAddress(address.getText().toString().trim());
    user.setEmail(email.getText().toString().trim());
    user.setPassword(password.getText().toString().trim());

}
    @Override
    public void onClick(View v) {

    encryption(password.toString());
    mref = new Firebase("https://encryptlogin.firebaseio.com/");
  createNewAccount(email.getText().toString(),password.getText().toString());

}
    private void createNewAccount(String email, String password) {
    Log.d(TAG, "createNewAccount:" + email);
    if (!validateForm()) {
        return;
    }
    //This method sets up a new User by fetching the user entered details.
    setUpUser();
    //This method  method  takes in an email address and password, validates them and then creates a new user
    // with the createUserWithEmailAndPassword method.
    // If the new account was created, the user is also signed in, and the AuthStateListener runs the onAuthStateChanged callback.
    // In the callback, you can use the getCurrentUser method to get the user's account data.

    showProgressDialog();
    mAuth.createUserWithEmailAndPassword(email, password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {



                 Log.d(TAG, "Register Successfully " + task.isSuccessful());
                    hideProgressDialog();

      // If sign in fails, display a message to the user. If sign in succeeds
          // the auth state listener will be notified and logic to handle the
                    // signed in user can be handled in the listener.

     if (!task.isSuccessful()) {
     Toast.makeText(RegisterActivity.this, "Registration failed.",  Toast.LENGTH_SHORT).show();
                        hideProgressDialog();

                    } else {
        onAuthenticationSuccess(task.getResult().getUser());
        Toast.makeText(RegisterActivity.this, "Register Successful.", Toast.LENGTH_SHORT).show();
                    } hideProgressDialog();
                }
            });
}
    private void onAuthenticationSuccess(FirebaseUser mUser) {
    // Write new user
    saveNewUser(mUser.getUid(),  user.getName(),user.getPhoneNumber(), user.getEmail(), user.getPassword()); 
    signOut();
    // Go to LoginActivity
    Intent i =new Intent(RegisterActivity.this, MainActivity.class);
    startActivity(i);
}
private void saveNewUser(String userId, String name, String phone, String               email, String password) {

    User user = new User(userId,name,phone,email,password);
    mref.child("Users").child(name).setValue(user);
}
private void signOut() {
    mAuth.signOut();
}
//This method, validates email address and password
private boolean validateForm() {
    boolean valid = true;

    String userEmail = email.getText().toString();
    if (TextUtils.isEmpty(userEmail)) {
        email.setError("Required.");
        valid = false;
    } else {
        email.setError(null);
    }

    String userPassword = password.getText().toString();
    if (TextUtils.isEmpty(userPassword)) {
        password.setError("Required.");
        valid = false;
    } else {
        password.setError(null);
    }

    String userPhoneNumber = phoneNumber.getText().toString();
    if (TextUtils.isEmpty(userPhoneNumber)){
        phoneNumber.setError("Required");
        valid = false;
    }else {
        phoneNumber.setError(null);
    }

    String userAddress = address.getText().toString();
    if (TextUtils.isEmpty(userAddress)){
        address.setError("Required");
        valid = false;
    }else {
        address.setError(null);
    }
    if(!Patterns.EMAIL_ADDRESS.matcher(userEmail).matches()){
    Toast.makeText(getApplicationContext(),"please enter valid email",
    Toast.LENGTH_LONG).show();
    }

    if (userEmail.isEmpty() && userPassword.isEmpty()userAddress.isEmpty()
    && userPhoneNumber.isEmpty()){
    Toast.makeText(getApplicationContext(),"all fields are mandatory",
    Toast.LENGTH_LONG).show();
    }

    return valid;
}
public void showProgressDialog() {
    if (mProgressDialog == null) {
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("Loading");
        mProgressDialog.setIndeterminate(true);
    }
    mProgressDialog.show();
}

public void hideProgressDialog() {
    if (mProgressDialog != null && mProgressDialog.isShowing()) {
        mProgressDialog.dismiss();
    }
}
    public void encryption(String pass){
    String seedValue = "secKey";
    try {
        password.setText(AESHelper.encrypt(seedValue,pass));
    }catch (Exception e){
        e.printStackTrace();
    }
}  
}

Login Activity

  public class MainActivity extends AppCompatActivity  {


EditText Email, pwd;
Button login;
TextView Register,Forgetpwd;
FirebaseAuth mAuth;
ProgressDialog progressDialog;

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

    Firebase.setAndroidContext(this);

    mAuth = FirebaseAuth.getInstance();

    if (mAuth.getCurrentUser() != null) {
        startActivity(new Intent(MainActivity.this, Forget_password.class));
        finish();
    }

    Email = (EditText) findViewById(R.id.myEmail);
    pwd = (EditText) findViewById(R.id.editpassword);
    login = (Button) findViewById(R.id.buttonlogin);
    Register = (TextView) findViewById(R.id.register);
    Forgetpwd = (TextView) findViewById(R.id.reset);

    mAuth = FirebaseAuth.getInstance();


    Register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this, RegisterActivity.class));
        }
    });

    Forgetpwd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this, Forget_password.class));
        }
    });

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


            String email = Email.getText().toString();
            final String password = pwd.getText().toString();


            if (TextUtils.isEmpty(email)) {
                Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
                return;
            }

            if (TextUtils.isEmpty(password)) {
                Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
                return;
            }

            if(!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
                Toast.makeText(getApplicationContext(),"please enter valid email",Toast.LENGTH_LONG).show();
            }

            if (email.isEmpty() && password.isEmpty()){
                Toast.makeText(getApplicationContext(),"all fields are mandatory",Toast.LENGTH_LONG).show();
            }

            showProgressDialog();
            mAuth.signInWithEmailAndPassword(email, password)
                    .addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            // If sign in fails, display a message to the user. If sign in succeeds
                            // the auth state listener will be notified and logic to handle the
                            // signed in user can be handled in the listener.
                          /*  progressBar.setVisibility(View.GONE);*/
                            if (!task.isSuccessful()) {
                                // there was an error
                                if (password.length() < 6) {
                                    Toast.makeText(getApplicationContext(), "minimum password!", Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(getApplicationContext(), "Authentication failed!", Toast.LENGTH_SHORT).show();                                    }
                            } else {
                                Toast.makeText(getApplicationContext(), "Login Successful", Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(MainActivity.this, Forget_password.class);
                                startActivity(intent);
                                finish();
                            }
                            hideProgressDialog();
                        }
                    });
        }
    });
}

private void showProgressDialog() {

    if (progressDialog == null) {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage(getString(R.string.loading));
        progressDialog.setIndeterminate(true);
    }

    progressDialog.show();
}

public void hideProgressDialog() {
    if (progressDialog != null && progressDialog.isShowing()) {
        progressDialog.dismiss();
    }
}    
 }

AESHelper Class

  import javax.crypto.Cipher;
  import javax.crypto.KeyGenerator;
  import javax.crypto.SecretKey;
  import javax.crypto.spec.SecretKeySpec;

  public class AESHelper {
  public static String encrypt(String seed, String cleartext 
     throwsException{

    byte[] rawKey = getRawKey(seed.getBytes());
    byte[] result = encrypt(rawKey, cleartext.getBytes());
    return toHex(result);
   }

      public static String decrypt(String seed, String encrypted) 
     throwsException{
       byte[] rawKey = getRawKey(seed.getBytes());
       byte[] enc = toByte(encrypted);
       byte[] result = decrypt(rawKey, enc);
       return new String(result);
   }
    private static byte[] getRawKey(byte[] seed) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG","Crypto");
    sr.setSeed(seed);
    kgen.init(128, sr); // 192 and 256 bits may not be available
    SecretKey skey = kgen.generateKey();
    byte[] raw = skey.getEncoded();
    return raw;
  }
    private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception{ 
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypted = cipher.doFinal(clear);
    return encrypted;
}
   private static byte[] decrypt(byte[] raw, byte[] encrypted)throws
   Exception{
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    byte[] decrypted = cipher.doFinal(encrypted);
    return decrypted;
   }
  public static String toHex(String txt) {
    return toHex(txt.getBytes());
   }
    public static String fromHex(String hex) {
    return new String(toByte(hex));
   }

    public static byte[] toByte(String hexString) {
    int len = hexString.length()/2;
    byte[] result = new byte[len];
    for (int i = 0; i < len; i++)
    result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).
    byteValue();
    return result;
  }
    public static String toHex(byte[] buf) {
    if (buf == null)
        return "";
    StringBuffer result = new StringBuffer(2*buf.length);
    for (int i = 0; i < buf.length; i++) {
        appendHex(result, buf[i]);
    }
    return result.toString();
   }
     private final static String HEX = "0123456789ABCDEF";
     private static void appendHex(StringBuffer sb, byte b) {
    sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
  }
  }

what do I do to match password at login activity. help me plz…

Writing data to Firebase, Android

I have an App which uses Firebase and it uses ‘push’ to write a record. My problem is with updating the content of that record. Any help very welcome. I am using Firebase Authentication email/password and that works fine. I also have my database in a Java Class which also works fine. In onCreate method I have the data referenced:

 databasePropertyData FirebaseDatabase.getInstance().getReference("users");

Using a button I can create a new record with it’s unique identifier, which is what I want:

    String ownerId = databasePropertyData.push().getKey();
    PropertyData propertyData = new PropertyData(ownerId, ownerName, name);
    databasePropertyData.child(ownerId).setValue(propertyData);

This code works fine and creates a record with the user id just as I want.

However, I now want to update that particular record and that is where the problems lies. The code I have used (and a myriad variations) sets up a new record rather than updating the existing data. This is one example of my failed experimentation:

   String ownerId = databasePropertyData.getKey();
   databasePropertyData.child(ownerId).setValue(name,ownerName);

Any help would be much appreciated.