- Home
- >> Nerd Digest
- >> Android
-
Andorid FireBase Integration
over 9 years ago
Firebase is a real-time database. It is a NoSQL database which stores data as simple JSON. Benefit of using firebase is, it sync data by itself. Suppose if we update some data in the database then we will get listeners in our code to listen for the updated data. Same way it does for adding new data, removing of data.
Create Firebase account :
Create app name and it will give you app url for your database having ".firebaseio.com" in the end.
Download the library from https://www.firebase.com/docs/android/.
Full source code is also attached as attachment. You can also find the firebase library under libs folder.
In this Activity we have created a form to input 3 fields from user. On Add button click data will be added to firebase database. On Update button click data will be updated to firebase database. We have placed listeners in code, so if we make any changes in the database it will automatically read that data and will be display the changes made in the app.
MainActivity.java
public class MainActivity extends Activity { private EditText nameEditText; private EditText ageEditText; private EditText cityEditText; private HashMap<String, String> addHashMap = new HashMap<>(); private HashMap<String, Object> updateHashMap = new HashMap<>(); private ProgressDialog hideProgressBarCustom; private TextView nameTextView; private TextView ageTextView; private TextView cityTextView; private String name = ""; private String age = ""; private String city = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Firebase Firebase.setAndroidContext(getApplicationContext()); initControls(); fetchData(); } private void initControls(){ nameEditText = (EditText) findViewById(R.id.NameEditText); ageEditText = (EditText) findViewById(R.id.AgeEditText); cityEditText = (EditText) findViewById(R.id.CityEditText); nameTextView = (TextView) findViewById(R.id.NameTextView); ageTextView = (TextView) findViewById(R.id.AgeTextView); cityTextView = (TextView) findViewById(R.id.CityTextView); findViewById(R.id.AddButton).setOnClickListener(buttonClick); findViewById(R.id.UpdateButton).setOnClickListener(buttonClick); nameEditText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } @Override public void afterTextChanged(Editable arg0) { nameEditText.setError(null); } }); ageEditText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } @Override public void afterTextChanged(Editable arg0) { ageEditText.setError(null); } }); cityEditText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } @Override public void afterTextChanged(Editable arg0) { cityEditText.setError(null); } }); } OnClickListener buttonClick = new OnClickListener() { @Override public void onClick(View v) { hideKeyboard(); int id = v.getId(); if(id == R.id.AddButton){ if(isNetworkAvailable(getApplicationContext())){ addButtonClick(); }else{ Toast.makeText(getApplicationContext(), "Connect to working Internet." , Toast.LENGTH_SHORT).show(); } }else if(id == R.id.UpdateButton){ if(isNetworkAvailable(getApplicationContext())){ updateButtonClick(); }else{ Toast.makeText(getApplicationContext(), "Connect to working Internet." , Toast.LENGTH_SHORT).show(); } } } }; private void addButtonClick(){ String nameVal = nameEditText.getText().toString(); String ageVal = ageEditText.getText().toString(); String cityVal = cityEditText.getText().toString(); if(nameVal.trim().length()==0){ nameEditText.setError(getString(R.string.name_error)); }else if(ageVal.trim().length()==0){ ageEditText.setError(getString(R.string.age_error)); }else if(cityVal.trim().length()==0){ cityEditText.setError(getString(R.string.city_error)); }else{ showProgressDialogCustom(this); addHashMap.clear(); addHashMap.put("Name", nameVal); addHashMap.put("Age", ageVal); addHashMap.put("City", cityVal); AddDataOnFireBase(addHashMap); } } private void updateButtonClick(){ String ageVal = ageEditText.getText().toString(); String cityVal = cityEditText.getText().toString(); if(ageVal.trim().length()==0){ ageEditText.setError(getString(R.string.age_error)); }else if(cityVal.trim().length()==0){ cityEditText.setError(getString(R.string.city_error)); }else{ showProgressDialogCustom(this); updateHashMap.clear(); updateHashMap.put("Age", ageVal); updateHashMap.put("City", cityVal); UpdateDataOnFireBase(updateHashMap); } } /** * Adding data to firebase server * @param data */ private void AddDataOnFireBase(HashMap<String, String> data){ Constant.baseUrl.setValue(data, new Firebase.CompletionListener() { @Override public void onComplete(FirebaseError firebaseError, Firebase firebase) { if(firebaseError != null){ hideProgressBarCustom.dismiss(); Toast.makeText(getApplicationContext(), "Failed to add. " , Toast.LENGTH_SHORT).show(); }else { hideProgressBarCustom.dismiss(); nameEditText.setText(""); ageEditText.setText(""); cityEditText.setText(""); Toast.makeText(getApplicationContext(), "Added successfully." , Toast.LENGTH_SHORT).show(); } } }); } /** * updating data to firebase database * @param data */ private void UpdateDataOnFireBase(HashMap<String, Object> data){ Constant.baseUrl.updateChildren(data, new Firebase.CompletionListener() { @Override public void onComplete(FirebaseError firebaseError, Firebase firebase) { if(firebaseError != null){ hideProgressBarCustom.dismiss(); Toast.makeText(getApplicationContext(), "Failed to update. " , Toast.LENGTH_SHORT).show(); }else { hideProgressBarCustom.dismiss(); nameEditText.setText(""); ageEditText.setText(""); cityEditText.setText(""); Toast.makeText(getApplicationContext(), "Updated successfully." , Toast.LENGTH_SHORT).show(); } } }); } /** * Fetching data from firebase database. */ public void fetchData(){ Constant.baseUrl.addChildEventListener(new ChildEventListener() { @Override // If new data is added, we will get call in this listener. public void onChildAdded(DataSnapshot snapshot, String previousChild) { try{ if(snapshot.getKey().equalsIgnoreCase("name")) name = snapshot.getValue().toString(); }catch (Exception e){} try{ if(snapshot.getKey().equalsIgnoreCase("age")) age = snapshot.getValue().toString(); }catch (Exception e){} try{ if(snapshot.getKey().equalsIgnoreCase("city")) city = snapshot.getValue().toString(); }catch (Exception e){} nameTextView.setText("Name : " + name); ageTextView.setText("Age : " + age); cityTextView.setText("City : " + city); } @Override public void onCancelled(FirebaseError arg0) { } @Override // If data is updated, we will get call in this listener. public void onChildChanged(DataSnapshot snapshot, String arg1) { try{ if(snapshot.getKey().equalsIgnoreCase("name")) name = snapshot.getValue().toString(); }catch (Exception e){} try{ if(snapshot.getKey().equalsIgnoreCase("age")) age = snapshot.getValue().toString(); }catch (Exception e){} try{ if(snapshot.getKey().equalsIgnoreCase("city")) city = snapshot.getValue().toString(); }catch (Exception e){} nameTextView.setText("Name : " + name); ageTextView.setText("Age : " + age); cityTextView.setText("City : " + city); } @Override public void onChildMoved(DataSnapshot arg0, String arg1) { } @Override // If data is deleted, we will get call in this listener. public void onChildRemoved(DataSnapshot snapshot) { try{ if(snapshot.getKey().equalsIgnoreCase("name")) name = snapshot.getValue().toString(); }catch (Exception e){} try{ if(snapshot.getKey().equalsIgnoreCase("age")) age = snapshot.getValue().toString(); }catch (Exception e){} try{ if(snapshot.getKey().equalsIgnoreCase("city")) city = snapshot.getValue().toString(); }catch (Exception e){} nameTextView.setText("Name : " + name); ageTextView.setText("Age : " + age); cityTextView.setText("City : " + city); } }); } // Checking network private boolean isNetworkAvailable(Context context) { return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null; } //Progress Dialog private void showProgressDialogCustom(Context context){ hideProgressBarCustom = new ProgressDialog(context); hideProgressBarCustom.setCancelable(false); hideProgressBarCustom.setMessage("Please wait ..."); hideProgressBarCustom.show(); } // Hide keyboard public void hideKeyboard() { //start with an 'always hidden' command for the activity's window getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); //now tell the IMM to hide the keyboard FROM whatever has focus in the activity InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE); View currentFocusedView = getCurrentFocus(); if(currentFocusedView != null) { inputMethodManager.hideSoftInputFromWindow(currentFocusedView.getWindowToken(), 0); } } } Declaring the firebase url. Constant.java public class Constant { public static Firebase baseUrl =new Firebase("https://blogsample.firebaseio.com/"); }
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="${relativePackage}.${activityClass}" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" android:padding="10dp" android:text="@string/title" android:textSize="18sp" /> <EditText android:id="@+id/NameEditText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginTop="5dp" android:hint="@string/name" android:singleLine="true" /> <EditText android:id="@+id/AgeEditText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginTop="5dp" android:hint="@string/age" android:inputType="numberSigned" android:singleLine="true" /> <EditText android:id="@+id/CityEditText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginTop="5dp" android:hint="@string/city" android:singleLine="true" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginTop="5dp" android:orientation="horizontal" > <Button android:id="@+id/AddButton" android:layout_width="85dp" android:layout_height="wrap_content" android:layout_marginRight="5dp" android:text="@string/add" android:textColor="@color/black" /> <Button android:id="@+id/UpdateButton" android:layout_width="85dp" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:text="@string/update" android:textColor="@color/black" /> </LinearLayout> <TextView android:id="@+id/NameTextView" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="10dp" /> <TextView android:id="@+id/AgeTextView" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="10dp" /> <TextView android:id="@+id/CityTextView" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="10dp" /> </LinearLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="title">Firebase</string> <string name="name">Enter name</string> <string name="age">Enter age</string> <string name="city">Enter city</string> <string name="add">Add</string> <string name="update">Update</string> <string name="fetch_data">Fetch data</string> <string name="name_error">Please enter name.</string> <string name="age_error">Please enter age.</string> <string name="city_error">Please enter city.</string> </resources>
color.xml
color.xml <?xml version="1.0" encoding="utf-8"?> <resources> <color name="white">#FFFFFF</color> <color name="black">#000000</color> </resources>
Manifest permissions
Manifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.INTERNET" />
0 Comment(s)