banner



How To Move Pictures From Downloads To Gallery Android

How-do-you-do, and welcome to android pick single or multiple images from gallery or camera in android studio instance.

I accept fabricated two demos, ane will guide y'all to select single image and some other will be for selecting multiple images as per below links

1. Android Pick Paradigm from gallery or camera programmatically

ii. Android Select Multiple Images from gallery or photographic camera programmatically

1. Android Choice Prototype from gallery or camera programmatically

Option image from gallery or camera in android tutorial guides you lot how to select/get the paradigm from a gallery in android programmatically.

Nosotros will choose/take a photo from gallery or camera in the Android Studio by opening via Intent.

Later getting image from gallery or photographic camera, we will testify information technology in an ImageView.

You need to implement this feature when you lot are creating a sign upward folio with image of the user.

Another example can be similar when you are getting a review from the user about a specific place. Here, the user may desire to add images.

First, check the output of pick image from gallery or photographic camera in android example and then we will develop information technology.

Footstep 1: Create a new projection in Android Studio.

I recommend y'all to make a split new android project earlier you get to second step.

Benefit of doing making fresh new project is that you have empty work space in your main activity and then the complication of the coding lines is decreased.

When making new project, select Empty Activity every bit a default action and so primary activity will non include whatever prewritten codes.

Step 2: Updating AndroidManifest.xml file

 add together required permissions between <manifest>….</manifest> tag.

          <uses-permission android:proper noun="android.permission.READ_EXTERNAL_STORAGE" />  <uses-permission android:proper name="android.permission.WRITE_EXTERNAL_STORAGE" />  <uses-permission android:name="android.permission.Photographic camera" />

Final code for AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"     parcel="com.example.parsaniahardik.selectimage2018">      <uses-permission android:proper noun="android.permission.READ_EXTERNAL_STORAGE" />     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />     <uses-permission android:proper name="android.permission.Camera" />      <application         android:allowBackup="true"         android:icon="@mipmap/ic_launcher"         android:label="@cord/app_name"         android:roundIcon="@mipmap/ic_launcher_round"         android:supportsRtl="true"         android:theme="@style/AppTheme">         <action android:proper noun=".MainActivity">             <intent-filter>                 <activity android:proper name="android.intent.action.MAIN" />                  <category android:proper name="android.intent.category.LAUNCHER" />             </intent-filter>         </activeness>     </application>  </manifest>

Now add the post-obit lines in the build.gradle (Module:app) file

          implementation 'com.karumi:dexter:v.0.0'

So the whole source code forbuild.gradle (Module:app) file looks similar the below

