0

I want to retrieve data from Firebase and display it in an EditText and allow the user make changes to it if the need arises

This is an android note app using Firebase as the database

I want to retrieve data from Firebase and display it in an EditText and allow the user make changes to it if the need arises.


public class HomeActivity extends AppCompatActivity {

    private Toolbar mToolbar;
    private FloatingActionButton mFABCreate;

    private FirebaseAuth mFirebaseAuth;
    private RecyclerView mRecyclerView;
    private DatabaseReference mDatabaseReference;

    String mPost_Key;
    String mKey;
    String mTitle;
    String mNote;

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

        mFirebaseAuth  = FirebaseAuth.getInstance();
        FirebaseUser lFirebaseUser = mFirebaseAuth.getCurrentUser();
        assert lFirebaseUser  != null;
        String uid = lFirebaseUser.getUid();
        mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("AllData").child(uid);
        mDatabaseReference.keepSynced(true);



        mRecyclerView = findViewById(R.id.recycler);

        LinearLayoutManager lLinearLayoutManager = new LinearLayoutManager(this);
        lLinearLayoutManager.setStackFromEnd(true);
        lLinearLayoutManager.setReverseLayout(true); 
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(lLinearLayoutManager);


        mToolbar = findViewById(R.id.toolbar);
        mToolbar.setTitle("Quick Note");

        FloatingActionButton fab = findViewById(R.id.Add_Data);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
                startActivity(new Intent(HomeActivity.this, AddActivity.class));
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();

        FirebaseRecyclerAdapter<Items, RecyclerViewAdapter> lAdapter = new FirebaseRecyclerAdapter<Items, RecyclerViewAdapter>(
                Items.class,
                R.layout.show_note,
                RecyclerViewAdapter.class,
                mDatabaseReference) {
            @Override
            protected void populateViewHolder(RecyclerViewAdapter recyclerViewAdapter, final Items items, final int i) {
                recyclerViewAdapter.setTitle(items.getTitle());
                recyclerViewAdapter.setNote(items.getNote());
                recyclerViewAdapter.setDate(items.getDate());

                recyclerViewAdapter.mView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPost_Key = getRef(i).getKey();
                        mTitle = items.getTitle();
                        mNote = items.getNote();

                        editData();
                    }
                });

            }
        };
        mRecyclerView.setAdapter(lAdapter);
    }


    private void editData(){
        startActivity(new Intent(getApplicationContext(), EditActivity.class));
    }


    public static class RecyclerViewAdapter extends RecyclerView.ViewHolder{
        View mView;
        public RecyclerViewAdapter(@NonNull View itemView) {
            super(itemView);
            mView = itemView;
        }
        public void setTitle (String title){
            TextView lTitle = mView.findViewById(R.id.showTitle);
            lTitle.setText(title);
        }

        public void setNote (String note){
            TextView lNote = mView.findViewById(R.id.showNote);
            lNote.setText(note);
        }

        public void setDate (String date){
            TextView lDate = mView.findViewById(R.id.showDate);
            lDate.setText(date);
        }
    }

}



public class EditActivity extends AppCompatActivity {
    private FirebaseAuth mAuth;
    private DatabaseReference mDatabaseReference;
    private FirebaseDatabase mFirebaseDatabase;
    RecyclerView mRecyclerView;

    String mPost_Key;
    String mTitle, mNote;
    String lTitleFire;
    String lNoteFire;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        final EditText lTitle = findViewById(R.id.YourTitleEdit);
        final TextView lNote = findViewById(R.id.Your_Note_Add);
        mAuth = FirebaseAuth.getInstance();
        mFirebaseDatabase = FirebaseDatabase.getInstance();
        mDatabaseReference = mFirebaseDatabase.getReference(mAuth.getUid());
        mDatabaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                Items lGetValues  = dataSnapshot.getValue(Items.class);
                assert lGetValues != null;
                lTitle.setText(lGetValues.getTitle());
                lNote.setText(lGetValues.getNote());
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(getApplicationContext(), "Getting value failed", Toast.LENGTH_LONG).show();

            }
        });

    }

}



public class Items {
    String title;
    String note;
    String date;
    String id;

    public Items() {
    }

