1

Estou desenvolvendo um app que contém uma galeria e encontrei um tutorial que mostrava como preencher o GridView com foto tiradas da câmera.

Porém, estou com dificuldade para fazer algo para quando a foto for clicada, abrir uma activity com a foto clicada.

Segue meu código:

public class GaleriaSp extends Activity implements OnClickListener{

    Button captureBtn = null;
    final int CAMERA_CAPTURE = 1;
    private Uri picUri;
    private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private GridView grid;
    private  List<String> listOfImagesPath;

    public static final String GridViewDemo_ImagePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/GridViewDemo/";


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

        captureBtn = (Button)findViewById(R.id.capture_btn1);
        captureBtn.setOnClickListener(this);
        grid = ( GridView) findViewById(R.id.gridviewimg);

        listOfImagesPath = null;
        listOfImagesPath = RetriveCapturedImagePath();
        if(listOfImagesPath!=null){
            grid.setAdapter(new ImageListAdapter(this,listOfImagesPath));
       }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_galeria_sp, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View arg1) {
        if (arg1.getId() == R.id.capture_btn1) {

            try {
    //use standard intent to capture an image
                Intent captureIntent = new         Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    //we will handle the returned data in onActivityResult
                startActivityForResult(captureIntent, CAMERA_CAPTURE);
            } catch(ActivityNotFoundException anfe){
//display an error message
                String errorMessage = "Whoops - your device doesn't support capturing images!";
                Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
                toast.show();
            }
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
   //user is returning from capturing an image using the camera
            if(requestCode == CAMERA_CAPTURE){
                Bundle extras = data.getExtras();
                Bitmap thePic = extras.getParcelable("data");
                String imgcurTime = dateFormat.format(new Date());
                File imageDirectory = new File(GridViewDemo_ImagePath);
                imageDirectory.mkdirs();
                String _path = GridViewDemo_ImagePath + imgcurTime+".jpg";
                try {
                    FileOutputStream out = new FileOutputStream(_path);
                    thePic.compress(Bitmap.CompressFormat.JPEG, 90, out);
                    out.close();
                } catch (FileNotFoundException e) {
                    e.getMessage();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                listOfImagesPath = null;
                listOfImagesPath = RetriveCapturedImagePath();
                if(listOfImagesPath!=null){
                    grid.setAdapter(new ImageListAdapter(this,listOfImagesPath));
                }
            }
        }
    }

    private List<String> RetriveCapturedImagePath() {
        List<String> tFileList = new ArrayList<String>();
        File f = new File(GridViewDemo_ImagePath);
        if (f.exists()) {
            File[] files=f.listFiles();
            Arrays.sort(files);

            for(int i=0; i<files.length; i++){
                File file = files[i];
                if(file.isDirectory())
                    continue;
                tFileList.add(file.getPath());
            }
        }
        return tFileList;
    }

    public class ImageListAdapter extends BaseAdapter
    {
        private Context context;
        private List<String> imgPic;
        public ImageListAdapter(Context c, List<String> thePic)
        {
            context = c;
            imgPic = thePic;
        }
        public int getCount() {
            if(imgPic != null)
                return imgPic.size();
            else
                return 0;
        }

        //---returns the ID of an item---
        public Object getItem(int position) {
            return position;
        }

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

        //---returns an ImageView view---
        public View getView(int position, View convertView, ViewGroup parent)
        {
            ImageView imageView;
            BitmapFactory.Options bfOptions=new BitmapFactory.Options();
            bfOptions.inDither=false;                     //Disable Dithering mode
            bfOptions.inPurgeable=true;                   //Tell to gc that whether it needs free memory, the Bitmap can be cleared
            bfOptions.inInputShareable=true;              //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future
            bfOptions.inTempStorage=new byte[32 * 1024];
            if (convertView == null) {
                imageView = new ImageView(context);
                imageView.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                imageView.setPadding(0, 0, 0, 0);
            } else {
                imageView = (ImageView) convertView;
            }
            FileInputStream fs = null;
            Bitmap bm;
            try {
                fs = new FileInputStream(new File(imgPic.get(position).toString()));

                if(fs!=null) {
                    bm=BitmapFactory.decodeFileDescriptor(fs.getFD(), null, bfOptions);
                    imageView.setImageBitmap(bm);
                    imageView.setId(position);
                    imageView.setLayoutParams(new GridView.LayoutParams(150, 150));
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally{
                if(fs!=null) {
                    try {
                        fs.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return imageView;
        }
    }
}

uma obs: na outra activity tive que declara essas variaveis.

private int position;
private BitmapFactory.Options bfOptions;

Aqui o logcat:

08-16 09:30:25.730  16083-16083/sptour.hotmail.com E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.ClassCastException: android.widget.AbsListView$LayoutParams cannot be cast to android.widget.RelativeLayout$LayoutParams
            at android.widget.RelativeLayout$DependencyGraph.findRoots(RelativeLayout.java:1352)
            at android.widget.RelativeLayout$DependencyGraph.getSortedViews(RelativeLayout.java:1299)
            at android.widget.RelativeLayout.sortChildren(RelativeLayout.java:316)
            at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:337)
            at android.view.View.measure(View.java:15598)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5118)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
            at android.view.View.measure(View.java:15598)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5118)
            at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:391)
            at android.view.View.measure(View.java:15598)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5118)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at android.view.View.measure(View.java:15598)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5118)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1396)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
            at android.view.View.measure(View.java:15598)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5118)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2423)
            at android.view.View.measure(View.java:15598)
            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2008)
            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1247)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1422)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1140)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4647)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
            at android.view.Choreographer.doCallbacks(Choreographer.java:555)
            at android.view.Choreographer.doFrame(Choreographer.java:525)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
            at android.os.Handler.handleCallback(Handler.java:615)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:174)
            at android.app.ActivityThread.main(ActivityThread.java:4952)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
            at dalvik.system.NativeStart.main(Native Method)

1 Resposta 1

1

No seu Adapter, coloque um Listener na imageView:

                imageView.setImageBitmap(bm);
                imageView.setId(position);
                imageView.setLayoutParams(new GridView.LayoutParams(150, 150));
                imageView.setOnClickListener(new View.OnClickListener()
                {
                  @Override
                  public void onClick(View v){
                  String imagem = imgPic.get(position).toString();
                  Intent i = new Intent(GaleriaSp.this, OutraActivity.class);//mude aqui de acordo com a sua activity
                  i.putExtra("img", imagem);
                  startActivity(i);
                }

                });

Na outra Activity, receba a imagem usando:

String img = getIntent().getStringExtra("img");

E coloque a imagem na imageView:

FileInputStream fs = null;
            Bitmap bm;
            try {
                fs = new FileInputStream(new File(img));

                if(fs!=null) {
                    bm=BitmapFactory.decodeFileDescriptor(fs.getFD(), null, bfOptions);
                    imageView.setImageBitmap(bm);
                    imageView.setId(position);
                    imageView.setLayoutParams(new GridView.LayoutParams(150, 150));
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally{
                if(fs!=null) {
                    try {
                        fs.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
7
  • ola Rosário Pereira Fernandez , obg por me responder , Só que tive problema , fiz tudo que me passo e ta dando error , meu logcat postei na minha pergunta Agradeço desde de já Commented 17/08/2016 às 17:27
  • Nas linhas onde voce tem : imageView.setLayoutParams(new GridView.LayoutParams(150, 150)); mude para imageView.setLayoutParams(new ImageView.LayoutParams(150, 150)); Commented 17/08/2016 às 20:03
  • CARA MUITO OBRIGADO VOCÊ SALVOU MINHA VIDA, OBRIGADO A ESSE SITE EXELENTE. OBG DE CORAÇÃO JA CONSEGUIR Commented 18/08/2016 às 0:20
  • Meu querido como eu faço para tem um botão para apaga certa foto que usuário quer ???? Commented 26/08/2016 às 19:07
  • Isso é outro assunto. Você tem de criar uma outra pergunta no site para que eu e/ou outras perguntas possamos responder. :) Commented 28/08/2016 às 9:30

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .