4

I've already made a code for capturing an image using device built-in camera and archiving it in the database server. For each time I captures an image and views it, it will make another ImageView layout dynamically (ex: the image is ic_launcher).

Whenever the ic_launcher image is clicked, it will go to the MainActivity.java page, with the use of intent, to take another image.

My question is, how can I view all of the captured images / archived images in the uploadActivity.java?

Note: the image is viewed in the uploadactivity.java

mainactivity.java

 private void captureImage() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

    // start the image capture Intent
    startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
 @Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    // save file url in bundle as it will be null on screen orientation
    // changes
    outState.putParcelable("file_uri", fileUri);
}

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

    // get the file url
    fileUri = savedInstanceState.getParcelable("file_uri");
}



/**
 * Receiving activity result method will be called after closing the camera
 * */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // if the result is capturing Image
    if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {

            launchUploadActivity(true);


        } else if (resultCode == RESULT_CANCELED) {

            // user cancelled Image capture
            Toast.makeText(getApplicationContext(),
                    "User cancelled image capture", Toast.LENGTH_SHORT)
                    .show();

        } else {
            // failed to capture image
            Toast.makeText(getApplicationContext(),
                    "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                    .show();
        }

    }
}

private void launchUploadActivity(boolean isImage){
    Intent i = new Intent(MainActivity.this, UploadActivity.class);
    i.putExtra("filePath", fileUri.getPath());
    i.putExtra("isImage", isImage);
    startActivity(i);
}

/**
 * ------------ Helper Methods ---------------------- 
 * */


public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}


private static File getOutputMediaFile(int type) {

    // External sdcard location
    File mediaStorageDir = new File(
            Environment
                  .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            Config.IMAGE_DIRECTORY_NAME);

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d(TAG, "Oops! Failed create "
                    + Config.IMAGE_DIRECTORY_NAME + " directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
            Locale.getDefault()).format(new Date());
    File mediaFile;
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");


    return mediaFile;
}

UploadActivity.java

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_upload);

    txtPercentage = (TextView) findViewById(R.id.txtPercentage);
    btnUpload = (Button) findViewById(R.id.btnUpload);      
    Button  btnTaking = (Button)findViewById(R.id.btntake);
    layout2 = (LinearLayout) findViewById(R.id.ly2);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    vidPreview = (VideoView) findViewById(R.id.videoPreview);


    // Changing action bar background color
    getActionBar().setBackgroundDrawable(
            new ColorDrawable(Color.parseColor(getResources().getString(
                    R.color.action_bar))));

    // Receiving the data from previous activity
    Intent intent = getIntent();

    // image or video path that is captured in previous activity
    filePath = intent.getStringExtra("filePath");


    ArrayList<String> yourFilePaths = new ArrayList<>();// Create ArrayList

    // first you have to check if you've saved filepaths
    SharedPreferences prefs = getSharedPreferences("SavedFilePaths",
            Context.MODE_PRIVATE);
    String myJSONArrayString = prefs.getString("SavedFilePathsJSONArray",
            "");
    if (!myJSONArrayString.isEmpty()) {
        JSONArray jsonArray = null;
        try {
            jsonArray = new JSONArray(myJSONArrayString);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        for (int i = 0; i < jsonArray.length(); i++) {
            try {
                yourFilePaths.add(jsonArray.get(i).toString());
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }


    // add the last photo you've taken
    yourFilePaths.add(filePath);
    // Save the new ArrayList in SharedPreferences:
    JSONArray mJSONArray = new JSONArray(yourFilePaths);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString("SavedFilePathsJSONArray", mJSONArray.toString());

    // Show images by filePaths
    File imgFile;
    for (int i = 0; i < yourFilePaths.size(); ++i) {
        imgFile = new File(yourFilePaths.get(i));
        if (imgFile.exists()) {
              final BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 8;

               Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(),options);

            ImageView myImage = new ImageView(this);

            myImage.setImageBitmap(myBitmap);// In this step you've to
                                                // create dynamic imageViews
                                                // to see more than one
                                                // picture
            layout2.addView(myImage);// Then add your dynamic imageviews to
                                    // your layout

        }
    }

    btnTaking.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
        Intent intent = new Intent(UploadActivity.this, MainActivity.class);
        startActivity(intent);
        }
    });

    btnUpload.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // uploading the file to server
            new UploadFileToServer().execute();
        }
    });

}

Activity_Upload

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/view_background"
android:orientation="vertical"
android:padding="10dp" >

<!-- To display picture taken -->


<LinearLayout
    android:id="@+id/ly2"
    android:layout_width="wrap_content"
    android:layout_height="100dp"
    android:orientation="vertical" >

</LinearLayout>

<TextView
    android:id="@+id/txtPercentage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginBottom="15dp"
    android:layout_marginTop="15dp"
    android:textColor="@color/txt_font"
    android:textSize="30dp" />

<ProgressBar
    android:id="@+id/progressBar"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="fill_parent"
    android:layout_height="20dp"
    android:layout_marginBottom="35dp"
    android:visibility="gone" />

<Button
    android:id="@+id/btnUpload"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginBottom="20dp"
    android:background="@color/btn_bg"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:text="@string/btnUploadToServer"
    android:textColor="@color/white"
    android:visibility="gone"
     />
<TextView 
    android:id="@+id/idt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"

    />

<Button
    android:id="@+id/btntake"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginBottom="20dp"
    android:background="@color/btn_bg"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:text="Take Another Picture"
    android:textColor="@color/white" />

Output

enter image description here

Note: i got this code from androidhive

arvin
  • 79
  • 1
  • 8
  • So you want to see the images you taken on UploadActivity in MaintActivity? – Fabio Venturi Pastor Jan 21 '16 at 08:40
  • Actually MainActivity is only for access camera to take image. the UploadActivity is for viewing all the image and upload. if i want to take another picture, i click the imageview (with intent) to mainactivity for taking another picture. In the uploadactivity.java, i can only view 1 image only. so, how can i view all the image i take? thx @FabioVenturiPastor – arvin Jan 21 '16 at 09:10
  • please take 3 photos then after String myJSONArrayString = prefs.getString("SavedFilePathsJSONArray", ""); do a System.out.println(myJSONArrayString); and after yourFilePaths.add(filePath); do a for (int j = 0; j < images.size(); ++j) { System.out.println(yourFilePaths.get(i)); } and tell me what you got – Fabio Venturi Pastor Jan 25 '16 at 09:18
  • the result of System.out.println(yourFilePaths.get(i)); is "/storage/.../imagename.jpg". but there is no result from System.out.println(myJSONArrayString);. i already take 3 photo, and it shows the result with different image name – arvin Jan 25 '16 at 09:56
  • ok now im at work, when i go home ill try your code on my pc and ill show you the result – Fabio Venturi Pastor Jan 25 '16 at 10:31

1 Answers1

3

Ok now i think i understand your problem. To understand my code check this:

what is sharedPreferences?

Show Image View from file path in android?

Create ImageViews dynamically inside a loop

Last Edit: add commit() solve the problem

What we are going to try is save the file paths in ArrayList and save this array in a SharedPreferences:

layout_example.xml <-- create a Layout on your xml to add imageViews inside

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dp"
    android:padding="5dp">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:id="@+id/myLinearLayout"></LinearLayout>
</RelativeLayout>

