Php 在android中未使用AsyncTask上载图像

Php 在android中未使用AsyncTask上载图像,php,android,mysql,image,Php,Android,Mysql,Image,我正在开发用于图像上传的android应用程序。在我的应用程序中,我用名为“点击并上传”的按钮创建了六行。当用户点击按钮时,它打开相机并捕获图像,然后上传到服务器。我使用PHP MYSQL服务器上传图像。我使用异步任务将图像上传到服务器。但我面临的一个问题是,当我点击第二行按钮时,图像正在上传,但在成功上传图像后,Toast会显示两次。同样的事情发生在第三、第四、第六排的按钮上。我不知道为什么会发生 我面临的另一个问题是,当我在PreExecuted()中使用ProgressBar时方法快速上载

我正在开发用于图像上传的android应用程序。在我的应用程序中,我用名为“点击并上传”的按钮创建了六行。当用户点击按钮时,它打开相机并捕获图像,然后上传到服务器。我使用PHP MYSQL服务器上传图像。我使用异步任务将图像上传到服务器。但我面临的一个问题是,当我点击第二行按钮时,图像正在上传,但在成功上传图像后,Toast会显示两次。同样的事情发生在第三、第四、第六排的按钮上。我不知道为什么会发生

我面临的另一个问题是,当我在PreExecuted()中使用ProgressBar时方法快速上载第一个图像。但在第二个图像时,它仅显示正在运行的进度条。图像未成功上载。因此,我删除了进度条,然后将所有图像成功上载到服务器,但它显示Toast消息问题,如上所述

Kindle帮助我解决我的问题。我在这里附上完整的源代码

public class Upload extends Activity 
{   
    String type,fname,lname;
    TextView txttype,txtfname,txtlname;
    Button btnCapturePicture,btnupload,btnpp2,btnuplpp2,btnv1,btnuplv1,btnvisa2,btnuplv2,btnv3,btnuplv3,btnv4,btnuplv4;
    ProgressDialog pd;
    InputStream is;
    Bitmap bitmap,bitmap1,bitmap2,bitmap3,bitmap4,bitmap5;
    HashMap<String, String> dicCapturedImg = new HashMap<String, String>();
    private ImageView imgPreview,imgpp2,imgv1,imgv2,imgv3,imgv4; 
    private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
    private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;
    private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";
    //private Uri fileUri; // file url to store image/video

    protected void onCreate(Bundle savedInstanceState) 
    {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.upload);
        //thread.start();
        SharedPreferences sp=getSharedPreferences("mysp",0);
        type=sp.getString("type",null);
        fname=sp.getString("fname",null);
        lname=sp.getString("lname",null);

        btnCapturePicture=(Button)findViewById(R.id.button1);
        btnupload=(Button)findViewById(R.id.button2);
        btnpp2=(Button)findViewById(R.id.btnpp2);
        btnuplpp2=(Button)findViewById(R.id.nbtbpp2);

        btnv1=(Button)findViewById(R.id.btnv1);
        btnuplv1=(Button)findViewById(R.id.btnv2);

        btnvisa2=(Button)findViewById(R.id.btnvisa2);
        btnuplv2=(Button)findViewById(R.id.btnuplv2);

        btnv3=(Button)findViewById(R.id.btnv3);
        btnuplv3=(Button)findViewById(R.id.btnuplv3);

        btnv4=(Button)findViewById(R.id.btnv4);
        btnuplv4=(Button)findViewById(R.id.btnuplv4);


        imgPreview=(ImageView)findViewById(R.id.imgupload);
        imgpp2=(ImageView)findViewById(R.id.imgpp2);
        imgv1=(ImageView)findViewById(R.id.imgv1);
        imgv2=(ImageView)findViewById(R.id.imgv2);
        imgv3=(ImageView)findViewById(R.id.imgv3);
        imgv4=(ImageView)findViewById(R.id.imgv4);



        txtfname=(TextView)findViewById(R.id.txtfname);
        txtlname=(TextView)findViewById(R.id.txtlname);
        txttype=(TextView)findViewById(R.id.txttype);

        txtfname.setText(fname);
        txtlname.setText(lname);
        txttype.setText(type);



        btnCapturePicture.setOnClickListener(new View.OnClickListener() 
        {
            @Override
            public void onClick(View v) 
            {
                // capture picture
                captureImage("PP1");
                //btnupload.setVisibility(View.VISIBLE);

            }
        });

        btnupload.setOnClickListener(new View.OnClickListener() 
        {
            @Override
            public void onClick(View v) 
            {
                // TODO Auto-generated method stub
                if(bitmap==null)
                {
                    Toast.makeText(getApplicationContext(), "Please Select Image",Toast.LENGTH_LONG).show();

                }
                else
                {
                    new ImageUpload(bitmap).execute();
                    btnupload.setVisibility(View.GONE);
                }

            }
        });

        /*call this method on each button */
        btnpp2.setOnClickListener(new View.OnClickListener() 
        {
            @Override
            public void onClick(View v) 
            {
                // TODO Auto-generated method stub
                captureImage("PP2");
                //btnuplpp2.setVisibility(View.VISIBLE);
            }


        });

        btnuplpp2.setOnClickListener(new View.OnClickListener() 
        {

            @Override
            public void onClick(View v) 
            {
                // TODO Auto-generated method stub
                if(bitmap1==null)
                {
                    Toast.makeText(getApplicationContext(), "Please Select Image",Toast.LENGTH_LONG).show();

                }
                else
                {
                    new ImageUpload(bitmap1).execute();
                    btnuplpp2.setVisibility(View.GONE);
                }
            }
        });

        btnv1.setOnClickListener(new View.OnClickListener() 
        {

            @Override
            public void onClick(View v) 
            {
                // TODO Auto-generated method stub
                captureImage("V1");
                //btnuplv1.setVisibility(View.VISIBLE);


            }
        });

