Advertisement
moastomer

firebase , single and structure read and write

Nov 25th, 2017
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. download the google-services.json file and add it to the app folder
  2.  
  3.  
  4. build.gradle   <project>
  5. ============================
  6. add to dependencies
  7.         classpath 'com.google.gms:google-services:3.0.0'
  8.  
  9.  
  10. build.gradle <app>
  11. ====================
  12. add to dependencies
  13.         compile 'com.google.firebase:firebase-core:9.0.2'
  14.         compile 'com.google.firebase:firebase-database:9.0.2'
  15.  
  16. add to the bottom
  17. apply plugin: 'com.google.gms.google-services'
  18.  
  19.  
  20. activity_main.xml
  21. ======================
  22. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  23.     android:layout_width="match_parent"
  24.     android:layout_height="match_parent"
  25.     android:orientation="vertical">
  26.  
  27.     <EditText
  28.         android:layout_width="match_parent"
  29.         android:layout_height="wrap_content"
  30.         android:hint="Enter message....."
  31.         android:id="@+id/helloMsg"/>
  32.  
  33.     <Button
  34.         android:layout_width="match_parent"
  35.         android:layout_height="wrap_content"
  36.         android:text="Send message..."
  37.         android:onClick="sendMsg"/>
  38.     <Button
  39.         android:layout_width="match_parent"
  40.         android:layout_height="wrap_content"
  41.         android:text="Read Message...."
  42.         android:onClick="readMsg"/>
  43.     <EditText
  44.         android:layout_width="match_parent"
  45.         android:layout_height="wrap_content"
  46.         android:hint="Enter User Name....."
  47.         android:id="@+id/uName"/>
  48.     <EditText
  49.         android:layout_width="match_parent"
  50.         android:layout_height="wrap_content"
  51.         android:id="@+id/uPass"
  52.         android:hint="Enter User Pass"/>
  53.     <Button
  54.         android:layout_width="match_parent"
  55.         android:layout_height="wrap_content"
  56.         android:text="Create User"
  57.         android:onClick="createUser"/>
  58.     <Button
  59.         android:layout_width="match_parent"
  60.         android:layout_height="wrap_content"
  61.         android:text="Get all"
  62.         android:onClick="displayUsers"/>
  63. </LinearLayout>
  64.  
  65.  
  66.  
  67. Users.java (for holding the structure of Json and db)
  68. ===========================================================
  69. import android.content.Context;
  70. import android.net.wifi.WifiInfo;
  71. import android.net.wifi.WifiManager;
  72. import android.widget.Toast;
  73.  
  74. import com.google.firebase.database.DataSnapshot;
  75. import com.google.firebase.database.DatabaseError;
  76. import com.google.firebase.database.DatabaseReference;
  77. import com.google.firebase.database.FirebaseDatabase;
  78. import com.google.firebase.database.ValueEventListener;
  79.  
  80. import java.util.ArrayList;
  81. import java.util.List;
  82.  
  83. /**
  84.  * Created by app0811 on 05/06/2016.
  85.  */
  86. public class Users {
  87.     public String userName;  //hold userName
  88.     public String userPass;  //hold userPass
  89.     public String userId;    //hold userId
  90.  
  91.     public Users(){}  //empty constructor, must have
  92.  
  93.     public Users(String userName, String userPass, String uid)
  94.     {
  95.         this.userName=userName;
  96.         this.userPass=userPass;
  97.         this.userId=uid;  //represent the UUID
  98.     }
  99.  
  100.     public void saveUser()
  101.     {
  102.         //create an instance of User class
  103.         Users user=new Users(userName,userPass,userId,context);
  104.  
  105.         //creating a connection to fire base
  106.         FirebaseDatabase database=FirebaseDatabase.getInstance();
  107.        
  108.         //creating a reference to Users object
  109.         DatabaseReference myRef=database.getReference("Users");
  110.        
  111.         //saving the user under the UUID
  112.         myRef.child(userId).setValue(user);
  113.     }
  114. }
  115.  
  116. MainActivity.java
  117. ==================================
  118.  
  119. public class MainActivity extends AppCompatActivity {
  120.  
  121.     EditText myMsg;
  122.     EditText uName;
  123.     EditText uPass;
  124.     Context context;
  125.     final List<Users> myData=new ArrayList<>();
  126.  
  127.     @Override
  128.     protected void onCreate(Bundle savedInstanceState) {
  129.         super.onCreate(savedInstanceState);
  130.         setContentView(R.layout.activity_main);
  131.         myMsg=(EditText)findViewById(R.id.helloMsg);
  132.         uName=(EditText)findViewById(R.id.uName);
  133.         uPass=(EditText)findViewById(R.id.uPass);
  134.         context=this;
  135.     }
  136.  
  137.     private String getMac()
  138.     {
  139.         //seeting WifiManager
  140.         WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
  141.         //getting the info for the manager
  142.         WifiInfo info = manager.getConnectionInfo();
  143.         //getting mac address , physical address of the wifi card
  144.         String address = info.getMacAddress();
  145.         //returning the address
  146.         return address;
  147.     }
  148.  
  149.     private String getUUID()
  150.     {
  151.         //create a unique UUID
  152.         UUID idOne = UUID.randomUUID();
  153.         //returning the UUID
  154.         return idOne.toString();
  155.     }
  156.  
  157.  
  158.     public void sendMsg(View v)  // Write a message to the database
  159.     {
  160.         //creating an instance to the database
  161.         FirebaseDatabase database = FirebaseDatabase.getInstance();
  162.         //creating a reference to message object
  163.         DatabaseReference myRef = database.getReference("message");
  164.         //getting the message from the activity
  165.         String myString = myMsg.getText().toString();
  166.         //setting the value
  167.         myRef.setValue(myString);
  168.     }
  169.  
  170.     public void readMsg(View v)
  171.     {
  172.         //creating a connection to the database
  173.         FirebaseDatabase database = FirebaseDatabase.getInstance();
  174.         //creating a reference to the database
  175.         DatabaseReference myRef = database.getReference("message");
  176.         //creating an event listener to the reference
  177.         myRef.addValueEventListener(new ValueEventListener() {
  178.             @Override
  179.             public void onDataChange(DataSnapshot dataSnapshot) {
  180.                 // This method is called once with the initial value and again
  181.                 // whenever data at this location is updated.
  182.                 String value = dataSnapshot.getValue(String.class);
  183.                 Toast.makeText(MainActivity.this, "Read:"+value, Toast.LENGTH_SHORT).show();
  184.             }
  185.  
  186.             @Override
  187.             public void onCancelled(DatabaseError error) {
  188.                 // Failed to read value
  189.                 Toast.makeText(MainActivity.this, "Failed to read value.", Toast.LENGTH_SHORT).show();
  190.             }
  191.         });
  192.     }
  193.  
  194.     public void createUser(View v)
  195.     {
  196.         //getting the info from the activity
  197.         final String userName=uName.getText().toString();
  198.         final String userPass=uPass.getText().toString();
  199.         //creating new instance of the project
  200.         Users user=new Users(userName,userPass,getUUID(),this);
  201.         //calling inside method from the class to save the data
  202.         user.saveUser();
  203.     }
  204.  
  205.     public void displayUsers(View v)
  206.     {
  207.         //creating an instance to the database
  208.         FirebaseDatabase database = FirebaseDatabase.getInstance();
  209.         //creating a reference to the database
  210.         final DatabaseReference myRef = database.getReference("Users");
  211.  
  212.         //adding an event listener to the Event
  213.         myRef.addListenerForSingleValueEvent(new ValueEventListener() {
  214.             @Override
  215.             //method for data change
  216.             public void onDataChange(DataSnapshot dataSnapshot) {
  217.                 //moving on entire data that we received from the database
  218.                 for (DataSnapshot item:dataSnapshot.getChildren()) {
  219.                     //get a single value, and push it to User instance by the Users class build
  220.                     Users recivedUser = item.getValue(Users.class);
  221.                     //add the value to our list
  222.                     myData.add(recivedUser);
  223.                 }
  224.                 //display the message to the screen
  225.                 Toast.makeText(context, "we got:"+myData.size(), Toast.LENGTH_SHORT).show();
  226.             }
  227.  
  228.             @Override
  229.             public void onCancelled(DatabaseError databaseError) {
  230.                 //handle in error case
  231.             }
  232.         });
  233.     }
  234.  
  235. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement