java - 安卓方法 : Method 1 returns empty String value with error and Method 2 returns a null pointer exceptions

标签 java android

谁能帮我看看这两个函数有什么问题 方法一返回空String值无任何错误,方法二返回空指针异常 我已经尝试了所有可以在这里找到的类似示例,但几天来仍然存在问题。提前致谢。

//Funtion1 Converting File to Base64.encode String type but returns empty string
        public String getStringFile(File f) {
             InputStream inputStream = null; 
                String encodedFile= "", lastVal;
                try {
                    String uriString = filePath2.toString();
                    f = new File(uriString).getAbsoluteFile();
                    inputStream = new FileInputStream(f);

                byte[] buffer = new byte[10240];//specify the size to allow
                int bytesRead;
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);

                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        output64.write(buffer, 0, bytesRead);
                    }
                output64.close();
                encodedFile =  output64.toString();
                } 
                 catch (FileNotFoundException e1 ) {
                        e1.printStackTrace();
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                    }
                Log.i("Base64 String", "=" +  encodedFile);
                Log.v("Base64 String", "=" +  encodedFile);
                Log.e("Base64 String", "=" +  encodedFile);
                lastVal = encodedFile;
                return lastVal;

        }

// Funtion 2 also Converting File to Base64 encode String but returns NullPointerException
    public String getStringFile(File f) throws FileNotFoundEception, IOException {
        InputStream inputStream = null; 
        String encodedFile= "", lastVal;
         f = new File(f.getAbsoluthPath());
            inputStream = new FileInputStream(f);

        byte[] buffer = new byte[10240];//specify the size to allow
        int bytesRead;
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);

            while ((bytesRead = inputStream.read(buffer)) != -1) {
                output64.write(buffer, 0, bytesRead);
            }
        output64.close();
        encodedFile =  output.toString();



         return = encodedFile;

    }

这是下面的完整代码。除此任务外,其他一切正常。谢谢

package com.aquacareer;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Base64OutputStream;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;

public class Employee_Reg extends Activity implements OnItemSelectedListener, OnClickListener {
    byte[] bytes;
    RelativeLayout rl;
    String strCat1, strCat2, imagePath, docPath, result, displayName, encodedFile;
    Spinner spCat1, spCat2;
    Button b1, b2, b3;
    EditText ed1, ed2, ed3, ed4, ed5, ed6, ed7, ed8, ed9, ed10, ed11;
    String fullname, password, comfPassword, gender, email, contAddr, phoneNo, mobileNo, currLoc, currSal, currInd,
            quali, carProfile, path, path2;

    Intent intent;
    TextView txt1, txt2, txt3, txt4, txt5, txt6, txt7;
    int counter = 3;
    Uri filePath, filePath2;

    String URL = "http://www.aquabytestechnologies.com/aquacareer/android/employeeregister.php";
    // Alert Dialog Manager
    AlertDialogManager alert = new AlertDialogManager();

    public static final String KEY_IMAGE = "image";
    public static final String KEY_FILE = "file";

    // Image request code
    private int PICK_IMAGE_REQUEST = 2;
    private int PICK_FILE_REQUEST = 1;

    // storage permission code
    private static final int STORAGE_PERMISSION_CODE = 123;

     InputStream inputStream = null ; 
     ByteArrayOutputStream output = null;
     Base64OutputStream output64 = null;


    // Uri to store the image uri
    // private Uri filePath;
    private File fileDoc;
    private Bitmap bitmap;

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

        // getActionBar().setTitle(Html.fromHtml("<font color='#FFFFFF' >
        // AquaCareer </font>"));
        getActionBar().setTitle(Html.fromHtml("<font color='#FFFFFF' ><h1>AquaCareer</h1></font>"));
        getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#1c2833")));

        b1 = (Button) findViewById(R.id.button1);
        b2 = (Button) findViewById(R.id.button2);
        b3 = (Button) findViewById(R.id.button3);
        ed1 = (EditText) findViewById(R.id.txt1);
        ed2 = (EditText) findViewById(R.id.txt2);
        ed3 = (EditText) findViewById(R.id.txt3);
        ed4 = (EditText) findViewById(R.id.txt4);
        ed5 = (EditText) findViewById(R.id.txt5);
        ed6 = (EditText) findViewById(R.id.txt6);
        ed7 = (EditText) findViewById(R.id.txt7);
        ed8 = (EditText) findViewById(R.id.txt8);
        ed9 = (EditText) findViewById(R.id.txt9);
        ed10 = (EditText) findViewById(R.id.txt10);
        ed11 = (EditText) findViewById(R.id.txt11);

        txt1 = (TextView) findViewById(R.id.textView1);
        txt2 = (TextView) findViewById(R.id.textView2);
        txt3 = (TextView) findViewById(R.id.textView3);
        txt4 = (TextView) findViewById(R.id.textView4);
        txt5 = (TextView) findViewById(R.id.textView5);
        txt6 = (TextView) findViewById(R.id.textView6);
        txt7 = (TextView) findViewById(R.id.textView7);
        txt2.setVisibility(View.GONE);
        txt3.setVisibility(View.GONE);
        txt5.setVisibility(View.GONE);
        txt7.setVisibility(View.GONE);

        spCat1 = (Spinner) findViewById(R.id.spinner1);
        spCat2 = (Spinner) findViewById(R.id.spinner2);

        List<String> listGender = new ArrayList<String>();
        listGender.add("Select Gender");
        listGender.add("Male");
        listGender.add("Female");
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(Employee_Reg.this, R.layout.spinner_item,
                listGender);
        dataAdapter.setDropDownViewResource(R.layout.spinner_item2);
        spCat1.setAdapter(dataAdapter);

        List<String> listQual = new ArrayList<String>();
        listQual.add("Select Highest Qualification");
        listQual.add("PHD");
        listQual.add("Masters");
        listQual.add("First Degree");
        listQual.add("HND");
        listQual.add("OND");
        listQual.add("Diploma");
        listQual.add("Secondary Cert");
        listQual.add("Primary Cert");
        ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(Employee_Reg.this, R.layout.spinner_item,
                listQual);
        dataAdapter2.setDropDownViewResource(R.layout.spinner_item2);
        spCat2.setAdapter(dataAdapter2);

        spCat1.setOnItemSelectedListener(this);
        spCat2.setOnItemSelectedListener(this);

        this.b1.setOnClickListener(this);
        this.b2.setOnClickListener(this);
        this.b3.setOnClickListener(this);

        ed3.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable s) {
                String strPass1 = ed2.getText().toString();
                String strPass2 = ed3.getText().toString();
                if (strPass1.equals(strPass2)) {
                    txt2.setVisibility(View.VISIBLE);
                    txt2.setText("Passwords Match");

                } else {
                    txt2.setVisibility(View.VISIBLE);
                    txt2.setText("Passwords don't Match");
                }
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
        });

    }

    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.button1) {
            showFileChooser();
        }

        else if (v.getId() == R.id.button2) {
            fullname = ed1.getText().toString().trim();
            password = ed2.getText().toString().trim();
            comfPassword = ed3.getText().toString().trim();
            gender = spCat1.getSelectedItem().toString().trim();
            email = ed4.getText().toString().trim();
            contAddr = ed5.getText().toString().trim();
            phoneNo = ed6.getText().toString().trim();
            mobileNo = ed7.getText().toString().trim();
            currLoc = ed8.getText().toString().trim();
            currSal = ed9.getText().toString().trim();
            currInd = ed10.getText().toString().trim();
            quali = spCat2.getSelectedItem().toString().trim();
            carProfile = ed11.getText().toString().trim();
            path = txt5.getText().toString().trim();
            path2 = txt7.getText().toString().trim();
            // Check if username, password is filled
            if (fullname.trim().length() > 0 && password.trim().length() > 0 && comfPassword.trim().length() > 0
                    && gender.trim().length() > 0 && email.trim().length() > 0 && contAddr.trim().length() > 0
                    && phoneNo.trim().length() > 0 && mobileNo.trim().length() > 0 && currLoc.trim().length() > 0
                    && currSal.trim().length() > 0 && currInd.trim().length() > 0 && carProfile.trim().length() > 0
                    && path.trim().length() > 0) {
                // For testing puspose username, password is checked with sample
                // data3E 54
                String strPass1 = ed2.getText().toString();
                String strPass2 = ed3.getText().toString();
                if (strPass1.equals(strPass2)) {
                    if (gender.equals("Male") || gender.equals("Female")) {

                        if (quali.equals("Select Highest Qualification")) {
                            alert.showAlertDialog(Employee_Reg.this, "Registration Failed..", "Select Qualification",
                                    false);
                        } else {

                            registerUser();

                        }
                    } else {
                        alert.showAlertDialog(Employee_Reg.this, "Registration Failed..", "Select Genger", false);
                    }

                } else {
                    alert.showAlertDialog(Employee_Reg.this, "Registration Failed..", "Passwords don't Match", false);
                }

            } else {
                // user didn't entered username or password
                // Show alert asking him to enter the details
                alert.showAlertDialog(Employee_Reg.this, "Registration Failed..", "Please fill all details", false);
            }

        } else if (v.getId() == R.id.button3) {
            showFileChooser2();
        }

    }

    private void registerUser() {
        register();
    }

    // method to show file chooser for image
        private void showFileChooser() {

            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            try {
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
            } catch (android.content.ActivityNotFoundException ex) {
                Toast.makeText(Employee_Reg.this, "Please install a File Manager.", Toast.LENGTH_SHORT).show();
            }
        }

    // method to show file chooser for resume
        private void showFileChooser2() {
            Intent intent = new Intent();
            intent.setType("*/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            try {
                startActivityForResult(Intent.createChooser(intent, "Select Document"), PICK_FILE_REQUEST);
            } catch (android.content.ActivityNotFoundException ex) {
                Toast.makeText(Employee_Reg.this, "Please install a File Manager.", Toast.LENGTH_SHORT).show();
            }

        }

        // handling the image chooser activity result
        @SuppressLint("InlinedApi")
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {

            if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
                filePath = data.getData();
                try {
                    bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                    // imageView.setImageBitmap(bitmap);
                    int permissionCheck = ContextCompat.checkSelfPermission(this,
                            Manifest.permission.READ_EXTERNAL_STORAGE);

                    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.READ_EXTERNAL_STORAGE },
                                STORAGE_PERMISSION_CODE);
                    } else {

                        imagePath = getPath(filePath);
                        txt5.setVisibility(View.VISIBLE);
                        txt5.setText(imagePath);
                        Log.i("Base64 imagePath", "=" + imagePath);

                        alert.showAlertDialog(Employee_Reg.this, "Image Loaded..", "Photo Successfully Selected", true);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (requestCode == PICK_FILE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
                filePath2 = data.getData();
                try {
                    // docPath = getPath2(filePath2);
                    String uriString = filePath2.toString();
                    fileDoc = new File(uriString);

                    docPath = fileDoc.getAbsolutePath();

                    if (uriString.startsWith("content://")) {
                        Cursor cursor = null;
                        try {
                            cursor = Employee_Reg.this.getContentResolver().query(filePath2, null, null, null, null);
                            if (cursor != null && cursor.moveToFirst()) {
                                displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                            }
                        } finally {
                            cursor.close();
                        }
                    } else if (uriString.startsWith("file://")) {
                        displayName = fileDoc.getName();
                    }

                    int permissionCheck = ContextCompat.checkSelfPermission(this,
                            Manifest.permission.READ_EXTERNAL_STORAGE);

                    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.READ_EXTERNAL_STORAGE },
                                STORAGE_PERMISSION_CODE);
                    } else {

                        txt7.setVisibility(View.VISIBLE);
                        txt7.setText(displayName);
                        //Log.i("Base64 URIString", "=" + uriString);
                        //Log.i("Base64 docPath", "=" + docPath);
                        alert.showAlertDialog(Employee_Reg.this, "Resume Loaded..", "Resume Successfully Selected", true);
                    }

                } catch (NullPointerException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            super.onActivityResult(requestCode, resultCode, data);
        }

        // Converting Bitmap image to Base64.encode String type
        public String getStringImage(Bitmap bmp) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] imageBytes = baos.toByteArray();
            String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
            return encodedImage;
        }

        // Converting File to Base64.encode String type
        public String getStringFile(File f) {
             InputStream inputStream = null; 
                String encodedFile= "", lastVal;
                try {
                    String uriString = filePath2.toString();
                    f = new File(uriString).getAbsoluteFile();
                    inputStream = new FileInputStream(f);

                byte[] buffer = new byte[10240];//specify the size to allow
                int bytesRead;
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);

                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        output64.write(buffer, 0, bytesRead);
                    }
                output64.close();
                encodedFile =  output64.toString();
                } 
                 catch (FileNotFoundException e1 ) {
                        e1.printStackTrace();
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                    }
                Log.i("Base64 String", "=" +  encodedFile);
                Log.v("Base64 String", "=" +  encodedFile);
                Log.e("Base64 String", "=" +  encodedFile);
                lastVal = encodedFile;
                return lastVal;

        }




        // method to get the file Name from uri
        public String getPath(Uri uri) {

            String uriString = uri.toString();
            File myFile = new File(uriString);

            @SuppressWarnings("unused")
            String mPath = myFile.getAbsolutePath();
            String dispName = null;

            if (uriString.startsWith("content://")) {
                Cursor cursor = null;
                try {
                    cursor = Employee_Reg.this.getContentResolver().query(uri, null, null, null, null);
                    if (cursor != null && cursor.moveToFirst()) {
                        dispName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                    }
                } finally {
                    cursor.close();
                }
            } else if (uriString.startsWith("file://")) {
                dispName = myFile.getName();
            }

            return dispName;
        }

        // Requesting permission
        @SuppressLint("InlinedApi")
        private void requestStoragePermission() {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
                return;

            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                // If the user has denied the permission previously your code will
                // come to this block
                // Here you can explain why you need this permission
                // Explain here why you need this permission

            }
            // And finally ask for the permission
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.READ_EXTERNAL_STORAGE },
                    STORAGE_PERMISSION_CODE);
        }

        // This method will be called when the user will tap on allow or deny
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                @NonNull int[] grantResults) {

            // Checking the request code of our request
            if (requestCode == STORAGE_PERMISSION_CODE) {

                // If permission is granted
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Displaying a toast
                    Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
                } else {
                    // Displaying another toast if permission is not granted
                    Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
                }
            }
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.signup, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();

            if (id == R.id.abt) {
                Toast.makeText(this, "We are in About US", Toast.LENGTH_LONG).show();
                return true;
            }
            if (id == R.id.conUs) {
                Toast.makeText(this, "We are in Contact Us", Toast.LENGTH_LONG).show();
                return true;
            }

            return super.onOptionsItemSelected(item);
        }

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    private void register()  {

        class RegisterUser extends AsyncTask<Void, Void, String>  {
            ProgressDialog loading;
            final String fullname = ed1.getText().toString().trim();
            final String password = ed2.getText().toString().trim();
            // final String comfPassword = ed3.getText().toString().trim();
            final String gender = spCat1.getSelectedItem().toString().trim();
            final String email = ed4.getText().toString().trim();
            final String contAddr = ed5.getText().toString().trim();
            final String phoneNo = ed6.getText().toString().trim();
            final String mobileNo = ed7.getText().toString().trim();
            final String currLoc = ed8.getText().toString().trim();
            final String currSal = ed9.getText().toString().trim();
            final String currInd = ed10.getText().toString().trim();
            final String quali = spCat2.getSelectedItem().toString().trim();
            final String carProfile = ed11.getText().toString().trim();
            final String path = txt5.getText().toString().trim();
            final String path2 = txt7.getText().toString().trim();
            final String image = getStringImage(bitmap);
            final String file = getStringFile(fileDoc);
            RequestHandler rh = new RequestHandler();





            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(Employee_Reg.this, "Please Wait: ", "Performing Registration", true,
                        true);
            }

            @Override
            protected String doInBackground(Void... params){


                HashMap<String, String> param = new HashMap<String, String>();
                param.put("fullname", fullname);
                param.put("email", email);
                param.put("password", password);
                param.put("gender", gender);
                param.put("contAddr", contAddr);
                param.put("phoneNo", phoneNo);
                param.put("mobileNo", mobileNo);
                param.put("currLoc", currLoc);
                param.put("currSal", currSal);
                param.put("currInd", currInd);
                param.put("quali", quali);
                param.put("carProfile", carProfile);
                param.put("path", path);
                param.put("path2", path2);
                param.put(KEY_IMAGE, image);
                param.put(KEY_FILE, file);

                String result = rh.sendPostRequest(URL, param);

                return result;

            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                if (s.equalsIgnoreCase("Sorry, email id already exists")) {

                    alert.showAlertDialog(Employee_Reg.this, "Registration Failed..",
                            "Sorry, email id already exists, choose another email.", false);
                } else if (s.equalsIgnoreCase("success")) {
                    alert.showAlertDialog(Employee_Reg.this, "Successful Registration..",
                            "We have just sent you an email for confirmation before you log-in.", true);
                    ed1.setText("");
                    ed2.setText("");
                    ed3.setText("");
                    ed4.setText("");
                    ed5.setText("");
                    ed6.setText("");
                    ed7.setText("");
                    ed8.setText("");
                    ed9.setText("");
                    ed10.setText("");
                    ed11.setText("");
                    txt5.setText("");
                    txt7.setText("");
                    txt3.setVisibility(View.VISIBLE);
                    txt3.setText("We have just sent you an email for confirmation before you log-in.");

                } else if (s.equalsIgnoreCase("test")) {
                    // username / password doesn't match
                    alert.showAlertDialog(Employee_Reg.this, "Registration Failed..",
                            "You cannot register empty details", false);

                } else {
                    // if no category not is selected
                    alert.showAlertDialog(Employee_Reg.this, "Registration Failed..", s, false);

                }
            }

        }

        RegisterUser ru = new RegisterUser();
        ru.execute();
        }

}

