Wednesday, 22 March 2017
Friday, 17 March 2017
Send Push Notification to Different Devices using OneSignal & Firebase -...
Send Push Notification to Different Devices using OneSignal - Firebase - part 3
Source Code of Part (1,2,3)
MainActivity:
package com.example.administrator.firebasetutorial;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.UserProfileChangeRequest;
import com.onesignal.OneSignal;
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private EditText email,password,name;
private Button signin, signup;
FirebaseUser user;
static String LoggedIn_User_Email;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OneSignal.startInit(this).init();
mAuth = FirebaseAuth.getInstance(); // important Call
signin = (Button)findViewById(R.id.signin);
signup = (Button)findViewById(R.id.signup);
email = (EditText)findViewById(R.id.etEmail);
password = (EditText)findViewById(R.id.etPassword);
name = (EditText)findViewById(R.id.etName);
//Check if User is Already LoggedIn
if(mAuth.getCurrentUser() != null)
{
//User NOT logged In
finish();
startActivity(new Intent(getApplicationContext(),SignIn.class));
}
user = mAuth.getCurrentUser();
//Setting the tags for Current User.
LoggedIn_User_Email =user.getEmail();
OneSignal.sendTag("User_ID", LoggedIn_User_Email);
signin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String getemail = email.getText().toString().trim();
String getepassword = password.getText().toString().trim();
callsignin(getemail,getepassword);
}
});
signup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String getemail = email.getText().toString().trim();
String getepassword = password.getText().toString().trim();
callsignup(getemail,getepassword);
}
});
}
//Create Account
private void callsignup(String email,String password) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d("TESTING", "Sign up Successful" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Toast.makeText(MainActivity.this, "Signed up Failed", Toast.LENGTH_SHORT).show();
}
else
{
userProfile();
Toast.makeText(MainActivity.this, "Created Account", Toast.LENGTH_SHORT).show();
Log.d("TESTING", "Created Account");
}
}
});
}
//Set UserDisplay Name
private void userProfile()
{
FirebaseUser user = mAuth.getCurrentUser();
if(user!= null)
{
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(name.getText().toString().trim())
//.setPhotoUri(Uri.parse("https://example.com/jane-q-user/profile.jpg")) // here you can set image link also.
.build();
user.updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d("TESTING", "User profile updated.");
}
}
});
}
}
//Now start Sign In Process
//SignIn Process
private void callsignin(String email,String password) {
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d("TESTING", "sign In Successful:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w("TESTING", "signInWithEmail:failed", task.getException());
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
else {
Intent i = new Intent(MainActivity.this, SignIn.class);
finish();
startActivity(i);
}
}
});
}
}
package com.example.administrator.firebasetutorial;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
/**
* Created by Administrator on 16-03-2017.
*/
public class ShowData extends AppCompatActivity {
RecyclerView recyclerView;
FirebaseDatabase firebaseDatabase;
DatabaseReference myRef;
private FirebaseRecyclerAdapter<ShowDataItems, ShowDataViewHolder> mFirebaseAdapter;
public ShowData() {
// Required empty public constructor
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_data_layout);
firebaseDatabase = FirebaseDatabase.getInstance();
myRef = FirebaseDatabase.getInstance().getReference("User_Details");
recyclerView = (RecyclerView)findViewById(R.id.show_data_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(ShowData.this));
Toast.makeText(ShowData.this, "Wait ! Fetching List...", Toast.LENGTH_SHORT).show();
}
@Override
protected void onStart() {
super.onStart();
//Log.d("LOGGED", "IN onStart ");
mFirebaseAdapter = new FirebaseRecyclerAdapter<ShowDataItems, ShowDataViewHolder>
(ShowDataItems.class, R.layout.show_data_single_item, ShowDataViewHolder.class, myRef)
{
public void populateViewHolder(final ShowDataViewHolder viewHolder, ShowDataItems model, final int position) {
viewHolder.Image_URL(model.getImage_URL());
viewHolder.Image_Title(model.getImage_Title());
//OnClick Item it will Delete data from Database
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(ShowData.this);
builder.setMessage("Do you want to Delete this data ?").setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
int selectedItems = position;
mFirebaseAdapter.getRef(selectedItems).removeValue();
mFirebaseAdapter.notifyItemRemoved(selectedItems);
recyclerView.invalidate();
onStart();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.setTitle("Confirm");
dialog.show();
}
});
}
};
recyclerView.setAdapter(mFirebaseAdapter);
}
//View Holder For Recycler View
public static class ShowDataViewHolder extends RecyclerView.ViewHolder {
private final TextView image_title;
private final ImageView image_url;
public ShowDataViewHolder(final View itemView) {
super(itemView);
image_url = (ImageView) itemView.findViewById(R.id.fetch_image);
image_title = (TextView) itemView.findViewById(R.id.fetch_image_title);
}
private void Image_Title(String title) {
image_title.setText(title);
}
private void Image_URL(String title) {
// image_url.setImageResource(R.drawable.loading);
Glide.with(itemView.getContext())
.load(title)
.crossFade()
.placeholder(R.drawable.loading)
.thumbnail(0.1f)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(image_url);
}
}
}
Source Code of Part (1,2,3)
MainActivity:
package com.example.administrator.firebasetutorial;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.UserProfileChangeRequest;
import com.onesignal.OneSignal;
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private EditText email,password,name;
private Button signin, signup;
FirebaseUser user;
static String LoggedIn_User_Email;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OneSignal.startInit(this).init();
mAuth = FirebaseAuth.getInstance(); // important Call
signin = (Button)findViewById(R.id.signin);
signup = (Button)findViewById(R.id.signup);
email = (EditText)findViewById(R.id.etEmail);
password = (EditText)findViewById(R.id.etPassword);
name = (EditText)findViewById(R.id.etName);
//Check if User is Already LoggedIn
if(mAuth.getCurrentUser() != null)
{
//User NOT logged In
finish();
startActivity(new Intent(getApplicationContext(),SignIn.class));
}
user = mAuth.getCurrentUser();
//Setting the tags for Current User.
LoggedIn_User_Email =user.getEmail();
OneSignal.sendTag("User_ID", LoggedIn_User_Email);
signin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String getemail = email.getText().toString().trim();
String getepassword = password.getText().toString().trim();
callsignin(getemail,getepassword);
}
});
signup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String getemail = email.getText().toString().trim();
String getepassword = password.getText().toString().trim();
callsignup(getemail,getepassword);
}
});
}
//Create Account
private void callsignup(String email,String password) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d("TESTING", "Sign up Successful" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Toast.makeText(MainActivity.this, "Signed up Failed", Toast.LENGTH_SHORT).show();
}
else
{
userProfile();
Toast.makeText(MainActivity.this, "Created Account", Toast.LENGTH_SHORT).show();
Log.d("TESTING", "Created Account");
}
}
});
}
//Set UserDisplay Name
private void userProfile()
{
FirebaseUser user = mAuth.getCurrentUser();
if(user!= null)
{
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(name.getText().toString().trim())
//.setPhotoUri(Uri.parse("https://example.com/jane-q-user/profile.jpg")) // here you can set image link also.
.build();
user.updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d("TESTING", "User profile updated.");
}
}
});
}
}
//Now start Sign In Process
//SignIn Process
private void callsignin(String email,String password) {
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d("TESTING", "sign In Successful:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w("TESTING", "signInWithEmail:failed", task.getException());
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
else {
Intent i = new Intent(MainActivity.this, SignIn.class);
finish();
startActivity(i);
}
}
});
}
}
ShowData:
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
/**
* Created by Administrator on 16-03-2017.
*/
public class ShowData extends AppCompatActivity {
RecyclerView recyclerView;
FirebaseDatabase firebaseDatabase;
DatabaseReference myRef;
private FirebaseRecyclerAdapter<ShowDataItems, ShowDataViewHolder> mFirebaseAdapter;
public ShowData() {
// Required empty public constructor
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_data_layout);
firebaseDatabase = FirebaseDatabase.getInstance();
myRef = FirebaseDatabase.getInstance().getReference("User_Details");
recyclerView = (RecyclerView)findViewById(R.id.show_data_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(ShowData.this));
Toast.makeText(ShowData.this, "Wait ! Fetching List...", Toast.LENGTH_SHORT).show();
}
@Override
protected void onStart() {
super.onStart();
//Log.d("LOGGED", "IN onStart ");
mFirebaseAdapter = new FirebaseRecyclerAdapter<ShowDataItems, ShowDataViewHolder>
(ShowDataItems.class, R.layout.show_data_single_item, ShowDataViewHolder.class, myRef)
{
public void populateViewHolder(final ShowDataViewHolder viewHolder, ShowDataItems model, final int position) {
viewHolder.Image_URL(model.getImage_URL());
viewHolder.Image_Title(model.getImage_Title());
//OnClick Item it will Delete data from Database
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(ShowData.this);
builder.setMessage("Do you want to Delete this data ?").setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
int selectedItems = position;
mFirebaseAdapter.getRef(selectedItems).removeValue();
mFirebaseAdapter.notifyItemRemoved(selectedItems);
recyclerView.invalidate();
onStart();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.setTitle("Confirm");
dialog.show();
}
});
}
};
recyclerView.setAdapter(mFirebaseAdapter);
}
//View Holder For Recycler View
public static class ShowDataViewHolder extends RecyclerView.ViewHolder {
private final TextView image_title;
private final ImageView image_url;
public ShowDataViewHolder(final View itemView) {
super(itemView);
image_url = (ImageView) itemView.findViewById(R.id.fetch_image);
image_title = (TextView) itemView.findViewById(R.id.fetch_image_title);
}
private void Image_Title(String title) {
image_title.setText(title);
}
private void Image_URL(String title) {
// image_url.setImageResource(R.drawable.loading);
Glide.with(itemView.getContext())
.load(title)
.crossFade()
.placeholder(R.drawable.loading)
.thumbnail(0.1f)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(image_url);
}
}
}
ShowDataItems:
package com.example.administrator.firebasetutorial;
/**
* Created by Administrator on 16-03-2017.
*/
//This is a data class, will help us to retrieve data from Database..
public class ShowDataItems {
private String Image_URL,Image_Title; //put this name same as Database Fields
public ShowDataItems(String image_URL, String image_Title) {
Image_URL = image_URL;
Image_Title = image_Title;
}
public ShowDataItems()
{
//Require a Empty Constructor
}
public String getImage_URL() {
return Image_URL;
}
public void setImage_URL(String image_URL) {
Image_URL = image_URL;
}
public String getImage_Title() {
return Image_Title;
}
public void setImage_Title(String image_Title) {
Image_Title = image_Title;
}
}
SignIn:
package com.example.administrator.firebasetutorial;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
/**
* Created by Administrator on 16-03-2017.
*/
public class SignIn extends AppCompatActivity {
Button signout,upload_bttn,showData,notification;
private FirebaseAuth mAuth;
TextView username;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
mAuth = FirebaseAuth.getInstance(); // important Call
signout = (Button)findViewById(R.id.signout);
username = (TextView) findViewById(R.id.tvName);
upload_bttn = (Button)findViewById(R.id.upload);
showData = (Button)findViewById(R.id.show_data);
notification = (Button)findViewById(R.id.notification);
//Again check if the user is Already Logged in or Not
if(mAuth.getCurrentUser() == null)
{
//User NOT logged In
finish();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
//Fetch the Display name of current User
FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
username.setText("Welcome, " + user.getDisplayName());
}
signout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAuth.signOut();
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
upload_bttn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),UploadInfo.class));
}
});
showData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),ShowData.class));
}
});
notification.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendNotification();
}
});
}
private void sendNotification()
{
AsyncTask.execute(new Runnable() {
@Override
public void run() {
int SDK_INT = android.os.Build.VERSION.SDK_INT;
if (SDK_INT > 8) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
String send_email;
//This is a Simple Logic to Send Notification different Device Programmatically....
if (MainActivity.LoggedIn_User_Email.equals("user1@gmail.com")) {
send_email = "user2@gmail.com";
} else {
send_email = "user1@gmail.com";
}
try {
String jsonResponse;
URL url = new URL("https://onesignal.com/api/v1/notifications");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("Authorization", "Basic YTUzMWE2M2UtMTZiYy00M2FhLWEyMjItYWQ5YWI1MDgzM2U2");
con.setRequestMethod("POST");
String strJsonBody = "{"
+ "\"app_id\": \"0523d5af-d75a-4916-a8dd-3e9109e0f10b\","
+ "\"filters\": [{\"field\": \"tag\", \"key\": \"User_ID\", \"relation\": \"=\", \"value\": \"" + send_email + "\"}],"
+ "\"data\": {\"foo\": \"bar\"},"
+ "\"contents\": {\"en\": \"English Message\"}"
+ "}";
System.out.println("strJsonBody:\n" + strJsonBody);
byte[] sendBytes = strJsonBody.getBytes("UTF-8");
con.setFixedLengthStreamingMode(sendBytes.length);
OutputStream outputStream = con.getOutputStream();
outputStream.write(sendBytes);
int httpResponse = con.getResponseCode();
System.out.println("httpResponse: " + httpResponse);
if (httpResponse >= HttpURLConnection.HTTP_OK
&& httpResponse < HttpURLConnection.HTTP_BAD_REQUEST) {
Scanner scanner = new Scanner(con.getInputStream(), "UTF-8");
jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
scanner.close();
} else {
Scanner scanner = new Scanner(con.getErrorStream(), "UTF-8");
jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
scanner.close();
}
System.out.println("jsonResponse:\n" + jsonResponse);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
});
}
}
UploadInfo:
package com.example.administrator.firebasetutorial;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.firebase.client.Firebase;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
/**
* Created by Administrator on 16-03-2017.
*/
public class UploadInfo extends AppCompatActivity {
Button select_image,upload_button;
ImageView user_image;
TextView title;
public static final int READ_EXTERNAL_STORAGE = 0;
private static final int GALLERY_INTENT = 2;
private ProgressDialog mProgressDialog;
private Firebase mRoofRef;
private Uri mImageUri = null;
private DatabaseReference mdatabaseRef;
private StorageReference mStorage;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upload_layout);
Firebase.setAndroidContext(this);
select_image = (Button)findViewById(R.id.select_image);
upload_button = (Button)findViewById(R.id.upload_bttn);
user_image = (ImageView) findViewById(R.id.user_image);
title = (TextView) findViewById(R.id.etTitle);
//Initialize the Progress Bar
mProgressDialog = new ProgressDialog(UploadInfo.this);
//Select Image From External Storage..
select_image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
//Check for Runtime Permission
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(getApplicationContext(), "Call for Permission", Toast.LENGTH_SHORT).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, READ_EXTERNAL_STORAGE);
}
}
else
{
callgalary();
}
}
});
//Initialize Firebase Database paths for database and Storage
mdatabaseRef = FirebaseDatabase.getInstance().getReference();
mRoofRef = new Firebase("https://fir-tutorial-5800f.firebaseio.com/").child("User_Details").push(); // Push will create new child every time we upload data
mStorage = FirebaseStorage.getInstance().getReferenceFromUrl("gs://fir-tutorial-5800f.appspot.com/");
//Click on Upload Button Title will upload to Database
upload_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String mName = title.getText().toString().trim();
if(mName.isEmpty())
{
Toast.makeText(getApplicationContext(), "Fill all Field", Toast.LENGTH_SHORT).show();
return;
}
Firebase childRef_name = mRoofRef.child("Image_Title");
childRef_name.setValue(mName);
Toast.makeText(getApplicationContext(), "Updated Info", Toast.LENGTH_SHORT).show();
}
});
}
//Check for Runtime Permissions for Storage Access
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
callgalary();
return;
}
Toast.makeText(getApplicationContext(), "...", Toast.LENGTH_SHORT).show();
}
//If Access Granted gallery Will open
private void callgalary() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_INTENT);
}
//After Selecting image from gallery image will directly uploaded to Firebase Database
//and Image will Show in Image View
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK) {
mImageUri = data.getData();
user_image.setImageURI(mImageUri);
StorageReference filePath = mStorage.child("User_Images").child(mImageUri.getLastPathSegment());
mProgressDialog.setMessage("Uploading Image....");
mProgressDialog.show();
filePath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUri = taskSnapshot.getDownloadUrl(); //Ignore This error
mRoofRef.child("Image_URL").setValue(downloadUri.toString());
Glide.with(getApplicationContext())
.load(downloadUri)
.crossFade()
.placeholder(R.drawable.loading)
.diskCacheStrategy(DiskCacheStrategy.RESULT)
.into(user_image);
Toast.makeText(getApplicationContext(), "Updated.", Toast.LENGTH_SHORT).show();
mProgressDialog.dismiss();
}
});
}
}
}
Store, Retrieve, Delete Data & Images from Firebase with RecyclerView - ...
Store, Retrieve, Delete Data & Images from Firebase with RecyclerView - Firebase - part 2
MainActivity:
package com.example.administrator.firebasetutorial;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.UserProfileChangeRequest;
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private EditText email,password,name;
private Button signin, signup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance(); // important Call
signin = (Button)findViewById(R.id.signin);
signup = (Button)findViewById(R.id.signup);
email = (EditText)findViewById(R.id.etEmail);
password = (EditText)findViewById(R.id.etPassword);
name = (EditText)findViewById(R.id.etName);
//Check if User is Already LoggedIn
if(mAuth.getCurrentUser() != null)
{
//User NOT logged In
finish();
startActivity(new Intent(getApplicationContext(),SignIn.class));
}
signin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String getemail = email.getText().toString().trim();
String getepassword = password.getText().toString().trim();
callsignin(getemail,getepassword);
}
});
signup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String getemail = email.getText().toString().trim();
String getepassword = password.getText().toString().trim();
callsignup(getemail,getepassword);
}
});
}
//Create Account
private void callsignup(String email,String password) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d("TESTING", "Sign up Successful" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Toast.makeText(MainActivity.this, "Signed up Failed", Toast.LENGTH_SHORT).show();
}
else
{
userProfile();
Toast.makeText(MainActivity.this, "Created Account", Toast.LENGTH_SHORT).show();
Log.d("TESTING", "Created Account");
}
}
});
}
//Set UserDisplay Name
private void userProfile()
{
FirebaseUser user = mAuth.getCurrentUser();
if(user!= null)
{
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(name.getText().toString().trim())
//.setPhotoUri(Uri.parse("https://example.com/jane-q-user/profile.jpg")) // here you can set image link also.
.build();
user.updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d("TESTING", "User profile updated.");
}
}
});
}
}
//Now start Sign In Process
//SignIn Process
private void callsignin(String email,String password) {
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d("TESTING", "sign In Successful:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w("TESTING", "signInWithEmail:failed", task.getException());
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
else {
Intent i = new Intent(MainActivity.this, SignIn.class);
finish();
startActivity(i);
}
}
});
}
}
MainActivity:
package com.example.administrator.firebasetutorial;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.UserProfileChangeRequest;
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private EditText email,password,name;
private Button signin, signup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance(); // important Call
signin = (Button)findViewById(R.id.signin);
signup = (Button)findViewById(R.id.signup);
email = (EditText)findViewById(R.id.etEmail);
password = (EditText)findViewById(R.id.etPassword);
name = (EditText)findViewById(R.id.etName);
//Check if User is Already LoggedIn
if(mAuth.getCurrentUser() != null)
{
//User NOT logged In
finish();
startActivity(new Intent(getApplicationContext(),SignIn.class));
}
signin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String getemail = email.getText().toString().trim();
String getepassword = password.getText().toString().trim();
callsignin(getemail,getepassword);
}
});
signup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String getemail = email.getText().toString().trim();
String getepassword = password.getText().toString().trim();
callsignup(getemail,getepassword);
}
});
}
//Create Account
private void callsignup(String email,String password) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d("TESTING", "Sign up Successful" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Toast.makeText(MainActivity.this, "Signed up Failed", Toast.LENGTH_SHORT).show();
}
else
{
userProfile();
Toast.makeText(MainActivity.this, "Created Account", Toast.LENGTH_SHORT).show();
Log.d("TESTING", "Created Account");
}
}
});
}
//Set UserDisplay Name
private void userProfile()
{
FirebaseUser user = mAuth.getCurrentUser();
if(user!= null)
{
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(name.getText().toString().trim())
//.setPhotoUri(Uri.parse("https://example.com/jane-q-user/profile.jpg")) // here you can set image link also.
.build();
user.updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d("TESTING", "User profile updated.");
}
}
});
}
}
//Now start Sign In Process
//SignIn Process
private void callsignin(String email,String password) {
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d("TESTING", "sign In Successful:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w("TESTING", "signInWithEmail:failed", task.getException());
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
else {
Intent i = new Intent(MainActivity.this, SignIn.class);
finish();
startActivity(i);
}
}
});
}
}
SignIn:
package com.example.administrator.firebasetutorial;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
/**
* Created by Administrator on 16-03-2017.
*/
public class SignIn extends AppCompatActivity {
Button signout, upload_bttn,showData;
private FirebaseAuth mAuth;
TextView username;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
mAuth = FirebaseAuth.getInstance(); // important Call
signout = (Button)findViewById(R.id.signout);
upload_bttn = (Button)findViewById(R.id.upload);
showData = (Button)findViewById(R.id.show_data);
username = (TextView) findViewById(R.id.tvName);
//Again check if the user is Already Logged in or Not
if(mAuth.getCurrentUser() == null)
{
//User NOT logged In
finish();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
//Fetch the Display name of current User
FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
username.setText("Welcome, " + user.getDisplayName());
}
signout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAuth.signOut();
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
upload_bttn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),Uploadinfo.class));
}
});
showData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),ShowData.class));
}
});
}
}
ShowData:
package com.example.administrator.firebasetutorial;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import static android.R.attr.direction;
import static java.security.AccessController.getContext;
/**
* Created by Administrator on 16-03-2017.
*/
public class ShowData extends AppCompatActivity {
RecyclerView recyclerView;
FirebaseDatabase firebaseDatabase;
DatabaseReference myRef;
private FirebaseRecyclerAdapter<ShowDataItems, ShowDataViewHolder> mFirebaseAdapter;
public ShowData() {
// Required empty public constructor
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_data_layout);
firebaseDatabase = FirebaseDatabase.getInstance();
// myRef = firebaseDatabase.getReference("User_Details");
myRef = FirebaseDatabase.getInstance().getReference("User_Details");
recyclerView = (RecyclerView)findViewById(R.id.show_data_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(ShowData.this));
Toast.makeText(ShowData.this, "Wait ! Fetching List...", Toast.LENGTH_SHORT).show();
}
@Override
public void onStart() {
super.onStart();
//Log.d("LOGGED", "IN onStart ");
mFirebaseAdapter = new FirebaseRecyclerAdapter<ShowDataItems, ShowDataViewHolder>(ShowDataItems.class, R.layout.show_data_single_item, ShowDataViewHolder.class, myRef) {
public void populateViewHolder(final ShowDataViewHolder viewHolder, ShowDataItems model, final int position) {
viewHolder.Image_URL(model.getImage_URL());
viewHolder.Image_Title(model.getImage_Title());
//OnClick Item
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(ShowData.this);
builder.setMessage("Do you want to Delete this data ?").setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
int selectedItems = position;
mFirebaseAdapter.getRef(selectedItems).removeValue();
mFirebaseAdapter.notifyItemRemoved(selectedItems);
recyclerView.invalidate();
onStart();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.setTitle("Confirm");
dialog.show();
}
});
}
};
recyclerView.setAdapter(mFirebaseAdapter);
}
//View Holder For Recycler View
public static class ShowDataViewHolder extends RecyclerView.ViewHolder {
private final TextView image_title;
private final ImageView image_url;
public ShowDataViewHolder(final View itemView) {
super(itemView);
image_url = (ImageView) itemView.findViewById(R.id.fetch_image);
image_title = (TextView) itemView.findViewById(R.id.fetch_image_title);
}
private void Image_Title(String title) {
image_title.setText(title);
}
private void Image_URL(String title) {
// image_url.setImageResource(R.drawable.loading);
Glide.with(itemView.getContext())
.load(title)
.crossFade()
.placeholder(R.drawable.loading)
.thumbnail(0.1f)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(image_url);
}
}
}
ShowDataItems:
package com.example.administrator.firebasetutorial;
/**
* Created by Administrator on 16-03-2017.
*/
public class ShowDataItems {
private String Image_URL,Image_Title; //put this name same as Database Fields
public ShowDataItems(String image_URL, String image_title) {
Image_URL = image_URL;
Image_Title = image_title;
}
public ShowDataItems()
{
//Empty Constructor Needed
}
public String getImage_URL() {
return Image_URL;
}
public void setImage_URL(String image_URL) {
Image_URL = image_URL;
}
public String getImage_Title() {
return Image_Title;
}
public void setTitle(String title) {
Image_Title = title;
}
}
UploadInfo:
package com.example.administrator.firebasetutorial;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.firebase.client.Firebase;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
/**
* Created by Administrator on 16-03-2017.
*/
public class Uploadinfo extends AppCompatActivity {
Button select_image,upload_button;
ImageView user_image;
TextView title;
public static final int READ_EXTERNAL_STORAGE = 0;
private static final int GALLERY_INTENT = 2;
private ProgressDialog mProgressDialog;
private Firebase mRoofRef;
private Uri mImageUri = null;
private DatabaseReference mdatabaseRef;
private StorageReference mStorage;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upload_layout);
Firebase.setAndroidContext(this);
select_image = (Button)findViewById(R.id.select_image);
upload_button = (Button)findViewById(R.id.upload_bttn);
user_image = (ImageView) findViewById(R.id.user_image);
title = (TextView) findViewById(R.id.etTitle);
//Initialize the Progress Bar
mProgressDialog = new ProgressDialog(Uploadinfo.this);
//Select image from External Storage...
select_image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
//Check for Runtime Permission
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(getApplicationContext(), "Call for Permission", Toast.LENGTH_SHORT).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, READ_EXTERNAL_STORAGE);
}
}
else
{
callgalary();
}
}
});
//Initialize Firebase Database paths for database and Storage
mdatabaseRef = FirebaseDatabase.getInstance().getReference();
mRoofRef = new Firebase("https://fir-tutorial-5800f.firebaseio.com/").child("User_Details").push(); // Push will create new child every time we upload data
mStorage = FirebaseStorage.getInstance().getReferenceFromUrl("gs://fir-tutorial-5800f.appspot.com/");
//Click on Upload Button Title will upload to Database
upload_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String mName = title.getText().toString().trim();
if(mName.isEmpty())
{
Toast.makeText(getApplicationContext(), "Fill all Field", Toast.LENGTH_SHORT).show();
return;
}
Firebase childRef_name = mRoofRef.child("Image_Title");
childRef_name.setValue(mName);
Toast.makeText(getApplicationContext(), "Updated Info", Toast.LENGTH_SHORT).show();
}
});
}
//Check for Runtime Permissions for Storage Access
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
callgalary();
return;
}
Toast.makeText(getApplicationContext(), "...", Toast.LENGTH_SHORT).show();
}
//If Access Granted gallery Will open
private void callgalary() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_INTENT);
}
//After Selecting image from gallery image will directly uploaded to Firebase Database
//and Image will Show in Image View
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK) {
mImageUri = data.getData();
user_image.setImageURI(mImageUri);
StorageReference filePath = mStorage.child("User_Images").child(mImageUri.getLastPathSegment());
mProgressDialog.setMessage("Uploading Image....");
mProgressDialog.show();
filePath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUri = taskSnapshot.getDownloadUrl(); //Ignore This error
mRoofRef.child("Image_URL").setValue(downloadUri.toString());
Glide.with(getApplicationContext())
.load(downloadUri)
.crossFade()
.placeholder(R.drawable.loading)
.diskCacheStrategy(DiskCacheStrategy.RESULT)
.into(user_image);
Toast.makeText(getApplicationContext(), "Updated.", Toast.LENGTH_SHORT).show();
mProgressDialog.dismiss();
}
});
}
}
}
Firebase Tutorial Authentication - Part 1
package com.example.administrator.firebasetutorial;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.UserProfileChangeRequest;
import com.onesignal.OneSignal;
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private EditText email,password,name;
private Button signin, signup;
static String LoggedIn_User_Email;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance(); // important Call
signin = (Button)findViewById(R.id.signin);
signup = (Button)findViewById(R.id.signup);
email = (EditText)findViewById(R.id.etEmail);
password = (EditText)findViewById(R.id.etPassword);
name = (EditText)findViewById(R.id.etName);
//Check if User is Already LoggedIn
if(mAuth.getCurrentUser() != null)
{
//User NOT logged In
finish();
startActivity(new Intent(getApplicationContext(),SignIn.class));
}
signin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String getemail = email.getText().toString().trim();
String getepassword = password.getText().toString().trim();
callsignin(getemail,getepassword);
}
});
signup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String getemail = email.getText().toString().trim();
String getepassword = password.getText().toString().trim();
callsignup(getemail,getepassword);
}
});
}
//Create Account
private void callsignup(String email,String password) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d("TESTING", "Sign up Successful" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Toast.makeText(MainActivity.this, "Signed up Failed", Toast.LENGTH_SHORT).show();
}
else
{
userProfile();
Toast.makeText(MainActivity.this, "Created Account", Toast.LENGTH_SHORT).show();
Log.d("TESTING", "Created Account");
}
}
});
}
//Set UserDisplay Name
private void userProfile()
{
FirebaseUser user = mAuth.getCurrentUser();
if(user!= null)
{
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(name.getText().toString().trim())
//.setPhotoUri(Uri.parse("https://example.com/jane-q-user/profile.jpg")) // here you can set image link also.
.build();
user.updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d("TESTING", "User profile updated.");
}
}
});
}
}
//Now start Sign In Process
//SignIn Process
private void callsignin(String email,String password) {
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d("TESTING", "sign In Successful:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w("TESTING", "signInWithEmail:failed", task.getException());
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
else {
Intent i = new Intent(MainActivity.this, SignIn.class);
finish();
startActivity(i);
}
}
});
}
}
Sign IN:
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
/**
* Created by Administrator on 16-03-2017.
*/
public class SignIn extends AppCompatActivity {
Button signout,upload_bttn,showData,notification;
private FirebaseAuth mAuth;
TextView username;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
mAuth = FirebaseAuth.getInstance(); // important Call
signout = (Button)findViewById(R.id.signout);
username = (TextView) findViewById(R.id.tvName);
//Again check if the user is Already Logged in or Not
if(mAuth.getCurrentUser() == null)
{
//User NOT logged In
finish();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
//Fetch the Display name of current User
FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
username.setText("Welcome, " + user.getDisplayName());
}
signout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAuth.signOut();
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
}
}
Subscribe to:
Posts (Atom)