package com.example.mortezasaadat.app63test;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

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;

public class MainActivity extends AppCompatActivity {

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

        final FirebaseDatabase database = FirebaseDatabase.getInstance();
       final DatabaseReference myRef = database.getReferenceFromUrl("https://app63test.firebaseio.com/");

        final EditText edtKey = (EditText) findViewById(R.id.edtKey);
        final EditText edtValue = (EditText) findViewById(R.id.edtValue);
        Button btnSendValueToServer = (Button) findViewById(R.id.btnSendValueToServer);
        Button btnGetDataFromServer = (Button) findViewById(R.id.btnGetDataFromServer);


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


                myRef.child(edtKey.getText().toString()).setValue(edtValue.getText().toString());



            }
        });


        final TextView txtValue = (TextView) findViewById(R.id.txtValue);


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

                myRef.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        String value = dataSnapshot.child("More").getValue(String.class);


                        if (value == null) {
                            value = "";
                        }

                        txtValue.setText(value);
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });


            }
        });





    }
}