最佳答案

我注意到返回空值的特定函数是正确的函数,然后我决定知道它返回空值的原因。

我决定全局声明以下对象和值类型变量,然后在 onCreate() 方法中初始化它们。

    InputStream inputStream = null ; 
     ByteArrayOutputStream output = null;
     Base64OutputStream output64 = null;
     byte[] buffer;
     int bytesRead;
     String encodedFile;

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

       buffer = new byte[10240];//specify the size to allow

         output = new ByteArrayOutputStream();
         output64 = new Base64OutputStream(output, Base64.DEFAULT);


        encodedFile =  output64.toString();
}



public String getStringFile(File f) {
             InputStream inputStream = null; 

                try {
                    //Please remember that filePath2 is an object of Uri 
                    String uriString = filePath2.toString();
                    f = new File(uriString).getAbsoluteFile();
                    inputStream = new FileInputStream(f);



                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        output64.write(buffer, 0, bytesRead);
                    }
                output64.close();
                encodedFile =  output64.toString();
                } 
                 catch (FileNotFoundException e1 ) {
                        e1.printStackTrace();
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                    }


                return encodedFile;

        }

最后,我们要注意,全局声明的变量(即值或对象类型变量)预计将在 Activity 类中单独访问,应该在 onCreate 方法中初始化,以便它们在类的任何点返回它们的值它将被调用,除非我们想为不同的值重新初始化它们。

关于java - 安卓方法 : Method 1 returns empty String value with error and Method 2 returns a null pointer exceptions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40686935/

相关文章:

java - Spring 安全 OAuth2 : How do I provide two seperate login links for two type of users?

android - 为什么我的 FAB 图标周围有一个黑框?

android - 如何从 inputmethodservice 调用 Activity 并获得响应

java - 未找到 AWTU 实用程序

java - 整洁的架构、数据请求编排器、演示器或用例/交互器?

android - 从 DialogFragment 调用 Activity.method() 而不是设置监听器的更简单方法是否存在一些弱点?

java - 使用 FirebaseUI 在 Android TextView 中绑定(bind)嵌套的 JSON

java - 解决 JPA 查询查找连接列表中的最后一个条目

java - 如何在 Spark 中使用 Java 8 Date 类和 Jackson?

java - Spring Boot 中的阴影 jar