简体   繁体   中英

why imageview cannot be cast in android widget button in android

I am very new in android programming. I want to show my captured picture after camera shot in my layout and also want to show picture which will be selected from gallery. i have made a alert dialog box for this option and has set implicit intent for uploading functionalities. but when i am going run program ClassCastException occur and it says

Caused by:java.lang.classcastException android.widget.ImageView cannot be cast to android.widget.Button

I have a selectbutton and a ImageView in my  activity_layout. here is my code

Main Activity

package com.example.imagelist;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;

import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;


public class MainImageListActivity extends Activity implements OnClickListener

{

    int REQUEST_CAMERA=0;
    int SELECT_FILE=1;

    Button selectButton;
    ImageView imgview;
    public String[]dialougeitems={"Capture Photo","Choose From Gallery","Cancel"};
    FileOutputStream fos;
    Bitmap bitmap;



    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_image_list);
        initialComponent();
        selectButton.setOnClickListener(this);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_image_list, 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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void initialComponent()
    {
       selectButton=(Button)findViewById(R.id.button1);
       imgview=(ImageView)findViewById(R.id.imageView1);
    }

    public void imageSelection()
    {
        AlertDialog.Builder alertbuilder=new AlertDialog.Builder(MainImageListActivity.this);
        alertbuilder.setTitle("Add Photo");
        alertbuilder.setItems(dialougeitems, new DialogInterface.OnClickListener() 
        {

            @Override
            public void onClick(DialogInterface dialog, int items) 
            {
                // TODO Auto-generated method stub
                if(dialougeitems[items].equals("Capture Photo"))
                {
                    Intent captureintent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(captureintent,REQUEST_CAMERA);

                }
                else if(dialougeitems[items].equals("Choose From Gallery"))
                {
                    Intent gallerychose=new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    gallerychose.setType("image/*");
                   startActivityForResult(Intent.createChooser(gallerychose, "SELECT FILE"),SELECT_FILE);

                }

                else if(dialougeitems[items].equals("Cancel"))
                {
                    dialog.dismiss();
                }



            }
        });

        alertbuilder.show();


    }
   @Override
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK)
        {
            if(requestCode==REQUEST_CAMERA)
            {
                Bitmap thumbshot=(Bitmap)data.getExtras().get("data");
                ByteArrayOutputStream bytes=new ByteArrayOutputStream();
                thumbshot.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
                File destfolder=new File(Environment.getExternalStorageDirectory(),System.currentTimeMillis()+".jpg");
                try
                {

                    destfolder.createNewFile();
                    fos=new FileOutputStream(destfolder);
                    fos.write(bytes.toByteArray());
                    fos.close();

                }
                catch(FileNotFoundException e)
                {
                    e.printStackTrace();

                }
                catch(IOException ie)
                {
                    ie.printStackTrace();
                }



                imgview.setImageBitmap(thumbshot);

            }

            else if(requestCode==SELECT_FILE)
            {
                Uri galleryImageUri=data.getData();
                String[]projection={MediaColumns.DATA};
                CursorLoader imagecursorloader=new CursorLoader(this,galleryImageUri,projection,null,null, null);
                Cursor imagecursor=imagecursorloader.loadInBackground();
                int imageColumnIndex=imagecursor.getColumnIndexOrThrow(MediaColumns.DATA);
                imagecursor.moveToFirst();
                String imagepath=imagecursor.getString(imageColumnIndex);
                BitmapFactory.Options mapoption=new BitmapFactory.Options();
                mapoption.inJustDecodeBounds=true;
                BitmapFactory.decodeFile(imagepath,mapoption);
                final int REQUIRED_SIZE=200;
                int scale=1;
                while(mapoption.outWidth/scale/2 >=REQUIRED_SIZE
                        && mapoption.outHeight/scale/2>=REQUIRED_SIZE)
                    scale*=2;
                mapoption.inSampleSize=scale;
                mapoption.inJustDecodeBounds=false;
                bitmap=BitmapFactory.decodeFile(imagepath,mapoption);
                imgview.setImageBitmap(bitmap);


            }


        }
    }


    @Override
    public void onClick(View v) 
    {
        // TODO Auto-generated method stub
        imageSelection();


    }
}

Moreover i want to show my imagefile path in a dynamic list that means i will select pic and the link will be automatically add in list. that is my final goal but i stucked from the beginning . i need guidance for procede . How can i solve this current exception . Any help will be appreciated thank you

You have an ImageView. You're trying to cast it as Button. That's only legal if the view returned is a Button or a subclass of Button. ImageView isn't, even if you're using it as one. Cast it to the correct class type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM