我尝试将图像和数据上传到Firebase

时间:2019-03-10 16:05:54

标签: java android

  

java.lang.NullPointerException:尝试调用虚拟方法   'com.google.firebase.storage.StorageReference   com.google.firebase.storage.StorageReference.child(java.lang.String)'   在null对象上引用java.lang.NullPointerException:尝试   调用虚拟方法'com.google.firebase.storage.StorageReference   com.google.firebase.storage.StorageReference.child(java.lang.String)'   在空对象引用上

     

SendingData.java

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sending_data);

        try {
            FirebaseOptions options = new FirebaseOptions.Builder()
                    .setApplicationId("-----")
                    .setApiKey("-------")
                    .setDatabaseUrl("-------")
                    .build();
            FirebaseApp.initializeApp(this, options, "second_database_name");
            FirebaseApp secondApp = FirebaseApp.getInstance("second_database_name");
            FirebaseStorage storage = FirebaseStorage.getInstance(secondApp, "---------");
            mDatabaseRef = FirebaseDatabase.getInstance(secondApp).getReference("Data");
            mStorageRef = storage.getReference("DataStorage");

        } catch (Exception e) {

        }

        try {
            textInputName = findViewById(R.id.input_layout_name);
            textInputJop = findViewById(R.id.input_layout_jop);
            textInputPhone = findViewById(R.id.input_layout_phone);
            textInputPlace = findViewById(R.id.input_layout_place);

            edit_name = findViewById(R.id.edit_name);
            edit_jop = findViewById(R.id.edit_jop);
            edit_phone = findViewById(R.id.edit_phone);
            edit_place = findViewById(R.id.edit_place);
            button = findViewById(R.id.btn_save);
            mImageView = findViewById(R.id.profile_image_card);
            mImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    SetImage();
                }
            });
        } catch (Exception e) {
        }
        try {


            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (!validateJop() | !validateName() | !validatePhone() | !validatePlace()) {

                        return;
                    }

                    uploadFile();

                }
            });
        } catch (Exception e) {

        }
    }

    private void SetImage() {

        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, REQUEST_CODE_PROFILE);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PROFILE && resultCode == RESULT_OK && data != null && data.getData() != null) {

            filePath = data.getData();
            Picasso.get().load(filePath).into(mImageView);

        }

    }

    private boolean validateName() {

        String name = edit_name.getText().toString().trim();
        if (name.isEmpty()) {
            textInputName.setError("يرجى ادخال البيانات");
            return false;
        } else if (name.length() > 20) {

            textInputName.setError("لا تتجاوز الحد المسموح");
            return false;


        } else {

            textInputName.setError(null);
            return true;
        }

    }

    private boolean validateJop() {

        String Jop = edit_jop.getText().toString().trim();
        if (Jop.isEmpty()) {
            textInputJop.setError("يرجى ادخال البيانات");
            return false;
        } else {

            textInputJop.setError(null);
            return true;
        }

    }


    private boolean validatePhone() {

        String Phone = edit_phone.getText().toString().trim();
        if (Phone.isEmpty()) {
            textInputPhone.setError("يرجى ادخال البيانات");
            return false;
        } else {

            textInputPhone.setError(null);
            return true;
        }

    }

    private boolean validatePlace() {

        String Place = edit_place.getText().toString().trim();
        if (Place.isEmpty()) {
            textInputPlace.setError("يرجى ادخال البيانات");
            return false;
        } else {

            textInputPlace.setError(null);
            return true;
        }

    }

    private String getFileExtension(Uri filePath) {

        ContentResolver cR = getContentResolver();
        MimeTypeMap mam = MimeTypeMap.getSingleton();
        return mam.getExtensionFromMimeType(cR.getType(filePath));

    }


    private void uploadFile() {


        if (filePath != null) {

            final ProgressDialog progressDialog = new ProgressDialog(this);

            progressDialog.show();
            final StorageReference fileReference = mStorageRef.child("DiskStorage").child(filePath.getLastPathSegment());

            fileReference.putFile(filePath).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {

                    progressDialog.dismiss();

                }
            }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                    double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();

                    //displaying percentage in progress dialog
                    progressDialog.setMessage("يتم ارسال البيانات %" + "..." + " " + ((int) progress));
                }
            }).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                @Override
                public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                    if (!task.isSuccessful()) {
                        throw task.getException();
                    }
                    return fileReference.getDownloadUrl();
                }
            }).addOnSuccessListener(new OnSuccessListener<Uri>() {
                @Override
                public void onSuccess(@NonNull Uri downloadUri) {
                    progressDialog.dismiss();

                    Toast.makeText(SendingData.this, "تم ارسال البيانات بنجاح", Toast.LENGTH_SHORT).show();
                    Worker_Item upload = new Worker_Item(downloadUri.toString(),
                            edit_name.getText().toString().trim(),
                            edit_jop.getText().toString().trim()
                            , edit_phone.getText().toString().trim(),
                            edit_place.getText().toString().trim());
                    String uploadId = mDatabaseRef.push().getKey();
                    assert uploadId != null;
                    mDatabaseRef.child(uploadId).setValue(upload);
                }
            });

        }
    }
}

0 个答案:

没有答案