apply plugin: 'com.android.awarding'  android {     compileSdkVersion 27     defaultConfig {         applicationId "com.example.parsaniahardik.selectimage2018"         minSdkVersion 15         targetSdkVersion 27         versionCode one         versionName "1.0"         testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"     }     buildTypes {         release {             minifyEnabled false             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'         }     } }  dependencies {     implementation fileTree(dir: 'libs', include: ['*.jar'])     implementation 'com.android.support:appcompat-v7:27.1.i'     implementation 'com.android.support.constraint:constraint-layout:i.one.3'     testImplementation 'junit:junit:4.12'     androidTestImplementation 'com.android.support.test:runner:i.0.ii'     androidTestImplementation 'com.android.back up.test.espresso:espresso-core:iii.0.2'      implementation 'com.karumi:dexter:5.0.0'  }        

This line allow us to utilise the dexter library.

Using this library, we volition enquire for the runtime permissions in the easy manner.

Step three: Updating activity_main.xml file

Copy and paste beneath source lawmaking in activity_main.xml file

<?xml version="one.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical">      <Button         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:id="@+id/btn"         android:layout_gravity="center_horizontal"         android:layout_marginTop="40dp"         android:textAppearance="?android:attr/textAppearanceLarge"         android:text="Select or Capture Epitome" />      <ImageView         android:layout_width="300dp"         android:layout_height="300dp"         android:layout_gravity="centre"         android:layout_marginTop="20dp"         android:scaleType="fitXY"         android:src="@mipmap/ic_launcher"         android:id="@+id/iv"/> </LinearLayout>

I have taken 1 button and Imageview in the main layout.

On the push button click, compiler volition open up one dialog where in that location are two options.

One is to pick image from gallery and other is to capture image from camera.

If user selects prototype from the gallery, image will be shown in the Imageview. And if user captures epitome from the camera, the captured image will be shown in the ImageView.

Pace 4: Preparing MainActivity.coffee form

Add following source lawmaking in MainActivity.coffee class

import android.Manifest; import android.support.v7.app.AppCompatActivity; import android.os.Parcel; import android.widget.Toast;  import com.karumi.dexter.Dexter; import com.karumi.dexter.MultiplePermissionsReport; import com.karumi.dexter.PermissionToken; import com.karumi.dexter.listener.DexterError; import com.karumi.dexter.listener.PermissionRequest; import com.karumi.dexter.listener.PermissionRequestErrorListener; import com.karumi.dexter.listener.multi.MultiplePermissionsListener;  import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.MediaScannerConnection; import android.cyberspace.Uri; import android.bone.Environment; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast;  import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import coffee.util.Calendar;  import coffee.util.List;  public class MainActivity extends AppCompatActivity {      private Button btn;     private ImageView imageview;     private static final String IMAGE_DIRECTORY = "/demonuts";     private int GALLERY = 1, CAMERA = 2;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          requestMultiplePermissions();          btn = (Button) findViewById(R.id.btn);         imageview = (ImageView) findViewById(R.id.4);          btn.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                 showPictureDialog();             }         });      }      private void showPictureDialog(){         AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);         pictureDialog.setTitle("Select Activeness");         String[] pictureDialogItems = {                 "Select photo from gallery",                 "Capture photo from camera" };         pictureDialog.setItems(pictureDialogItems,                 new DialogInterface.OnClickListener() {                     @Override                     public void onClick(DialogInterface dialog, int which) {                         switch (which) {                             instance 0:                                 choosePhotoFromGallary();                                 break;                             case one:                                 takePhotoFromCamera();                                 intermission;                         }                     }                 });         pictureDialog.prove();     }      public void choosePhotoFromGallary() {         Intent galleryIntent = new Intent(Intent.ACTION_PICK,                 android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);          startActivityForResult(galleryIntent, GALLERY);     }      private void takePhotoFromCamera() {         Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);         startActivityForResult(intent, CAMERA);     }      @Override     public void onActivityResult(int requestCode, int resultCode, Intent data) {          super.onActivityResult(requestCode, resultCode, data);         if (resultCode == this.RESULT_CANCELED) {             return;         }         if (requestCode == GALLERY) {             if (data != aught) {                 Uri contentURI = data.getData();                 try {                     Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);                     String path = saveImage(bitmap);                     Toast.makeText(MainActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();                     imageview.setImageBitmap(bitmap);                  } take hold of (IOException eastward) {                     e.printStackTrace();                     Toast.makeText(MainActivity.this, "Failed!", Toast.LENGTH_SHORT).show();                 }             }          } else if (requestCode == CAMERA) {             Bitmap thumbnail = (Bitmap) data.getExtras().go("data");             imageview.setImageBitmap(thumbnail);             saveImage(thumbnail);             Toast.makeText(MainActivity.this, "Prototype Saved!", Toast.LENGTH_SHORT).bear witness();         }     }      public String saveImage(Bitmap myBitmap) {         ByteArrayOutputStream bytes = new ByteArrayOutputStream();         myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);         File wallpaperDirectory = new File(                 Surround.getExternalStorageDirectory() + IMAGE_DIRECTORY);         // take the object build the directory structure, if needed.         if (!wallpaperDirectory.exists()) {             wallpaperDirectory.mkdirs();         }          effort {             File f = new File(wallpaperDirectory, Agenda.getInstance()                     .getTimeInMillis() + ".jpg");             f.createNewFile();             FileOutputStream fo = new FileOutputStream(f);             fo.write(bytes.toByteArray());             MediaScannerConnection.scanFile(this,                     new String[]{f.getPath()},                     new String[]{"image/jpeg"}, null);             fo.close();             Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());              return f.getAbsolutePath();         } take hold of (IOException e1) {             e1.printStackTrace();         }         return "";     }      private void  requestMultiplePermissions(){         Dexter.withActivity(this)                 .withPermissions(                         Manifest.permission.CAMERA,                         Manifest.permission.WRITE_EXTERNAL_STORAGE,                         Manifest.permission.READ_EXTERNAL_STORAGE)                 .withListener(new MultiplePermissionsListener() {                     @Override                     public void onPermissionsChecked(MultiplePermissionsReport report) {                         // bank check if all permissions are granted                         if (report.areAllPermissionsGranted()) {                             Toast.makeText(getApplicationContext(), "All permissions are granted by user!", Toast.LENGTH_SHORT).show();                         }                          // check for permanent deprival of any permission                         if (report.isAnyPermissionPermanentlyDenied()) {                             // show alert dialog navigating to Settings                             //openSettingsDialog();                         }                     }                      @Override                     public void onPermissionRationaleShouldBeShown(Listing<PermissionRequest> permissions, PermissionToken token) {                         token.continuePermissionRequest();                     }                 }).                 withErrorListener(new PermissionRequestErrorListener() {                     @Override                     public void onError(DexterError error) {                         Toast.makeText(getApplicationContext(), "Some Fault! ", Toast.LENGTH_SHORT).show();                     }                 })                 .onSameThread()                 .check();     }  }

