[Tutorial] Developing Cloud Base App [GoogleCloud][Android]

Search This thread

Geeks Empire

Senior Member
Aug 29, 2014
1,312
1,265
Nashville
GeeksEmpire.co

attachment.php


In this Tutorial I try to explain general aspects of Cloud Computing & Cloud Concepts & Authentication You will learn What is Cloud & If already know basics of Android Programming, you will be able to develop your Cloud Base App after reading carefully this guide.

Featured By XDA
Aamir Siddiqui | May 19, 2016
XDA Senior Member Geeks Empire has posted an extensive tutorial on developing a cloud based app.
The tutorial teaches users how to make use of Google Cloud and Firebase to achieve their goals.

Why are so many businesses moving to the cloud? It’s because cloud computing increases efficiency, helps improve cash flow and offers many more benefits…Here's ten of the best.
1. Flexibility
2. Disaster recovery
3. Automatic software updates
4. Capital-expenditure Free
5. Increased collaboration
6. Work from anywhere
7. Document control
8. Security
9. Competitiveness
10. Environmentally friendly
READ MORE
If you want to design & develop cloud service for your business it is better to understand What you Know & Need.
Try to read again carefully All descriptions & Link above to get reach knowledge of Cloud.
In This Tutorial I used All Alphabet Services. Google Cloud, Firebase, Google Play Services & etc.
I prefer Alphabet cause It is Google ;)
“Firebase — a powerful platform for building iOS, Android, and web-based apps, offering real-time data storage and synchronization, user authentication, and more.”
INDEX
*
Data Transferring
*
- FireBase
Cloud Service
* Authentication *

- Google Account By GoogleSignIn API
- Twitter By Fabric API
- Email/Pass By Firebase API


# Let Start #


What you Need to Continue is;
1. Google Account
2. Ability to Create Hello World! Project in Android Studio


* Application Configuration
Run Android Studio & Create New Project with Blank Activity. (Set Proper AppName & Package)
After Gradle Building finished go to File > Project Structure > Cloud & Enable Firebase.
Go to Manifest > Add Get_Account & Internet Permissions above the <application />

Code:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
then Inside Application tag add Google_Play_Service <meta-data />
Code:
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
Then Open build.gradle (Module: App) & Add these excludes to prevent errors during test process inside android{}
Code:
packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE-FIREBASE.txt'
        exclude 'META-INF/NOTICE'
 }
Also Add this library for auth-process into dependencies{}
Code:
compile 'com.google.android.gms:play-services-auth:8.4.0'
Now your App is Ready to Add Codes for Cloud API But your Need to Configure Cloud Side too.

* Google Cloud & Firebase Configuration
Here some parts doesn't need for beginning Android Coding But It can be tricky & easy for you to do everything on Browser for Google Section and then Focus on Coding. At End you can Review All Parts & Test it by yourself. I will explain more about each part.
Generate your Sign APK to Get SHA-1 Key
Code:
keytool -list -v -keystore '/PATH/TO/kEY_STORE'
To Transfer Data to Cloud you need to Have a Cloud Service. Here I am using Firebase.

Go to www.Firebase.com & Login with your Google Account.
Firebase will automatically Create a Project for you named 'MY FIRST APP' that you can delete or modify it.
Firebase has Free Plan for Small Business, Testing & etc. So after you learn more about cloud you can upgrade your plan for existing projects.
firebase-ct4as-firebase-dashboard.png

The URL of Firebase for your Project is Like this
HTML:
https://YOUR_APP_NAME.firebaseio.com/
Every task with Firebase API needs this URL.

Go to https://Console.Gloud.Google.com Sign-Up & Get 60 Days Trial Period & 300$ to spend on Google Cloud Platform.
So Feel Free to Create Projects & Enabling APIs.
After Creating Google Cloud Project go to Project Dashboard & from Left Panel navigate to API Manager > Credentials. Click on Create Credential & Select OAuth client ID After Loading New Page Select Android Then Create. Now Set Carefully your SHA-1 key & Android App PackageName then Save.

Go to https://Developers.Google.com/ First of All If you are new to Developing Spend some times in this page & Enjoy All Google Services for Everything. :good:
Then Navigate to Google Service for Mobile > Android > Sign-In with Google > Click Get Start > Scroll Down > Click Get Configuration File.
Again Type your Android App PackageName then Click Continue & Type SHA-1 Key & Click ENABLE GOOGLE SIGN-IN after that Scroll Down and Click on Generate Configuration File and Download the File.
Copy google-service.json File & Paste it to App Level Project.
Code:
To do this Now Open Android Studio Change View of Project Explorer from Android View to Project View. 
Expand Project and Paste JSON file under the APP Level.


Now you are ready to use Firebase Services & Login with Google.
Next Post is About Working with Firebase Send/Receive Data.


Oo. DOWNLOAD .oO
SOURCE.CODE
APK.FILE


Thanks for Supporting GeeksEmpire projects

Don't Forget To Hit Thanks


 

Attachments

  • Untitled.jpg
    Untitled.jpg
    71.5 KB · Views: 6,220
  • CloudAppTest.apk
    4 MB · Views: 346
Last edited:

Geeks Empire

Senior Member
Aug 29, 2014
1,312
1,265
Nashville
GeeksEmpire.co
Google Cloud & Firebase [Data Transferring]


attachment.php


