При нажатии метод в режиме просмотра изображений не работает - PullRequest
1 голос
/ 29 сентября 2019

У меня есть фрагментный раздел, чтобы загрузить фотографию из галереи или камеры и отправить ее на сервер. У меня есть одна кнопка и одно изображение. Отображает просмотр изображений Но когда я нажимаю на просмотр изображений, он не работает и не отображает раздел.

Как это исправить?

И загружает ли этот код изображения размером более 2 мг?

загрузить фрагмент кода:

public class upload extends Fragment implements View.OnClickListener {

Button upload;
ImageView imageview;
private static final int PERMISSION_REQUEST_CODE = 1;
private static final int PICK_IMAGE_REQUEST = 200;
Bitmap bitmap;
private String userChoosenTask;

private int REQUEST_CAMERA = 0, SELECT_FILE = 1;

public upload() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_upload, container, false);
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    imageview = getActivity().findViewById(R.id.imageView);
    imageview.setOnClickListener(this);
    upload = getActivity().findViewById(R.id.upload);
    upload.setOnClickListener(this);

    if (Build.VERSION.SDK_INT >= 23) {
        if (checkPermission()) {
            // Code for above or equal 23 API Oriented Device
            // Your Permission granted already .Do next code
        } else {
            requestPermission();
        }
    }

}

private void requestPermission() {
    if
    (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        Toast.makeText(getActivity(), " Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
    } else {
        ActivityCompat.requestPermissions(getActivity(), new String[]
                        {android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
                PERMISSION_REQUEST_CODE);
    }
}

private boolean checkPermission() {
    int result = ContextCompat.checkSelfPermission(Objects.requireNonNull(getActivity()),
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
    if (result == PackageManager.PERMISSION_GRANTED) {
        return true;
    } else {
        return false;
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_REQUEST_CODE:
            if (grantResults.length > 0 && grantResults[0] ==
                    PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(getActivity(), "Permission Granted Successfully! ", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getActivity(), "Permission Denied :( ",
                        Toast.LENGTH_LONG).show();
            }
            break;
    }
}

private void showFileChooser() {
    final CharSequence[] items = {"Take Photo", "Choose from Library",
            "Cancel"};
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("Add Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            boolean result = Utility.checkPermission(getActivity());

            if (items[item].equals("Take Photo")) {
                userChoosenTask = "Take Photo";
                if (result) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(intent, REQUEST_CAMERA);
                    // startActivityForResult(Intent.createChooser(intent, "Select File"), PICK_IMAGE_REQUEST);
                }
            } else if (items[item].equals("Choose from Library")) {
                userChoosenTask = "Choose from Library";
                if (result) {
                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent, "Select File"), PICK_IMAGE_REQUEST);
                }
            } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
        onSelectFromGalleryResult(data);

    } else if (requestCode == REQUEST_CAMERA && resultCode == RESULT_OK && data != null && data.getData() != null) {
        onCaptureImageResult(data);
    }
}
private void onCaptureImageResult(Intent data) {
    bitmap = (Bitmap) data.getExtras().get("data");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 90, bytes);
    File destination = new File(Environment.getExternalStorageDirectory(),
            System.currentTimeMillis() + ".jpg");
    FileOutputStream fo;
    try {
        destination.createNewFile();
        fo = new FileOutputStream(destination);
        fo.write(bytes.toByteArray());
        fo.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    imageview.setImageBitmap(bitmap);
}
private void onSelectFromGalleryResult(Intent data) {
    Uri filePath = data.getData();
    try {
        bitmap = MediaStore.Images.Media.getBitmap(getActivity().getApplicationContext().getContentResolver(), filePath);
        Toast.makeText(getActivity(), "" + bitmap, Toast.LENGTH_SHORT).show();
        imageview.setImageBitmap(bitmap);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
public void uploaduserimage() {
    RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
    StringRequest stringRequest = new StringRequest(Request.Method.POST, myurl, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.i("Myresponse", "" + response);
            Toast.makeText(getActivity(), "" + response, Toast.LENGTH_SHORT).show();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.i("Mysmart", "" + error);
            Toast.makeText(getActivity(), "" + error, Toast.LENGTH_SHORT).show();
        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> param = new HashMap<>();

            String images = getStringImage(bitmap);
            Log.i("Mynewsam", "" + images);
            param.put("image", images);
            return param;
        }
    };
    requestQueue.add(stringRequest);
}
public String getStringImage(Bitmap bitmap) {
    Log.i("MyHitesh", "" + bitmap);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
    byte[] b = baos.toByteArray();
    String temp = Base64.encodeToString(b, Base64.DEFAULT);
    return temp;
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.upload:
            uploaduserimage();

            break;
        case R.id.imageView:
            showFileChooser();
            break;

}}}

...