Question

I am new to android programming. So i am following some tutorials in order to learn it. I am trying to upload an image to a php server. I have followed this tutorial http://monstercoda.wordpress.com/2012/04/15/android-image-upload-tutorial-part-i/

everything works but the only problem is i dont know where to write this code and on which method.

HttpUploader uploader = new HttpUploader();
try {
  String image_name = uploader.execute(getRealPathFromURI(currImageURI)).get();        
} catch (InterruptedException e) {
  e.printStackTrace();
} catch (ExecutionException e) {
  e.printStackTrace();
}

i have tried to write this code in my onCreate Method of MainActivity or my MainUploader class but the app crashes. if i dont write this code the app works but obviously i cant be able to perform the full functionality.

here i have written this code which causes the app crash

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    HttpUploader uploader = new HttpUploader();
    try {
        image_name = uploader.execute(getRealPathFromURI(currImageURI)).get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    Button upload_btn = (Button) this.findViewById(R.id.uploadButton);
}

please tell me where i can place the above code.

Was it helpful?

Solution 2

You can't run this Code in onCreate() i guess, because you don't have the URI of your picture set yet. You are getting that URI after you browse with Get Content Intent, so you have to excute the HttpUploader after that.

One possible Solution is to put that HttpUploader Code into onActivityResult() after getting the realPath, so after:

currImageURI = data.getData();

EDIT:

// To handle when an image is selected from the browser
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
    if (requestCode == 1) {
    // currImageURI is the global variable I’m using to hold the content:
        currImageURI = data.getData();
        System.out.println(“Current image Path is ----->” + 
                       getRealPathFromURI(currImageURI));
        TextView tv_path = (TextView) findViewById(R.id.path);
        tv_path.setText(getRealPathFromURI(currImageURI));

        try{
            HttpUploader uploader = new HttpUploader();
            image_name = uploader.execute(getRealPathFromURI(currImageURI)).get();       
        } catch (Exception e) {
           e.printStackTrace();
        }
    }
}
}

OTHER TIPS

use following code for uploading

 public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon);           ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
        byte [] byte_arr = stream.toByteArray();
        String image_str = Base64.encodeBytes(byte_arr);
        ArrayList<NameValuePair> nameValuePairs = new  ArrayList<NameValuePair>();

        nameValuePairs.add(new BasicNameValuePair("image",image_str));

         Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
              try{
                     HttpClient httpclient = new DefaultHttpClient();
                     HttpPost httppost = new HttpPost("http://10.0.2.2/Upload_image_ANDROID/upload_image.php");
                     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                     HttpResponse response = httpclient.execute(httppost);
                     String the_string_response = convertResponseToString(response);
                     runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                Toast.makeText(UploadImage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();                          
                            }
                        });

                 }catch(Exception e){
                      runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            Toast.makeText(UploadImage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();                              
                        }
                    });
                       System.out.println("Error in http connection "+e.toString());
                 }  
        }
    });
     t.start();
    }

    public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{

         String res = "";
         StringBuffer buffer = new StringBuffer();
         inputStream = response.getEntity().getContent();
         int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
          runOnUiThread(new Runnable() {

        @Override
        public void run() {
            Toast.makeText(UploadImage.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();                     
        }
    });

         if (contentLength < 0){
         }
         else{
                byte[] data = new byte[512];
                int len = 0;
                try
                {
                    while (-1 != (len = inputStream.read(data)) )
                    {
                        buffer.append(new String(data, 0, len)); //converting to string and appending  to stringbuffer…..
                    }
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                try
                {
                    inputStream.close(); // closing the stream…..
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                res = buffer.toString();     // converting stringbuffer to string…..

                runOnUiThread(new Runnable() {

                @Override
                public void run() {
                   Toast.makeText(UploadImage.this, "Result : " + res, Toast.LENGTH_LONG).show();
                }
            });
                //System.out.println("Response => " +  EntityUtils.toString(response.getEntity()));
         }
         return res;
    }

}

hope it will help you...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top