Now It is time to Focus on Coding. It is not difficult to understand Firebase API But Using URL carefully to Create New User, Data, Section & etc is important.
Open MainActivity.Java
At First the Class must extended from Fragment that required for Firebase API (& later for Google Sign-In). In this case I use AppCompatActivity.
Code:
public class MainActivity extends AppCompatActivity{}
To work with Firebase API you have to define it like other objects.
You can do it when you need it Or define it at first part of app onCreate(Bundle){}
Code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
[B]Firebase.setAndroidContext(getApplicationContext());[/B]
After that you need to declare instance of your views. For Example I declare ListView that will use for showing loaded Data.
Code:
ListView listView = (ListView)findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, android.R.id.text1);
//built-in adaptor
listView.setAdapter(adapter);
NOTE: Save your Firebase URL to <resource> <string /></resource> Or Save it as Universal String Object inside Class.
For Example Before onCreate(Bundle)
Code:
String FirebaseLink = "https://[B]YOUR_APP_NAME[/B].firebaseio.com/";
String FirebaseTitle = "GeeksEmpire";
String FirebaseSub = "gX";
To Get Data from User you should define input method like <EditText/>
With This methods you can Save Data Locally in Application Private Storage on System
Code:
//Save Content
try {
FileOutputStream fOut = openFileOutput(NAME, MODE_PRIVATE);
fOut.write((DATA).getBytes());

//Always Close All Streams
fOut.close();
fOut.flush();
} 
catch (Exception e) {
 System.out.println(e);
} finally {}
Code:
//Read-File
public String READ(String S, Context context){
File Fav = new File(S);
String Read = null;
FileInputStream fin;
BufferedReader br = null;    
try{
fin = new FileInputStream(Fav);
br = new BufferedReader(new InputStreamReader(fin, "UTF-8"), 1024);
System.out.println(br);
int c;
String temp = "";
while( (c = br.read()) != -1){temp = temp + Character.toString((char)c);}         
Read = temp;}
catch(Exception e)
{System.out.println(e);}
finally{try {br.close();} catch (IOException e) {e.printStackTrace();}}
return Read;
}
But to Store Data on Firebase Server you should declare instance of Firebase API, Push & setValue(DATA)
Code:
upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String DATA = editText.getText().toString();//"[COLOR=Red][I]GeeksEmpire DataBase on FireBase[/I][/COLOR]"
new Firebase([B]FirebaseLink[/B]/*[COLOR=Red][I]https://YOUR_APP_NAME.firebaseio.com[/I]/[/COLOR]*/ + FirebaseTitle/*[COLOR=Red][I]GeeksEmpire[/I][/COLOR]*/)
.push()
.child(FirebaseSub/*[COLOR=Red][I]gX[/I][/COLOR]*/)
.setValue(DATA);
}
});
Compare red texts with image. Firebase URL is submitted but you can Modify both FirebaseTitle & FirebaseSub.

attachment.php


In this Case I used GeeksEmpire as Title & gX as SubTitle & then Data.
It is depend on your design.
you can set GeeksEmpire as User & gX as Title OR Whatever you need.



Data Uploaded to Server & Now you should make an option to Download them. I created function to gather all components.
Code:
public void SetUpCloudContent(){
Firebase.setAndroidContext(this);
new Firebase(FirebaseLink/*[COLOR=Red]https://YOUR_APP_NAME.firebaseio.com/[/COLOR]*/ + FirebaseTitle/*[COLOR=Red]GeeksEmpire[/COLOR]*/).addChildEventListener(new ChildEventListener() {
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
adapter.add((String)dataSnapshot.child(FirebaseSub/*[COLOR=Red]gX[/COLOR]*/).getValue());//add each value to ListView
}
public void onChildRemoved(DataSnapshot dataSnapshot) {
adapter.remove((String)dataSnapshot.child(FirebaseSub).getValue());
}
public void onChildChanged(DataSnapshot dataSnapshot, String s) { }
public void onChildMoved(DataSnapshot dataSnapshot, String s) { }
public void onCancelled(FirebaseError firebaseError) { }
});
}

To Change Data Just Use ID you got to User (For Example GeeksEmpire > gX) and OverWrite Data.
But here is a method to Delete Data.
// Delete items when clicked
Code:
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new Firebase([COLOR=Red]FirebaseLink [/COLOR]+ [COLOR=Red]FirebaseTitle[/COLOR])
.orderByChild([COLOR=Red]FirebaseSub[/COLOR])
.equalTo((String) listView.getItemAtPosition(position)/*[I]get data from ListView[/I]*/)
.addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChildren()) {
DataSnapshot firstChild = dataSnapshot.getChildren().iterator().next();
firstChild.getRef().removeValue();
}
}
public void onCancelled(FirebaseError firebaseError) { }
});
return false;
}
});

Sending & Receiving Data to Firebase Cloud Service is Done.
Again It depends on you How to define Users & Create Individual ID for each one.
Next Posts Will Show How to Create Sign-In Options for your App. That Also Help a lot to create Individual ID.


Thanks for Supporting GeeksEmpire projects

Don't Forget To Hit Thanks
 

Attachments

  • images.png
    images.png
    6.4 KB · Views: 12,799
  • Untitled.png
    Untitled.png
    21.3 KB · Views: 12,640
Last edited:

Geeks Empire

Senior Member
Aug 29, 2014
1,312
1,265
Nashville
GeeksEmpire.co
Google Account [Authentication]

attachment.php


I used Google API for Google Account Auth cause you can get more info about Google Account to use and customize your App. Info that you cannot retrieve by Firebase.Auth("google"). For Example Account Pic to Use inside your app for user.
(Set Google Account Pic as Pic of Account on your App)

In First Post Google Sign-In Setup Completed.
Sign-In API Enabled & Configuration file add to Project.

Another modification needed to apply on build.gradle (Module: App)
Add this plugin at end of your gradle file.
Code:
apply plugin: 'com.google.gms.google-services'
& Also for build.gradle (Project)
Add this classpath under dependencies {}
Code:
classpath 'com.google.gms:google-services:2.0.0-alpha5'
You should Implement you class to GoogleApiClient.ConnectionCallbacks & GoogleApiClient.OnConnectionFailedListener.
& Add required methods.
Code:
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {}
@Override
public void onConnected(@Nullable Bundle bundle) {}
@Override
public void onConnectionSuspended(int i) {}
Define GoogleApiClient as universal variable (Outside of any Function).
Get instance of GoogleApiClient & GoogleSignInOptions onCreate(Bundle).
Code:
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)//FragmentActivity
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
To perform Sign Action normally button used If you don't want to do it at start up of app.
For this Google Service has its own button design that used in sample. However you can design your own view.
Code:
<com.google.android.gms.common.SignInButton />
Like other Android system function calling we should use Intent to Invoke Google Account Chooser and Get Result on CallBack.
Code:
google.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, [COLOR=Red]7[/COLOR]);
}
});
On result CallBack you should declare GoogleSignResult
Code:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if(requestCode == [COLOR=Red]7[/COLOR]){
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if(result.isSuccess()){
//[B]Handle Security Inside App[/B]
GoogleSignInAccount acct = result.getSignInAccount();

Toast.makeText(getApplicationContext(), "getEmail >> " + [B]acct.getEmail()[/B], Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "getDisplayName >> " + [B]acct.getDisplayName()[/B], Toast.LENGTH_LONG).show();
//Can get more Info by using GoogleSignInAccount 
}
}
NOTE: You can use Google Account as UserName for your Users on Firebase & By Calling Sign-In Process at App Start Provide Security for your App.


Thanks for Supporting GeeksEmpire projects

Don't Forget To Hit Thanks
 

Attachments

  • index.png
    index.png
    1.7 KB · Views: 12,293
Last edited:

Geeks Empire

Senior Member
Aug 29, 2014
1,312
1,265
Nashville
GeeksEmpire.co
Twitter Account [Authentication]


attachment.php


Authentication by Twitter has Complex aspect.
First you should Create Twitter Account, Then Create Web App through www.twitter.com (to get Public & Secret Key), Enable Twitter on Firebase (Not Required But I recommend it) & Install 3rd-Party Plugin on Android Studio (Fabric API).

Go to https://twitter.com/ & Sign Up then go to https://apps.twitter.com/ & Create App.
Name the App & Write Description & WebSite.
In App Page > Keys & Access Token
. Consumer Key (API Key) = XXXXX
. Consumer Secret (API Secret) = XXXXX
Save these value to resources of your app. res > values > string
Code:
</resources>
<string name="twitter_consumer_key">[B]API Key[/B]</string>
<string name="twitter_consumer_secret">[B]API Secret[/B]</string>
</resources>
- Go to Login & Auth on Firebase Select Twitter & Paste API Key + API Secret.
On Android Studio navigate to File > Setting > Plugin& Search for Fabric (Click Browse)
After Plugin Downloaded It will ask for Restart to Complete Installation.
Then Fabric Plugin icon will appear on toolbar & maybe Right-Panel.
Click on Plugin & Sign Up. Then you will see your current project on Fabric list. Select it & click Next.
From List of All Kits select Twitter & click Install. It will ask for API Key + API Secret
Fabric will Apply All Modification it needs to your project & after that you project will be ready for Twitter Auth.
But for Developer It is always important points to understand every part of tools and apps.
* Fabric Inside build.grade (Module: App)
before Android Plugin
Code:
apply plugin: 'com.android.application'
Add this Script
Code:
buildscript {
repositories {
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
classpath 'io.fabric.tools:gradle:1.+'
}
}
after Android Plugin set up fabric plugin
Code:
apply plugin: 'io.fabric'
after android{} functions add Fabric Repositories
Code:
repositories {
mavenCentral()
maven { url 'https://maven.fabric.io/public' }
}
& Inside dependencies{} add
Code:
compile('com.twitter.sdk.android:twitter:1.13.1@aar') {
transitive = true;
}
* Fabric Inside Manifest
in <application/> add
Code:
<meta-data
android:name="io.fabric.ApiKey"
android:value="API_KEY" />
* Fabric Inside MainActivity Class
before setContentView(VIEW) under onCreate(Bundle)
Code:
TwitterAuthConfig authConfig = new TwitterAuthConfig([COLOR=Red]API_KEY[/COLOR], [COLOR=Red]API_SECRET[/COLOR]);
Fabric.with(this, new Twitter(authConfig));
Fabric Also provides Button design for Twitter with custom features to handle Auth CallBack.
Code:
<com.twitter.sdk.android.core.identity.TwitterLoginButton/>
You define it in layout.xml & then Declare it like normal views on activity.
But performing action is different.
Code:
/*TWITTER Sign-In*/
twitterButton.setCallback(new Callback<TwitterSession>() {
@Override
public void success(Result<TwitterSession> result) {
Toast.makeText(getApplicationContext(), [COLOR=Red][B]result[/B][/COLOR].data.getUserName(), Toast.LENGTH_LONG).show();
}
@Override
public void failure(TwitterException exception) {}
});
without any extra Intent it will redirect you to Twitter Auth Page.
Also By using this button you can handle CallBack Result.
Code:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
twitterButton.onActivityResult(requestCode, resultCode, [COLOR=Red][B]data[/B][/COLOR]);
}
Also I used Fabric for Twitter Auth cause I can retrieve more Info than Firebase.Auth("twitter").
Fabric Plugin Developed by Twitter Developers So It really works smoothly & really best way to Auth with Twitter Account.


Thanks for Supporting GeeksEmpire projects

Don't Forget To Hit Thanks
 

Attachments

  • findex.png
    findex.png
    1.6 KB · Views: 29,600
  • indtex.png
    indtex.png
    1.3 KB · Views: 12,123
Last edited:

Geeks Empire

Senior Member
Aug 29, 2014
1,312
1,265
Nashville
GeeksEmpire.co
Email/Password Account [Authentication]

attachment.php


Auth with Email/Password Using Firebase API is so simple.
Go to Firebase Project Dashboard > Login & Auth & Enable Email & Password Authentication

Define 2 <EditText /> for Email & Password in layout.xml Don't forget to set inputType
Code:
[CENTER][LEFT]Email
<EditText
android:id="@+id/email"
android:inputType="textEmailAddress" />
[/LEFT]
[/CENTER]
Password
<EditText
android:id="@+id/password"
android:inputType="textPassword" />
Declare Firebase & then Set Auth method.
Code:
//Remember from first post
Firebase ref = new Firebase(FirebaseLink/*[COLOR=Red]https://FIREBASE_PROJECT_NAME.firebaseio.com/[/COLOR]*/);

Define Login/SignUp Button and onClick setup Email/Pass Auth
Code:
//E-MAIL SignUp
signup.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    Toast.makeText(getApplicationContext(), "User Created", Toast.LENGTH_LONG).show();
    String email = user.getText().toString();
    String pass = password.getText().toString();

    Firebase ref = new Firebase([COLOR=Red]FirebaseLink[/COLOR]);
    ref.createUser([COLOR=Red][B]email[/B][/COLOR], [COLOR=Red][B]pass[/B][/COLOR], new Firebase.ValueResultHandler<Map<String, Object>>() {
        @Override
        public void onSuccess(Map<String, Object> result) {
            System.out.println("Successfully created user account with uid: " + result.get("uid"));
        }
        @Override
        public void onError(FirebaseError firebaseError) {
            // there was an error
        }
    });
    }
});
Code:
//E-MAIL Login
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = user.getText().toString();
String pass = password.getText().toString();

Firebase ref = new Firebase([COLOR=Red]FirebaseLink[/COLOR]);
ref.authWithPassword([COLOR=Red][B]email[/B][/COLOR], [COLOR=Red][B]pass[/B][/COLOR], new Firebase.AuthResultHandler() {
@Override
public void onAuthenticated(AuthData authData) {
System.out.println("User ID: " + authData.getUid() + ", Provider: " + authData.getProvider());
Toast.makeText(getApplicationContext(), "User Authenticated", Toast.LENGTH_LONG).show();
}
@Override
public void onAuthenticationError(FirebaseError firebaseError) {}});
}}
});

