我相对较不熟悉android开发,因此尝试将图像URL从Firebase存储保存到Firebase实时数据库。
但是,当我将链接保存到实时数据库时,它会另存为"com.google.android.gms.tasks.zzu@c834bfd"
之类的链接
它不是像通常的http链接那样保存,而是像上面那样保存,我不确定确切需要更改什么。
package com.example.android.gymbuddies;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
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.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.util.Calendar;
import java.util.HashMap;
import de.hdodenhof.circleimageview.CircleImageView;
public class setUpDetailsActivity extends AppCompatActivity {
EditText username, fullName, height, weight;
TextView dob;
DatePickerDialog.OnDateSetListener mDateSetListener;
CircleImageView profileIV;
Button saveBT;
ProgressBar progressbar;
RadioGroup gender;
RadioButton genderOption;
private FirebaseAuth mAuth;
private DatabaseReference userRef;
private StorageReference profileImageRef;
String currentUserID, strGender;
final static int galleryPic = 1;
private String TAG;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_up_details);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
userRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID);
profileImageRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
username = (EditText) findViewById(R.id.username);
fullName = (EditText) findViewById(R.id.fullName);
height = (EditText) findViewById(R.id.height);
weight = (EditText) findViewById(R.id.weight);
gender = findViewById(R.id.gender);
dob = (TextView) findViewById(R.id.dob);
saveBT = (Button) findViewById(R.id.saveBT);
profileIV = (CircleImageView) findViewById(R.id.profileIV);
progressbar = (ProgressBar) findViewById(R.id.progressbar);
saveBT.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
saveAccountDetails();
}
});
profileIV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, galleryPic);
}
});
dob.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(
setUpDetailsActivity.this,
android.R.style.Theme_Holo_Light_Dialog_MinWidth,
mDateSetListener,
year,month,day);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
});
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
month = month + 1;
Log.d(TAG, "onDateSet: dd/mm/yyy: " + day + "/" + month + "/" + year);
String date = day + "/" + month + "/" + year;
dob.setText(date);
}
};
userRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
if (dataSnapshot.hasChild("profileImage")){
String image1 = dataSnapshot.child("profileImage").getValue(String.class);
Picasso.get().load(image1).placeholder(R.drawable.ic_profilepic).into(profileIV);
}
else{
Toast.makeText(setUpDetailsActivity.this, "Please enter you image first", Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==galleryPic && resultCode==RESULT_OK && data!= null) {
Uri ImageUri = data.getData();
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
progressbar.setVisibility(View.VISIBLE);
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
StorageReference filePath = profileImageRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
Toast.makeText(setUpDetailsActivity.this, "Profile image stored in firebase storage successfully", Toast.LENGTH_LONG).show();
final String downloadUrl = task.getResult().getMetadata().getReference().getDownloadUrl().toString().trim();
userRef.child("profileImage").setValue(downloadUrl).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
progressbar.setVisibility(View.GONE);
if (task.isSuccessful()) {
Intent selfIntent = new Intent(setUpDetailsActivity.this, setUpDetailsActivity.class);
startActivity(selfIntent);
Toast.makeText(setUpDetailsActivity.this, "Profile image stored in firebase database successfully", Toast.LENGTH_LONG).show();
} else {
String message = task.getException().getMessage();
Toast.makeText(setUpDetailsActivity.this, "Error Occured: " + message, Toast.LENGTH_LONG).show();
}
}
});
} else {
Toast.makeText(setUpDetailsActivity.this, "Error Occured: not stored in firebase storage", Toast.LENGTH_LONG).show();
}
}
});
} else {
Toast.makeText(setUpDetailsActivity.this, "Error Occured: Image can not be cropped try again.", Toast.LENGTH_LONG).show();
progressbar.setVisibility(View.GONE);
}
}
}
private void saveAccountDetails() {
String musername = username.getText().toString();
String mfullname = fullName.getText().toString();
String mheight = height.getText().toString();
String mweight = weight.getText().toString();
String mdob = dob.getText().toString();
gender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
genderOption = gender.findViewById(checkedId);
switch (checkedId){
case R.id.male:
strGender = genderOption.getText().toString();
break;
case R.id.female:
strGender = genderOption.getText().toString();
break;
default:
}
}
});
if (TextUtils.isEmpty(musername)) {
Toast.makeText(this, "Please Enter your Username", Toast.LENGTH_LONG).show();
}
if (TextUtils.isEmpty(mfullname)) {
Toast.makeText(this, "Please Enter your Full Name", Toast.LENGTH_LONG).show();
}
if (TextUtils.isEmpty(mheight)) {
Toast.makeText(this, "Please Enter your Height in cm", Toast.LENGTH_LONG).show();
}
if (TextUtils.isEmpty(mweight)) {
Toast.makeText(this, "Please Enter your Weight in lbs", Toast.LENGTH_LONG).show();
}
if (TextUtils.isEmpty(mdob)) {
Toast.makeText(this, "Please Enter your Date-Of-Birth", Toast.LENGTH_LONG).show();
}
if (TextUtils.isEmpty(strGender)) {
Toast.makeText(this, "Please Select your Gender", Toast.LENGTH_LONG).show();
}else {
progressbar.setVisibility(View.VISIBLE);
HashMap userMap = new HashMap();
userMap.put("username", musername);
userMap.put("fullName", mfullname);
userMap.put("liftingGoal", "Default");
userMap.put("height", mheight + " cm");
userMap.put("weight", mweight + " pounds");
userMap.put("dob", mdob);
userMap.put("gender", strGender);
userRef.updateChildren(userMap).addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
progressbar.setVisibility(View.GONE);
if (task.isSuccessful()) {
sendUserToMainActivity();
Toast.makeText(setUpDetailsActivity.this, "Account created Successfully", Toast.LENGTH_LONG).show();
} else {
String message = task.getException().getMessage();
Toast.makeText(setUpDetailsActivity.this, "An Error Occured: " + message, Toast.LENGTH_LONG).show();
}
}
});
}
}
private void sendUserToMainActivity() {
Intent mainIntent = new Intent(setUpDetailsActivity.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
}
答案 0 :(得分:0)
这一切正常, 首先将尝试并了解如何使Firebase工作。非常容易享受。
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
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.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import static android.widget.Toast.LENGTH_SHORT;
public class MainActivity extends AppCompatActivity {
private EditText inputEmail, inputPassword,f_name,l_name,phone;
private Button btnSignUp,back;
private ProgressBar progressBar;
private FirebaseAuth auth;
FirebaseStorage storage;
private DatabaseReference mCustomerDatabase,mCustomerDatabase1;
ImageView profileImage;
Uri resultUri = Uri.parse("android.resource://com.example.chetan.printerprinting/" + R.drawable.ic_launcher_background);
ProgressDialog progress;
public static final int PICK_IMAGE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCustomerDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child("Customers").child("UploadFile");
storage = FirebaseStorage.getInstance();
btnSignUp = (Button) findViewById(R.id.sign_up_button);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
f_name = (EditText) findViewById(R.id.f_name);
l_name = (EditText) findViewById(R.id.l_name);
phone = (EditText) findViewById(R.id.phone);
back = (Button) findViewById(R.id.back);
profileImage = (ImageView) findViewById(R.id.image_profile);
profileImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
selectPdf();
}
else {
ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},9);
}
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String email = inputEmail.getText().toString().trim();
final String password = inputPassword.getText().toString().trim();
final String F_name = f_name.getText().toString().trim();
final String L_name = l_name.getText().toString().trim();
final String Phone = phone.getText().toString().trim();
if (TextUtils.isEmpty(F_name)) {
f_name.setError("Enter First Name!");
return;
}
if (TextUtils.isEmpty(L_name)) {
l_name.setError("Enter Last Name!");
return;
}
if (TextUtils.isEmpty(Phone)) {
phone.setError("Enter Phone Number!");
return;
}
if(isValidPhone(Phone)){
//Toast.makeText(getApplicationContext(),"Phone number is valid",Toast.LENGTH_SHORT).show();
}else {
phone.setError("Phone number is not valid");
// Toast.makeText(getApplicationContext(),"Phone number is not valid",Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(email)) {
inputEmail.setError("Enter Email Address!");
return;
}
else if (isValidEmail(email)){
}
else {
inputEmail.setError("Enter Valid Email Address!");
return;
}
if (TextUtils.isEmpty(password)) {
inputPassword.setError("Enter Password!");
return;
}
if (password.length() < 6) {
inputPassword.setError("Password too short, enter minimum 6 characters!");
return;
}
Map userInfo = new HashMap();
userInfo.put("email", email);
userInfo.put("password", password);
userInfo.put("f_name", F_name);
userInfo.put("l_name", L_name);
userInfo.put("phone", Phone);
mCustomerDatabase.updateChildren(userInfo);
final String fileName = System.currentTimeMillis()+"";
if(resultUri != null) {
StorageReference storageReference = storage.getReference();
storageReference.child("profileImageUrl").child(fileName).putFile(resultUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String url = taskSnapshot.getDownloadUrl().toString();
mCustomerDatabase.child("profileImageUrl").setValue(url).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){ }
else{
Toast.makeText(getApplicationContext(),"File not Successfully Uploaded",LENGTH_SHORT).show(); }
}
});
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getApplicationContext(),"File not Successfully Uploaded",LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
}
});
}else{
}
}
});
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
}
public boolean isValidPhone(CharSequence phone) {
boolean check=false;
if(!Pattern.matches("[a-zA-Z]+", phone))
{
if(phone.length() < 10 || phone.length() > 11)
{
check = false;
}
else
{
check = true;
}
}
else
{
check=false;
}
return check;
}
public static boolean isValidEmail(CharSequence target) {
return (!TextUtils.isEmpty(target) && Patterns.EMAIL_ADDRESS.matcher(target).matches());
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == 9 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
selectPdf();
}
else{
Toast.makeText(getApplicationContext(),"Please provide the permission", LENGTH_SHORT).show();
}
}
private void selectPdf() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
startActivityForResult(intent,86);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 86 && resultCode == RESULT_OK && data != null){
final Uri imageUri = data.getData();
resultUri = imageUri;
profileImage.setImageURI(resultUri);
}
else {
Toast.makeText(getApplicationContext(),"Please select file", LENGTH_SHORT).show();
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FBFBFB"
android:orientation="vertical"
tools:context=".MainActivity"
tools:layout_editor_absoluteY="25dp">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30dp"
android:textColor="#4B74FF"
android:layout_marginRight="30dp"
android:layout_marginLeft="30dp"
android:text="Create an account"/>
<ImageView
android:id="@+id/image_profile"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_marginRight="50dp"
android:layout_marginLeft="50dp"
android:layout_below="@id/text"
android:layout_marginTop="20dp"
android:src="@drawable/ic_launcher_background" />
<EditText
android:id="@+id/f_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="First Name"
android:layout_marginTop="20dp"
android:layout_marginRight="30dp"
android:layout_marginLeft="30dp"
android:layout_below="@id/image_profile"
android:inputType="textEmailAddress"
android:textColor="#aaa"
android:fontFamily="monospace"
android:textSize="22dp" />
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_marginTop="-10dp"
android:layout_marginLeft="30dp"
android:layout_below="@id/f_name"
android:layout_marginRight="30dp"
android:background="#aaaaaa" />
<EditText
android:id="@+id/l_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Last Name"
android:layout_marginTop="20dp"
android:layout_marginRight="30dp"
android:layout_marginLeft="30dp"
android:layout_below="@id/f_name"
android:inputType="textEmailAddress"
android:textColor="#aaa"
android:fontFamily="monospace"
android:textSize="22dp" />
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_marginTop="-10dp"
android:layout_marginLeft="30dp"
android:layout_below="@id/l_name"
android:layout_marginRight="30dp"
android:background="#aaaaaa" />
<EditText
android:id="@+id/phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Phone No."
android:layout_marginTop="20dp"
android:layout_marginRight="30dp"
android:layout_marginLeft="30dp"
android:layout_below="@id/l_name"
android:inputType="phone"
android:textColor="#aaa"
android:fontFamily="monospace"
android:textSize="22dp" />
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_marginTop="-10dp"
android:layout_marginLeft="30dp"
android:layout_below="@id/phone"
android:layout_marginRight="30dp"
android:background="#aaaaaa" />
<EditText
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="email"
android:layout_marginRight="30dp"
android:layout_marginTop="20dp"
android:layout_marginLeft="30dp"
android:layout_below="@id/phone"
android:inputType="textEmailAddress"
android:textColor="#aaa"
android:fontFamily="monospace"
android:textSize="22dp" />
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_marginTop="-10dp"
android:layout_marginLeft="30dp"
android:layout_below="@id/email"
android:layout_marginRight="30dp"
android:background="#aaaaaa" />
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="password"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_marginTop="20dp"
android:layout_below="@id/email"
android:maxLength="11"
android:inputType="textPassword"
android:textColor="#aaa"
android:textSize="22dp"
/>
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_marginTop="-10dp"
android:layout_marginLeft="30dp"
android:layout_below="@id/password"
android:layout_marginRight="30dp"
android:background="#aaaaaa" />
<Button
android:id="@+id/sign_up_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@android:color/background_light"
android:layout_marginTop="10dp"
android:padding="20dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:textSize="20dp"
android:layout_marginBottom="10dp"
android:layout_below="@id/password"
android:textStyle="bold" />
</RelativeLayout>
</ScrollView>
<!-- Link to Login Screen -->
</RelativeLayout>
希望完全使用