转换位图图像在活动中工作但在片段

时间:2018-04-10 08:38:38

标签: android onclicklistener nullreferenceexception android-fragmentactivity

将位图转换为字符串并压缩位图在活动中工作正常,但在片段活动中,它会生成空对象引用错误

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.news.androidapp, PID: 5777
                  java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
                      at com.news.androidapp.News_Yeb.convertBitmapToString(News_Yeb.java:161)
                      at com.news.androidapp.News_Yeb.onClick(News_Yeb.java:110)

扩展片段

public class News_Yeb extends Fragment implements OnClickListener {
    Button bt_register;
    TextInputLayout til_name;
    ImageView iv_profile;
    String name, profile;
    RequestQueue requestQueue;
    boolean IMAGE_STATUS = false;
    Bitmap profilePicture;
    View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.news_yeb, container, false);
        til_name = view.findViewById(R.id.til_name_reg);
        iv_profile = view.findViewById(R.id.im_profile);
        bt_register = view.findViewById(R.id.bt_register);

        iv_profile.setOnClickListener(this);
        bt_register.setOnClickListener(this);

        return view;
    }

使用switch case添加两个onClick事件,一个用于imageview,另一个用于提交按钮

@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.im_profile:

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

        case R.id.bt_register:
            name = til_name.getEditText().getText().toString();
            if (     validateName(name)       )

            {
         final ProgressDialog progress = new ProgressDialog(getActivity());
                progress.setTitle("Please Wait");
                progress.setMessage("Creating Your Account");
                progress.setCancelable(false);
                progress.show();
                convertBitmapToString(profilePicture);
                RegisterRequest registerRequest = new RegisterRequest(name, profile, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.i("Response", response);
                        progress.dismiss();
                        try {
                            if (new JSONObject(response).getBoolean("success")) {
                                Toast.makeText(getActivity().getApplicationContext(), "Account Successfully Created", Toast.LENGTH_SHORT).show();
                                finish();
                            } else
                                Toast.makeText(getActivity().getApplicationContext(), "Something Has Happened. Please Try Again!", Toast.LENGTH_SHORT).show();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
                requestQueue.add(registerRequest);

            }
     break;  
    }

}

使用PHP / Mysql连接

public class RegisterRequest extends StringRequest {

    private static final String REGISTER_URL = "..";
    private Map<String, String> parameters;

    public RegisterRequest(String name, String mobile, String email, String image, Response.Listener<String> listener) {
        super(Method.POST, REGISTER_URL, listener, null);
        parameters = new HashMap<>();
        parameters.put("name", name);
        parameters.put("image", image);
    }
    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return parameters;
    }
}

将位图图像转换为ByteArrayOutputStream,然后将流转换为字节数组

private void convertBitmapToString(Bitmap profilePicture) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    profilePicture.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
    byte[] array = byteArrayOutputStream.toByteArray();
    profile = Base64.encodeToString(array, Base64.DEFAULT);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1000 && resultCode == Activity.RESULT_OK && data != null) {
        //Image Successfully Selected
        try {
            //parsing the Intent data and displaying it in the imageview
            Uri imageUri = data.getData();//Geting uri of the data

                    InputStream imageStream = getActivity().getApplicationContext().getContentResolver().openInputStream(imageUri);//creating an imputstrea
            profilePicture = BitmapFactory.decodeStream(imageStream);//decoding the input stream to bitmap
            iv_profile.setImageBitmap(profilePicture);
            IMAGE_STATUS = true;//setting the flag
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

发生这种情况是因为 profilePicture 为空,原因是,onActivityResult为您的意图在托管活动中调用而不是在调用片段类中,这就是为什么代码在活动中工作而不是在片段中; P

选项1:

由于Activity获取onActivityResult()的结果,您需要覆盖活动的onActivityResult()并调用super.onActivityResult()以传播到未处理的结果代码或所有的相应片段。

如果上述选项不起作用,请参阅选项2,因为它肯定会有效。

选项2:

从片段到onActivityResult函数的显式调用如下。

在父Activity类中,覆盖onActivityResult()方法,甚至覆盖Fragment类中的相同内容,并调用以下代码。

在活动类中:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.x);
    fragment.onActivityResult(requestCode, resultCode, data);
}

在片段类中:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // do your stuff
}

希望这可以解决您的问题