For this everything provided simply by Firebase API. You completely Handle all process.
Here are more helpful Functions.

Code:
public void [B]ResetPassword[/B](String [COLOR=Red]E_MAIL_ADDRESS[/COLOR]){
Firebase ref = new Firebase("https://[COLOR=Red]<YOUR-FIREBASE-APP>[/COLOR].firebaseio.com");
ref.resetPassword([COLOR=Red]E_MAIL_ADDRESS[/COLOR], new Firebase.ResultHandler() {
@Override
public void onSuccess() {
// password reset email sent
}
@Override
public void onError(FirebaseError firebaseError) {
// error encountered
}
});
}
Code:
public void [B]ChangePassword[/B](String [COLOR=Red]E_MAIL[/COLOR], String [COLOR=Red]oldPass[/COLOR], String [COLOR=Red]newPass[/COLOR]){
Firebase ref = new Firebase("https://[COLOR=Red]<YOUR-FIREBASE-APP>[/COLOR].firebaseio.com");
ref.changePassword([COLOR=Red]E_MAIL[/COLOR], [COLOR=Red]oldPass[/COLOR], [COLOR=Red]newPass[/COLOR], new Firebase.ResultHandler() {
@Override
public void onSuccess() {
// password changed
}
@Override
  public void onError(FirebaseError firebaseError) {
// error encountered
}
});
}
Code:
public void [B]RemoveAccount[/B](String [COLOR=Red]E_MAIL[/COLOR], String [COLOR=Red]Password[/COLOR]){
Firebase ref = new Firebase("https://[COLOR=Red]<YOUR-FIREBASE-APP>[/COLOR].firebaseio.com");
ref.removeUser([COLOR=Red]E_MAIL[/COLOR], [COLOR=Red]Password[/COLOR], new Firebase.ResultHandler() {
@Override
public void onSuccess() {
// user removed
}
@Override
public void onError(FirebaseError firebaseError) {
// error encountered
}
});
}


Thanks for Supporting GeeksEmpire projects

Don't Forget To Hit Thanks


 
Last edited:

Geeks Empire

Senior Member
Aug 29, 2014
1,312
1,265
Nashville
GeeksEmpire.co
Google Firebase.Storage


image00.png


It s time to do something important with Cloud Service; Upload & Download File.
Google Cloud Service (Firebase) has lots of Useful Features + Really Straight & Manageable API.

First Read Preface Post & Firebase Basics to Prepare your Project for Cloud Services.
Now you will Understand upcoming codes.

Inside build.gradle of AppLevel declare Firebase.Storage SDK in dependencies
Code:
compile 'com.google.firebase:firebase-[B]storage[/B]:9.0.2'
compile 'com.google.firebase:firebase-[B]auth[/B]:9.0.2'
In update Sample Code I created new activity to handle Files. You can do whatever you like.

NOTE: You have to Authenticate Users with Firebase Services to Perform any Server action. For example Uploading File. check out SourceCode

In activity onCreate() declare instance of Firebase.Storage & Firebase.Auth
Code:
firebaseStorage = [B]FirebaseStorage[/B].getInstance();
firebaseAuth = [B]FirebaseAuth[/B].getInstance();
To Perform Both Upload & Download Task you need to create a Reference.
There is different method for creating StorageReference that I chose:
Code:
getReferenceFromUrl() for Uploading
& getFile() for Downloading.
Before anything do Auth Process. As Public APP I used Anonymously option & call the function when Activity Start.
Code:
private void signInAnonymously() {
mAuth.signInAnonymously().addOnSuccessListener(this, new OnSuccessListener<AuthResult>() {
@Override
public void onSuccess(AuthResult authResult) {}
}).addOnFailureListener(this, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {}
});
}
Now you can Add StorageReference & Perform Actions
UPLOAD Function check out SourceCode
Code:
private void uploadFromUri(InputStream fileUri) {
StorageReference mStorageRef = storage.getReferenceFromUrl("gs://[I][COLOR=Red][B][YOUR_FIREBASE_PROJECT_LINK][/B][/COLOR][/I]/");
StorageReference photoRef = mStorageRef.child("Dir").child("File");

UploadTask uploadTask = photoRef.putStream(fileUri);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
System.out.println("DONE!");
//Get Download Address for Future 
Uri dl = taskSnapshot.getMetadata().getDownloadUrl();
//Save Download Address in App Dir
SharedPreferences sharedpreferences = getSharedPreferences("Info", Context.MODE_PRIVATE);
SharedPreferences.Editor dlLink = sharedpreferences.edit();
dlLink.putString("path", String.valueOf(dl));
dlLink.apply();

infoFile.append("\n" + dl.getPath());
System.out.println("Download >> " + dl);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
System.out.println("!Damn!");
}
});
}
DOWNLOAD Function check out SourceCode
Code:
public void downloadFromUri(StorageReference storageRef) throws Exception {
//Create File
final File localFile = new File(Environment.getExternalStorageDirectory().getPath() + "/CloudAppTest_GeeksEmpire.jpg");

storageRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
@Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
System.out.println("DONE!");
//Using Downloaded File
Bitmap bitmap = BitmapFactory.decodeFile(localFile.getAbsolutePath());  System.out.println("Downloaded >> " + localFile.getAbsolutePath());
imageFile.setImageBitmap(bitmap);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle any errors
}
});
}
For Deleting & any Modification you Just Need to Declare StorageReference & Call Functions. check out SourceCode



Thanks for Supporting GeeksEmpire projects

Don't Forget To Hit Thanks
 

Attachments

  • image00.png
    image00.png
    49.7 KB · Views: 25
Last edited:

Geeks Empire

Senior Member
Aug 29, 2014
1,312
1,265
Nashville
GeeksEmpire.co
Firebase.RemoteConfiguration


http%3A%2F%2Fdl-1.va.us.xda-developers.com%2F3%2F7%2F9%2F6%2F5%2F6%2F2%2Fimage00.png%3Fkey%3DOTyCQtLGAzreojAUrp2qcQ%26ts%3D1467073525


The Most Interesting Features from Google Firebase is Remote Configuration.
It is not difficult to Apply & Super Helpful.
By Adding this Feature to your App you can Remotely Change Value of Defined Variable.
It can be String of InApp Texts Or Integer of InApp Color. Whatever you decide to remotely Config.
And Also Conditional Value. For Example Specific Price Tag for a Region Or even a Single User.
Google Cloud Service (Firebase) has lots of Useful Features + Really Straight & Manageable API.

Firebase Remote Config is a cloud service that lets you change the behavior and appearance of your app without requiring users to download an app update...
First Read Preface Post & Firebase Basics to Prepare your Project for Cloud Services.
Now you will Understand upcoming codes.

Inside build.gradle of AppLevel declare Firebase.Storage SDK in dependencies.
Code:
compile 'com.google.firebase:firebase-config:9.0.2'
Create xml folder into the res directory res/xml.
Now create remote_config_default.xml file to define all default Value & KEY for remote configuration.
For Example: check out SourceCode
Code:
<?xml version="1.0" encoding="utf-8"?>
<!-- START xml_defaults -->
<defaultsMap>
<entry>
[B]<key>[COLOR=Red]KeyToChange[/COLOR]</key>
<value>[COLOR=Red]Content To Change[/COLOR]</value>[/B]
</entry>
</defaultsMap>
<!-- END xml_defaults -->
You Should go to Firebase Console & you Project Dir & Select Remote Config from Left Panel.
Set <key>KeyToChange</key>& Create New Content.

Untitled.jpg

Now go to your Activity Class that want to Handle these changes from cloud & declare FirebaseRemoteConfig & Set Default Value that defined in XML file. check out SourceCode
Code:
firebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
firebaseRemoteConfig.setDefaults(R.xml.remote_config_default);
after that you can perform to check If there is New Content & Apply it to your App. check out SourceCode
Code:
public void GetNewContent(){
mFirebaseRemoteConfig.fetch(cacheExpiration)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d("", "Fetch Succeeded");
// Once the config is successfully fetched it must be activated before newly fetched
// values are returned.
mFirebaseRemoteConfig.activateFetched();
} else {
Log.d("", "Fetch failed");
}
[B]//Handle New Content[/B]
textView.setText([B]firebaseRemoteConfig.getString([COLOR=Red]KeyToChange[/COLOR]_String)[/B]);
}
});
}
Thanks for Supporting GeeksEmpire projects

Don't Forget To Hit Thanks

 

Attachments

  • Untitled.jpg
    Untitled.jpg
    129.3 KB · Views: 20
Last edited:

getapp

Member
Sep 12, 2015
8
2
Needed

This tutorial is awesome!
complete and easy to understand
there is few guide about using cloud services
really appreciate :good:
 

Geeks Empire

Senior Member
Aug 29, 2014
1,312
1,265
Nashville
GeeksEmpire.co
Info

Featured By XDA

Top Forum Discussions
Aamir Siddiqui | May 19, 2016
XDA Senior Member Geeks Empire has posted an extensive tutorial on developing a cloud based app.
The tutorial teaches users how to make use of Google Cloud and Firebase to achieve their goals.

Thanks for Support XDA-Developer :good:

I am waiting for FeedBack of all Users/Devs
 

iprabu

New member
May 26, 2016
2
0
Thanks for your effort :good:

I'm newbie in android programming, but i find this tutorial is usefull :good:
 

Geeks Empire

Senior Member
Aug 29, 2014
1,312
1,265
Nashville
GeeksEmpire.co
Info

Thanks for your effort :good:

I'm newbie in android programming, but i find this tutorial is usefull :good:
Thanks for Rating & Review
+ There is lots of Android Programming Tutorial by GeeksEmpire
you can find all off them in my signature Or Geeky Tutorial

Also Almost All GeeksEmpire Apps on Google Play Store is OpenSource with Full Code Comments
So you can Check them to learn more
you can find all off them in my signature Or Geeky Open Source Project
Don't Forget to hit Thanks :good:

I am waiting for FeedBack of all Users/Devs
 

