将图库中的选定图像上传到gridview

时间:2019-04-14 01:07:29

标签: android gridview path gallery

此应用程序包括打开照片库并选择我需要的照片库,然后将其上传到应用程序的gridview,问题是当我选择画廊的图像时,它们没有在gridview中上传图像,我认为错误可能是提取图像的路由并在适配器中实例化它时,请让我知道问题出在哪里。 我在这里留下代码。

public class MainActivity extends AppCompatActivity {

final int COD_SELECCIONA=1;

String[]paths = new String[]{};
ArrayList<String> imagesEncodedList;

GridView imagenesGrid;
Button btnFoto;
ArrayList<String> array;
FileInputStream in;
File file = null;

private GridView gridView;
private GridViewAdapter gridAdapter;

public MainActivity() {
}

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

imagesEncodedList =new ArrayList<>();

gridView = (GridView) findViewById(R.id.imagenesGrid);

btnFoto= (Button) findViewById(R.id.btnFoto);


}

private void grid() {


gridAdapter = new GridViewAdapter(this,paths);
    gridView.setAdapter(gridAdapter);

}
public void cargarImagen() {

final CharSequence[] opciones={"Cargar Imagen","Cancelar"};
final AlertDialog.Builder alertOpciones=new AlertDialog.Builder(MainActivity.this);
alertOpciones.setTitle("Seleccione una Opción");
alertOpciones.setItems(opciones, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {

            if (opciones[i].equals("Cargar Imagen")){
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_GET_CONTENT);
                intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("*/*");
                String[] extraMimeTypes = {"image/*", "video/*"};
                intent.putExtra(Intent.EXTRA_MIME_TYPES, extraMimeTypes);
                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);


                startActivityForResult(Intent.createChooser(intent,"Select Picture"), COD_SELECCIONA);
            }else{
                dialogInterface.dismiss(); } }
});
    alertOpciones.show();

}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    try {
        if (requestCode == COD_SELECCIONA && resultCode == RESULT_OK
                && null != data) {

        ClipData clipData = data.getClipData();
        if(clipData != null){
            for(int i=0; i<clipData.getItemCount(); i++){
                ClipData.Item item = clipData.getItemAt(i);
                Uri uri = item.getUri();
                paths = new String[]{getRealPathFromURI(uri)};
            }
        }
    } else {
        Toast.makeText(this, "You haven't picked Image",
                Toast.LENGTH_LONG).show();
    }
} catch (Exception e) {
    Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
            .show();
}

super.onActivityResult(requestCode, resultCode, data);
grid();
}

public String getRealPathFromURI(Uri contentUri) {
    String[] proj = {MediaStore.Images.Media.DATA};
    CursorLoader cursorLoader = new CursorLoader(
            this,
            contentUri, proj, null, null, null);
    Cursor cursor = cursorLoader.loadInBackground();

    int column_index =
            cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}
public void onClick(View view) {
    switch (view.getId()) {

        case R.id.btnFoto:
            cargarImagen();

            break;
    } }}

<<<<<<<<<适配器>>>>>>>>

public class GridViewAdapter extends BaseAdapter {
private Activity activity;
private String[] filepath;


private static LayoutInflater inflater = null;

public GridViewAdapter(Activity a, String[] fpath) {
    activity = a;
    filepath = fpath;

    inflater = (LayoutInflater) activity
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
    return filepath.length;
}
public Object getItem(int position) {
    return position;
}
public long getItemId(int position) {
    return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
    View vi = convertView;
    if (convertView == null)
        vi = inflater.inflate(R.layout.grid_item, null);
    ImageView image = (ImageView) vi.findViewById(R.id.imagen);
    Bitmap bmp = BitmapFactory.decodeFile(filepath[position]);

    image.setImageBitmap(bmp);
    return vi;
}}

<<<<<<<<<活动主要>>>>>>>>

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="vertical">

<Button
    android:id="@+id/btnFoto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:onClick="onClick"
    android:text="Button" />
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

<android.support.v7.widget.Toolbar
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:id="@+id/toolbar"
    android:background="?attr/colorPrimary"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

<GridView
    android:id="@+id/imagenesGrid"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:columnWidth="100dp"
    android:gravity="center"
    android:horizontalSpacing="5dp"
    android:numColumns="auto_fit"
    android:verticalSpacing="5dp" />
</LinearLayout>

<<<<<<<<<活动项目适配器>>>>>>>>

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">

<android.support.v7.widget.CardView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/imagen"
            android:layout_width="100dp"
            android:layout_height="130dp"
            android:scaleType="centerCrop"
            card_view:srcCompat="@android:drawable/ic_menu_camera" />

    </LinearLayout>
</android.support.v7.widget.CardView>

<<<<<<<<<清单>>>>>>>>

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.darkenemig.galeriagridview">
    <uses-permission android:name="android.permission.CAMERA" />

<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="cunoraz.ACTION_PICK" />
            <action android:name="cunoraz.ACTION_MULTIPLE_PICK" />
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

1 个答案:

答案 0 :(得分:0)

有时图像尺寸会导致运行时错误,请尝试按比例缩小图像尺寸

  bitmap= scaleDown(bitmap,700,true);
  agentamage.setImageBitmap(bitmap);
 public static Bitmap scaleDown(Bitmap realImage, float maxImageSize,
                                   boolean filter) {
        float ratio = Math.min(
                (float) maxImageSize / realImage.getWidth(),
                (float) maxImageSize / realImage.getHeight());
        int width = Math.round((float) ratio * realImage.getWidth());
        int height = Math.round((float) ratio * realImage.getHeight());

        Bitmap newBitmap = Bitmap.createScaledBitmap(realImage, width,
                height, filter);
        if (ratio>=1)
        {
            return realImage;
        }
        else {
            return newBitmap;
        }
    }