UploadActivity.java

     Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_upload);//add the LinearLayout of the layout_example.xml

    txtPercentage = (TextView) findViewById(R.id.txtPercentage);
    btnUpload = (Button) findViewById(R.id.btnUpload);
    layout = (LinearLayout) findViewById(R.id.ly1);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    imgPreview = (ImageView) findViewById(R.id.imgPreview);

    addImageView(layout);

    // Changing action bar background color
    getActionBar().setBackgroundDrawable(
            new ColorDrawable(Color.parseColor(getResources().getString(
                    R.color.action_bar))));

    // Receiving the data from previous activity
    Intent i = getIntent();

    // image or video path that is captured in previous activity
    filePath = i.getStringExtra("filePath");

   LinearLayour ly_myLayout = (LinearLayout)findViewById(R.id.myLinearLayout);
   ArrayList<String> yourFilePaths = new ArrayList<>();//Create ArrayList

    //first you have to check if you've saved filepaths
    SharedPreferences prefs = getSharedPreferences("SavedFilePaths",   Context.MODE_PRIVATE);
    String myJSONArrayString = prefs.getString("SavedFilePathsJSONArray", "");
    if(!myJSONArrayString.isEmpty()){
    JSONArray jsonArray = new JSONArray(myJSONArrayString);
      for (int i=0;i<jsonArray.length();i++){ 
        yourFilePaths.add(jsonArray.get(i).toString());
       } 
    }
    //add the last photo you've taken
     yourFilePaths.add(filePath);

    //Save the new ArrayList in SharedPreferences:
     JSONArray mJSONArray = new JSONArray(yourFilePaths);
     SharedPreferences.Editor editor = prefs.edit();
     editor.putString("SavedFilePathsJSONArray",mJSONArray.toString()).commit(); // add commit

    //Show images by filePaths             
    File imgFile;
      for (int i = 0; i < yourFilePaths.size(); ++i) {
        imgFile = new  File(yourFilePaths.get(i));
        if(imgFile.exists()){

        Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());

        ImageView myImage = new ImageView(this);

        myImage.setImageBitmap(myBitmap);// In this step you've to create dynamic imageViews to see more than one picture

        ly_myLayout.addView(myImage);//Then add your dynamic imageviews to your layout

        }
      }

    btnUpload.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // uploading the file to server
            new UploadFileToServer().execute();
        }
    });

}

/**
 * Displaying captured image/video on the screen
 * */
private void previewMedia(boolean isImage) {
    // Checking whether captured media is image or video
    if (isImage) {
        imgPreview.setVisibility(View.VISIBLE);
        vidPreview.setVisibility(View.GONE);
        // bimatp factory
        BitmapFactory.Options options = new BitmapFactory.Options();

        // down sizing image as it throws OutOfMemory Exception for larger
        // images
        options.inSampleSize = 8;

        final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);

        imgPreview.setImageBitmap(bitmap);

    } 
}

    private void addImageView(LinearLayout layout) {
    i = 0;
    ImageView imageView = new ImageView(this);
    imageView.setImageResource(R.drawable.ic_launcher);
    imageView.setId(i);
    layout.addView(imageView);
    imageView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(UploadActivity.this,
                    MainActivity.class);
            startActivity(intent);
        }
    });
}

enter image description here Solve your problem?

Community
  • 1
  • 1
Fabio Venturi Pastor
  • 2,519
  • 3
  • 19
  • 32
  • sorry if i am still new to this.but i thought that "yourfilepath.length()" is undefined to Arraylist. i try to use yourfilepath.size() but it still didn't work. i've already capture about 10 images, but it still only show the last image that i captured. so can you help me with this? i also input your code in my project, but i wonder if it still won't work or maybe i make a mistake when i input the code. thx – arvin Jan 22 '16 at 06:18
  • Ok wait i will insert my code on your project wait a min – Fabio Venturi Pastor Jan 22 '16 at 08:49
  • Done check the new answer and sorry is yourfilepath.size() not yourfilepath.length() – Fabio Venturi Pastor Jan 22 '16 at 09:22
  • i already put the code, but it still the same. the looping ArrayList didn't work. also the imageview dynamic weren't made. it still show the last image i take. i already edit the UploadActivity.java and Activity_Upload code. please check if i've mistake. thx – arvin Jan 25 '16 at 06:08
  • change ly2 to android:layout_width="match_parent" android:layout_height="wrap_content" and after yourFilePaths.add(filePath); loop yourFilePaths and check how many filepath you got. – Fabio Venturi Pastor Jan 25 '16 at 08:24
  • already change the ly2 and loop yourfilepaths. only 1 filepath i got. i tried using textview to check how many loop with setText. And the result is 0 (means no loop). i think there's problem with looping for maybe. wait , i'll send the output ss. – arvin Jan 25 '16 at 09:06
  • Hey arvin did you see the last edit?, i can share an example with another code – Fabio Venturi Pastor Jan 26 '16 at 08:20
  • thank u for your help sir.. its working now..can u share in your github? – arvin Jan 26 '16 at 11:39