Top Liked Posts

  • There are no posts matching your filters.
  • 12

    attachment.php


    In this Tutorial I try to explain general aspects of Cloud Computing & Cloud Concepts & Authentication You will learn What is Cloud & If already know basics of Android Programming, you will be able to develop your Cloud Base App after reading carefully this guide.

    Featured By XDA
    Aamir Siddiqui | May 19, 2016
    XDA Senior Member Geeks Empire has posted an extensive tutorial on developing a cloud based app.
    The tutorial teaches users how to make use of Google Cloud and Firebase to achieve their goals.

    Why are so many businesses moving to the cloud? It’s because cloud computing increases efficiency, helps improve cash flow and offers many more benefits…Here's ten of the best.
    1. Flexibility
    2. Disaster recovery
    3. Automatic software updates
    4. Capital-expenditure Free
    5. Increased collaboration
    6. Work from anywhere
    7. Document control
    8. Security
    9. Competitiveness
    10. Environmentally friendly
    READ MORE
    If you want to design & develop cloud service for your business it is better to understand What you Know & Need.
    Try to read again carefully All descriptions & Link above to get reach knowledge of Cloud.
    In This Tutorial I used All Alphabet Services. Google Cloud, Firebase, Google Play Services & etc.
    I prefer Alphabet cause It is Google ;)
    “Firebase — a powerful platform for building iOS, Android, and web-based apps, offering real-time data storage and synchronization, user authentication, and more.”
    INDEX
    *
    Data Transferring
    *
    - FireBase
    Cloud Service
    * Authentication *

    - Google Account By GoogleSignIn API
    - Twitter By Fabric API
    - Email/Pass By Firebase API


    # Let Start #


    What you Need to Continue is;
    1. Google Account
    2. Ability to Create Hello World! Project in Android Studio


    * Application Configuration
    Run Android Studio & Create New Project with Blank Activity. (Set Proper AppName & Package)
    After Gradle Building finished go to File > Project Structure > Cloud & Enable Firebase.
    Go to Manifest > Add Get_Account & Internet Permissions above the <application />

    Code:
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    then Inside Application tag add Google_Play_Service <meta-data />
    Code:
    <meta-data
    android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />
    Then Open build.gradle (Module: App) & Add these excludes to prevent errors during test process inside android{}
    Code:
    packagingOptions {
            exclude 'META-INF/LICENSE'
            exclude 'META-INF/LICENSE-FIREBASE.txt'
            exclude 'META-INF/NOTICE'
     }
    Also Add this library for auth-process into dependencies{}
    Code:
    compile 'com.google.android.gms:play-services-auth:8.4.0'
    Now your App is Ready to Add Codes for Cloud API But your Need to Configure Cloud Side too.

    * Google Cloud & Firebase Configuration
    Here some parts doesn't need for beginning Android Coding But It can be tricky & easy for you to do everything on Browser for Google Section and then Focus on Coding. At End you can Review All Parts & Test it by yourself. I will explain more about each part.
    Generate your Sign APK to Get SHA-1 Key
    Code:
    keytool -list -v -keystore '/PATH/TO/kEY_STORE'
    To Transfer Data to Cloud you need to Have a Cloud Service. Here I am using Firebase.

    Go to www.Firebase.com & Login with your Google Account.
    Firebase will automatically Create a Project for you named 'MY FIRST APP' that you can delete or modify it.
    Firebase has Free Plan for Small Business, Testing & etc. So after you learn more about cloud you can upgrade your plan for existing projects.
    firebase-ct4as-firebase-dashboard.png

    The URL of Firebase for your Project is Like this
    HTML:
    https://YOUR_APP_NAME.firebaseio.com/
    Every task with Firebase API needs this URL.

    Go to https://Console.Gloud.Google.com Sign-Up & Get 60 Days Trial Period & 300$ to spend on Google Cloud Platform.
    So Feel Free to Create Projects & Enabling APIs.
    After Creating Google Cloud Project go to Project Dashboard & from Left Panel navigate to API Manager > Credentials. Click on Create Credential & Select OAuth client ID After Loading New Page Select Android Then Create. Now Set Carefully your SHA-1 key & Android App PackageName then Save.

    Go to https://Developers.Google.com/ First of All If you are new to Developing Spend some times in this page & Enjoy All Google Services for Everything. :good:
    Then Navigate to Google Service for Mobile > Android > Sign-In with Google > Click Get Start > Scroll Down > Click Get Configuration File.
    Again Type your Android App PackageName then Click Continue & Type SHA-1 Key & Click ENABLE GOOGLE SIGN-IN after that Scroll Down and Click on Generate Configuration File and Download the File.
    Copy google-service.json File & Paste it to App Level Project.
    Code:
    To do this Now Open Android Studio Change View of Project Explorer from Android View to Project View. 
    Expand Project and Paste JSON file under the APP Level.


    Now you are ready to use Firebase Services & Login with Google.
    Next Post is About Working with Firebase Send/Receive Data.


    Oo. DOWNLOAD .oO
    SOURCE.CODE
    APK.FILE


    Thanks for Supporting GeeksEmpire projects

    Don't Forget To Hit Thanks


    6
    Google Cloud & Firebase [Data Transferring]


    attachment.php


    Now It is time to Focus on Coding. It is not difficult to understand Firebase API But Using URL carefully to Create New User, Data, Section & etc is important.
    Open MainActivity.Java
    At First the Class must extended from Fragment that required for Firebase API (& later for Google Sign-In). In this case I use AppCompatActivity.
    Code:
    public class MainActivity extends AppCompatActivity{}
    To work with Firebase API you have to define it like other objects.
    You can do it when you need it Or define it at first part of app onCreate(Bundle){}
    Code:
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    [B]Firebase.setAndroidContext(getApplicationContext());[/B]
    After that you need to declare instance of your views. For Example I declare ListView that will use for showing loaded Data.
    Code:
    ListView listView = (ListView)findViewById(R.id.listView);
    ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, android.R.id.text1);
    //built-in adaptor
    listView.setAdapter(adapter);
    NOTE: Save your Firebase URL to <resource> <string /></resource> Or Save it as Universal String Object inside Class.
    For Example Before onCreate(Bundle)
    Code:
    String FirebaseLink = "https://[B]YOUR_APP_NAME[/B].firebaseio.com/";
    String FirebaseTitle = "GeeksEmpire";
    String FirebaseSub = "gX";
    To Get Data from User you should define input method like <EditText/>
    With This methods you can Save Data Locally in Application Private Storage on System
    Code:
    //Save Content
    try {
    FileOutputStream fOut = openFileOutput(NAME, MODE_PRIVATE);
    fOut.write((DATA).getBytes());
    
    //Always Close All Streams
    fOut.close();
    fOut.flush();
    } 
    catch (Exception e) {
     System.out.println(e);
    } finally {}
    Code:
    //Read-File
    public String READ(String S, Context context){
    File Fav = new File(S);
    String Read = null;
    FileInputStream fin;
    BufferedReader br = null;    
    try{
    fin = new FileInputStream(Fav);
    br = new BufferedReader(new InputStreamReader(fin, "UTF-8"), 1024);
    System.out.println(br);
    int c;
    String temp = "";
    while( (c = br.read()) != -1){temp = temp + Character.toString((char)c);}         
    Read = temp;}
    catch(Exception e)
    {System.out.println(e);}
    finally{try {br.close();} catch (IOException e) {e.printStackTrace();}}
    return Read;
    }
    But to Store Data on Firebase Server you should declare instance of Firebase API, Push & setValue(DATA)
    Code:
    upload.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    String DATA = editText.getText().toString();//"[COLOR=Red][I]GeeksEmpire DataBase on FireBase[/I][/COLOR]"
    new Firebase([B]FirebaseLink[/B]/*[COLOR=Red][I]https://YOUR_APP_NAME.firebaseio.com[/I]/[/COLOR]*/ + FirebaseTitle/*[COLOR=Red][I]GeeksEmpire[/I][/COLOR]*/)
    .push()
    .child(FirebaseSub/*[COLOR=Red][I]gX[/I][/COLOR]*/)
    .setValue(DATA);
    }
    });
    Compare red texts with image. Firebase URL is submitted but you can Modify both FirebaseTitle & FirebaseSub.

    attachment.php


    In this Case I used GeeksEmpire as Title & gX as SubTitle & then Data.
    It is depend on your design.
    you can set GeeksEmpire as User & gX as Title OR Whatever you need.



    Data Uploaded to Server & Now you should make an option to Download them. I created function to gather all components.
    Code:
    public void SetUpCloudContent(){
    Firebase.setAndroidContext(this);
    new Firebase(FirebaseLink/*[COLOR=Red]https://YOUR_APP_NAME.firebaseio.com/[/COLOR]*/ + FirebaseTitle/*[COLOR=Red]GeeksEmpire[/COLOR]*/).addChildEventListener(new ChildEventListener() {
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
    adapter.add((String)dataSnapshot.child(FirebaseSub/*[COLOR=Red]gX[/COLOR]*/).getValue());//add each value to ListView
    }
    public void onChildRemoved(DataSnapshot dataSnapshot) {
    adapter.remove((String)dataSnapshot.child(FirebaseSub).getValue());
    }
    public void onChildChanged(DataSnapshot dataSnapshot, String s) { }
    public void onChildMoved(DataSnapshot dataSnapshot, String s) { }
    public void onCancelled(FirebaseError firebaseError) { }
    });
    }

    To Change Data Just Use ID you got to User (For Example GeeksEmpire > gX) and OverWrite Data.
    But here is a method to Delete Data.
    // Delete items when clicked
    Code:
    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
    new Firebase([COLOR=Red]FirebaseLink [/COLOR]+ [COLOR=Red]FirebaseTitle[/COLOR])
    .orderByChild([COLOR=Red]FirebaseSub[/COLOR])
    .equalTo((String) listView.getItemAtPosition(position)/*[I]get data from ListView[/I]*/)
    .addListenerForSingleValueEvent(new ValueEventListener() {
    public void onDataChange(DataSnapshot dataSnapshot) {
    if (dataSnapshot.hasChildren()) {
    DataSnapshot firstChild = dataSnapshot.getChildren().iterator().next();
    firstChild.getRef().removeValue();
    }
    }
    public void onCancelled(FirebaseError firebaseError) { }
    });
    return false;
    }
    });

    Sending & Receiving Data to Firebase Cloud Service is Done.
    Again It depends on you How to define Users & Create Individual ID for each one.
    Next Posts Will Show How to Create Sign-In Options for your App. That Also Help a lot to create Individual ID.


    Thanks for Supporting GeeksEmpire projects

    Don't Forget To Hit Thanks
    6
    Google Account [Authentication]

    attachment.php


    I used Google API for Google Account Auth cause you can get more info about Google Account to use and customize your App. Info that you cannot retrieve by Firebase.Auth("google"). For Example Account Pic to Use inside your app for user.
    (Set Google Account Pic as Pic of Account on your App)

    In First Post Google Sign-In Setup Completed.
    Sign-In API Enabled & Configuration file add to Project.

    Another modification needed to apply on build.gradle (Module: App)
    Add this plugin at end of your gradle file.
    Code:
    apply plugin: 'com.google.gms.google-services'
    & Also for build.gradle (Project)
    Add this classpath under dependencies {}
    Code:
    classpath 'com.google.gms:google-services:2.0.0-alpha5'
    You should Implement you class to GoogleApiClient.ConnectionCallbacks & GoogleApiClient.OnConnectionFailedListener.
    & Add required methods.
    Code:
    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {}
    @Override
    public void onConnected(@Nullable Bundle bundle) {}
    @Override
    public void onConnectionSuspended(int i) {}
    Define GoogleApiClient as universal variable (Outside of any Function).
    Get instance of GoogleApiClient & GoogleSignInOptions onCreate(Bundle).
    Code:
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
    .requestEmail()
    .build();
    mGoogleApiClient = new GoogleApiClient.Builder(this)
    .enableAutoManage(this, this)//FragmentActivity
    .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
    .build();
    To perform Sign Action normally button used If you don't want to do it at start up of app.
    For this Google Service has its own button design that used in sample. However you can design your own view.
    Code:
    <com.google.android.gms.common.SignInButton />
    Like other Android system function calling we should use Intent to Invoke Google Account Chooser and Get Result on CallBack.
    Code:
    google.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
    startActivityForResult(signInIntent, [COLOR=Red]7[/COLOR]);
    }
    });
    On result CallBack you should declare GoogleSignResult
    Code:
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    
    if(requestCode == [COLOR=Red]7[/COLOR]){
    GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
    if(result.isSuccess()){
    //[B]Handle Security Inside App[/B]
    GoogleSignInAccount acct = result.getSignInAccount();
    
    Toast.makeText(getApplicationContext(), "getEmail >> " + [B]acct.getEmail()[/B], Toast.LENGTH_LONG).show();
    Toast.makeText(getApplicationContext(), "getDisplayName >> " + [B]acct.getDisplayName()[/B], Toast.LENGTH_LONG).show();
    //Can get more Info by using GoogleSignInAccount 
    }
    }
    NOTE: You can use Google Account as UserName for your Users on Firebase & By Calling Sign-In Process at App Start Provide Security for your App.


    Thanks for Supporting GeeksEmpire projects

    Don't Forget To Hit Thanks
    6
    Email/Password Account [Authentication]

    attachment.php


    Auth with Email/Password Using Firebase API is so simple.
    Go to Firebase Project Dashboard > Login & Auth & Enable Email & Password Authentication

    Define 2 <EditText /> for Email & Password in layout.xml Don't forget to set inputType
    Code:
    [CENTER][LEFT]Email
    <EditText
    android:id="@+id/email"
    android:inputType="textEmailAddress" />
    [/LEFT]
    [/CENTER]
    Password
    <EditText
    android:id="@+id/password"
    android:inputType="textPassword" />
    Declare Firebase & then Set Auth method.
    Code:
    //Remember from first post
    Firebase ref = new Firebase(FirebaseLink/*[COLOR=Red]https://FIREBASE_PROJECT_NAME.firebaseio.com/[/COLOR]*/);

    Define Login/SignUp Button and onClick setup Email/Pass Auth
    Code:
    //E-MAIL SignUp
    signup.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        Toast.makeText(getApplicationContext(), "User Created", Toast.LENGTH_LONG).show();
        String email = user.getText().toString();
        String pass = password.getText().toString();
    
        Firebase ref = new Firebase([COLOR=Red]FirebaseLink[/COLOR]);
        ref.createUser([COLOR=Red][B]email[/B][/COLOR], [COLOR=Red][B]pass[/B][/COLOR], new Firebase.ValueResultHandler<Map<String, Object>>() {
            @Override
            public void onSuccess(Map<String, Object> result) {
                System.out.println("Successfully created user account with uid: " + result.get("uid"));
            }
            @Override
            public void onError(FirebaseError firebaseError) {
                // there was an error
            }
        });
        }
    });
    Code:
    //E-MAIL Login
    login.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    String email = user.getText().toString();
    String pass = password.getText().toString();
    
    Firebase ref = new Firebase([COLOR=Red]FirebaseLink[/COLOR]);
    ref.authWithPassword([COLOR=Red][B]email[/B][/COLOR], [COLOR=Red][B]pass[/B][/COLOR], new Firebase.AuthResultHandler() {
    @Override
    public void onAuthenticated(AuthData authData) {
    System.out.println("User ID: " + authData.getUid() + ", Provider: " + authData.getProvider());
    Toast.makeText(getApplicationContext(), "User Authenticated", Toast.LENGTH_LONG).show();
    }
    @Override
    public void onAuthenticationError(FirebaseError firebaseError) {}});
    }}
    });

    For this everything provided simply by Firebase API. You completely Handle all process.
    Here are more helpful Functions.

    Code:
    public void [B]ResetPassword[/B](String [COLOR=Red]E_MAIL_ADDRESS[/COLOR]){
    Firebase ref = new Firebase("https://[COLOR=Red]<YOUR-FIREBASE-APP>[/COLOR].firebaseio.com");
    ref.resetPassword([COLOR=Red]E_MAIL_ADDRESS[/COLOR], new Firebase.ResultHandler() {
    @Override
    public void onSuccess() {
    // password reset email sent
    }
    @Override
    public void onError(FirebaseError firebaseError) {
    // error encountered
    }
    });
    }
    Code:
    public void [B]ChangePassword[/B](String [COLOR=Red]E_MAIL[/COLOR], String [COLOR=Red]oldPass[/COLOR], String [COLOR=Red]newPass[/COLOR]){
    Firebase ref = new Firebase("https://[COLOR=Red]<YOUR-FIREBASE-APP>[/COLOR].firebaseio.com");
    ref.changePassword([COLOR=Red]E_MAIL[/COLOR], [COLOR=Red]oldPass[/COLOR], [COLOR=Red]newPass[/COLOR], new Firebase.ResultHandler() {
    @Override
    public void onSuccess() {
    // password changed
    }
    @Override
      public void onError(FirebaseError firebaseError) {
    // error encountered
    }
    });
    }
    Code:
    public void [B]RemoveAccount[/B](String [COLOR=Red]E_MAIL[/COLOR], String [COLOR=Red]Password[/COLOR]){
    Firebase ref = new Firebase("https://[COLOR=Red]<YOUR-FIREBASE-APP>[/COLOR].firebaseio.com");
    ref.removeUser([COLOR=Red]E_MAIL[/COLOR], [COLOR=Red]Password[/COLOR], new Firebase.ResultHandler() {
    @Override
    public void onSuccess() {
    // user removed
    }
    @Override
    public void onError(FirebaseError firebaseError) {
    // error encountered
    }
    });
    }


    Thanks for Supporting GeeksEmpire projects

    Don't Forget To Hit Thanks


    5
    Twitter Account [Authentication]


    attachment.php


    Authentication by Twitter has Complex aspect.
    First you should Create Twitter Account, Then Create Web App through www.twitter.com (to get Public & Secret Key), Enable Twitter on Firebase (Not Required But I recommend it) & Install 3rd-Party Plugin on Android Studio (Fabric API).

    Go to https://twitter.com/ & Sign Up then go to https://apps.twitter.com/ & Create App.
    Name the App & Write Description & WebSite.
    In App Page > Keys & Access Token
    . Consumer Key (API Key) = XXXXX
    . Consumer Secret (API Secret) = XXXXX
    Save these value to resources of your app. res > values > string
    Code:
    </resources>
    <string name="twitter_consumer_key">[B]API Key[/B]</string>
    <string name="twitter_consumer_secret">[B]API Secret[/B]</string>
    </resources>
    - Go to Login & Auth on Firebase Select Twitter & Paste API Key + API Secret.
    On Android Studio navigate to File > Setting > Plugin& Search for Fabric (Click Browse)
    After Plugin Downloaded It will ask for Restart to Complete Installation.
    Then Fabric Plugin icon will appear on toolbar & maybe Right-Panel.
    Click on Plugin & Sign Up. Then you will see your current project on Fabric list. Select it & click Next.
    From List of All Kits select Twitter & click Install. It will ask for API Key + API Secret
    Fabric will Apply All Modification it needs to your project & after that you project will be ready for Twitter Auth.
    But for Developer It is always important points to understand every part of tools and apps.
    * Fabric Inside build.grade (Module: App)
    before Android Plugin
    Code:
    apply plugin: 'com.android.application'
    Add this Script
    Code:
    buildscript {
    repositories {
    maven { url 'https://maven.fabric.io/public' }
    }
    dependencies {
    classpath 'io.fabric.tools:gradle:1.+'
    }
    }
    after Android Plugin set up fabric plugin
    Code:
    apply plugin: 'io.fabric'
    after android{} functions add Fabric Repositories
    Code:
    repositories {
    mavenCentral()
    maven { url 'https://maven.fabric.io/public' }
    }
    & Inside dependencies{} add
    Code:
    compile('com.twitter.sdk.android:twitter:1.13.1@aar') {
    transitive = true;
    }
    * Fabric Inside Manifest
    in <application/> add
    Code:
    <meta-data
    android:name="io.fabric.ApiKey"
    android:value="API_KEY" />
    * Fabric Inside MainActivity Class
    before setContentView(VIEW) under onCreate(Bundle)
    Code:
    TwitterAuthConfig authConfig = new TwitterAuthConfig([COLOR=Red]API_KEY[/COLOR], [COLOR=Red]API_SECRET[/COLOR]);
    Fabric.with(this, new Twitter(authConfig));
    Fabric Also provides Button design for Twitter with custom features to handle Auth CallBack.
    Code:
    <com.twitter.sdk.android.core.identity.TwitterLoginButton/>
    You define it in layout.xml & then Declare it like normal views on activity.
    But performing action is different.
    Code:
    /*TWITTER Sign-In*/
    twitterButton.setCallback(new Callback<TwitterSession>() {
    @Override
    public void success(Result<TwitterSession> result) {
    Toast.makeText(getApplicationContext(), [COLOR=Red][B]result[/B][/COLOR].data.getUserName(), Toast.LENGTH_LONG).show();
    }
    @Override
    public void failure(TwitterException exception) {}
    });
    without any extra Intent it will redirect you to Twitter Auth Page.
    Also By using this button you can handle CallBack Result.
    Code:
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    twitterButton.onActivityResult(requestCode, resultCode, [COLOR=Red][B]data[/B][/COLOR]);
    }
    Also I used Fabric for Twitter Auth cause I can retrieve more Info than Firebase.Auth("twitter").
    Fabric Plugin Developed by Twitter Developers So It really works smoothly & really best way to Auth with Twitter Account.


    Thanks for Supporting GeeksEmpire projects

    Don't Forget To Hit Thanks