Step 5: Description of MainActivity.java

In the onCreate() method, compiler will call the requestMultiplePermissions() method.

Source code for requestMultiplePermissions() is as the post-obit

          private void  requestMultiplePermissions(){         Dexter.withActivity(this)                 .withPermissions(                         Manifest.permission.Photographic camera,                         Manifest.permission.WRITE_EXTERNAL_STORAGE,                         Manifest.permission.READ_EXTERNAL_STORAGE)                 .withListener(new MultiplePermissionsListener() {                     @Override                     public void onPermissionsChecked(MultiplePermissionsReport report) {                         // check if all permissions are granted                         if (report.areAllPermissionsGranted()) {                             Toast.makeText(getApplicationContext(), "All permissions are granted by user!", Toast.LENGTH_SHORT).prove();                         }                          // check for permanent denial of any permission                         if (report.isAnyPermissionPermanentlyDenied()) {                             // show alarm dialog navigating to Settings                             //openSettingsDialog();                         }                     }                      @Override                     public void onPermissionRationaleShouldBeShown(Listing<PermissionRequest> permissions, PermissionToken token) {                         token.continuePermissionRequest();                     }                 }).                 withErrorListener(new PermissionRequestErrorListener() {                     @Override                     public void onError(DexterError error) {                         Toast.makeText(getApplicationContext(), "Some Error! ", Toast.LENGTH_SHORT).show();                     }                 })                 .onSameThread()                 .check();     }

This method will enquire for multile runtime permissions using dexter library.

We volition ask for all permissions at i time.

It is better to allow every permission when you are testing this tutorial on your device to avoid unnecessary complication.

When the user clicks the button, dialog with select options appears.

Following is the button click method.

btn.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                 showPictureDialog();             }         });

The dialog contains options whether to select an prototype from gallery or to capture the epitome from camera.

Below is the code for showPictureDialog() method.

private void showPictureDialog(){     AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);     pictureDialog.setTitle("Select Activity");     Cord[] pictureDialogItems = {             "Select photo from gallery",             "Capture photograph from camera" };     pictureDialog.setItems(pictureDialogItems,             new DialogInterface.OnClickListener() {                 @Override                 public void onClick(DialogInterface dialog, int which) {                     switch (which) {                         case 0:                             choosePhotoFromGallary();                             intermission;                         case 1:                             takePhotoFromCamera();                             break;                     }                 }             });     pictureDialog.evidence(); }

This method creates a dialog with two options.

One option is to select an paradigm from the  gallery.

Another selection is to capture image from the camera.

If a user selects gallery, then following method is executed.

          public void choosePhotoFromGallary() {         Intent galleryIntent = new Intent(Intent.ACTION_PICK,                 android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);          startActivityForResult(galleryIntent, GALLERY);     }

Above gallery intent will open a new screen which includes all the gallery images.

User will select image from this screen.

And if user choose camera, then below method is run past compiler.

          private void takePhotoFromCamera() {         Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);         startActivityForResult(intent, Photographic camera);     }

Above code will create a camera intent (a camera preview) So the user tin can capture prototype from here.

After selecting an prototype from gallery or capturing photo from camera, anonActivityResult() method is executed.

Code foronActivityResult(), is every bit beneath.

@Override     public void onActivityResult(int requestCode, int resultCode, Intent data) {          super.onActivityResult(requestCode, resultCode, data);         if (resultCode == this.RESULT_CANCELED) {             return;         }         if (requestCode == GALLERY) {             if (data != nix) {                 Uri contentURI = data.getData();                 endeavor {                     Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);                     String path = saveImage(bitmap);                     Toast.makeText(MainActivity.this, "Paradigm Saved!", Toast.LENGTH_SHORT).testify();                     imageview.setImageBitmap(bitmap);                  } grab (IOException due east) {                     east.printStackTrace();                     Toast.makeText(MainActivity.this, "Failed!", Toast.LENGTH_SHORT).bear witness();                 }             }          } else if (requestCode == CAMERA) {             Bitmap thumbnail = (Bitmap) data.getExtras().get("data");             imageview.setImageBitmap(thumbnail);             saveImage(thumbnail);             Toast.makeText(MainActivity.this, "Prototype Saved!", Toast.LENGTH_SHORT).show();         }     }

If an image comes from an gallery, then compiler goes at the below code.

          if (requestCode == GALLERY) {             if (data != naught) {                 Uri contentURI = data.getData();                 attempt {                     Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);                     String path = saveImage(bitmap);                     Toast.makeText(MainActivity.this, "Epitome Saved!", Toast.LENGTH_SHORT).show();                     imageview.setImageBitmap(bitmap);                  } catch (IOException east) {                     due east.printStackTrace();                     Toast.makeText(MainActivity.this, "Failed!", Toast.LENGTH_SHORT).show();                 }             }          }

If a photo is from a camera, then compiler goes to following.

else if (requestCode == CAMERA) {             Bitmap thumbnail = (Bitmap) information.getExtras().get("data");             imageview.setImageBitmap(thumbnail);             saveImage(thumbnail);             Toast.makeText(MainActivity.this, "Image Saved!", Toast.LENGTH_SHORT).evidence();         }

Beneath is the method to save the prototype or photo.

public String saveImage(Bitmap myBitmap) {         ByteArrayOutputStream bytes = new ByteArrayOutputStream();         myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);         File wallpaperDirectory = new File(                 Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);         // have the object build the directory structure, if needed.         if (!wallpaperDirectory.exists()) {             wallpaperDirectory.mkdirs();         }          endeavor {             File f = new File(wallpaperDirectory, Agenda.getInstance()                     .getTimeInMillis() + ".jpg");             f.createNewFile();             FileOutputStream fo = new FileOutputStream(f);             fo.write(bytes.toByteArray());             MediaScannerConnection.scanFile(this,                     new String[]{f.getPath()},                     new String[]{"paradigm/jpeg"}, null);             fo.close();             Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());              render f.getAbsolutePath();         } catch (IOException e1) {             e1.printStackTrace();         }         render "";     }

In the above code, IMAGE_DIRECTORYis the folder name in which all the images will be saved.

So that's all for pick paradigm from gallery or photographic camera in the android example. If you lot have queries, then ask them in the comment section. Thank you lot 🙂





2. Android Select Multiple Images from gallery or camera programmatically

Android select multiple images from gallery Programmatically tutorial example is for you coders.

In this case, we will pick/go the multiple images from gallery and we will bear witness them in a gridview.

We volition choose/have multiple photos from gallery in the Android Studio by opening via Gallery Intent.

You can also select single paradigm in this tutorial.

Last Images of app

The output of this tutorial is wait similar beneath images.

android select multiple images from gallery
Beginning Screen
android pick image
2d Screen
android select multiple images from gallery
Tertiary Screen
android pick image
Quaternary Screen

Footstep 1. Making Layout

By default you have activity_main.xml layout file.

Add following source code into information technology.

<?xml version="1.0" encoding="utf-viii"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-machine"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical"     tools:context=".MainActivity">      <GridView         android:layout_width="match_parent"         android:layout_height="0dp"         android:id="@+id/gv"         android:numColumns="3"         android:layout_weight="1">     </GridView>      <Button         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:id="@+id/btn"         android:text="Select Multiple Images"         android:layout_marginTop="10dp"         android:layout_marginBottom="10dp"         android:layout_marginLeft="10dp"         />  </LinearLayout>

I have taken one button and one gridview in this layout file.

When the user volition click the push button, it will open all the images available on the android device.

