install android studio

Firebase Save and Retrieve data in Android Studio

Firebase Save and Retrieve:

implementation:

For saving and retrieving the data from firebase to android app , we need to follow the steps:

Saving the data:

1.activity_save.xml:


LinearLayout
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_marginTop="50dp"
android:layout_height="wrap_content"
android:orientation="horizontal">

Button
android:id="@+id/buttonChoose"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Choose" />

EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4"
android:hint="Enter name for Image" />

</LinearLayout>

ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="@+id/linearLayout" />

LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="vertical">

Button
android:id="@+id/buttonUpload"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Upload" />

TextView
android:id="@+id/textViewShow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="View Uploads"
android:textAlignment="center"
android:textColor="@color/colorPrimary"
android:textStyle="bold" />
/LinearLayout>

2.saveactivity.java :


public class Tees extends AppCompatActivity
implements View.OnClickListener, NavigationView.OnNavigationItemSelectedListener {
private static final int PICK_IMAGE_REQUEST = 234;

//view objects
private Button buttonChoose;
private Button buttonUpload;
public EditText editTextName;
private TextView textViewShow;
private ImageView imageView;

//uri to store file
public Uri filePath;
;

//firebase objects
public StorageReference storageReference;
public DatabaseReference mDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tees);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
imageView = (ImageView) findViewById(R.id.imageView);
editTextName = (EditText) findViewById(R.id.editText);
textViewShow = (TextView) findViewById(R.id.textViewShow);

storageReference = FirebaseStorage.getInstance().getReference();
mDatabase = FirebaseDatabase.getInstance().getReference(Constants.DATABASE_PATH_UPLOADS);

buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
textViewShow.setOnClickListener(this);

}

private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
public void uploadFile() {
//checking if file is available
if (filePath != null) {
//displaying progress dialog while image is uploading
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading");
progressDialog.show();

//getting the storage reference
StorageReference sRef = storageReference.child(Constants.STORAGE_PATH_UPLOADS + System.currentTimeMillis() + "." + getFileExtension(filePath));

//adding the file to reference
sRef.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//dismissing the progress dialog
progressDialog.dismiss();

//displaying success toast
Toast.makeText(getApplicationContext(), "File Uploaded ", Toast.LENGTH_LONG).show();

//creating the upload object to store uploaded image details
Upload upload = new Upload(editTextName.getText().toString().trim(), taskSnapshot.getDownloadUrl().toString());

//adding an upload to firebase database
String uploadId = mDatabase.push().getKey();
mDatabase.child(uploadId).setValue(upload);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
//displaying the upload progress
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
}
});
} else {
//display an error if no file is selected
Toast.makeText(getApplicationContext(),"Please select the file ", Toast.LENGTH_LONG).show();
}
}
@Override
public void onClick(View v) {
if (v == buttonChoose) {
showFileChooser();
} else if (v == buttonUpload) {
uploadFile();
} else if (v == textViewShow) {
Intent intent= new Intent(Tees.this,ShowImagesActivity.class);
startActivity(intent);
}
}
}

3.uploads.java


public class Upload {
public String name;
public String url;

// Default constructor required for calls to
// DataSnapshot.getValue(User.class)
public Upload() {
}

public Upload(String name, String url) {
this.name = name;
this.url= url;
}

public String getName() {
return name;
}

public String getUrl() {
return url;
}
}

4.constants.java


public class Constants {
public static final String STORAGE_PATH_UPLOADS = "uploads/";
public static final String DATABASE_PATH_UPLOADS = "uploads";
}

Retrieving data

5. activity_retrieve.xml:


android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content">

</android.support.v7.widget.RecyclerView>

6. retrieveactivity.java:


public class ShowImagesActivity extends AppCompatActivity {
//recyclerview object
private RecyclerView recyclerView;

//adapter object
private RecyclerView.Adapter adapter;

//database reference
private DatabaseReference mDatabase;

//progress dialog
private ProgressDialog progressDialog;

//list to hold all the uploaded images
public List<Upload> uploads;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_images);

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

initCollapsingToolbar();

recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
recyclerView.setItemAnimator(new DefaultItemAnimator());

// recyclerView.setHasFixedSize(true);
//recyclerView.setLayoutManager(new LinearLayoutManager(this));

progressDialog = new ProgressDialog(this);

uploads = new ArrayList<>();

//displaying progress dialog while fetching images
//progressDialog.setMessage("Please wait...");
progressDialog.setIcon(R.drawable.tshirt);
progressDialog.show();
mDatabase = FirebaseDatabase.getInstance().getReference(Constants.DATABASE_PATH_UPLOADS);

//adding an event listener to fetch values
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
//dismissing the progress dialog
progressDialog.dismiss();

//iterating through all the values in database
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
Upload upload = postSnapshot.getValue(Upload.class);
uploads.add(upload);
}
//creating adapter
adapter = new MyAdapter(getApplicationContext(), uploads);

//adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}

@Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
}
});}

private void initCollapsingToolbar() {
final CollapsingToolbarLayout collapsingToolbar =
(CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
collapsingToolbar.setTitle(" ");
AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
appBarLayout.setExpanded(true);

// hiding & showing the title when toolbar expanded & collapsed
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = false;
int scrollRange = -1;

@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
collapsingToolbar.setTitle(getString(R.string.app_name));
isShow = true;
} else if (isShow) {
collapsingToolbar.setTitle(" ");
isShow = false;
}}
});}
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

private int spanCount;
private int spacing;
private boolean includeEdge;

public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
this.spanCount = spanCount;
this.spacing = spacing;
this.includeEdge = includeEdge;
}

@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view); // item position
int column = position % spanCount; // item column

if (includeEdge) {
outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

if (position < spanCount) { // top edge
outRect.top = spacing;
}
outRect.bottom = spacing; // item bottom
} else {
outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing)
if (position >= spanCount) {
outRect.top = spacing; // item top
}}}}

/**
* Converting dp to pixel
*/
private int dpToPx(int dp) {
Resources r = getResources();
return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}}

7. myadapter.java:


public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{

private Context context;
public List<Upload> uploads;
public TextView name ;

public MyAdapter(Context context, List<Upload> uploads) {
this.uploads = uploads;
this.context = context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.layout_images, parent, false);

// Dialog mydialog = new Dialog(context);
//mydialog.setContentView(R.layout.fragment_product_detail);

ViewHolder viewHolder = new ViewHolder(v);
/* viewHolder.layout_images.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

// TextView name= (TextView) findViewById(R.id.name_text);
//ImageView image =(ImageView) mydialog.findViewById(R.id.image_text);
// String name1= name.getText(uploads.get(viewHolder.getAdapterPosition()).getName());

// Glide.with(context).load(viewHolder.getAdapterPosition()).into(image);

Toast.makeText(context, "test click" + String.valueOf(viewHolder.getAdapterPosition()), Toast.LENGTH_LONG).show();

// mydialog.show();
// Product_detail frag = new Product_detail();

} */
return viewHolder;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Upload upload = uploads.get(position);

holder.textViewName.setText(upload.getName());

Glide.with(context).load(upload.getUrl()).into(holder.imageView);
holder.layout_images.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context,collar.class);
intent.putExtra("image_url", upload.getUrl());
intent.putExtra("image_name",upload.getName());
context.startActivity(intent);
}
});

}

@Override
public int getItemCount() {
return uploads.size();
}
public void filterList(ArrayList<Upload> filteredList) {
uploads = filteredList;
notifyDataSetChanged();
}

class ViewHolder extends RecyclerView.ViewHolder {
public LinearLayout layout_images;
public TextView textViewName;
public ImageView imageView;

public ViewHolder(View itemView) {
super(itemView);
layout_images=(LinearLayout) itemView.findViewById(R.id.layout_images);
textViewName = (TextView) itemView.findViewById(R.id.textViewName);
imageView = (ImageView) itemView.findViewById(R.id.imageView);

}

}

}

 

 

About the author

Generic Bytes

Hi! we are from Generic Bytes an aspiring bloggers with an obsession of things tech.This blog is dedicated to people who want to learn the technology.

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *