1

Here, I have two Activity.In the first activity, I want to pick an image from gallery and transfer that image onto the second activity and set on image view of that activity.

I am transferring the path of image to another activity by intent but it does not work for all images. I am able to get some images from gallery only and for some it will close my app or show nothing and get back to first activity.

How can i improve my code to work for all images. I check so many times, I think the problem is in transferring the file path and get it into another activity.

My First activity:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button choose;
    private Bitmap bitmap;

    private int PICK_IMAGE_REQUEST = 1;

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

        choose = (Button) findViewById(R.id.choose);
        choose.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        if (view == choose) {
            showFileChooser();
        }
    }

    private void showFileChooser() {


        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
    }

    @Override
    protected 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) {
            Uri filePath = data.getData();


            try {
                //Getting the Bitmap from Gallery
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                Intent i = new Intent(getApplicationContext(), SecondActivity.class);
                i.putExtra("picture", bitmap);
                startActivity(i);
                } 
            catch (IOException e) {
                e.printStackTrace();


            }
        }

    }
}

my second activity

public class SecondActivity extends AppCompatActivity implements View.OnClickListener {

    ImageView image;
    Button upload;

    Bitmap bitmap;

    SharedPreferences sp;
    String rollno;

    private String UPLOAD_URL ="http://aptronnoida.com/applock/image_insert.php";


        private String KEY_Rollno = "rollno";
        private String KEY_IMAGE = "image";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
         image=(ImageView)findViewById(R.id.image);

         bitmap= getIntent().getParcelableExtra("picture") ;
         image.setImageBitmap(bitmap);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);


        upload = (Button) findViewById(R.id.upload);
        upload.setOnClickListener(this);
        sp=getSharedPreferences("rajput",MODE_PRIVATE);
        rollno=sp.getString("rollno",null);
    }



    @Override
    public void onClick(View view) {
        if(view == upload){
          uploadImage();
         }
    }

      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;
       }

    private void uploadImage() {

        final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
                new Response.Listener<String>() {
    @Override
            public void onResponse(String s) {
                 //Disimissing the progress dialog
                      loading.dismiss();
                       //Showing toast message of the response
                      Toast.makeText(SecondActivity.this, s , Toast.LENGTH_LONG).show();
                      }
                    },
                    new Response.ErrorListener() {
                       @Override
                      public void onErrorResponse(VolleyError volleyError) {
                          //Dismissing the progress dialog
                   loading.dismiss();

                        //Showing toast
                         Toast.makeText(SecondActivity.this, "Error", Toast.LENGTH_LONG).show();
            }
             }){
              @Override
               protected Map<String, String> getParams() throws AuthFailureError {
                  //Converting Bitmap to String
                  String image = getStringImage(bitmap);

                //Creating parameters
                  Map<String,String> params = new Hashtable<String, String>();

              //Adding parameters
                  /*params.put(KEY_Rollno,rollno);*/
                  params.put(KEY_IMAGE, image);


                  //returning parameters
                     return params;
                    }
};

          //Creating a Request Queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

          //Adding request to the queue
          requestQueue.add(stringRequest);
    }


    @Override
    public boolean onSupportNavigateUp(){
        onBackPressed();
        return true;
    }
    public void onBackPressed(){

        super.finish();
    }


}
Rakibul Haq
  • 1,348
  • 23
  • 32

2 Answers2

3

You can pass the image path instead of the whole image to the second activity and load it in second activity when it is initialized. You can use glide or picasso library for loading image if library usage is not an issue for you.

Steps:

  1. get the path of image
  2. save it in String variable
  3. create a Bundle object, put the path string in the bundle.
  4. start the second activity with that bundle.
  5. Fetch the path value from the bundle in the second activity. Finally,
  6. Load image with glide or picasso.
Rakibul Haq
  • 1,348
  • 23
  • 32
1

In your first MainActivity inside bitmap declare "public static" as below code:

class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button choose;
    public static Bitmap bitmap;

    private int PICK_IMAGE_REQUEST = 1;

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

        choose = (Button) findViewById(R.id.choose);
        choose.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        if (view == choose) {
            showFileChooser();
        }
    }

    private void showFileChooser() {


        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
    }

    @Override
    protected 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) {
            Uri filePath = data.getData();


            try {
                //Getting the Bitmap from Gallery
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                startActivity(new Intent(getApplicationContext(), SecondActivity.class));
                } 
            catch (IOException e) {
                e.printStackTrace();


            }
        }

    }
}

And SecondActivity access code:

public class SecondActivity extends AppCompatActivity implements View.OnClickListener {

    ImageView image;
    Button upload;

    Bitmap bitmap;

    SharedPreferences sp;
    String rollno;

    private String UPLOAD_URL ="http://aptronnoida.com/applock/image_insert.php";


        private String KEY_Rollno = "rollno";
        private String KEY_IMAGE = "image";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
         image=(ImageView)findViewById(R.id.image);

         bitmap= MainActivity.bitmap ;
         image.setImageBitmap(bitmap);
    }
}
Patel Vicky
  • 766
  • 8
  • 17