Tuesday, November 27, 2012

download data from url using http post

HttpClient httpclient = new DefaultHttpClient();

        HttpPost httppost = new HttpPost(mcontext.getString(R.string.find_link));
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("name", value);
        try {
            httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
        HttpResponse response = null;
        try {
            response = httpclient.execute(httppost);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        InputStream is = null;
        try {
            is = response.getEntity().getContent();
        } catch (IllegalStateException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        StringBuilder sb = new StringBuilder();
        byte[] buffer = new byte[512];
        int bytes_read = 0;

        try {
            while ((bytes_read = is.read(buffer, 0, buffer.length)) > 0) {
                sb.append(new String(buffer, 0, bytes_read));
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        mresult=sb.toString();

Add focus to a view

mhandler.post(new Runnable() {
            public void run() {
                    (EditText ref).requestFocus();                           
               
            }
        });

Wednesday, September 5, 2012

set the text size and font to datepicker

DatePicker picker = (DatePicker)findViewById(R.id.dp_date);
        ViewGroup childpicker

         = (ViewGroup)
        findViewById(Resources.getSystem().getIdentifier("month" /*rest is:
        day, year*/, "id", "android"));

        EditText textview = (EditText)
        picker.findViewById(Resources.getSystem().getIdentifier("timepicker_input",
        "id", "android"));
        textview.setTextSize(30);
        textview.setTextColor(Color.GREEN);

Sunday, January 29, 2012

send image from url as email attachemnt


                try {
                    File rootSdDirectory = Environment.getExternalStorageDirectory();

                    File pictureFile = new File(rootSdDirectory, "attachment.jpg");
                    if (pictureFile.exists()) {
                        pictureFile.delete();
                    }                  
                    pictureFile.createNewFile();

                    FileOutputStream fos = new FileOutputStream(pictureFile);

                    URL url = new URL(string);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setDoOutput(true);
                    connection.connect();
                    InputStream in = connection.getInputStream();

                    byte[] buffer = new byte[1024];
                    int size = 0;
                    while ((size = in.read(buffer)) > 0) {
                        fos.write(buffer, 0, size);
                    }
                    fos.close();
                   
                   
                   
                   
                   
                   
                    Intent sendIntent = new Intent(Intent.ACTION_SEND);
                    //Mime type of the attachment (or) u can use sendIntent.setType("*/*")
                    sendIntent.setType("image/jpeg");
                    //Subject for the message or Email
                    sendIntent.putExtra(Intent.EXTRA_SUBJECT, "My Picture");
                   
                    //Full Path to the attachment
                    Uri pictureUri = Uri.fromFile(pictureFile);
                    sendIntent.putExtra(Intent.EXTRA_STREAM, pictureUri);

                    //Use a chooser to decide whether email or mms
                    startActivity(Intent.createChooser(sendIntent, "Email:"));

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

               
           

Monday, November 21, 2011

Trusting all certificates using HttpClient over HTTPS

public class MySSLSocketFactory extends SSLSocketFactory {
        SSLContext sslContext = SSLContext.getInstance("TLS");

        public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException,
        KeyManagementException, KeyStoreException, UnrecoverableKeyException {
            super(truststore);

            TrustManager tm = new X509TrustManager() {
              

                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkClientTrusted(X509Certificate[] chain,
                        String authType) throws CertificateException {
                    // TODO Auto-generated method stub
                   
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain,
                        String authType) throws CertificateException {
                    // TODO Auto-generated method stub
                   
                }
            };

            sslContext.init(null, new TrustManager[] { tm }, null);
        }

        public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
        throws IOException, UnknownHostException {
            return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
        }

        @Override
        public Socket createSocket() throws IOException {
            return sslContext.getSocketFactory().createSocket();
        }
    }

    public HttpClient getNewHttpClient() {
        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);

            SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            registry.register(new Scheme("https", sf, 443));

            ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

            return new DefaultHttpClient(ccm, params);
        } catch (Exception e) {
            return new DefaultHttpClient();
        }
    }

   
    HttpClient httpclient = getNewHttpClient();
   
   
   

Wednesday, October 19, 2011

Resize the image

By using below code we can resize the image


            Bitmap bitmap  = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            int newWidth = 100;
            int newHeight = 100;

            // calculate the scale - in this case = 0.4f
            float scaleWidth = ((float) newWidth) / width;
            float scaleHeight = ((float) newHeight) / height;

            // createa matrix for the manipulation
            Matrix matrix = new Matrix();
            // resize the bit map
            matrix.postScale(scaleWidth, scaleHeight);

            Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                    width, height, matrix, true);

            ((ImageView) findViewById(R.id.ImageviewTest)).setImageBitmap(resizedBitmap);

Thursday, September 29, 2011

send json object to a json request

Through Below code we can add the json object to json request in android

HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(HTTPname);
        JSONObject json=new JSONObject();

        JSONArray Text_Field_Array = new JSONArray();

        JSONObject json_Text_Field = new JSONObject();
        json_Text_Field.put("pagenum", "1");
        json_Text_Field.put("text", "text field 1");
        json_Text_Field.put("font", "Arial");
        json_Text_Field.put("fontSize", "18");
        json_Text_Field.put("color", "ff0000");
        json_Text_Field.put("x", "100");
        json_Text_Field.put("y", "0");
        json_Text_Field.put("alignment", "left");

        Text_Field_Array.put(json_Text_Field);


        JSONArray image_Field_Array = new JSONArray();
        JSONObject json_image_Field = new JSONObject();
       
       
        File f=new File("/sdcard/SelectImage.png");
        ContentBody cb=new FileBody(f,"image/png");
//        reqEntity.addPart("point_image", cb);
       
        json_image_Field.put("image", cb);
        json_image_Field.put("pagenum", "1");
        json_image_Field.put("scale", "1");
        json_image_Field.put("rotation", "90");
        json_image_Field.put("x", "100");
        json_image_Field.put("y", "10");
        json_image_Field.put("width", "100");
        json_image_Field.put("height", "100");

        image_Field_Array.put(json_image_Field);

        json.put("images", image_Field_Array);
        json.put("all_text_fields", Text_Field_Array);
        json.put("sku", "CCI1022537");

        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        nvps.add(new BasicNameValuePair("carddata", json.toString()));
        httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        HttpResponse response = httpclient.execute(httppost);
        InputStream is = response.getEntity().getContent();

        if(response!=null){ 
            sb = new StringBuilder();
            byte[] buffer = new byte[512];
            int bytes_read = 0;

            while((bytes_read = is.read(buffer, 0, buffer.length)) > 0)
            {
                sb.append( new String(buffer,0,bytes_read));
            }
            System.out.println("Preview image Result=="+sb.toString());
        }