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();
}
});
}
}
}
can u send me the project link or full project
ReplyDeletecan u send me the project link or full project(with xml files)
ReplyDeleteYou should have uploaded at least a video proving that this code works
ReplyDeleteMy application is crashing wen i click on show_uploaded_Data button..!
ReplyDeleteafter showing "Wait ! Fetching List..."
Upload XML files too
ReplyDelete