It volition let the user choose 1 or multiple images from hither.

When the user finishes picking up the images, all the selected images will exist shown in the gridview.

Step 2. Java Coding

Now Add beneath source code in to MainActivity.java file

import android.content.ClipData; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.bone.Bundle; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.GridView; import android.widget.Toast; import java.util.ArrayList; import java.util.List;  public grade MainActivity extends AppCompatActivity {      private Button btn;     int PICK_IMAGE_MULTIPLE = 1;     String imageEncoded;     Listing<String> imagesEncodedList;     private GridView gvGallery;     private GalleryAdapter galleryAdapter;      @Override     protected void onCreate(Package savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          btn = findViewById(R.id.btn);         gvGallery = (GridView)findViewById(R.id.gv);          btn.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View 5) {                 Intent intent = new Intent();                 intent.setType("prototype/*");                 intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);                 intent.setAction(Intent.ACTION_GET_CONTENT);                 startActivityForResult(Intent.createChooser(intent,"Select Movie"), PICK_IMAGE_MULTIPLE);             }         });      }      @Override     protected void onActivityResult(int requestCode, int resultCode, Intent information) {         endeavour {             // When an Paradigm is picked             if (requestCode == PICK_IMAGE_MULTIPLE && resultCode == RESULT_OK                     && zippo != data) {                 // Become the Image from data                  String[] filePathColumn = { MediaStore.Images.Media.DATA };                 imagesEncodedList = new ArrayList<String>();                 if(data.getData()!=nada){                      Uri mImageUri=information.getData();                      // Go the cursor                     Cursor cursor = getContentResolver().query(mImageUri,                             filePathColumn, null, zippo, null);                     // Motility to starting time row                     cursor.moveToFirst();                      int columnIndex = cursor.getColumnIndex(filePathColumn[0]);                     imageEncoded  = cursor.getString(columnIndex);                     cursor.shut();                      ArrayList<Uri> mArrayUri = new ArrayList<Uri>();                     mArrayUri.add(mImageUri);                     galleryAdapter = new GalleryAdapter(getApplicationContext(),mArrayUri);                     gvGallery.setAdapter(galleryAdapter);                     gvGallery.setVerticalSpacing(gvGallery.getHorizontalSpacing());                     ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) gvGallery                             .getLayoutParams();                     mlp.setMargins(0, gvGallery.getHorizontalSpacing(), 0, 0);                  } else {                     if (data.getClipData() != zero) {                         ClipData mClipData = data.getClipData();                         ArrayList<Uri> mArrayUri = new ArrayList<Uri>();                         for (int i = 0; i < mClipData.getItemCount(); i++) {                              ClipData.Item item = mClipData.getItemAt(i);                             Uri uri = item.getUri();                             mArrayUri.add(uri);                             // Get the cursor                             Cursor cursor = getContentResolver().query(uri, filePathColumn, zippo, nix, nada);                             // Move to first row                             cursor.moveToFirst();                              int columnIndex = cursor.getColumnIndex(filePathColumn[0]);                             imageEncoded  = cursor.getString(columnIndex);                             imagesEncodedList.add together(imageEncoded);                             cursor.close();                              galleryAdapter = new GalleryAdapter(getApplicationContext(),mArrayUri);                             gvGallery.setAdapter(galleryAdapter);                             gvGallery.setVerticalSpacing(gvGallery.getHorizontalSpacing());                             ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) gvGallery                                     .getLayoutParams();                             mlp.setMargins(0, gvGallery.getHorizontalSpacing(), 0, 0);                          }                         Log.v("LOG_TAG", "Selected Images" + mArrayUri.size());                     }                 }             } else {                 Toast.makeText(this, "Y'all haven't picked Image",                         Toast.LENGTH_LONG).show();             }         } grab (Exception e) {             Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)                     .show();         }          super.onActivityResult(requestCode, resultCode, data);     } }

Now let united states empathize what output will nosotros have when the above lawmaking is run by the compiler.

When the user will click on the button, below lawmaking will be run.

btn.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View five) {                 Intent intent = new Intent();                 intent.setType("image/*");                 intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);                 intent.setAction(Intent.ACTION_GET_CONTENT);                 startActivityForResult(Intent.createChooser(intent,"Select Motion picture"), PICK_IMAGE_MULTIPLE);             }         });

