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.
Related
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));
}
}
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()
}
When I try to upload the image and click the submit button, the logcat show out this message.
Logcat Result
2018-10-15 22:21:32.191 22289-22477/com.example.edward.neweventmanagementsystem E/StorageUtil: error getting token java.util.concurrent.ExecutionException: com.google.firebase.internal.api.FirebaseNoSignedInUserException: Please sign in before trying to get a token.
Java File
package com.example.edward.neweventmanagementsystem;
import android.Manifest;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
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.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.edward.neweventmanagementsystem.Model.EventInfo;
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.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.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.util.Calendar;
import java.util.regex.Pattern;
import static android.widget.Toast.LENGTH_SHORT;
public class CreateEvent extends AppCompatActivity {
private static final String TAG = "activity_create_event";
private Uri filePath;
private TextView mDisplayDate;
private DatePickerDialog.OnDateSetListener mDateSetListener;
private DatabaseReference mDatabaseReference;
private Button mRegisterButton;
EditText mEventNameText, mContactNumText, mEventLocationText, mRegisterEventId;;
TextView mEventDate;
RadioGroup mEventType;
FirebaseStorage storage;
StorageReference storageRef,imageRef;
Uri uriImage ;//= Uri.parse("com.example.edward.eventmanagementsystem.ManageEvent/"+ R.drawable.ic_launcher_background);
public static final int PICK_IMAGE = 1;
ImageView mimageToUpload;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_event);
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
FirebaseDatabase firebaseDatabase;
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("ListOfEvent"); //.push();
mRegisterButton = (Button)findViewById(R.id.btnRegisterEvent);
storage = FirebaseStorage.getInstance();
storageRef = storage.getReference();
mDisplayDate = (TextView) findViewById(R.id.RegisterEventStartDate);
mDisplayDate.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(
CreateEvent.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 view, int year, int month, int day) {
month = month + 1;
Log.d(TAG, "onDateSet: date: mm/dd/yyyy: " + month + "/" + day + "/" + year);
String date = month + "/" + day + "/" + year;
mDisplayDate.setText(date);
}
};
//insert data to database
mRegisterEventId = (EditText) findViewById(R.id.RegisterEventId);
mEventNameText = (EditText) findViewById(R.id.RegisterEventName);
mContactNumText = (EditText) findViewById(R.id.RegisterContactNumber);
mEventDate = (TextView) findViewById(R.id.RegisterEventStartDate);
mEventType = (RadioGroup) findViewById(R.id.RegisterEventRadiogroup);
mEventLocationText = (EditText) findViewById(R.id.RegisterEventLocation);
mimageToUpload = (ImageView) findViewById(R.id.imageToUpload);
mRegisterButton = (Button) findViewById(R.id.btnRegisterEvent);
mimageToUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(CreateEvent.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
selectPdf();
}
else {
ActivityCompat.requestPermissions(CreateEvent.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},9);
}
}
});
mRegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog mDialog = new ProgressDialog(CreateEvent.this);
mDialog.setMessage("Please waiting...");
mDialog.show();
int selectedId = mEventType.getCheckedRadioButtonId();
final RadioButton radioButton = (RadioButton)findViewById(selectedId);
final String id = mRegisterEventId.getText().toString().trim();
final String name = mEventNameText.getText().toString().trim();
final String contact = mContactNumText.getText().toString().trim();
final String date = mEventDate.getText().toString().trim();
final String type = radioButton.getText().toString().trim();
final String location = mEventLocationText.getText().toString().trim();
if (TextUtils.isEmpty(id)) {
mRegisterEventId.setError("Enter Event ID!");
return;
}
if (TextUtils.isEmpty(name)) {
mEventNameText.setError("Enter Event Name!");
return;
}
if (TextUtils.isEmpty(location)) {
mEventLocationText.setError("Enter Location!");
return;
}
if (TextUtils.isEmpty(type)) {
radioButton.setError("Please select type of event type!");
return;
}
if(isValidPhone(contact)){
Toast.makeText(getApplicationContext(),"Phone number is valid",Toast.LENGTH_SHORT).show();
}else {
mContactNumText.setError("Phone number is not valid");
Toast.makeText(getApplicationContext(),"Phone number is not valid",Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(date)) {
mEventDate.setError("Please select event date!");
return;
}
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.child(mRegisterEventId.getText().toString()).exists()) {
mDialog.dismiss();
Toast.makeText(CreateEvent.this, "ID already exists!", Toast.LENGTH_SHORT).show();
}else {
mDialog.dismiss();
EventInfo eventInfo = new EventInfo(mRegisterEventId.getText().toString().trim(),mEventNameText.getText().toString().trim(), mContactNumText.getText().toString().trim(), mEventDate.getText().toString().trim(), radioButton.getText().toString().trim(), mEventLocationText.getText().toString().trim());
mDatabaseReference.child(mRegisterEventId.getText().toString()).setValue(eventInfo);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
final String fileName = System.currentTimeMillis()+"";
if(uriImage != null) {
final StorageReference storageReference = storage.getReference();
System.out.println(uriImage);
storageReference.child("profileImageUrl").child(fileName).putFile(uriImage)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
String url = taskSnapshot.getMetadata().getReference().getDownloadUrl().toString();
// Uri downloadUrl = taskSnapshot.getMetadata().getReference().getDownloadUrl().getResult();
// String urlImage = downloadUrl.toString();
mDatabaseReference.child(id).child("profileImageUrl").setValue(url).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
System.out.println(taskSnapshot.getUploadSessionUri().toString());
}
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{
}
Toast.makeText(getApplicationContext(),"New event created successfully!",LENGTH_SHORT).show();
Intent ManageEventMenu = new Intent(CreateEvent.this, com.example.edward.neweventmanagementsystem.ManageEventMenu.class);
startActivity(ManageEventMenu);
}
});
}
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;
}
private void selectPdf() {
Intent photoPickerIntent = new Intent();
photoPickerIntent .setType("image/*");
photoPickerIntent .setAction(Intent.ACTION_OPEN_DOCUMENT);
startActivityForResult(photoPickerIntent ,86);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 86 && resultCode == RESULT_OK && data != null){
final Uri imageUri = data.getData();
uriImage = imageUri;
mimageToUpload.setImageURI(uriImage);
}
else {
Toast.makeText(getApplicationContext(),"Please select file", LENGTH_SHORT).show();
}
}
}
Anyone know how to solve this problem. Thanks a lot.
Also that, I also face problem when try to display the message in my apps. There was no problem with other field such as Text, RadioButton, Date, only photo I unable to up the real url.
fyi. currenly the url display in firebase database is the photo storage location
It seems like the user is not signed (authenticated from the Firebase ) .
their is two method to solve the problem
1)authenticate the user using authentication
2)set your rule to public for fire-base real-time database
copy and paste this rule in Firebase real-time database >rule
{
"rules": {
".read": true,
".write": true
}
}
But doing this will make
your security rules are defined as public, so anyone can steal, modify or delete data in your database
The Exception clearly says that you are trying to perform operations without having the user logged in.
You can follow this manuel to authenticate and then perform your operations
https://firebase.google.com/docs/auth/android/password-auth
I have this code in android studio for an app, I am trying to read from a file for the information of the login but anything after BufferedReader is not executing.
both the registration and login page open, the first page in the app i have sa login button and a registration button, when i click on the login button nothng happen, not even checking if the user exist or not
I tried many ways for reading and writing to a file but I couldn't figure out the error
it is not reading anything and not writing any thing, it simply does nothing.
this is the login page
package com.example.admin.projectfinal;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.admin.projectfinal.val.inputValidation;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class LoginActivity extends AppCompatActivity {
private inputValidation InputValidation;
private TextInputLayout IDLayout;
private TextInputLayout PASSWORDlayout;
private TextInputEditText LogID;
private TextInputEditText PASS;
Button SI;
TextView TV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().hide();
PASS = findViewById(R.id.password);
LogID = findViewById(R.id.idd);
IDLayout = findViewById(R.id.IDLayout);
PASSWORDlayout = findViewById(R.id.PasswordLayout);
TV = findViewById(R.id.tv);
SI = findViewById(R.id.signin);
SI.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
}
});
TV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Navigate to RegisterActivity
Toast.makeText(LoginActivity.this, "we are in tv.", Toast.LENGTH_LONG).show();
Intent intentRegister = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intentRegister);
}
});
InputValidation = new inputValidation(LoginActivity.this);
}
private void login() {
if (!InputValidation.isInputEditTextFilled(LogID, IDLayout, "ID not filled ")) return;
if (!InputValidation.isInputEditTextFilled(PASS, PASSWORDlayout, "Password not filled"))
return;
TextView FileContentTextView = findViewById(R.id.tv_file_content);
try {
File f = new File ("User.txt");
BufferedReader reader = new BufferedReader(new FileReader(f));
if (reader.ready()) {
FileContentTextView.setText("No User registered");
return;
} else {
Toast.makeText(LoginActivity.this, "else", Toast.LENGTH_LONG).show();
boolean found = false;
String role = null;
String line;
while ((line = reader.readLine()) != null) {
Toast.makeText(LoginActivity.this, "while", Toast.LENGTH_LONG).show();
StringTokenizer user = new StringTokenizer(line);
String name = user.nextToken();
String Id = user.nextToken();
String dob = user.nextToken();
String pas = user.nextToken();
String Campus = user.nextToken();
String gender = user.nextToken();
role = user.nextToken();
if (LogID.equals(Id)) {
Toast.makeText(LoginActivity.this, "id is good", Toast.LENGTH_LONG).show();
if (PASS.equals(pas)) {
Toast.makeText(LoginActivity.this, "pass good", Toast.LENGTH_LONG).show();
found = true;
break;
}
}
if (found) {
Toast.makeText(LoginActivity.this, "break.", Toast.LENGTH_LONG).show();
break;
}
}
if (found) {
Toast.makeText(LoginActivity.this, "found", Toast.LENGTH_LONG).show();
if (role.equals("Security")) {
Intent accountsIntent = new Intent(LoginActivity.this, SecurityPage.class);
accountsIntent.putExtra("ID", LogID.getText().toString().trim());
} else {
Intent accountsIntent = new Intent(LoginActivity.this, StudentPage.class);
accountsIntent.putExtra("ID", LogID.getText().toString().trim());
}
} else
reader.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
this is the registration code, it has the same problem where anything after the BufferedReader is not executing.
package com.example.admin.projectfinal;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.admin.projectfinal.val.inputValidation;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{
private TextInputLayout textInputLayoutName;
private TextInputLayout textInputLayoutId;
private TextInputLayout textInputLayoutPassword;
private TextInputLayout textInputLayoutDate;
TextInputEditText Name;
TextInputEditText id;
TextInputEditText Password;
TextInputEditText DOB;
Spinner campus;
Spinner Role;
Spinner Gender;
Button btn;
Button Cancel;
private inputValidation InputValidation;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Name = findViewById(R.id.name);
id = findViewById(R.id.ID);
Password = findViewById(R.id.password);
DOB = findViewById(R.id.dob);
btn = findViewById(R.id.next);
Cancel = findViewById(R.id.cancel);
campus = findViewById(R.id.campus);
Gender = findViewById(R.id.gender);
Role = findViewById(R.id.role);
textInputLayoutName = findViewById(R.id.NameLayout);
textInputLayoutId = findViewById(R.id.IdLayout);
textInputLayoutPassword = findViewById(R.id.PasswordLayout);
textInputLayoutDate = findViewById(R.id.DOBLayout);
//list for campus
String[] CampusList = new String[]{"MainCampus", "SasAlNakhlCampus", "MasdarCampus"};
ArrayAdapter<String> adapter1 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, CampusList);
campus.setAdapter(adapter1);
//list for gender
String[] gen = new String[]{"Male", "Female"};
ArrayAdapter<String> genAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, gen);
Gender.setAdapter(genAdapter);
//list for role
String[] rolee = new String[]{"Student", "Security"};
ArrayAdapter<String> roleAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, rolee);
Role.setAdapter(roleAdapter);
// Buttons validation
btn.setOnClickListener(this);
Cancel.setOnClickListener(this);
InputValidation = new inputValidation(RegisterActivity.this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.next:
try {
validate();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
break;
case R.id.cancel:
// Navigate to RegisterActivity
Intent intentRegister = new Intent(this, LoginActivity.class);
startActivity(intentRegister);
break;
}
}
private void validate() throws IOException {
boolean filled = true;
if (!InputValidation.isInputEditTextFilled(Name, textInputLayoutName, "Fill Name")) {
filled = false;
return;
}
if (!InputValidation.isInputEditTextFilled(id, textInputLayoutId, "Fill ID")) {
filled = false;
return;
}
if (!InputValidation.isInputEditTextFilled(DOB, textInputLayoutDate, "Fill Date")) {
filled = false;
return;
}
if (!InputValidation.isInputEditTextFilled(Password, textInputLayoutPassword, "Invalid Password")) {
filled = false;
return;
}
if (filled){
//if (!UserInfo.exists()) UserInfo.createNewFile();
String line;
boolean found = false;
BufferedReader reader= new BufferedReader(new FileReader("User.txt"));
Toast.makeText(getBaseContext(), "ready", Toast.LENGTH_LONG).show();
while ((line = reader.readLine()) != null) {
Toast.makeText(getBaseContext(), "while", Toast.LENGTH_LONG).show();
String[] user = line.split(" ");
String name = user[0];
String Id = user[1];
String dob = user[2];
String password = user[3];
String Campus = user[4];
String gender = user[5];
String role = user[6];
if (id.equals(Id)) {
found = true;
Toast.makeText(getBaseContext(), "User Exist", Toast.LENGTH_LONG).show();
break;
}
if (!found) {
// Adds a line to the file
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("User.txt")));
writer.append(Name + " " + id + " " + DOB + " " + Password + " "
+ campus.getSelectedItem() + " " + Gender.getSelectedItem() + " " + Role.getSelectedItem() + "/n" );
}
}
reader.close();
}
}
}
Input validation class I used in the code:
package com.example.admin.projectfinal.val;
import android.app.Activity;
import android.content.Context;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
public class inputValidation {
private static Context context;
/**
* constructor
*
* #param context
*/
public inputValidation(Context context) {
this.context = context;
}
/**
* method to check InputEditText filled .
*
* #param textInputEditText
* #param textInputLayout
* #param message
* #return
*/
public static boolean isInputEditTextFilled(TextInputEditText textInputEditText, TextInputLayout textInputLayout, String message) {
String value = textInputEditText.getText().toString().trim();
if (value.isEmpty()) {
textInputLayout.setError(message);
hideKeyboardFrom(textInputEditText);
return false;
} else {
textInputLayout.setErrorEnabled(false);
}
return true;
}
/**
* method to Hide keyboard
*
* #param view
*/
private static void hideKeyboardFrom(View view) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
}