I am trying to call for the UID that firebase provides and register it to the Realtime Database. For some reason the two UIDs are different. I think Authentication UID is changing after I register the original UID to Realtime Database. Perhaps the way I am calling the UID is wrong?
Authentication UID: zD40xuce4SWPiidMGOm62hFWOFP2
Realtime Database UID: rhqgglru9FXV5jhITSQmpqwBdc53
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_user);
email = findViewById(R.id.email_create);
password = findViewById(R.id.password_create);
con_password = findViewById(R.id.password_confirm);
auth = FirebaseAuth.getInstance();
registerBtn = findViewById(R.id.Register);
registerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String txt_email = email.getText().toString();
String txt_password = password.getText().toString();
String txt_con_password = con_password.getText().toString();
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser() ;
Toast.makeText(New_User.this, "" + currentFirebaseUser.getUid(), Toast.LENGTH_SHORT).show();
String txt_UID = currentFirebaseUser.getUid();
//check empty fields
if (txt_email.isEmpty() || txt_password.isEmpty()) {
Toast.makeText(New_User.this, "Please fill all fields", Toast.LENGTH_SHORT).show();
}
//check passwords match
else if (!txt_password.equals(txt_con_password)){
Toast.makeText(New_User.this, "Passwords are not matching", Toast.LENGTH_SHORT).show();
}
else{
databaseReference.child("User ID").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.hasChild(txt_UID)) {
Toast.makeText(New_User.this, "User ID is taken", Toast.LENGTH_SHORT).show();
}
else {
registerUser(txt_email, txt_password, txt_UID);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
});
}
private void registerUser(String email, String password, String UID) {
auth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(New_User.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//doesnt upload login information into realtime database, but registers account
if (task.isSuccessful()) {
databaseReference.child("User ID").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
databaseReference.child("User ID").child(UID).child("email").setValue(email);
databaseReference.child("User ID").child(UID).child("password").setValue(password);
Toast.makeText(New_User.this, "User registered successfully.", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(New_User.this, PhysicalParameters.class);
startActivity(intent);
finish();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
FirebaseUser user = auth.getCurrentUser();
Toast.makeText(New_User.this, "Registering user successful", Toast.LENGTH_SHORT).show();
//Intent intent = new Intent(New_User.this, Welcome_Page.class);
//startActivity(intent);
}else {
Toast.makeText(New_User.this, "Failed Registration: " + task.getException(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
fAuth = FirebaseAuth.getInstance();
fAuth.getUid()
For more reference. This is my project
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.Base64;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
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.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.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import org.w3c.dom.Text;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import com.google.android.gms.vision.Frame;
import com.google.android.gms.vision.face.Face;
import com.google.android.gms.vision.face.FaceDetector;
public class Register extends AppCompatActivity {
EditText mFullName, mEmail, mPassword, mPhone;
Button mRegisterBtn, pickimagebtn;
TextView mLoginHereBtn,imgsourcetxtview;
FirebaseAuth fAuth;
ProgressBar progressBar;
String encryptionimagestring;
Bitmap bitmap;
ImageView ProfileImage;
SparseArray<Face> faces;
private static final int PICK_IMAGE = 1;
int count = 0;
private byte encryptionkey[] = {9, 115, 51, 86, 105, 4, -31, 23, -68, 88, 17, 20, 3, -105, 119, -53};
private Cipher cipher, decipher;
private SecretKeySpec secretKeySpec;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
imgsourcetxtview =(TextView) findViewById(R.id.imagesoucetxtview);
imgsourcetxtview.setMovementMethod(new ScrollingMovementMethod());
imgsourcetxtview.setSingleLine();
//pick image
pickimagebtn = findViewById(R.id.pickimagebtn);
pickimagebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CropImage.activity(null)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(Register.this);
}
});
try {
cipher = Cipher.getInstance("AES");
decipher = Cipher.getInstance("AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
secretKeySpec = new SecretKeySpec(encryptionkey, "AES");
mFullName = findViewById(R.id.Register_FullName);
mEmail = findViewById(R.id.Email);
mPassword = findViewById(R.id.Password);
mPhone = findViewById(R.id.Register_Phone);
mRegisterBtn = findViewById(R.id.Register_button);
mLoginHereBtn = findViewById(R.id.LoginHere);
mFullName = findViewById(R.id.Register_FullName);
fAuth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progressBar);
if (fAuth.getCurrentUser() != null) {
startActivity(new Intent(getApplicationContext(), MainActivity.class).putExtra("fuid", String.valueOf(fAuth.getUid())));
finish();
}
mRegisterBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
if (TextUtils.isEmpty(mFullName.getText().toString().trim())) {
mFullName.setError("Name is required.");
return;
}
if (TextUtils.isEmpty(email)) {
mEmail.setError("Email is required.");
return;
}
if (TextUtils.isEmpty(mPhone.getText().toString().trim())) {
mPhone.setError("Phone is required.");
return;
}
if (TextUtils.isEmpty(password)) {
mPassword.setError("Password is required.");
return;
}
if (password.length() < 6) {
mPassword.setError("Password must be >= 6 characters.");
return;
}
if (TextUtils.isEmpty(imgsourcetxtview.getText().toString().trim())) {
imgsourcetxtview.setError("Image is required.");
return;
}
else{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inMutable = true;
detectFace(options);
if (faces.size() < 1) {
imgsourcetxtview.setError("Can't detect face.");
return;
}
if (faces.size() > 1) {
imgsourcetxtview.setError("More than one face is detected.");
return;
}
}
progressBar.setVisibility(View.VISIBLE);
fAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
//add information to firebase
myRef.child("Account").child(fAuth.getUid()).child("name").setValue(AESEncryptionmethod(mFullName.getText().toString()));
myRef.child("Account").child(fAuth.getUid()).child("phone").setValue(AESEncryptionmethod(mPhone.getText().toString()));
myRef.child("Account").child(fAuth.getUid()).child("email").setValue(AESEncryptionmethod(mEmail.getText().toString()));
myRef.child("Account").child(fAuth.getUid()).child("photo").setValue(encryptionimagestring);
myRef.child("Account").child(fAuth.getUid()).child("coin").setValue("0");
Toast.makeText(Register.this, "User created.", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), MainActivity.class).putExtra("fuid", String.valueOf(fAuth.getUid())));
} else {
Toast.makeText(Register.this, "Error!" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
mLoginHereBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), Login.class));
}
});
}
private String AESEncryptionmethod(String string) {
byte[] stringByte = string.getBytes();
byte[] encryptedByte = new byte[stringByte.length];
try {
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
encryptedByte = cipher.doFinal(stringByte);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
String returnString = null;
try {
returnString = new String(encryptedByte, "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return returnString;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// handle result of CropImageActivity
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), result.getUri());
} catch (IOException e) {
e.printStackTrace();
}
imgsourcetxtview.setText(String.valueOf(result.getUri()));
Toast.makeText(
this, "Cropping successful, Sample: " + result.getUri(), Toast.LENGTH_LONG)
.show();
encryptionimage(bitmap);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Toast.makeText(this, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
}
}
}
public void encryptionimage(Bitmap bitmap){
ByteArrayOutputStream baos=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
byte [] b=baos.toByteArray();
String string=Base64.encodeToString(b, Base64.DEFAULT);
byte[] stringByte = string.getBytes();
byte[] encryptedByte = new byte[stringByte.length];
try {
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
encryptedByte = cipher.doFinal(stringByte);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
String returnString = null;
try {
returnString = new String(encryptedByte, "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
encryptionimagestring = returnString;
}
private void detectFace(BitmapFactory.Options options) {
/*Bitmap bitmap = BitmapFactory.decodeResource(
this.getResources(), R.drawable.test1,
options
);*/
Paint paint = new Paint();
paint.setStrokeWidth(6);
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.STROKE);
Bitmap tempBitmap = Bitmap.createBitmap(bitmap.getWidth(),bitmap.getHeight(), Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(tempBitmap);
canvas.drawBitmap(bitmap,0,0,null);
FaceDetector faceDetector = new FaceDetector.Builder(Register.this).setTrackingEnabled(false)
.build();
if(!faceDetector.isOperational()){
new AlertDialog.Builder(this).setMessage("Could not set up Face Detector!").show();
return;
}
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
faces = faceDetector.detect(frame);
/*for(int i=0; i<faces.size(); i++) {
Face thisFace = faces.valueAt(i);
float x1 = thisFace.getPosition().x;
float y1 = thisFace.getPosition().y;
float x2 = x1 + thisFace.getWidth();
float y2 = y1 + thisFace.getHeight();
canvas.drawRoundRect(new RectF(x1, y1, x2, y2), 2, 2, paint);
}*/
// imageView.setImageDrawable(new BitmapDrawable(getResources(),tempBitmap));
}
}
Related
So I set up an event listener, but after checking several times, I see that it doesn't even trigger in the first place.
package com.example.globe_all;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
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.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;
public class LoginScreen extends AppCompatActivity {
private Button signup, login;
private EditText user_email, password;
private TextView errortext, forgotpassword, usernameText, passwordText, appearText;
private String checkPass;
private int count = 0;
private ImageView globe;
private FrameLayout frame;
private Boolean buttonFlag = false;
private String accessKey = "";
private FirebaseAuth mAuth;
private FirebaseDatabase database;
private DatabaseReference mDatabase;
private SharedPreferences loginPreferences;
private SharedPreferences.Editor loginPrefsEditor;
private SharedPreferences gamePrefs;
private SharedPreferences.Editor gamePrefsEditor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
signup = findViewById(R.id.signup);
login = findViewById(R.id.loginButton);
user_email = findViewById(R.id.user_email);
password = findViewById(R.id.password);
errortext = findViewById(R.id.loginerror);
usernameText = findViewById(R.id.usernametext);
passwordText = findViewById(R.id.passwordtext);
forgotpassword = findViewById(R.id.forgotpassword);
globe = findViewById(R.id.globe);
frame = findViewById(R.id.frame);
appearText = findViewById(R.id.appearText);
loginPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);
loginPrefsEditor = loginPreferences.edit();
gamePrefs = getSharedPreferences("gamePrefs", MODE_PRIVATE);
gamePrefsEditor = gamePrefs.edit();
mAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance("https://globall-326315-default-rtdb.europe-west1.firebasedatabase.app/");
mDatabase = database.getReference("user");
globe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (giveBool("first") && giveBool("second")) {
Log.d("counter", " " + count);
switch (count) {
case 0:
signup.setVisibility(View.GONE);
case 1:
login.setVisibility(View.GONE);
case 2:
usernameText.setVisibility(View.GONE);
case 3:
password.setVisibility(View.GONE);
case 4:
user_email.setVisibility(View.GONE);
case 5:
passwordText.setVisibility(View.GONE);
case 6:
forgotpassword.setVisibility(View.GONE);
case 7:
ViewGroup.LayoutParams params = frame.getLayoutParams();
params.height = 300;
params.width = 300;
frame.setLayoutParams(params);
appearText.setVisibility(View.VISIBLE);
gamePrefsEditor.clear();
gamePrefsEditor.commit();
case 8:
Intent intent = new Intent(LoginScreen.this, MainActivity.class);
finish();
startActivity(intent);
}
count++;
}
}
});
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email_user = user_email.getText().toString();
String pass = password.getText().toString();
accessKey = encrypt(email_user) + "&&&" + encrypt(pass);
Log.d("useruser", " " + mDatabase.child(accessKey));
buttonFlag = true;
}
});
mDatabase.child(accessKey).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User u = snapshot.getValue(User.class);
checkPass = u.getPassword();
Log.d("checkPass", " " + checkPass);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.d("snapshot", "Error!");
throw error.toException();
}
});
if (buttonFlag && checkPass != null) {
checkPass = decrypt(checkPass);
String email_user = user_email.getText().toString();
String pass = password.getText().toString();
Log.d("decrypt", " " + checkPass);
if (pass.equals(checkPass)) {
errortext.setVisibility(View.GONE);
String email = mDatabase.child(accessKey).child("email").toString();
mAuth.signInWithEmailAndPassword(email, pass).addOnCompleteListener(LoginScreen.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
loginPrefsEditor.putString("username", encrypt(email_user));
loginPrefsEditor.putBoolean("loggedIn", true);
loginPrefsEditor.commit();
Toast.makeText(LoginScreen.this, "Successfully logged in!", Toast.LENGTH_LONG).show();
Intent home = new Intent(LoginScreen.this, MainActivity.class);
finish();
startActivity(home);
}
});
} else {
errortext.setVisibility(View.VISIBLE);
}
} else {
errortext.setVisibility(View.VISIBLE);
}
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent signup = new Intent(LoginScreen.this, SignupScreen.class);
startActivity(signup);
finish();
}
});
}
private String decrypt (String toDec) {
String sh = "abcdefghijklmnopqrstuvwxyz";
String ab = "xytaipckejzsrlfnmhvqgubowd";
String numshuf = "0123456789";
String num = "3298561740";
StringBuilder enc = new StringBuilder();
CharacterIterator it = new StringCharacterIterator(toDec);
while (it.current() != CharacterIterator.DONE)
{
char c = it.current();
if(!Character.isDigit(it.current())) {
for (int i = 0; i < ab.length(); i++) {
if (!(ab.charAt(i) == Character.toLowerCase(c)))
continue;
if (Character.isLowerCase(it.current()))
enc.append(sh.charAt(i));
else
enc.append(Character.toUpperCase(sh.charAt(i)));
break;
}
} else if (Character.isDigit(it.current())) {
for (int i = 0; i < num.length(); i++) {
if (!(num.charAt(i) == c))
continue;
enc.append(numshuf.charAt(i));
break;
}
} else if (!Character.isLetterOrDigit(it.current()))
enc.append(it.current());
it.next();
}
return enc.toString();
}
public String encrypt (String toEnc) {
String ab = "abcdefghijklmnopqrstuvwxyz";
String sh = "xytaipckejzsrlfnmhvqgubowd";
String num = "0123456789";
String numshuf = "3298561740";
StringBuilder enc = new StringBuilder();
CharacterIterator it = new StringCharacterIterator(toEnc);
while (it.current() != CharacterIterator.DONE)
{
char c = it.current();
if(!Character.isDigit(it.current())) {
for (int i = 0; i < ab.length(); i++) {
if (!(ab.charAt(i) == Character.toLowerCase(c)))
continue;
if (Character.isLowerCase(it.current()))
enc.append(sh.charAt(i));
else
enc.append(Character.toUpperCase(sh.charAt(i)));
break;
}
} else if (Character.isDigit(it.current())) {
for (int i = 0; i < num.length(); i++) {
if (!(num.charAt(i) == c))
continue;
enc.append(numshuf.charAt(i));
break;
}
} else if (!Character.isLetterOrDigit(it.current()))
enc.append(it.current());
it.next();
}
return enc.toString();
}
public boolean giveBool(String s) {
return gamePrefs.getBoolean(s, false);
}
}
I've updated the code, and pasted in the entirety of the code.
I've taken the addValueEventListener() out of my Onclick() method, and now I see that onDataChange does indeed trigger, but now I seem to face a problem of an Asynchronious nature, as I am still not getting a null out of my data. I am sure that the data I am trying to retrieve exists, so that's not the problem
So I figured out what was happening - seems that when I put my listener in the onClick() it wasn't triggering at all, so I took it out of there.
Then, it was always returning null so I figured it's about the async, and I went on checking how to fix that problem.
I followed the instructions and created a callback interface that was being used to retrieve the data from the database.
I called the interface in a function:
public void readData (MyCallBack myCallBack) {
mDatabase.child(accessKey).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String value = snapshot.getValue(User.class).getPassword();
myCallBack.onCallback(value);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
And the interface:
public interface MyCallBack {
void onCallback(String value);
}
I'm trying to add data to a document to Firebase Firestore. I've added a collection named users to it. Also, the read/write permissions are open for now. I'm following this doc. And I'm not able to add data to document only on this Activity. on other activity, I can add data easily
Here is my Code:
package com.example.ewulife;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.annotations.Nullable;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import de.hdodenhof.circleimageview.CircleImageView;
public class UserInfoActivity extends AppCompatActivity implements View.OnClickListener {
Button next;
FirebaseFirestore fstore;
FirebaseAuth fAuth;
String userID;
Spinner bloodgroup;
RadioGroup radioGroup;
RadioButton gender;
ArrayList<String> arrayList_blood;
ArrayAdapter<String> rr_blood;
EditText fullname,Mobile,credit,semister,cgpa;
String Fullname, Blood, Gender;
ImageView condition, upload;
CircleImageView profile_image;
StorageReference storageReference;
double cred2,semi2,cgpa2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_info);
fAuth = FirebaseAuth.getInstance();
fstore = FirebaseFirestore.getInstance();
userID = fAuth.getCurrentUser().getUid();
storageReference = FirebaseStorage.getInstance().getReference();
bloodgroup = findViewById(R.id.spinner00);
fullname = findViewById(R.id.editTextTextPersonName00);
Mobile =findViewById(R.id.editTextTextPersonName200);
next = findViewById(R.id.button1300);
upload = findViewById(R.id.imageView1600);
profile_image = findViewById(R.id.profile_image300);
credit = findViewById(R.id.editTextNumber);
semister = findViewById(R.id.editTextNumberDecimal);
cgpa = findViewById(R.id.editTextNumberDecimal2);
profile_image.setOnClickListener(this);
upload.setOnClickListener(this);
next.setOnClickListener(this);
{
radioGroup = findViewById(R.id.gender00);
arrayList_blood = new ArrayList<>();
arrayList_blood.add("Select");
arrayList_blood.add("BBA");
arrayList_blood.add("BSS in Economics");
arrayList_blood.add("BA in English");
arrayList_blood.add("LL.B (Hon’s)");
arrayList_blood.add("BSS in Sociology");
arrayList_blood.add("BSS in ISLM");
arrayList_blood.add("BS in Applied Statistics");
arrayList_blood.add("B.Sc. in ETE");
arrayList_blood.add("B.Sc. in ICE");
arrayList_blood.add("B.Sc. in CSE");
arrayList_blood.add("B.Sc. in EEE");
arrayList_blood.add("B.Pharm.");
arrayList_blood.add("B.Sc. in GEB");
arrayList_blood.add("B.Sc. in Civil Engineering");
arrayList_blood.add("B.Sc. in ECE");
arrayList_blood.add("Select");
arrayList_blood.add("MBA");
arrayList_blood.add("EMBA");
arrayList_blood.add("MDS");
arrayList_blood.add("MSS in Economics");
arrayList_blood.add("MA in English");
arrayList_blood.add("MA in ELT");
arrayList_blood.add("LL.M");
arrayList_blood.add("MPRHGD");
arrayList_blood.add("PPDM");
arrayList_blood.add("MS in Applied Statistics");
arrayList_blood.add("MS in TE");
arrayList_blood.add("MS in CSE");
arrayList_blood.add("MS in APE");
arrayList_blood.add("M. Pharm");
}
rr_blood = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_spinner_item, arrayList_blood);
bloodgroup.setAdapter(rr_blood);
int selectedId = radioGroup.getCheckedRadioButtonId();
gender = findViewById(selectedId);
StorageReference profRef = storageReference.child("ewuuser/"+userID+"profile.jpg");
profRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.get().load(uri).into(profile_image);
//Picasso.get().load(uri).into(edit_pic);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #androidx.annotation.Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1000) {
if (resultCode == Activity.RESULT_OK) {
Uri imageuri = data.getData();
profile_image.setImageURI(imageuri);
//back_pic.setImageURI(imageuri);
uploadImageToFirebase(imageuri);
}
}
}
private void uploadImageToFirebase(Uri imageUri) {
//upload
final StorageReference fileRef = storageReference.child("ewuuser/" + userID + "profile.jpg");
fileRef.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.get().load(uri).into(profile_image);
//Picasso.get().load(uri).into(back_pic);
//progressBar_prof.setVisibility(View.GONE);
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#androidx.annotation.NonNull Exception e) {
Toast.makeText(UserInfoActivity.this, "File is not Uploaded" + e, Toast.LENGTH_SHORT).show();
//progressBar_prof.setVisibility(View.GONE);
}
});
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.imageView1600) {
Intent openGalery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(openGalery, 1000);
}
if (v.getId() == R.id.button1300) {
int selectedId = radioGroup.getCheckedRadioButtonId();
gender = findViewById(selectedId);
final String name = fullname.getText().toString();
final String number = Mobile.getText().toString();
if (name.isEmpty()) {
fullname.setError("Name Required");
return;
}
if (gender == null) {
Toast.makeText(UserInfoActivity.this, "Selected Gender", Toast.LENGTH_SHORT).show();
return;
}
String blood_group = bloodgroup.getSelectedItem().toString();
if (blood_group.equals("Select")) {
Toast.makeText(UserInfoActivity.this, "Selected Department", Toast.LENGTH_SHORT).show();
return;
}
String gen = gender.getText().toString();
final String cre = credit.getText().toString();
if(cre.isEmpty()){
credit.setError("Enter Valid Credit");
Toast.makeText(UserInfoActivity.this, "Enter Valid Credit or leave it blank if you are new", Toast.LENGTH_SHORT).show();
return;
}
if((Double.parseDouble(cre))>200){
credit.setError("Enter valid Credit");
Toast.makeText(UserInfoActivity.this, "Enter valid CGPA or leave it blank if you are new", Toast.LENGTH_SHORT).show();
return;
}
final String semi = semister.getText().toString();
if(semi.isEmpty()){
semister.setError("Enter valid semister");
Toast.makeText(UserInfoActivity.this, "Enter valid Semister or leave it blank if you are new", Toast.LENGTH_SHORT).show();
return;
}
if((Double.parseDouble(semi))>20){
semister.setError("Enter valid Semister");
Toast.makeText(UserInfoActivity.this, "Enter valid CGPA or leave it blank if you are new", Toast.LENGTH_SHORT).show();
return;
}
final String cgpa1 = cgpa.getText().toString();
if(cgpa1.isEmpty()){
cgpa.setError("Enter valid CGPA");
Toast.makeText(UserInfoActivity.this, "Enter valid CGPA or leave it blank if you are new", Toast.LENGTH_SHORT).show();
return;
}
if((Double.parseDouble(cgpa1))>4){
cgpa.setError("Enter valid CGPA");
Toast.makeText(UserInfoActivity.this, "Enter valid CGPA or leave it blank if you are new", Toast.LENGTH_SHORT).show();
return;
}
final DocumentReference documentReference3 = fstore.collection("EWU_student").document(userID);
//here error 242 // documentReference3.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot documentSnapshot1, #Nullable FirebaseFirestoreException e2) {
Map<String, Object> user1 = new HashMap<>();
user1.put("Name",name);
user1.put("EWU_ID",number);
user1.put("Credit",cre);
user1.put("Semister",semi);
user1.put("Program",blood_group);
user1.put("Gender",gen);
user1.put("USER ID",userID);
user1.put("Drop",'0');
// user1.put("Profile Photo","ewuuser/"+userID+"profile.jpg");
user1.put("CGPA",cgpa1);
//here error show 260// documentReference3.set(user1).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(UserInfoActivity.this, "User Updated" + userID, Toast.LENGTH_LONG).show();
Intent intent = new Intent(UserInfoActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(UserInfoActivity.this, "User not updated 3 " + e.toString(), Toast.LENGTH_LONG).show();
}
});
}
});
}
}
}
In Logs I see only these thing and can not under the problem:
2021-03-20 15:15:05.637 8348-8348/com.example.ewulife E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ewulife, PID: 8348
java.lang.IllegalArgumentException: Could not serialize object. Characters are not supported, please use Strings (found in field 'Drop')
at com.google.firebase.firestore.util.CustomClassMapper.serializeError(CustomClassMapper.java:555)
at com.google.firebase.firestore.util.CustomClassMapper.serialize(CustomClassMapper.java:133)
at com.google.firebase.firestore.util.CustomClassMapper.serialize(CustomClassMapper.java:140)
at com.google.firebase.firestore.util.CustomClassMapper.serialize(CustomClassMapper.java:104)
at com.google.firebase.firestore.util.CustomClassMapper.convertToPlainJavaTypes(CustomClassMapper.java:78)
at com.google.firebase.firestore.UserDataReader.convertAndParseDocumentData(UserDataReader.java:231)
at com.google.firebase.firestore.UserDataReader.parseSetData(UserDataReader.java:75)
at com.google.firebase.firestore.DocumentReference.set(DocumentReference.java:167)
at com.google.firebase.firestore.DocumentReference.set(DocumentReference.java:147)
**at com.example.ewulife.UserInfoActivity$4.onEvent(UserInfoActivity.java:260)
at com.example.ewulife.UserInfoActivity$4.onEvent(UserInfoActivity.java:242)**
at com.google.firebase.firestore.DocumentReference.lambda$addSnapshotListenerInternal$2(DocumentReference.java:505)
at com.google.firebase.firestore.DocumentReference$$Lambda$3.onEvent(Unknown Source:6)
at com.google.firebase.firestore.core.AsyncEventListener.lambda$onEvent$0(AsyncEventListener.java:42)
at com.google.firebase.firestore.core.AsyncEventListener$$Lambda$1.run(Unknown Source:6)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
the error part is
**at com.example.ewulife.UserInfoActivity$4.onEvent(UserInfoActivity.java:260)
at com.example.ewulife.UserInfoActivity$4.onEvent(UserInfoActivity.java:242)**
**There are the sreenshot 1
There are the screenshot 2
**
Write this code user1.put("Drop","0") instead of this
user1.put("Drop",'0')
I keep getting this error
Attempt to invoke virtual method 'void com.google.firebase.database.DatabaseReference.addListenerForSingleValueEvent(com.google.firebase.database.ValueEventListener)' on a null object reference
and I don't know how to fix it. How can I correct it?
Code:
package com.example.macdate;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
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.auth.FirebaseUser;
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 java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.io.IOException;
public class SettingsActivity extends AppCompatActivity {
private EditText mNameField, mPhoneField;
private Button mBack, mConfirm;
private ImageView mProfileImage;
private FirebaseAuth mAuth;
private DatabaseReference mCustomerDatabase;
private String userId, name, phone, profileImageUrl;
private Uri resultUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
String userSex = getIntent().getExtras().getString("userSex");
mNameField = (EditText) findViewById(R.id.name);
mPhoneField = (EditText) findViewById(R.id.phone);
mProfileImage = (ImageView) findViewById(R.id.profileImage);
mBack = (Button) findViewById(R.id.back);
mConfirm = (Button) findViewById(R.id.confirm);
mAuth = FirebaseAuth.getInstance();
FirebaseUser mFirebaseUser = mAuth.getCurrentUser();
if(mFirebaseUser != null && userSex != null) {
userId = mFirebaseUser.getUid();
mCustomerDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(userSex).child(userId);
}
getUserInfo();
mProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 1);
}
});
mConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveUserInformation();
}
});
mBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
return;
}
});
}
private void getUserInfo() {
mCustomerDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists() && dataSnapshot.getChildrenCount()>0){
Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
if(map.get("name")!=null){
name = map.get("name").toString();
mNameField.setText(name);
}
if(map.get("phone")!=null){
phone = map.get("phone").toString();
mPhoneField.setText(phone);
}
if(map.get("profileImageUrl")!=null){
profileImageUrl = map.get("profileImageUrl").toString();
switch(profileImageUrl){
case "default":
Glide.with(getApplication()).load(R.mipmap.ic_launcher).into(mProfileImage);
break;
default:
Glide.with(getApplication()).load(profileImageUrl).into(mProfileImage);
break;
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void saveUserInformation() {
name = mNameField.getText().toString();
phone = mPhoneField.getText().toString();
Map userInfo = new HashMap();
userInfo.put("name", name);
userInfo.put("phone", phone);
mCustomerDatabase.updateChildren(userInfo);
if(resultUri != null){
StorageReference filepath = FirebaseStorage.getInstance().getReference().child("profileImages").child(userId);
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getApplication().getContentResolver(), resultUri);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = filepath.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
finish();
}
});
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> downloadUrl = taskSnapshot.getMetadata().getReference().getDownloadUrl();
Map userInfo = new HashMap();
userInfo.put("profileImageUrl", downloadUrl.toString());
mCustomerDatabase.updateChildren(userInfo);
finish();
return;
}
});
}else{
finish();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == Activity.RESULT_OK){
final Uri imageUri = data.getData();
resultUri = imageUri;
mProfileImage.setImageURI(resultUri);
}
}
}
Here is the logcat
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.firebase.database.DatabaseReference.addListenerForSingleValueEvent(com.google.firebase.database.ValueEventListener)' on a null object reference
at com.example.macdate.SettingsActivity.getUserInfo(SettingsActivity.java:101)
at com.example.macdate.SettingsActivity.onCreate(SettingsActivity.java:74)
at android.app.Activity.performCreate(Activity.java:7009)
at android.app.Activity.performCreate(Activity.java:7000)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Put getUserInfo() mothod in the if statement
if(mFirebaseUser != null && userSex != null) {
userId = mFirebaseUser.getUid();
mCustomerDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(userSex).child(userId);
getUserInfo()
}
Here in this class i m generating the qRcode and saving it tot the firebase storage everything is working fine but problem is everytime the qrcode is saved with same name i.e "QR Codes".I want to save the qRcode with different name for diffrent user in QRCodes Folder of Firebase Storage.
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.ExifInterface;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
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.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.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageMetadata;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import java.io.ByteArrayOutputStream;
import static android.R.attr.bitmap;
public class Register extends AppCompatActivity {
//firebase auth object
private FirebaseAuth firebaseAuth;
private StorageReference mStorage;
private DatabaseReference mDatabse;
//our new views
private EditText editTextName, editTextAddress, editTextEmail, editTextPhoneOrRid, editTextPassword;
private Button buttonSave;
private ProgressDialog progressDialog;
public final static int QRcodeWidth = 500;
private Bitmap bitmap;
private FirebaseUser user;
private ExifInterface exif;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
progressDialog = new ProgressDialog(this);
firebaseAuth = FirebaseAuth.getInstance();
user = firebaseAuth.getCurrentUser();
mDatabse = FirebaseDatabase.getInstance().getReferenceFromUrl("https://lpuevents-8f661.firebaseio.com/AppUsers");
mStorage = FirebaseStorage.getInstance().getReferenceFromUrl("gs://lpuevents-8f661.appspot.com/QR codes/");
//getting the views from xml resource
editTextAddress = (EditText) findViewById(R.id.editText7);
editTextName = (EditText) findViewById(R.id.editText3);
editTextEmail = (EditText) findViewById(R.id.editText4);
editTextPhoneOrRid = (EditText) findViewById(R.id.editText6);
editTextPassword = (EditText) findViewById(R.id.editText8);
buttonSave = (Button) findViewById(R.id.button3);
if (user == null) {
//closing this activity
finish();
//starting login activity
startActivity(new Intent(this, Login.class));
}
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveUserInformation();
// wait(360000);
registerUser();
}
});
}
Bitmap TextToImageEncode(String Value) throws WriterException {
BitMatrix bitMatrix;
try {
bitMatrix = new MultiFormatWriter().encode(
Value,
BarcodeFormat.DATA_MATRIX.QR_CODE,
QRcodeWidth, QRcodeWidth, null
);
} catch (IllegalArgumentException Illegalargumentexception) {
return null;
}
int bitMatrixWidth = bitMatrix.getWidth();
int bitMatrixHeight = bitMatrix.getHeight();
int[] pixels = new int[bitMatrixWidth * bitMatrixHeight];
for (int y = 0; y < bitMatrixHeight; y++) {
int offset = y * bitMatrixWidth;
for (int x = 0; x < bitMatrixWidth; x++) {
pixels[offset + x] = bitMatrix.get(x, y) ?
getResources().getColor(R.color.black) : getResources().getColor(R.color.white);
}
}
Bitmap bitmap = Bitmap.createBitmap(bitMatrixWidth, bitMatrixHeight, Bitmap.Config.ARGB_4444);
bitmap.setPixels(pixels, 0, 500, 0, 0, bitMatrixWidth, bitMatrixHeight);
return bitmap;
}
private void saveUserInformation() {
//Getting values from database
final String name = editTextName.getText().toString().trim();
final String address = editTextAddress.getText().toString().trim();
final String email = editTextEmail.getText().toString().trim();
final String phone = editTextPhoneOrRid.getText().toString().trim();
//String id = user.getUid().trim();
try {
bitmap = TextToImageEncode(phone+" "+email);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = mStorage.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
Toast.makeText(Register.this, "Succesfully Saved...", Toast.LENGTH_LONG).show();
DatabaseReference userInfo = mDatabse.push();
Uri downloadUrl = taskSnapshot.getDownloadUrl();
taskSnapshot.getMetadata();
userInfo.child("name").setValue(name);
userInfo.child("email").setValue(email);
userInfo.child("address").setValue(address);
userInfo.child("phone").setValue(phone);
userInfo.child("image").setValue(downloadUrl.toString());
}
});
//imageView.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
}
private void registerUser() {
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
//checking if email and passwords are empty
if (TextUtils.isEmpty(email)) {
Toast.makeText(this, "Please enter email", Toast.LENGTH_LONG).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(this, "Please enter password", Toast.LENGTH_LONG).show();
return;
}
progressDialog.setMessage("Registering Please Wait...");
progressDialog.show();
progressDialog.dismiss();
//creating a new user
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//checking if success
if (task.isSuccessful()) {
//display some message here
Toast.makeText(Register.this, "Successfully registered", Toast.LENGTH_LONG).show();
} else {
//display some message here
Toast.makeText(Register.this, "Registration Error", Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
}
});
}
}
The issue comes with these two lines:
mStorage = FirebaseStorage.getInstance().getReferenceFromUrl("gs://.../QR codes/");
...
UploadTask uploadTask = mStorage.putBytes(data);
This means that you're uploading to a file named QR%20codes and overwriting it. Instead you need to add a distinct identifier to each file being uploaded:
UploadTask uploadTask = mStorage.child(some-generated-uuid).putBytes(data); // "QR%20codes/some-generated-uuid"
Read our docs on creating references, which hopefully provides some more information. If you're looking for unique names, see this SO post on the subject.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
Is there any api for facebook to integration in android?
I got a requirement to publish images to facebook through android application.
Please give links or suggestions regarding this..
If you had taken the time to Google "Android Facebook SDK" you'd have immediately found the official Android Facebook SDK: http://github.com/facebook/facebook-android-sdk
Having used it in a project I can say it's a little rough around the edges as the new oAuth / Graph API based stuff is quite young, but it works well with a little tweaking.
import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import com.sun.medialib.mlib.Image;
import net.xeomax.FBRocket.FBRocket;
import net.xeomax.FBRocket.Facebook;
import net.xeomax.FBRocket.LoginListener;
import net.xeomax.FBRocket.ServerErrorException;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Handler.Callback;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
public class TestRocket extends Activity implements LoginListener {
public FBRocket fbRocket;
public static String currentFileName ;
public final String images[] = {"http://safesport.site40.net/tv.jpg"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
shareFacebook();
}
public void shareFacebook() {
fbRocket = new FBRocket(this, "test",
"ommited");
if (fbRocket.existsSavedFacebook()) {
fbRocket.loadFacebook();
return;
} else {
//fbRocket.login(R.layout.testrocket);
fbRocket.login(R.layout.testrocket);
}
}
public void onLoginFail() {
fbRocket.displayToast("Login failed!");
//fbRocket.login(R.layout.correr);
}
public String setFileName(String filename) {
// TODO Auto-generated method stub
TestRocket.currentFileName = filename;
return filename;
}
public void onLoginSuccess(Facebook facebook) {
SimpleDateFormat sdf = new SimpleDateFormat("dd:MM:yyyy");
SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm:ss");
String data = sdf.format(new Date());
String time = sdf1.format(new Date());
try {
facebook.setStatus("Start Walk:"+time+"\n"+ "Day:"+data+"\n"+"Where:"+"\n"
+"http://maps.google.com/?q=http://safesport.site40.net/"+currentFileName);
fbRocket.displayToast("Status Posted Successfully!! ");
return ;
} catch (ServerErrorException e) {
if (e.notLoggedIn()) {
fbRocket.login(R.layout.ciclismo);
} else {
System.out.println(e);
}
}
}
}
I explained the process in detail together with a simple sample code. You can find it here:
http://developer.blog.appxtream.com/?p=34
Download source code from here (https://deepshikhapuri.wordpress.com/2017/04/07/get-location-of-facebook-user-using-graph-api-in-android/)
package facebooklocation.facebooklocation;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import org.json.JSONObject;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
CallbackManager callbackManager;
ImageView iv_image, iv_facebook;
TextView tv_name, tv_email, tv_dob, tv_location, tv_facebook;
LinearLayout ll_facebook;
String str_facebookname, str_facebookemail, str_facebookid, str_birthday, str_location;
boolean boolean_login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
getKeyHash();
listener();
}
private void init() {
iv_image = (ImageView) findViewById(R.id.iv_image);
iv_facebook = (ImageView) findViewById(R.id.iv_facebook);
tv_name = (TextView) findViewById(R.id.tv_name);
tv_email = (TextView) findViewById(R.id.tv_email);
tv_dob = (TextView) findViewById(R.id.tv_dob);
tv_location = (TextView) findViewById(R.id.tv_location);
tv_facebook = (TextView) findViewById(R.id.tv_facebook);
ll_facebook = (LinearLayout) findViewById(R.id.ll_facebook);
FacebookSdk.sdkInitialize(this.getApplicationContext());
}
private void listener() {
tv_facebook.setOnClickListener(this);
ll_facebook.setOnClickListener(this);
iv_facebook.setOnClickListener(this);
}
private void facebookLogin() {
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.e("ONSUCCESS", "User ID: " + loginResult.getAccessToken().getUserId()
+ "\n" + "Auth Token: " + loginResult.getAccessToken().getToken()
);
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
boolean_login = true;
tv_facebook.setText("Logout from Facebook");
Log.e("object", object.toString());
str_facebookname = object.getString("name");
try {
str_facebookemail = object.getString("email");
} catch (Exception e) {
str_facebookemail = "";
e.printStackTrace();
}
try {
str_facebookid = object.getString("id");
} catch (Exception e) {
str_facebookid = "";
e.printStackTrace();
}
try {
str_birthday = object.getString("birthday");
} catch (Exception e) {
str_birthday = "";
e.printStackTrace();
}
try {
JSONObject jsonobject_location = object.getJSONObject("location");
str_location = jsonobject_location.getString("name");
} catch (Exception e) {
str_location = "";
e.printStackTrace();
}
fn_profilepic();
} catch (Exception e) {
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, name, email,gender,birthday,location");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
if (AccessToken.getCurrentAccessToken() == null) {
return; // already logged out
}
new GraphRequest(AccessToken.getCurrentAccessToken(), "/me/permissions/", null, HttpMethod.DELETE, new GraphRequest
.Callback() {
#Override
public void onCompleted(GraphResponse graphResponse) {
LoginManager.getInstance().logOut();
LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile,email"));
facebookLogin();
}
}).executeAsync();
}
#Override
public void onError(FacebookException e) {
Log.e("ON ERROR", "Login attempt failed.");
AccessToken.setCurrentAccessToken(null);
LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile,email,user_birthday"));
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
callbackManager.onActivityResult(requestCode, resultCode, data);
} catch (Exception e) {
}
}
private void getKeyHash() {
// Add code to print out the key hash
try {
PackageInfo info = getPackageManager().getPackageInfo("facebooklocation.facebooklocation", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
private void fn_profilepic() {
Bundle params = new Bundle();
params.putBoolean("redirect", false);
params.putString("type", "large");
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"me/picture",
params,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
Log.e("Response 2", response + "");
try {
String str_facebookimage = (String) response.getJSONObject().getJSONObject("data").get("url");
Log.e("Picture", str_facebookimage);
Glide.with(MainActivity.this).load(str_facebookimage).skipMemoryCache(true).into(iv_image);
} catch (Exception e) {
e.printStackTrace();
}
tv_name.setText(str_facebookname);
tv_email.setText(str_facebookemail);
tv_dob.setText(str_birthday);
tv_location.setText(str_location);
}
}
).executeAsync();
}
#Override
public void onClick(View view) {
if (boolean_login) {
boolean_login = false;
LoginManager.getInstance().logOut();
tv_location.setText("");
tv_dob.setText("");
tv_email.setText("");
tv_name.setText("");
Glide.with(MainActivity.this).load(R.drawable.profile).into(iv_image);
tv_facebook.setText("Login with Facebook");
} else {
LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile,email,user_birthday,user_location"));
facebookLogin();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
LoginManager.getInstance().logOut();
}
}