I have created one intent object here.

This intent volition call the action which will fetch all the images from android devices.

User will select necessary images from here and when he completes this task, he volition exist taken back to our app.

When compiler comes back to our app, information technology as well takes selected images with information technology.

At this time, onActivityResult() method is called and these images are available in this method.

Take a look at the code structure ofonActivityResult() method.

@Override     protected void onActivityResult(int requestCode, int resultCode, Intent data) {         try {             // When an Image is picked             if (requestCode == PICK_IMAGE_MULTIPLE && resultCode == RESULT_OK                     && null != data) {                 // Get the Image from information                  String[] filePathColumn = { MediaStore.Images.Media.Data };                 imagesEncodedList = new ArrayList<String>();                 if(data.getData()!=null){                      Uri mImageUri=data.getData();                      // Become the cursor                     Cursor cursor = getContentResolver().query(mImageUri,                             filePathColumn, null, null, zippo);                     // Movement to beginning row                     cursor.moveToFirst();                      int columnIndex = cursor.getColumnIndex(filePathColumn[0]);                     imageEncoded  = cursor.getString(columnIndex);                     cursor.shut();                      ArrayList<Uri> mArrayUri = new ArrayList<Uri>();                     mArrayUri.add(mImageUri);                     galleryAdapter = new GalleryAdapter(getApplicationContext(),mArrayUri);                     gvGallery.setAdapter(galleryAdapter);                     gvGallery.setVerticalSpacing(gvGallery.getHorizontalSpacing());                     ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) gvGallery                             .getLayoutParams();                     mlp.setMargins(0, gvGallery.getHorizontalSpacing(), 0, 0);                  } else {                     if (data.getClipData() != nix) {                         ClipData mClipData = data.getClipData();                         ArrayList<Uri> mArrayUri = new ArrayList<Uri>();                         for (int i = 0; i < mClipData.getItemCount(); i++) {                              ClipData.Item item = mClipData.getItemAt(i);                             Uri uri = item.getUri();                             mArrayUri.add(uri);                             // Get the cursor                             Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);                             // Motility to showtime row                             cursor.moveToFirst();                              int columnIndex = cursor.getColumnIndex(filePathColumn[0]);                             imageEncoded  = cursor.getString(columnIndex);                             imagesEncodedList.add together(imageEncoded);                             cursor.shut();                              galleryAdapter = new GalleryAdapter(getApplicationContext(),mArrayUri);                             gvGallery.setAdapter(galleryAdapter);                             gvGallery.setVerticalSpacing(gvGallery.getHorizontalSpacing());                             ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) gvGallery                                     .getLayoutParams();                             mlp.setMargins(0, gvGallery.getHorizontalSpacing(), 0, 0);                          }                         Log.v("LOG_TAG", "Selected Images" + mArrayUri.size());                     }                 }             } else {                 Toast.makeText(this, "Y'all haven't picked Epitome",                         Toast.LENGTH_LONG).show();             }         } catch (Exception eastward) {             Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)                     .show();         }          super.onActivityResult(requestCode, resultCode, data);     }

All the core logic is nowadays in the above source lawmaking.

If user choose single image

When compiler comes to this code, offset information technology will check whether user take selected single paradigm or multiple image.

If user take picked upwardly single image so compiler volition run below code

if (requestCode == PICK_IMAGE_MULTIPLE && resultCode == RESULT_OK                     && null != data) {                 // Go the Paradigm from data                  String[] filePathColumn = { MediaStore.Images.Media.DATA };                 imagesEncodedList = new ArrayList<Cord>();                 if(information.getData()!=null){                      Uri mImageUri=data.getData();                      // Get the cursor                     Cursor cursor = getContentResolver().query(mImageUri,                             filePathColumn, goose egg, null, null);                     // Motility to start row                     cursor.moveToFirst();                      int columnIndex = cursor.getColumnIndex(filePathColumn[0]);                     imageEncoded  = cursor.getString(columnIndex);                     cursor.close();                      ArrayList<Uri> mArrayUri = new ArrayList<Uri>();                     mArrayUri.add(mImageUri);                     galleryAdapter = new GalleryAdapter(getApplicationContext(),mArrayUri);                     gvGallery.setAdapter(galleryAdapter);                     gvGallery.setVerticalSpacing(gvGallery.getHorizontalSpacing());                     ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) gvGallery                             .getLayoutParams();                     mlp.setMargins(0, gvGallery.getHorizontalSpacing(), 0, 0);                  }

Here, nosotros will accept the data of the selected image in the grade of URI.

We tin can gear up the image in the imageview by using this URI.

After retrieving the paradigm, compiler will set the gridview with this image.

I will depict the code for gridview and information technology'due south adapter in the last chapter of this tutorial.

When the user have selected multiple images

At present if the user have selected multiple images and so the below code will be initiated.

          if (data.getClipData() != aught) {                         ClipData mClipData = data.getClipData();                         ArrayList<Uri> mArrayUri = new ArrayList<Uri>();                         for (int i = 0; i < mClipData.getItemCount(); i++) {                              ClipData.Particular item = mClipData.getItemAt(i);                             Uri uri = item.getUri();                             mArrayUri.add(uri);                             // Get the cursor                             Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);                             // Movement to beginning row                             cursor.moveToFirst();                              int columnIndex = cursor.getColumnIndex(filePathColumn[0]);                             imageEncoded  = cursor.getString(columnIndex);                             imagesEncodedList.add(imageEncoded);                             cursor.close();                              galleryAdapter = new GalleryAdapter(getApplicationContext(),mArrayUri);                             gvGallery.setAdapter(galleryAdapter);                             gvGallery.setVerticalSpacing(gvGallery.getHorizontalSpacing());                             ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) gvGallery                                     .getLayoutParams();                             mlp.setMargins(0, gvGallery.getHorizontalSpacing(), 0, 0);                          }                         Log.5("LOG_TAG", "Selected Images" + mArrayUri.size());                     }

Compiler volition make ane arraylist which contains all the URIs of all the selected images.

1 for loop is initiated hither. In the every iteration of this for loop, URI of the epitome is added into the arraylist.

The number of iterations of the for loop equal to the number of selected images, means that if the user have taken three images then the for loop volition have three iterations.

This arraylist is then used to set up the gridview.

Pace three. Setting up the GridView

Before setting up the gridview, offset we need to create one layout resource file.

This layout resource file (gv_item.xml) will represent the every single cell of the gridview.

Code for gv_item.xml

<?xml version="one.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-machine"     android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:orientation="vertical">      <ImageView         android:layout_height="130dp"         android:layout_width="130dp"         android:padding="10dp"         android:id="@+id/ivGallery"         android:src="@mipmap/ic_launcher_round"         android:scaleType="fitXY"         />  </LinearLayout>        

Every gridview implementation requires the adapter class which will provide necessary information to the gridview.

Here, I accept written GalleryAdapter.java class for this purpose.

Source lawmaking forGalleryAdapter.java is equally post-obit

import android.content.Context; import android.internet.Uri; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView;  import java.util.ArrayList;  public form GalleryAdapter extends BaseAdapter {      private Context ctx;     private int pos;     private LayoutInflater inflater;     individual ImageView ivGallery;     ArrayList<Uri> mArrayUri;     public GalleryAdapter(Context ctx, ArrayList<Uri> mArrayUri) {          this.ctx = ctx;         this.mArrayUri = mArrayUri;     }      @Override     public int getCount() {         return mArrayUri.size();     }      @Override     public Object getItem(int position) {         render mArrayUri.get(position);     }      @Override     public long getItemId(int position) {         return 0;     }      @Override     public View getView(int position, View convertView, ViewGroup parent) {          pos = position;         inflater = (LayoutInflater) ctx                 .getSystemService(Context.LAYOUT_INFLATER_SERVICE);          View itemView = inflater.inflate(R.layout.gv_item, parent, fake);          ivGallery = (ImageView) itemView.findViewById(R.id.ivGallery);          ivGallery.setImageURI(mArrayUri.get(position));          return itemView;     }   }

Nosotros are passing an arraylist of paradigm URIs in the second parameter of the constructor.

Compiler will use this arraylist to prepare upwards the prototype in the imageview.

Look at the getView() method in the adapter form. Image is set upwardly with the URI in this method.

All the technical aspects for android select multiple images from gallery example is over at present

Source: https://demonuts.com/pick-image-gallery-camera-android/

Posted by: garciasuccall.blogspot.com

0 Response to "How To Move Pictures From Downloads To Gallery Android"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel