Unable to upload right photo URL to firebase - android

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

Related

Why I am not able to add Data to Firestore

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')

App crashes everytime the "settings" button is hit, how can I debug?

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()
}

Getting Error in onResponse in Retrofit

I am a newbie to the android world. I am trying to develop an app for my school project and stumble upon this issue. please someone help me.
My fragment code is bellow. Where I want to fill up a form with Image and upload to PHP, Mysql server for registration. But the app is crashing.
package com.dgdev.mtmicds;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.support.v4.app.Fragment;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatImageView;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.dgdev.mtmicds.DbAccess.Remote.APIClient;
import com.dgdev.mtmicds.DbAccess.Remote.ApiInterface;
import com.dgdev.mtmicds.DbAccess.Remote.UserRegistrationModel;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static android.app.Activity.RESULT_OK;
import static android.provider.MediaStore.Images.Media.*;
import static android.support.v4.content.PermissionChecker.checkSelfPermission;
/**
* A simple {#link Fragment} subclass.
*/
public class ProfileFragment extends Fragment {
View view;
AppCompatImageView imageView;
AppCompatEditText etFullname, etEmail, etDob, etMobile, etPsw, etRePsw, etAddr;
AppCompatButton btnRegister, btnCancel;
private static final int IMAGE_REQUEST = 7777;
Bitmap bitmap;
public ProfileFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_profile, container, false);
imageView = (AppCompatImageView) view.findViewById(R.id.ProfileDP);
etFullname = (AppCompatEditText) view.findViewById(R.id.tvfullanme);
etEmail = (AppCompatEditText) view.findViewById(R.id.tvemail);
etDob = (AppCompatEditText) view.findViewById(R.id.tvdob);
etPsw = (AppCompatEditText) view.findViewById(R.id.tvpsw);
etRePsw = (AppCompatEditText) view.findViewById(R.id.tvpsw_re);
etAddr = (AppCompatEditText) view.findViewById(R.id.tvaddr);
etMobile = (AppCompatEditText) view.findViewById(R.id.tvmobile);
btnRegister = (AppCompatButton) view.findViewById(R.id.btnRegister);
btnCancel = (AppCompatButton) view.findViewById(R.id.btnCancel);
/*-----------------------------------------------------------------------------*/
/* this onClickListener will be responsible for getting image URI from gallery */
/*-----------------------------------------------------------------------------*/
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImageFromGallery();
}
});
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadData();
}
});
return view;
}
private void uploadData() {
String fullname = etFullname.getText().toString();
String dob = convertTOMysqlDate(etDob.getText().toString());
String mobile = etMobile.getText().toString();
String addr = etAddr.getText().toString();
String psw = etPsw.getText().toString();
String prof_pic = imageToString();
Toast.makeText(view.getContext(), dob, Toast.LENGTH_LONG).show();
ApiInterface apiInterface = APIClient.GetClient().create(ApiInterface.class);
Call<UserRegistrationModel> call = apiInterface.RegisterUser(fullname, dob, mobile, addr, psw, prof_pic);
call.enqueue(new Callback<UserRegistrationModel>() {
#Override
public void onResponse(Call<UserRegistrationModel> call, Response<UserRegistrationModel> response) {
UserRegistrationModel res = response.body();
Toast.makeText(view.getContext(), res.getStatus(), Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(Call<UserRegistrationModel> call, Throwable t) {
Toast.makeText(view.getContext(), "You are not able to talk to server!", Toast.LENGTH_LONG).show();
}
});
}
private String convertTOMysqlDate(String s) {
String $MysqlDateString;
String[] DateParts = s.split("/");
$MysqlDateString = DateParts[2] + "-" + DateParts[1] + "-" + DateParts[0];
return $MysqlDateString;
}
private void selectImageFromGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, IMAGE_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
Uri path = data.getData();
try {
bitmap = getBitmap(getActivity().getApplicationContext().getContentResolver(), path);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String imageToString() {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, outputStream);
byte[] ImageBytes = outputStream.toByteArray();
return Base64.encodeToString(ImageBytes, Base64.DEFAULT);
}
}
And I am getting bellow message in logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.dgdev.mtmicds.DbAccess.Remote.UserRegistrationModel.getStatus()' on a null object reference
at com.dgdev.mtmicds.ProfileFragment$3.onResponse(ProfileFragment.java:105)
Please Help me...I am a newbie...
Try this
#Override
public void onResponse(Call<UserRegistrationModel> call, Response<UserRegistrationModel> response) {
if(response.isSuccessful()) {
UserRegistrationModel res = response.body();
if(res!=null) {
Toast.makeText(view.getContext(), res.getStatus(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(view.getContext(), "Didn't get response", Toast.LENGTH_LONG).show();
}
}
}
Your com.dgdev.mtmicds.DbAccess.Remote.UserRegistrationModel is null. Check whether it is being alloted any value by getting in debug mode. Run the code step by step in debug mode and check how it is getting initialized.
Hint: Check this line of your code in debugger:
UserRegistrationModel res = response.body();

QRCode bitmap Uploading To Fiebase Databse with different filename

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.

Android Parse.com android allow to get data from table but not for update

package symca.gescoe.com.sampleparseapp.payment_task;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import symca.gescoe.com.sampleparseapp.R;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.FindCallback;
import com.parse.GetCallback;
import com.parse.ParseACL;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import java.util.List;
public class PayRent extends Activity {
TextView ownerName, ownerEmail, ownerPropType, ownerLocation, ownerAccountNo, renterAccountNo;
EditText propId;
int confirmFlag = 0;
int rentFinal = 0, mainFinal = 0, totalFinal = 0;
int rent;
int maintenance;
String ownerNameStr;
String ownerEmailStr;
String ownerPropTypeStr;
String ownerLocationStr;
String ownerAccountNoStr;
String renterAccountNoStr;
String propIdStr;
Button btnpayRent;
ImageView btnConfirm;
int payInterestFlag = 1;
ProgressDialog progressDialog;
String proType, location, email, fname, lname, ownerAccount, renterAccount;
String ownerObjId,ownerAvlBal;
int bhk;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pay_rent);
// ParseACL defaultACL = new ParseACL();
// defaultACL.setPublicWriteAccess(true);//------temp
btnConfirm = (ImageView) findViewById(R.id.btnConfirmIDPay);
btnpayRent = (Button) findViewById(R.id.btnPayRent);
propId = (EditText) findViewById(R.id.tvPropIDPay);
ownerName = (TextView) findViewById(R.id.tvNamePay);
ownerEmail = (TextView) findViewById(R.id.tvEmailPay);
ownerPropType = (TextView) findViewById(R.id.tvPropTypePay);
ownerLocation = (TextView) findViewById(R.id.tvLocPay);
ownerAccountNo = (TextView) findViewById(R.id.tvLandAccountNoPay);
renterAccountNo = (TextView) findViewById(R.id.tvRenterAccountNoPay);
final RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativeLauPropertyPay);
btnConfirm.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
confirmFlag = 1;
progressDialog = ProgressDialog.show(PayRent.this, "Please Wait...", "Property Details Loading..");
String propIdStr = propId.getText().toString();
if (!propIdStr.equals(""))
{
final ParseQuery<ParseObject> query = ParseQuery.getQuery("PostAdd");
query.whereEqualTo("objectId", propIdStr);
query.getFirstInBackground(new GetCallback<ParseObject>()
{
#Override
public void done(ParseObject object, ParseException e)
{
if (e == null)//-----from Post Add Table--------------
{
email = object.getString("PostEmail");
bhk = object.getInt("BHK");
proType = object.getString("PropType");
location = object.getString("Location");
rent = object.getInt("ERent");
maintenance = object.getInt("Emaintainance");
//-------------from User Table-------
ParseQuery query = ParseUser.getQuery();
query.whereEqualTo("email", email);
query.getFirstInBackground(new GetCallback()
{
#Override
public void done(ParseObject object, ParseException e)
{
String interest = object.getString("PaymentInterest");
if (interest.equals("Interested"))
{
payInterestFlag = 0;
fname = object.getString("FirstName");
lname = object.getString("LastName");
ownerAccount = object.getString("AccountNo");
renterAccount = ParseUser.getCurrentUser().getString("AccountNo");
ownerName.setText(fname + " " + lname);
ownerAccountNo.setText(ownerAccount);
renterAccountNo.setText(renterAccount);
ownerEmail.setText(email);
ownerLocation.setText(location);
ownerPropType.setText(bhk + " " + "BHK " + proType);
progressDialog.dismiss();
} else
{
progressDialog.dismiss();
payInterestFlag = 1;
AlertDialog.Builder alertPayInterest = new AlertDialog.Builder(PayRent.this);
alertPayInterest.setTitle("Not Interested!");
alertPayInterest.setIcon(R.drawable.notonline);
alertPayInterest.setMessage("Ohhh!!!\nSelected Add Owner Not Interested In Online Payment");
alertPayInterest.show();
}
}
});
} else
{
progressDialog.dismiss();
propId.setError("Property Id is Not Valid!!!");
}
}
});
}//if
else {
progressDialog.dismiss();
propId.setError("Property Id Blank");
}
}
});
//----------------------------------------------------------------------
btnpayRent.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "Click Rent", Toast.LENGTH_SHORT).show();
if ((!propId.getText().toString().equals("")) && (confirmFlag == 1))
{
LayoutInflater factory = LayoutInflater.from(PayRent.this);
final View textEntryView = factory.inflate(R.layout.custom_dialogue_payrent, null);
final EditText inputRent = (EditText) textEntryView.findViewById(R.id.edtRentCustom);
inputRent.setEnabled(false);
final EditText inputMain = (EditText) textEntryView.findViewById(R.id.edtMainCustom);
inputMain.setEnabled(false);
ImageView imgRent = (ImageView) textEntryView.findViewById(R.id.edtImgRentPay);
ImageView imgMain = (ImageView) textEntryView.findViewById(R.id.edtImgMainPay);
// Toast.makeText(getApplicationContext(),"rent is "+rent,Toast.LENGTH_SHORT).show();
inputRent.setText("" + rent);
inputMain.setText("" + maintenance);
imgRent.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
inputRent.setEnabled(true);
//inputRent.requestFocus();
}
});
imgMain.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
inputMain.setEnabled(true);
}
});
final AlertDialog.Builder alert = new AlertDialog.Builder(PayRent.this);
alert.setIcon(R.drawable.donation);
alert.setTitle("Payment Details");
alert.setView(textEntryView);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
//-------------Positive Button
rentFinal = Integer.parseInt(inputRent.getText().toString());
mainFinal = Integer.parseInt(inputMain.getText().toString());
totalFinal = rentFinal + mainFinal;
//--transaction table-------
ParseObject objTrans = new ParseObject("Transactions");
objTrans.put("Debtor", renterAccount);//renter
objTrans.put("Creditor", ownerAccount);//owner
objTrans.put("TotalAmt", totalFinal);
objTrans.saveInBackground();
//--------------------------------
final ParseQuery<ParseObject> querypradip = ParseQuery.getQuery("Pay");
querypradip.whereEqualTo("AccountNo", ownerAccount);
querypradip.getFirstInBackground(new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (object == null) {
Log.d("score", "The getFirst request failed."+e.getMessage());
} else {
Log.d("score", "Retrieved the object.");
ownerObjId=object.getObjectId();
ownerAvlBal=object.getString("AvailableBal");
Log.d("Oid", ownerObjId);
Log.d("OBal", ownerAvlBal);
Toast.makeText(getApplicationContext(), "ownerId"+ownerObjId+"\nAval Bal"+ownerAvlBal, Toast.LENGTH_LONG).show();
//--------------------UPDATE--------------
ParseQuery query = new ParseQuery("Pay");
query.getInBackground(ownerObjId, new GetCallback()
{
public void done(final ParseObject object, ParseException e)
{
if (e == null)
{
object.put("Bal", 5000);
object.saveInBackground();
Toast.makeText(getApplicationContext(), "After Save In Back", Toast.LENGTH_LONG).show();
object.saveInBackground(new SaveCallback()
{
public void done(ParseException e)
{
object.put("AvailableBal", 7000);
object.saveInBackground();
}
});
}
else
{
e.printStackTrace();
Log.e("In Update",e.getMessage());
}
}
});
}
}
});
//---reter table---------------
ParseQuery<ParseObject> queryPay = new ParseQuery<ParseObject>("Pay");
queryPay.whereEqualTo("AccountNo", renterAccount);
queryPay.getFirstInBackground(new GetCallback<ParseObject>() {
#Override
public void done(ParseObject object, ParseException e) {
String AvailBal = object.getString("AvailableBal");
String renterID = object.getObjectId();
final int remainsBal = Integer.parseInt(AvailBal) - totalFinal;
Log.e("Renter", "************" + remainsBal);
Log.e("RenterID", "************" + renterID);
//----------------Update------------------
ParseQuery queryUpdatePay = new ParseQuery("Pay");
queryUpdatePay.getInBackground(renterID, new GetCallback() {
#Override
public void done(ParseObject Obj, ParseException e) {
if (e == null) {
Obj.put("AvailableBal", "" + remainsBal);
Log.e("Update", "************" + remainsBal);
Obj.saveInBackground();
} else {
// do something with the error...
}
}
});
}//done
});
}
});//Ok
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
}
);
alert.show();
} else
if (propId.getText().toString().equals(""))
{
propId.setError("Property Id Blank!");
}
if (confirmFlag == 0)
{
Toast.makeText(getApplicationContext(), "Please Confirm Property Id before Pay", Toast.LENGTH_SHORT).show();
}
}
});
}//OnCreate
}
I am able to store(Simply put using object) data in Pay table as well as also get from table but when I am trying to update it doesn't show any change in table..........
same I am applying for Current User(renter data) it done all get data,update but except current user others users data not update
I do not want to try and understand such a large block of code. In the future please try and boil down the relevant pieces. However:
Looks like you do a query right after saving. Note that saveInBackground() is async, thus it starts (as the name suggests) to contact parse.com and save in a background thread. If the query depend on the object being saved, then you need to wait for it to complete by adding the SaveCallback parameter saveInBackground(new SaveCallback)
If it is because the update fails, then again implement the SaveCallback to see what Exception is thrown saveInBackground(new SaveCallback)
You should never be able to update any other User objects than your own. That would be a huge security issue. A work around could be to create a cloud function using useMasterKey() and call that function from your app.

Categories

Resources