这是5的“建立一个社交媒体应用程序在Android工作室”教程中的一部分,我们将要在本文中介绍了以下功能:
- 我们将添加任何用户的博客。在这里,我们将在AddBlogs Fragment中工作,其中用户将添加带有标题,描述和与该博客相关的图像的博客。
- 如果用户未写任何标题或描述,那么我们将显示一个错误。
分步实施
步骤1:使用fragment_add_blogs.xml文件
在此页面上将具有两个用于输入标题和描述的EditText,以及一个供用户选择图像的图像视图。导航至应用程序> res>布局> fragment_add_blogs.xml,然后将以下代码添加到该文件中。以下是fragment_add_blogs.xml文件的代码。
XML
Java
package com.example.socialmediaapp;
import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
/**
* A simple {@link Fragment} subclass.
*/
public class AddBlogsFragment extends Fragment {
public AddBlogsFragment() {
// Required empty public constructor
}
FirebaseAuth firebaseAuth;
EditText title, des;
private static final int CAMERA_REQUEST = 100;
private static final int STORAGE_REQUEST = 200;
String cameraPermission[];
String storagePermission[];
ProgressDialog pd;
ImageView image;
String edititle, editdes, editimage;
private static final int IMAGEPICK_GALLERY_REQUEST = 300;
private static final int IMAGE_PICKCAMERA_REQUEST = 400;
Uri imageuri = null;
String name, email, uid, dp;
DatabaseReference databaseReference;
Button upload;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
firebaseAuth = FirebaseAuth.getInstance();
View view = inflater.inflate(R.layout.fragment_add_blogs, container, false);
title = view.findViewById(R.id.ptitle);
des = view.findViewById(R.id.pdes);
image = view.findViewById(R.id.imagep);
upload = view.findViewById(R.id.pupload);
pd = new ProgressDialog(getContext());
pd.setCanceledOnTouchOutside(false);
Intent intent = getActivity().getIntent();
// Retrieving the user data like name ,email and profile pic using query
databaseReference = FirebaseDatabase.getInstance().getReference("Users");
Query query = databaseReference.orderByChild("email").equalTo(email);
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
name = dataSnapshot1.child("name").getValue().toString();
email = "" + dataSnapshot1.child("email").getValue();
dp = "" + dataSnapshot1.child("image").getValue().toString();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
// Initialising camera and storage permission
cameraPermission = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
// After click on image we will be selecting an image
image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showImagePicDialog();
}
});
// Now we will upload out blog
upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String titl = "" + title.getText().toString().trim();
String description = "" + des.getText().toString().trim();
// If empty set error
if (TextUtils.isEmpty(titl)) {
title.setError("Title Cant be empty");
Toast.makeText(getContext(), "Title can't be left empty", Toast.LENGTH_LONG).show();
return;
}
// If empty set error
if (TextUtils.isEmpty(description)) {
des.setError("Description Cant be empty");
Toast.makeText(getContext(), "Description can't be left empty", Toast.LENGTH_LONG).show();
return;
}
// If empty show error
if (imageuri == null) {
Toast.makeText(getContext(), "Select an Image", Toast.LENGTH_LONG).show();
return;
} else {
uploadData(titl, description);
}
}
});
return view;
}
private void showImagePicDialog() {
String options[] = {"Camera", "Gallery"};
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Pick Image From");
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// check for the camera and storage permission if
// not given the request for permission
if (which == 0) {
if (!checkCameraPermission()) {
requestCameraPermission();
} else {
pickFromCamera();
}
} else if (which == 1) {
if (!checkStoragePermission()) {
requestStoragePermission();
} else {
pickFromGallery();
}
}
}
});
builder.create().show();
}
// check for storage permission
private Boolean checkStoragePermission() {
boolean result = ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result;
}
// if not given then request for permission after that check if request is given or not
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case CAMERA_REQUEST: {
if (grantResults.length > 0) {
boolean camera_accepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean writeStorageaccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
// if request access given the pick data
if (camera_accepted && writeStorageaccepted) {
pickFromCamera();
} else {
Toast.makeText(getContext(), "Please Enable Camera and Storage Permissions", Toast.LENGTH_LONG).show();
}
}
}
// function end
break;
case STORAGE_REQUEST: {
if (grantResults.length > 0) {
boolean writeStorageaccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
// if request access given the pick data
if (writeStorageaccepted) {
pickFromGallery();
} else {
Toast.makeText(getContext(), "Please Enable Storage Permissions", Toast.LENGTH_LONG).show();
}
}
}
break;
}
}
// request for permission to write data into storage
private void requestStoragePermission() {
requestPermissions(storagePermission, STORAGE_REQUEST);
}
// check camera permission to click picture using camera
private Boolean checkCameraPermission() {
boolean result = ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED);
boolean result1 = ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return result && result1;
}
// request for permission to click photo using camera in app
private void requestCameraPermission() {
requestPermissions(cameraPermission, CAMERA_REQUEST);
}
// if access is given then pick image from camera and then put
// the imageuri in intent extra and pass to startactivityforresult
private void pickFromCamera() {
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.Media.TITLE, "Temp_pic");
contentValues.put(MediaStore.Images.Media.DESCRIPTION, "Temp Description");
imageuri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
Intent camerIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
camerIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageuri);
startActivityForResult(camerIntent, IMAGE_PICKCAMERA_REQUEST);
}
// if access is given then pick image from gallery
private void pickFromGallery() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, IMAGEPICK_GALLERY_REQUEST);
}
// Upload the value of blog data into firebase
private void uploadData(final String titl, final String description) {
// show the progress dialog box
pd.setMessage("Publishing Post");
pd.show();
final String timestamp = String.valueOf(System.currentTimeMillis());
String filepathname = "Posts/" + "post" + timestamp;
Bitmap bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] data = byteArrayOutputStream.toByteArray();
// initialising the storage reference for updating the data
StorageReference storageReference1 = FirebaseStorage.getInstance().getReference().child(filepathname);
storageReference1.putBytes(data).addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// getting the url of image uploaded
Task uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful()) ;
String downloadUri = uriTask.getResult().toString();
if (uriTask.isSuccessful()) {
// if task is successful the update the data into firebase
HashMap
步骤2:使用AddBlogsFragment。 Java文件
转到AddBlogsFragment。 Java文件并参考以下代码。下面是AddBlogsFragment的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。
Java
package com.example.socialmediaapp;
import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
/**
* A simple {@link Fragment} subclass.
*/
public class AddBlogsFragment extends Fragment {
public AddBlogsFragment() {
// Required empty public constructor
}
FirebaseAuth firebaseAuth;
EditText title, des;
private static final int CAMERA_REQUEST = 100;
private static final int STORAGE_REQUEST = 200;
String cameraPermission[];
String storagePermission[];
ProgressDialog pd;
ImageView image;
String edititle, editdes, editimage;
private static final int IMAGEPICK_GALLERY_REQUEST = 300;
private static final int IMAGE_PICKCAMERA_REQUEST = 400;
Uri imageuri = null;
String name, email, uid, dp;
DatabaseReference databaseReference;
Button upload;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
firebaseAuth = FirebaseAuth.getInstance();
View view = inflater.inflate(R.layout.fragment_add_blogs, container, false);
title = view.findViewById(R.id.ptitle);
des = view.findViewById(R.id.pdes);
image = view.findViewById(R.id.imagep);
upload = view.findViewById(R.id.pupload);
pd = new ProgressDialog(getContext());
pd.setCanceledOnTouchOutside(false);
Intent intent = getActivity().getIntent();
// Retrieving the user data like name ,email and profile pic using query
databaseReference = FirebaseDatabase.getInstance().getReference("Users");
Query query = databaseReference.orderByChild("email").equalTo(email);
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
name = dataSnapshot1.child("name").getValue().toString();
email = "" + dataSnapshot1.child("email").getValue();
dp = "" + dataSnapshot1.child("image").getValue().toString();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
// Initialising camera and storage permission
cameraPermission = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
// After click on image we will be selecting an image
image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showImagePicDialog();
}
});
// Now we will upload out blog
upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String titl = "" + title.getText().toString().trim();
String description = "" + des.getText().toString().trim();
// If empty set error
if (TextUtils.isEmpty(titl)) {
title.setError("Title Cant be empty");
Toast.makeText(getContext(), "Title can't be left empty", Toast.LENGTH_LONG).show();
return;
}
// If empty set error
if (TextUtils.isEmpty(description)) {
des.setError("Description Cant be empty");
Toast.makeText(getContext(), "Description can't be left empty", Toast.LENGTH_LONG).show();
return;
}
// If empty show error
if (imageuri == null) {
Toast.makeText(getContext(), "Select an Image", Toast.LENGTH_LONG).show();
return;
} else {
uploadData(titl, description);
}
}
});
return view;
}
private void showImagePicDialog() {
String options[] = {"Camera", "Gallery"};
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Pick Image From");
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// check for the camera and storage permission if
// not given the request for permission
if (which == 0) {
if (!checkCameraPermission()) {
requestCameraPermission();
} else {
pickFromCamera();
}
} else if (which == 1) {
if (!checkStoragePermission()) {
requestStoragePermission();
} else {
pickFromGallery();
}
}
}
});
builder.create().show();
}
// check for storage permission
private Boolean checkStoragePermission() {
boolean result = ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result;
}
// if not given then request for permission after that check if request is given or not
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case CAMERA_REQUEST: {
if (grantResults.length > 0) {
boolean camera_accepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean writeStorageaccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
// if request access given the pick data
if (camera_accepted && writeStorageaccepted) {
pickFromCamera();
} else {
Toast.makeText(getContext(), "Please Enable Camera and Storage Permissions", Toast.LENGTH_LONG).show();
}
}
}
// function end
break;
case STORAGE_REQUEST: {
if (grantResults.length > 0) {
boolean writeStorageaccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
// if request access given the pick data
if (writeStorageaccepted) {
pickFromGallery();
} else {
Toast.makeText(getContext(), "Please Enable Storage Permissions", Toast.LENGTH_LONG).show();
}
}
}
break;
}
}
// request for permission to write data into storage
private void requestStoragePermission() {
requestPermissions(storagePermission, STORAGE_REQUEST);
}
// check camera permission to click picture using camera
private Boolean checkCameraPermission() {
boolean result = ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED);
boolean result1 = ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return result && result1;
}
// request for permission to click photo using camera in app
private void requestCameraPermission() {
requestPermissions(cameraPermission, CAMERA_REQUEST);
}
// if access is given then pick image from camera and then put
// the imageuri in intent extra and pass to startactivityforresult
private void pickFromCamera() {
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.Media.TITLE, "Temp_pic");
contentValues.put(MediaStore.Images.Media.DESCRIPTION, "Temp Description");
imageuri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
Intent camerIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
camerIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageuri);
startActivityForResult(camerIntent, IMAGE_PICKCAMERA_REQUEST);
}
// if access is given then pick image from gallery
private void pickFromGallery() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, IMAGEPICK_GALLERY_REQUEST);
}
// Upload the value of blog data into firebase
private void uploadData(final String titl, final String description) {
// show the progress dialog box
pd.setMessage("Publishing Post");
pd.show();
final String timestamp = String.valueOf(System.currentTimeMillis());
String filepathname = "Posts/" + "post" + timestamp;
Bitmap bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] data = byteArrayOutputStream.toByteArray();
// initialising the storage reference for updating the data
StorageReference storageReference1 = FirebaseStorage.getInstance().getReference().child(filepathname);
storageReference1.putBytes(data).addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// getting the url of image uploaded
Task uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful()) ;
String downloadUri = uriTask.getResult().toString();
if (uriTask.isSuccessful()) {
// if task is successful the update the data into firebase
HashMap
输出:
在将数据成功添加到博客中之后,数据将在firebase中显示,如下所示:
对于本文中使用的所有可绘制文件,请参考以下链接: https://drive.google.com/drive/folders/1M_knOH_ugCuwSP5nkYzeD4dRp-Honzbe?usp=sharing
下面是执行这些操作后的文件结构: