2

I have an application where I need to snap camera image and upload accordingly. Below are my codes. I am having issue in uploading when I try from my phone and could not view what is the exact problem because I use async task. So I am testing on my emulator where I can the image but when comes to this line Toast.makeText(getApplicationContext(), "File Path is :"+selectedImage,Toast.LENGTH_LONG).show(); it prints null for the path on emulator but on the phone it prints the exact path. How to overcome this so that I can do debuging why it fails to upload.

public class Capture extends Activity implements OnClickListener {
    private static final int CAMERA_REQUEST = 1888; 
    private ImageView imageView;
    private Button scanBtn1,scanBtn2,submitBtn;
    private TextView vhlTxt,sstTxt;
    private int btnClicked = 0;
    private String selectedImagePath = ""; 

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.capture);
        this.imageView = (ImageView)this.findViewById(R.id.imageView1);
        Button photoButton = (Button) this.findViewById(R.id.button1);
        photoButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
                startActivityForResult(cameraIntent, CAMERA_REQUEST); 
            }
        });

        scanBtn1 = (Button)findViewById(R.id.button2);
        scanBtn2 = (Button)findViewById(R.id.button3);
        scanBtn2 = (Button)findViewById(R.id.btnSubmit);
        vhlTxt = (TextView)findViewById(R.id.editText1);
        sstTxt = (TextView)findViewById(R.id.editText2);
        scanBtn1.setOnClickListener(this);
        scanBtn2.setOnClickListener(this);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        //Toast.makeText(getApplicationContext(), "on activiet result",Toast.LENGTH_LONG).show();
        if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {  
            Bitmap photo = (Bitmap) data.getExtras().get("data"); 
            imageView.setImageBitmap(photo);
            Uri selectedImage = data.getData();
            //String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Toast.makeText(getApplicationContext(), "File Path is :"+selectedImage,Toast.LENGTH_LONG).show();
            try { 
                selectedImagePath = getPath(selectedImage);
                Toast.makeText(getApplicationContext(), "get path :"+selectedImagePath,Toast.LENGTH_LONG).show();

                File sourceFile = new File(selectedImagePath.toString()); 
                if(sourceFile.isFile())
                {
                Toast.makeText(getApplicationContext(), "build stream :"+selectedImage.toString(),Toast.LENGTH_LONG).show();

                FileInputStream fileInputStream = new FileInputStream(sourceFile);
                int bytesAvailable = fileInputStream.available();
                Toast.makeText(getApplicationContext(), "size of file is :"+bytesAvailable,Toast.LENGTH_LONG).show();
                }
                else
                    Toast.makeText(getApplicationContext(), "no source file",Toast.LENGTH_LONG).show();

            } 
            catch (Exception e) {

            }
        }  
        else{
            IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
            if (scanningResult != null) {
                String scanContent = scanningResult.getContents();
                Toast toast = Toast.makeText(getApplicationContext(), 
                        "Data received!"+scanContent, Toast.LENGTH_LONG);
                    toast.show();
                    if(btnClicked==2)
                        vhlTxt.setText(scanContent); 
                    else if(btnClicked==3)
                        sstTxt.setText(scanContent); 
                }
            else{
                Toast toast = Toast.makeText(getApplicationContext(), 
                    "No scan data received!", Toast.LENGTH_LONG);
                toast.show();
            }
        }
    }

    public void onClick(View v){
        //respond to clicks
        //Toast.makeText(getApplicationContext(), "Done with it",Toast.LENGTH_LONG).show();
        if(v.getId()==R.id.button2){
            btnClicked=2;
            //Toast.makeText(getApplicationContext(), "Done with it",Toast.LENGTH_LONG).show();
            IntentIntegrator scanIntegrator = new IntentIntegrator(this);
            scanIntegrator.initiateScan();

        }
        else if(v.getId()==R.id.button3){
            btnClicked=3;
            //Toast.makeText(getApplicationContext(), "Done with it",Toast.LENGTH_LONG).show();
            IntentIntegrator scanIntegrator = new IntentIntegrator(this);
            scanIntegrator.initiateScan();

        }
        else if(v.getId()==R.id.btnSubmit){

                ProgressDialog progressDialog = new ProgressDialog(Capture.this);
                progressDialog.setMessage("Uploading......");
                progressDialog.setCancelable(false);

                uploadTask ut = new uploadTask(Sealing.this, progressDialog);

                ut.execute(selectedImagePath,vhlTxt.getText().toString(),sstTxt.getText().toString());
          }
    }



    private String getPath(Uri uri) {

        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(uri, projection, null, null,null);

        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();

        return cursor.getString(column_index);
    }
    public void showUploadError(String result)
    {
        Toast.makeText(getApplicationContext(), "upload error :"+result.toString(),Toast.LENGTH_LONG).show();

    }
    public void showUploadOk(String result)
    {
        Toast.makeText(getApplicationContext(), "upload ok :"+result.toString(),Toast.LENGTH_LONG).show();

    }

}

Here is the upload task function which is called when I press the submit button. I have confirm my upload1.php is working fine because I have used my another php file to test upload on this page and it works. Any tips to improve or where could be the issue ?

public class uploadTask extends AsyncTask<String, Void, Integer> {

    private ProgressDialog progressDialog;
    private Capture activity;
    private int id = -1;
    private String resultUpload = "";

    public uploadTask(Capture activity, ProgressDialog progressDialog)
    {
        this.activity = activity;
        this.progressDialog = progressDialog;
    }

    @Override
    protected void onPreExecute()
    {
        progressDialog.show();
    }

    @Override
    protected Integer doInBackground(String... arg0) 
    {

         String lineEnd = "\r\n";
         String twoHyphens = "--";
         String boundary = "*****";
         String Tag="fSnd";


        String result = "";
        int responseCode = 0;
        try 
        {

            Log.e(Tag,"Starting Http File Sending to URL");
            URL connectURL = new URL("http://*****/upload1.php");
            File sourceFile = new File(arg0[0]);
            String iFileName = sourceFile.getName();

            if(sourceFile.isFile())
            {
            //Toast.makeText(getApplicationContext(), "build stream :"+selectedImage.toString(),Toast.LENGTH_LONG).show();

            FileInputStream fileInputStream = new FileInputStream(sourceFile);

            //Toast.makeText(getApplicationContext(), "size of file is :"+bytesAvailable,Toast.LENGTH_LONG).show();


            // Open a HTTP connection to the URL
            HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();

            // Allow Inputs
            conn.setDoInput(true);

            // Allow Outputs
            conn.setDoOutput(true);

            // Don't use a cached copy.
            conn.setUseCaches(false);

            // Use a post method.
            conn.setRequestMethod("POST");

            conn.setRequestProperty("Connection", "Keep-Alive");

            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"vhlID\""+ lineEnd);
            dos.writeBytes(lineEnd);
            dos.writeBytes(arg0[1]);
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + lineEnd);

            dos.writeBytes("Content-Disposition: form-data; name=\"sstID\""+ lineEnd);
            dos.writeBytes(lineEnd);
            dos.writeBytes(arg0[2]);
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + lineEnd);

            dos.writeBytes("Content-Disposition: form-data; name=\"uploadedFile\";filename=\"" + iFileName +"\"" + lineEnd);
            dos.writeBytes(lineEnd);

            Log.e(Tag,"Headers are written");

            // create a buffer of maximum size
            int bytesAvailable = fileInputStream.available();

            int maxBufferSize = 1024;
            int bufferSize = Math.min(bytesAvailable, maxBufferSize);
            byte[ ] buffer = new byte[bufferSize];

            // read file and write it into form...
            int bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0)
            {
                    dos.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable,maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0,bufferSize);
            }
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // close streams
            fileInputStream.close();

            dos.flush();

            Log.e(Tag,"File Sent, Response: "+String.valueOf(conn.getResponseCode()));

            InputStream is = conn.getInputStream();

            // retrieve the response from server
            int ch;

            StringBuffer b =new StringBuffer();
            while( ( ch = is.read() ) != -1 ){ b.append( (char)ch ); }
            resultUpload=b.toString();
           // Log.i("Response",s);
            dos.close();
            }

        }
        catch (Exception e) {
            responseCode = 408;
            e.printStackTrace();
        }
        return responseCode;
    }

    @Override
    protected void onPostExecute(Integer headerCode)
    {
        progressDialog.dismiss();


        if(headerCode == 200){

              activity.showUploadOk(resultUpload);
        }      
        else{
              activity.showUploadError(resultUpload);
        }
    }




}
user4126382
  • 125
  • 1
  • 12

1 Answers1

0

couple of things to try

Community
  • 1
  • 1
ashoke
  • 6,441
  • 2
  • 26
  • 25
  • Yes I did allocated 2000Mb for SD card on the emulator. I dont get your on the second suggestion where you mentioned try creating a file yourself ? Besides that I actually tried again on my phone I notice the code work but most of the times the response code is 200 but only at few time I see its on my server ? What could be the issue ? – user4126382 Oct 09 '14 at 18:31
  • 2nd suggestion is to make sure emulator photo app doesn't have problems creating a file itself to store the picture taken. If your app can pre-allocate the file, we can rule out that issue altogether. – ashoke Oct 09 '14 at 18:36
  • Ok I notice there is function saveFullImage which what I am missing. I am a bit lost where to call the function in the onActivityResult. Besides that do you see any major issue my codes because at times I notice the file gets uploaded successfully but most of the time it fails but response code is 200. – user4126382 Oct 09 '14 at 18:45
  • can you see image always before you click submit button ? – ashoke Oct 09 '14 at 19:01
  • Yes in both my emulator and phone I can see the image but in emulator I see Toast.makeText(getApplicationContext(), "File Path is :"+selectedImage,Toast.LENGTH_LONG).show(); prints ad File Path null but on the phone its ok. Issue now is that I notice some times on the phone it passes through and gets uploaded but most of the times it fails any think I can optimise ? – user4126382 Oct 09 '14 at 19:04
  • So I think now my focus is why it fails to upload but with responsecode 200. The main thing I wanted to see what that is the file details are passing which I know its passing but why it fails most of the time. – user4126382 Oct 09 '14 at 19:10
  • in your doInBackground, can you `Log.e(TAG, "File len : " + sourceFile.length());` Does it always show similar numbers for your uploads ? – ashoke Oct 09 '14 at 19:15
  • how to view the log if I am running on my phone. because on emulator I cant show it? – user4126382 Oct 09 '14 at 19:18
  • you will need to connect your phone with usb cable, type `adb devices` on cmd console window, verify your phone shows up in the list. Then, your IDE will ask which one to use for testing apk/app. Logcat will be relevant. – ashoke Oct 09 '14 at 19:20
  • @user4126382 try [using phone wifi with adb](http://stackoverflow.com/questions/4893953/android-run-install-debug-applications-over-wifi) if you do not have usb cable or having trouble. – ashoke Oct 09 '14 at 19:23
  • But where to type the adb devices which cmd console you mean the window one ? I type on the window one it say not recognised. I have cable not a problem for me but now I dont know to connect it so that when I run it directly run on my phone. – user4126382 Oct 09 '14 at 19:27
  • Beside that do you see any issue with my uploading do you advice to open a new question to ask why it showing response code 200 but upload is failed – user4126382 Oct 09 '14 at 19:27
  • yes, on windows console. `adb` is inside folder `\android-sdk\platform-tools\`, add it your path., try running `adb` now. – ashoke Oct 09 '14 at 19:28
  • @user4126382 yes, i suggest another question as this question seems related to emulator – ashoke Oct 09 '14 at 19:29
  • I am using the eclipse bundle from android. I dont see any place android-sdk where can I find it ? sorry I am new to this. – user4126382 Oct 09 '14 at 19:33
  • Click `Windows -> Preferences -> Android`, your SDK location path is shown there. Go to the folder, and there should be a `platform-tools` folder in it. Or just do a search for adb.exe in your windows explorer – ashoke Oct 09 '14 at 19:39