    public Items(String title, String note, String date, String id) {
        this.title = title;
        this.note = note;
        this.date = date;
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}    

Firebase data:


AllData
  nakrU3ArQNShLzyn9U8X9fAFNeL2
    -LopLNpUFmepM8gvCmHS
      date:
      id:
      note:
      title: 

My aim is to set the values gotten from Firebase and display it into the "EditActivity"

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Rex
  • 1
  • 3
  • It's not clear what the problem is here, but my first observation is that you have no way of knowing which note is clicked in the EditActivity... For that, you need to pass data through the Intent – OneCricketeer Sep 15 '19 at 19:52
  • I am trying to get the data stored in my firebase and display it into the edittext. – Rex Sep 15 '19 at 21:06
  • I understand that and your value event listener looks fine. Do you have data in Firebase to display? The values you've shown are blank, so is your question actually about how to write data? You'll need to call setValue somewhere https://firebase.google.com/docs/database/android/read-and-write – OneCricketeer Sep 15 '19 at 22:12
  • Yes I do have data in my firebase – Rex Sep 15 '19 at 22:35
  • Okay, so are you getting errors anywhere? And like I said, you need to pass a reference to the specific row to the edit activity. You've gotten `mPost_Key = getRef(i).getKey();`, but not doing anything with it, then you're doing `getReference(mAuth.getUid())`, which would return all items from the user, not a specific one – OneCricketeer Sep 15 '19 at 22:41
  • No am not getting any error, it just display blank EditText, can you please show me how to do it the right way. I don't mind sending you the apps source codes – Rex Sep 15 '19 at 22:49
  • Start here, and pass the post key, like I mention to the other activity https://stackoverflow.com/a/2091482/2308683 then edit the reference you use to lookup the value in the EditActivity – OneCricketeer Sep 15 '19 at 23:10
  • Am really confused, can you put me through. Am still new to programming – Rex Sep 15 '19 at 23:31

1 Answers1

0

it just display blank EditText

Assuming you get no errors, and there isn't empty strings saved in Firebase values, if you look at the data in Firebase, you have two ID values, yet you are only querying for the top one

AllData
    nakrU3ArQNShLzyn9U8X9fAFNeL2  # Uid
        -LopLNpUFmepM8gvCmHS  # a specific item 

You'll need to add another reference to the specific item, then add the value listener to that for it to show in the EditText. For example,

String itemId = ...;
mDatabaseReference.child(itemId)
    .addValueEventListener(... 

In order to get that id, you'll need to pass it to the next activity when you click it like so

editData(getRef(i).getKey());

Therefore, in that editData method, pass the id as an Intent extra so it can be found by the EditActivity

private void editData(String itemId) {
    Intent intent = new Intent(HomeActivity.this, EditActivity.class);
    intent.putExtra("EXTRA_ITEM_ID", itemId);
    startActivity(intent);
} 

Then over in the EditActivity, you need to get and use the item ID to query for a specific item

String itemId = getIntent().getStringExtra("EXTRA_ITEM_ID");
// wouldn't hurt to log the ID value for debugging here 
mDatabaseReference.child(itemId)
    .addValueEventListener(... 

Then keep everything else you already have

That should at least display something...


Then you'll want to add a save button somewhere so that you can write the value back to Firebase, as it won't save automatically as you type (unless you implement that, but I wouldn't recommend that because it'll create a lot of unnecessary network calls)

Items toSave =... 
mDatabaseReference.child(itemId).setValue(toSave);
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • On the EditActivity can you throw in more light, I am a bit confused. I have already done it the way you suggested but don't know how am am gonna continue from where you stopped. – Rex Sep 16 '19 at 06:47
  • Everything you already have should be the exact same. Add the listener, and get the value `dataSnapshot.getValue(Items.class)`, then set up the EditText – OneCricketeer Sep 16 '19 at 06:52
  • This is the error i get : Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.DatabaseReference.child(java.lang.String)' on a null object reference – Rex Sep 16 '19 at 07:12
  • This is my code ```mDatabaseReference.child(itemID).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { String Title = dataSnapshot.getValue(Items.class).getTitle(); String Note = dataSnapshot.getValue(Items.class).getTitle(); lTitle.setText(Title); lNote.setText(Note); }``` – Rex Sep 16 '19 at 07:17
  • Sounds like you deleted this line, or it returned null `mFirebaseDatabase.getReference(mAuth.getUid())` – OneCricketeer Sep 16 '19 at 07:21
  • ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); mAuth = FirebaseAuth.getInstance(); // Bundle lBundle = getIntent().getExtras(); // assert lBundle != null; // String data = lBundle.getString("position"); mFirebaseDatabase = FirebaseDatabase.getInstance(); FirebaseUser lFirebaseUser = mAuth.getCurrentUser(); ``` – Rex Sep 16 '19 at 07:25
  • ``` String uid = lFirebaseUser.getUid(); final EditText lTitle = findViewById(R.id.YourTitleEdit); final TextView lNote = findViewById(R.id.YourTextEdit); String lEXTRA_item_id = getIntent().getStringExtra("EXTRA_ITEM_ID"); mDatabaseReference.child(lEXTRA_item_id).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { }``` – Rex Sep 16 '19 at 07:26
  • `String Title = dataSnapshot.getValue(Items.class).getTitle(); String Note = dataSnapshot.getValue(Items.class).getTitle(); lTitle.setText(Title); lNote.setText(Note); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); }` – Rex Sep 16 '19 at 07:27
  • That is my EditActivity above – Rex Sep 16 '19 at 07:28