2017-09-16 71 views
0

我正在編寫此移動應用程序,在主屏幕上有一個網格視圖,應顯示移動設備上的所有照片。還有一個按鈕可以拍照。Android將移動存儲中的照片加載到GridView

我已經寫了imageAdaptor,現在我的應用程序可以顯示我放在R.drawable文件夾中的照片。

但是,我可以把所有照片存儲在設備上嗎?包括此應用拍攝的所有照片。

在此先感謝。

這裏是我的代碼:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" android:layout_height="match_parent"> 

<Button 
    android:id="@+id/button" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:text="Button" 
    android:layout_alignParentBottom="true" 
    android:layout_alignParentStart="true" 
    android:layout_marginBottom="12dp" /> 

<GridView 
    android:id="@+id/gridview" 
    android:layout_width="match_parent" 
    android:layout_height="450dp" 
    android:layout_alignParentStart="true" 
    android:layout_alignParentTop="true" 
    android:columnWidth="100dp" 
    android:numColumns="auto_fit" 
    android:verticalSpacing="10dp" 
    android:horizontalSpacing="10dp" 
    android:gravity="center" 
    /> 

主要方法:

public class MainActivity extends AppCompatActivity { 

public final String APP_TAG = "PhotoApp"; 
public String photoFileName = "photo.jpg"; 

private Uri imageUri; 


MarshMallowPermission marshMallowPermission = new MarshMallowPermission(this); 

@Override 

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

    GridView gridview = (GridView) findViewById(R.id.gridview); 
    gridview.setAdapter(new ImageAdapter(this)); 

    }; 



public Uri getFileUri(String fileName){ 
    Uri imageUri=null; 
    String typestr = "/images/"; 
    // Get safe storage directory for photos 
    File mediaStorageDir = new File(
      Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_PICTURES).getPath(), typestr+fileName); 



    // Create the storage directory if it does not exist 
    if (!mediaStorageDir.getParentFile().exists() && !mediaStorageDir.getParentFile().mkdirs()) { 
     Log.d(APP_TAG, "failed to create directory"); 
    } 

      //creating a URI for the file we just created 
      imageUri=Uri.fromFile(mediaStorageDir); 


    return imageUri; 


} 


public void takePhoto(View v){ 
    // Check permissions 
    if (!marshMallowPermission.checkPermissionForCamera() 
      || !marshMallowPermission.checkPermissionForExternalStorage()){ 
     marshMallowPermission.requestPermissionForCamera(); 
    } else { 

     // set file name, will pass to getFileUri to convert it into a URI 
     String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date()); 
     photoFileName = "IMG_"+timeStamp+".jpg"; 
     Uri file_uri = getFileUri(photoFileName); 

     //just to print it to see if everything alright 
     System.out.println(file_uri); 

     //a intent specifically to start the android camera 
     Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
     //a intent used in conjunction with the image/video taking, telling where (in URI formate) where to store the picture taken 
     takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, file_uri); 


     // Start the image capture intent to take photo 
     startActivityForResult(takePictureIntent, MY_PERMISSIONS_REQUEST_OPEN_CAMERA); 



    } 


} 

} 
*/ 

適配器:

public class ImageAdapter extends BaseAdapter { 

private Context mContext; 

public ImageAdapter(Context c) { 
    mContext = c; 
} 

public int getCount() { 
    return mThumbIds.length; 
} 

public Object getItem(int position) { 
    return null; 
} 

public long getItemId(int position) { 
    return 0; 
} 

// create a new ImageView for each item referenced by the Adapter 
public View getView(int position, View convertView, ViewGroup parent) { 
    ImageView imageView; 

    if (convertView == null) { 
     // if it's not recycled, initialize some attributes 
     imageView = new ImageView(mContext); 
     imageView.setLayoutParams(new GridView.LayoutParams(250, 250)); 
     imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); 
     imageView.setPadding(8, 8, 8, 8); 
    } else { 
     imageView = (ImageView) convertView; 
    } 

    imageView.setImageResource(mThumbIds[position]); 
    return imageView; 
} 

// references to our images 
private Integer[] mThumbIds = { 
     R.drawable.s1, R.drawable.s2, 
     R.drawable.s4, R.drawable.s5, 
     R.drawable.s6, R.drawable.s3, 

}; 

}

回答

0

這是解決方案btw,抱歉花了這麼長時間我沒有意識到其他人正在等待答案。抱歉。相關代碼如下。

這是AsyncTask,它將查詢設備的MediaStore並檢索所有照片。請注意,這是檢索縮略圖而不是全尺寸圖像,更具體地說是MICRO_KIND。還有一個Thumbnail.MINI_KIND。

/*----------------------------ASYNC TASK TO LOAD THE  PHOTOS------------- 
-------------------------------------------*/ 

public class LoadPhotos extends AsyncTask<Object, Object, Object> { 

@Override 
protected Object doInBackground(Object... params) { 
    try { 
     final String[] columns = { MediaStore.Images.Media._ID }; 
     final String orderBy = MediaStore.Images.Media._ID; 

     Cursor imagecursor = managedQuery(
       MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, 
       null, null, orderBy); 

     int image_column_index = imagecursor 
       .getColumnIndex(MediaStore.Images.Media._ID); 

     AllPhotosActivity.count = imagecursor.getCount(); 
     AllPhotosActivity.windows = new Bitmap[AllPhotosActivity.count]; 

     for (int i = 0; i < AllPhotosActivity.count; i++) { 
      imagecursor.moveToPosition(i); 
      // i = index; 
      int id = imagecursor.getInt(image_column_index); 
      windows[i] = MediaStore.Images.Thumbnails.getThumbnail(
        getApplicationContext().getContentResolver(), id, 
        MediaStore.Images.Thumbnails.MICRO_KIND, null); 
     } 

     imagecursor.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
     Log.d("AllPhotosActivity", 
       "Error occured while fetching all photos on device."); 
    } 
    return null; 

} 

@Override 
protected void onPostExecute(Object result) { 
    // TODO Auto-generated method stub 
    super.onPostExecute(result); 
    Handler mHandler = new Handler(); 

    mHandler.post(new Runnable() { 

     public void run() { 

      pd.dismiss(); 
      // imageAdapter.notifyDataSetChanged(); 
      // sdcardImages.setAdapter(imageAdapter); 

     } 

    }); 

    // pd.dismiss(); 
    imagegrid.setAdapter(imageAdapter); 
    // pd.dismiss(); 

} 

@Override 
protected void onProgressUpdate(Object... values) { 
    // TODO Auto-generated method stub 
    super.onProgressUpdate(values); 
} 

} 

這裏是GridView的適配器,它將綁定縮略圖到gridview。我的問題只是在我的ImageAdapter的getView方法,注意我設置我的ImageView資源從我稱爲Windows的Bitmaps數組的不同索引。

public class ImageAdapter extends BaseAdapter { 
private Context mContext; 

public ImageAdapter(Context c) { 
    mContext = c; 
} 

public Object getItem(int position) { 
    // TODO Auto-generated method stub 
    return position; 
} 

public long getItemId(int position) { 
    // TODO Auto-generated method stub 
    return position; 
} 

public View getView(int position, View convertView, ViewGroup parent) { 
    ImageView i = (ImageView) convertView; 
    if (i != null) { 
     i.setImageBitmap(windows[position]); 
    } else { 
     i = new ImageView(mContext.getApplicationContext()); 
     // i.setPadding(3, 3, 3, 3); 
     // i.setScaleType(ImageView.ScaleType.FIT_CENTER); 
     i.setAdjustViewBounds(true); 
     // i.setMaxHeight(200); 
     // i.setMaxWidth(200); 
     i.setPadding(3, 3, 3, 3); 
     i.setLayoutParams(new GridView.LayoutParams(92, 92)); 
     i.setImageBitmap(windows[position]); 

    } 
    return i; 
} 

public int getCount() { 
    // TODO Auto-generated method stub 
    return count; 
} 
} 
+0

它似乎沒有工作。某些變量和方法無法解決,例如AllPhotosActivity,managedQuery,getApplicationContext,windows –

+0

請幫忙解釋一下爲什麼我們需要在這裏使用縮略圖? –