        btnuplv1.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                if(bitmap2==null)
                {
                    Toast.makeText(getApplicationContext(),"Please Select Image",Toast.LENGTH_LONG).show();

                }
                else
                {
                    new ImageUpload(bitmap2).execute();
                    btnuplv1.setVisibility(View.GONE);

                }
            }
        });


        btnvisa2.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                captureImage("V2");
                //btnuplv2.setVisibility(View.VISIBLE);



            }
        });
        btnuplv2.setOnClickListener(new View.OnClickListener() 
        {
            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                if(bitmap3==null)
                {
                    Toast.makeText(getApplicationContext(),"Please Select Image",Toast.LENGTH_LONG).show();

                }
                else
                {
                    new ImageUpload(bitmap3).execute();
                    btnuplv2.setVisibility(View.GONE);

                }

            }
        });
        btnv3.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                captureImage("V3");
                //btnuplv3.setVisibility(View.VISIBLE);
            }
        });
        btnuplv3.setOnClickListener(new View.OnClickListener() 
        {

            @Override
            public void onClick(View v) 
            {
                // TODO Auto-generated method stub
                if(bitmap4==null)
                {
                    Toast.makeText(getApplicationContext(),"Please Select Image",Toast.LENGTH_LONG).show();

                }
                else
                {
                    new ImageUpload(bitmap4).execute();
                    btnuplv3.setVisibility(View.GONE);

                }
            }
        });
        btnv4.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                captureImage("V4");
                //btnuplv4.setVisibility(View.VISIBLE);


            }
        });

        btnuplv4.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                if(bitmap5==null)
                {
                    Toast.makeText(getApplicationContext(),"Please Select Image",Toast.LENGTH_LONG).show();

                }
                else
                {
                    new ImageUpload(bitmap5).execute();
                    btnuplv4.setVisibility(View.GONE);

                }

            }
        });
    }

    /*
     * Capturing Camera Image will lauch camera app requrest image capture
     */
    private void captureImage(String DocType)
    {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,fileUri);
        // start the image capture Intent
        startActivityForResult(intent,CAMERA_CAPTURE_IMAGE_REQUEST_CODE);


        if(dicCapturedImg.containsKey(DocType))
        {
            dicCapturedImg.remove(DocType);
        }

        dicCapturedImg.put(DocType,fileUri.getPath());


    }

    /*@Override
    protected void onSaveInstanceState(Bundle outState) 
    {
        super.onSaveInstanceState(outState);

        // save file url in bundle as it will be null on scren orientation
        // changes
        outState.putParcelable("file_uri", fileUri);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState)
    {
        super.onRestoreInstanceState(savedInstanceState);

        // get the file url
        fileUri = savedInstanceState.getParcelable("file_uri");
    }*/
    /**
     * Receiving activity result method will be called after closing the camera
     * */
    @Override
    protected void onActivityResult(int requestCode,int resultCode,Intent data) 
    {
        // if the result is capturing Image
        if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) 
        {
            if (resultCode == RESULT_OK) 
            {
                // successfully captured the image
                // display it in image view
                previewCapturedImage();
            } else if (resultCode == RESULT_CANCELED) 
            {
                // user cancelled Image capture
                Toast.makeText(getApplicationContext(),
                        "User cancelled image capture", Toast.LENGTH_SHORT)
                        .show();
            } else 
            {
                // failed to capture image
                Toast.makeText(getApplicationContext(),
                        "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                        .show();
            }
        } else if (requestCode==CAMERA_CAPTURE_VIDEO_REQUEST_CODE) 
        {
            if (resultCode == RESULT_OK) 
            {
                // video successfully recorded
                // preview the recorded video

            } else if (resultCode == RESULT_CANCELED) 
            {
                // user cancelled recording
                Toast.makeText(getApplicationContext(),
                        "User cancelled video recording", Toast.LENGTH_SHORT)
                        .show();
            } else 
            {
                // failed to record video
                Toast.makeText(getApplicationContext(),
                        "Sorry! Failed to record video", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }



     /* Display image from a path to ImageView
     */
    private void previewCapturedImage() 
    {
        try 
        {
            // hide video preview


            //
           /* btnupload.setVisibility(View.VISIBLE);
            btnuplpp2.setVisibility(View.VISIBLE);
            btnuplv1.setVisibility(View.VISIBLE);*/

            // this string will store the path of image 
            String strImgPath_PP1="";
            String strImgPath_PP2="";
            String strImgPath_V1="";
            String strImgPath_V2="";
            String strImgPath_V3="";
            String strImgPath_V4="";


            if(dicCapturedImg.containsKey("PP1"))
            {
                strImgPath_PP1=dicCapturedImg.get("PP1");
                System.out.println("path"+strImgPath_PP1);


            }
            if(dicCapturedImg.containsKey("PP2"))
            {
                strImgPath_PP2 = dicCapturedImg.get("PP2");
                System.out.println("path"+strImgPath_PP2);

            }
            if(dicCapturedImg.containsKey("V1"))
            {
                strImgPath_V1 = dicCapturedImg.get("V1");
                System.out.println("path"+strImgPath_V1);
            }
            if(dicCapturedImg.containsKey("V2"))
            {
                strImgPath_V2 = dicCapturedImg.get("V2");
                System.out.println("path"+strImgPath_V2);
            }
            if(dicCapturedImg.containsKey("V3"))
            {
                strImgPath_V3 = dicCapturedImg.get("V3");
                System.out.println("path"+strImgPath_V3);
            }
            if(dicCapturedImg.containsKey("V4"))
            {
                strImgPath_V4 = dicCapturedImg.get("V4");
                System.out.println("path"+strImgPath_V4);
            }

            if(strImgPath_PP1 != "")
            {
                // bimatp factory
                BitmapFactory.Options options = new BitmapFactory.Options();
                // downsizing image as it throws OutOfMemory Exception for larger
                // images
                options.inSampleSize =8;
                bitmap=BitmapFactory.decodeFile(strImgPath_PP1,options);
                imgPreview.setImageBitmap(bitmap);
                new ImageUpload(bitmap).execute();
                // start thread and perform operation 



            }

            if(strImgPath_PP2!="")
            {
                // bimatp factory
                BitmapFactory.Options options1 = new BitmapFactory.Options();
                // downsizing image as it throws OutOfMemory Exception for larger
                // images
                options1.inSampleSize =8;
                bitmap=BitmapFactory.decodeFile(strImgPath_PP2,options1);
                imgpp2.setImageBitmap(bitmap);
                //new ImageUpload(bitmap).execute();
                new ImageUpload(bitmap).execute();



            }

            if(strImgPath_V1!="")
            {
                // bimatp factory
                BitmapFactory.Options options2 = new BitmapFactory.Options();
                // downsizing image as it throws OutOfMemory Exception for larger
                // images
                options2.inSampleSize =8;
                bitmap2=BitmapFactory.decodeFile(strImgPath_V1,options2);

                imgv1.setImageBitmap(bitmap2);
                //new ImageUpload(bitmap2).execute();

            }
            if(strImgPath_V2!="")
            {
                // bimatp factory
                BitmapFactory.Options options3 = new BitmapFactory.Options();
                // downsizing image as it throws OutOfMemory Exception for larger
                // images
                options3.inSampleSize =8;
                bitmap3=BitmapFactory.decodeFile(strImgPath_V2,options3);

                imgv2.setImageBitmap(bitmap3);
                //new ImageUpload(bitmap3).execute();
            }
            if(strImgPath_V3!= "")
            {
                // bimatp factory
                BitmapFactory.Options options4 = new BitmapFactory.Options();
                // downsizing image as it throws OutOfMemory Exception for larger
                // images
                options4.inSampleSize =8;
                bitmap4=BitmapFactory.decodeFile(strImgPath_V3,options4);

                imgv3.setImageBitmap(bitmap4);
                //new ImageUpload(bitmap4).execute();
            }
            if(strImgPath_V4 != "")
            {
                // bimatp factory
                BitmapFactory.Options options5 = new BitmapFactory.Options();
                // downsizing image as it throws OutOfMemory Exception for larger
                // images
                options5.inSampleSize =8;
                bitmap5=BitmapFactory.decodeFile(strImgPath_V4,options5);
                imgv4.setImageBitmap(bitmap5);
                new ImageUpload(bitmap5).execute();             


            }


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

    /*Thread thread=new Thread(new Runnable()
    {

        @Override
        public void run()
        {
            // TODO Auto-generated method stub
            try
            {
            ByteArrayOutputStream bao = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG,75,bao);
            byte [] ba = bao.toByteArray();
            String ba1=Base64.encodeToString(ba,1);
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://192.168.1.86/camera/upload2.php");
            nameValuePairs.add(new BasicNameValuePair("image",ba1));
            nameValuePairs.add(new BasicNameValuePair("name",fname));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
           // Toast.makeText(getApplicationContext(), "Image Upload Successfully", Toast.LENGTH_LONG).show();
            }
            catch(Exception e)
            {
                Log.d("error", "thread",e);
            }
        }
    });*/
    /*
     * Creating file uri to store image/video
     */
    public Uri getOutputMediaFileUri(int type) 
    {
        return Uri.fromFile(getOutputMediaFile(type));
    }

    /*
     * returning image / video
     */
    private static File getOutputMediaFile(int type) 
    {

        // External sdcard location
        File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                IMAGE_DIRECTORY_NAME);

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
                        + IMAGE_DIRECTORY_NAME + " directory");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());

        // here id full path of image with names
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE) 
        {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "IMG_" + timeStamp + ".jpg");
        } else if (type == MEDIA_TYPE_VIDEO) 
        {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "VID_" + timeStamp + ".mp4");
        } else 
        {
            return null;
        }

        return mediaFile;
    }

    public class ImageUpload extends AsyncTask<String, String,Bitmap>
    {
        Bitmap bitmap;
        public ImageUpload(Bitmap bitmap) 
        {
            // TODO Auto-generated constructor stub
            this.bitmap=bitmap;
        }
        @Override
        protected void onPreExecute() 
        {
            // TODO Auto-generated method stub
            super.onPreExecute();
            /*pd=new ProgressDialog(Upload.this);
            pd.setMessage("Please Wait Image is Uploading");
            pd.setCancelable(false);
            pd.show();
*/      }
        @Override
        protected Bitmap doInBackground(String... params) 
        {
            // TODO Auto-generated method stub
            try
            {   
            ByteArrayOutputStream bao = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG,75,bao);
            byte [] ba = bao.toByteArray();
            String ba1=Base64.encodeToString(ba,1);
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://192.168.1.86/camera/upload2.php");
            nameValuePairs.add(new BasicNameValuePair("image",ba1));
            nameValuePairs.add(new BasicNameValuePair("name",fname));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            }
            catch(Exception e)
            {
            Log.e("log_tag", "Error in http connection "+e.toString());
            } 
            return null;
        }
        protected void onPostExecute(Bitmap result) 
        {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            Toast.makeText(getApplicationContext(), "Image Successfully Uploaded",Toast.LENGTH_SHORT).show();
            //pd.dismiss();

        }
    }



}
公共类上载扩展了活动
{   
字符串类型,fname,lname;
TextView txttype、txtfname、txtlname;
按钮btnCapturePicture、btnupload、btnpp2、btnuplpp2、btnv1、btnuplv1、btnvisa2、btnuplv2、btnv3、btnuplv3、btnv4、btnuplv4;
进展性帕金森病;
输入流为;
位图位图,位图1,位图2,位图3,位图4,位图5;
HashMap dicapturedimg=新HashMap();
私有ImageView imgPreview、imgpp2、imgv1、imgv2、imgv3、imgv4;
专用静态最终int摄像机\捕获\图像\请求\代码=100;
专用静态最终int摄像机\捕获\视频\请求\代码=200;
公共静态最终int媒体类型图像=1;
公共静态最终int媒体类型视频=2;
私有静态最终字符串图像\u目录\u NAME=“Hello Camera”;
//私有Uri fileUri;//用于存储图像/视频的文件url
创建时受保护的void(Bundle savedInstanceState)
{
//TODO自动生成的方法存根
super.onCreate(savedInstanceState);
setContentView(R.layout.upload);
//thread.start();
SharedReferences sp=getSharedReferences(“mysp”,0);
type=sp.getString(“type”,null);
fname=sp.getString(“fname”,null);
lname=sp.getString(“lname”,null);
btnCapturePicture=(按钮)findViewById(R.id.button1);
btnupload=(按钮)findViewById(R.id.button2);
btnpp2=(按钮)findViewById(R.id.btnpp2);
btnuplpp2=(按钮)findViewById(R.id.nbtbpp2);
btnv1=(按钮)findViewById(R.id.btnv1);
btnuplv1=(按钮)findViewById(R.id.btnv2);
btnvisa2=(按钮)findViewById(R.id.btnvisa2);
btnuplv2=(按钮)findViewById(R.id.btnuplv2);
btnv3=(按钮)findViewById(R.id.btnv3);
btnuplv3=(按钮)findviewbyd(R.id.btnuplv3);
btnv4=(按钮)findViewById(R.id.btnv4);
btnuplv4=(按钮)findViewById(R.id.btnuplv4);
imgPreview=(ImageView)findViewById(R.id.imgupload);
imgpp2=(ImageView)findViewById(R.id.imgpp2);
imgv1=(ImageView)findViewById(R.id.imgv1);
imgv2=(ImageView)findViewById(R.id.imgv2);
imgv3=(ImageView)findViewById(R.id.imgv3);
imgv4=(ImageView)findViewById(R.id.imgv4);
txtfname=(TextView)findViewById(R.id.txtfname);
txtlname=(TextView)findViewById(R.id.txtlname);
txttype=(TextView)findViewById(R.id.txttype);
txtfname.setText(fname);
txtlname.setText(lname);
txttype.setText(类型);
btnCapturePicture.setOnClickListener(新视图.OnClickListener()
{
@凌驾
公共void onClick(视图v)
{
//截图
captureImage(“PP1”);
//btnupload.setVisibility(View.VISIBLE);
}
});
btnupload.setOnClickListener(新视图.OnClickListener()
{
@凌驾
公共void onClick(视图v)
{
//TODO自动生成的方法存根
如果(位图==null)
{
Toast.makeText(getApplicationContext(),“请选择图像”,Toast.LENGTH\u LONG.show();
}
其他的
{
新建图像上载(位图).execute();
btnupload.setVisibility(View.GONE);
}
}
});
/*在每个按钮上调用此方法*/
btnpp2.setOnClickListener(新视图.OnClickListener()
{
@凌驾
公共void onClick(视图v)
{
//TODO自动生成的方法存根
captureImage(“PP2”);
//btnuplpp2.setVisibility(View.VISIBLE);
}
});
btnuplpp2.setOnClickListener(新视图.OnClickListener()
{
@凌驾
公共void onClick(视图v)
{
//TODO自动生成的方法存根
如果(位图1==null)
{
Toast.makeText(getApplicationContext(),“请选择图像”,Toast.LENGTH\u LONG.show();
}
其他的
{
新建ImageUpload(bitmap1).execute();
btnuplpp2.setVisibility(View.GONE);
}
}
});
btnv1.setOnClickListener(新视图.OnClickListener()
{
@凌驾
公共void onClick(视图v)
{
//TODO自动生成的方法存根
captureImage(“V1”);
//btnuplv1.setVisibility(View.VISIBLE);
}
});
btnuplv1.setOnClickListener(新视图.OnClickListener()
{
@凌驾
公共void onClick(视图v)
{
//TODO自动生成的方法存根
如果(位图2==null)
{
Toast.makeText(getApplicationContext(),“请选择图像”,Toast.LENGTH\u LONG.show();
}