Monday, June 27, 2022

Set a limit on EditText character

const val RESTRICTED_CHARS = "€<>;"
fun restrictCharacterFilter(regexString:String) = InputFilter { source, _, _, _, _, _ ->
if (source != null && regexString.contains(source)) {
""
} else null

}


textInputEditText.filters = arrayOf(restrictCharacterFilter(RESTRICTED_CHARS), 
emojiFilter(), InputFilter.LengthFilter(30))

Wednesday, August 3, 2016

Force Localisation Android

 Step 1:Create One java class which extends from 'Application'  
 public class LocaleApplication extends Application{  
   private Locale mLocale = null;  
   @Override  
   public void onConfigurationChanged(Configuration newConfig) {  
     super.onConfigurationChanged(newConfig);  
     if (mLocale != null) {  
       newConfig.locale = mLocale;  
       Locale.setDefault(mLocale);  
       getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics());  
     }  
   }  
   @Override  
   public void onCreate() {  
     super.onCreate();  
    updateLocale(BuildConfig.LOCALE);  
   }  
   public void updateLocale(Locale locale) {  
     Configuration config = getBaseContext().getResources().getConfiguration();  
     if (!config.locale.equals(locale)) {  
       mLocale = new Locale(locale.getLanguage(),locale.getCountry());  
       Locale.setDefault(mLocale);  
       config.locale = mLocale;  
       getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());  
       // reload challenge and achievement strings - these were created with the previous locale  
     }  
   }  
 }  
 Step 2: Mention this class name in Android manifest file under <application> tag  
 <application  
   android:name="LocaleApplication"  
   android:allowBackup="true"  
   android:icon="@mipmap/ic_launcher"  
   android:label="@string/app_name"  
   android:supportsRtl="true"  
   android:theme="@style/AppTheme">  
 Step 3: Take appropriate resource folders like values-es-rCO,values-el etc.   
 Step 4: Add below steps in build.gradle for resource configurations.  
 defaultConfig {  
   applicationId "com.example.ankitpr1.forcelocalisation_android"  
   minSdkVersion 15  
   targetSdkVersion 23  
   versionCode 1  
   versionName "1.0"  
   buildConfigField 'java.util.Locale', 'LOCALE_SPANISH_LATAM', 'new java.util.Locale(\"es\",\"US\")'  
   buildConfigField 'java.util.Locale', 'LOCALE_Greek', 'new java.util.Locale(\"el\")'  
 }  
 productFlavors {  
   esus{  
     applicationId 'com.colombia.us'  
     resConfigs 'es-rCO'  
     buildConfigField 'java.util.Locale', 'LOCALE', 'new java.util.Locale(\"es\",\"CO\")'  
     versionCode 3  
     versionName "3.0"  
     // ! any change in Locale, should be applied in defaultConfig as well  
   }  
   Greek {  
     applicationId 'com.test.greek'  
     resConfigs 'el'  
     buildConfigField 'java.util.Locale', 'LOCALE', 'new java.util.Locale(\"el\")'  
     versionCode 2  
     versionName "2.1"  
     l  
   }  
 }  
 //List all flavours in project to be used for check current flavour against others  
 productFlavours.all {  
   flavour ->  
     def flavourName = String.valueOf(flavour.name)  
     defaultConfig.buildConfigField 'String', 'Flavour_' + flavourName , '\"' + flavourName + '\"'  
 }  

Tuesday, March 1, 2016

Build variant type according to Locale

 Add below code under android--defaultConfig in build.gradle file  
 buildConfigField 'java.util.Locale', 'LOCALE_SPANISH_LATAM', 'new java.util.Locale(\"es\",\"US\")'  
 productFlavors {  
   esus{  
     applicationId 'com.praveena.test.us'  
     resConfigs 'es-rUS'  
     buildConfigField 'java.util.Locale', 'LOCALE', 'new java.util.Locale(\"es\",\"US\")'  
   }  
 }  
 By using this we can select the build variant type while running.  

Sunday, December 6, 2015

Web Service Call using Angulat JS


By using below code base we can do the web service call in Angular JS

 var req = {  
   method: 'GET',  
   url: LOGIN_URL,  
   params: {  
     registrationId: document.getElementById("username").value,  
     dob: document.getElementById("dob").value  
   }  
 }  
 $http(req).success(function(data, status, headers, config) {  
   var result = data;  
   if (result.status == 2) {  
     localStorage.permId = document.getElementById("username").value;  
     localStorage.applicantName = result.applicantName;  
     localStorage.Dob = result.Dob;  
     localStorage.mobileno = result.mobileno;  
     localStorage.Gender = result.Gender;  
     window.location.href = 'profile.html';  
   } else {  
     $scope.loading = false;  
     alert(data.returnObj2);  
     //Alert.render(data.returnObj2);  
   }  
 }).error(function() {  
   $scope.loading = false;  
   alert("Service is not available");  
   //AlertLogin.render();  
   //Alert.render("Service is not available");  
 });  

Thursday, December 3, 2015

Save Layout as image,Pdf to sdcard android


      private void saveLayoutAsPDFToSdcard() {  
           String PDF_FILE = "mnt/sdcard/invoice.pdf";  
           try {  
                View content = rootView.findViewById(R.id.ll_upperLayout);  
                content.setDrawingCacheEnabled(true);  
                content.setDrawingCacheEnabled(true);  
                // this is the important code :)   
                // Without it the view will have a dimension of 0,0 and the bitmap will be null       
                content.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),   
                      MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));  
                content.layout(0, 0, content.getMeasuredWidth(),content.getMeasuredHeight());   
                content.buildDrawingCache(true);  
                Bitmap bitmap = Bitmap.createBitmap(content.getDrawingCache());  
                content.setDrawingCacheEnabled(false);  
             Document document = new Document();  
             PdfWriter.getInstance(document, new FileOutputStream(PDF_FILE));  
             document.open();  
             ByteArrayOutputStream stream = new ByteArrayOutputStream();  
             bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);  
             byte[] byteArray = stream.toByteArray();  
             addImage(document,byteArray);  
             document.close();  
                 Log.v("PRAVEENA","====saved==");  
           } catch (FileNotFoundException e) {  
                // TODO Auto-generated catch block  
                Log.v("PRAVEENA","====failed==107"+e.toString());  
                e.printStackTrace();  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                Log.v("PRAVEENA","====failed 11111=="+e.toString());  
                e.printStackTrace();  
           } catch (DocumentException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
            }  
      private void addImage(Document document, byte[] byteArray) {  
           Image image = null;  
           try   
        {  
          image = Image.getInstance(byteArray);   
        }   
        catch (BadElementException e)   
        {  
          // TODO Auto-generated catch block  
          e.printStackTrace();  
        }  
        catch (MalformedURLException e)   
        {  
          // TODO Auto-generated catch block  
          e.printStackTrace();  
        }  
        catch (IOException e)   
        {  
          // TODO Auto-generated catch block  
          e.printStackTrace();  
        }  
         // image.scaleAbsolute(150f, 150f);  
         try   
         {  
          document.add(image);  
        } catch (DocumentException e) {  
          // TODO Auto-generated catch block  
          e.printStackTrace();  
        }  
      }  
 private void saveLayoutAsPNGToSdcard() {  
           try {  
                View content = rootView.findViewById(R.id.ll_upperLayout);  
                content.setDrawingCacheEnabled(true);  
                content.setDrawingCacheEnabled(true);  
                // this is the important code :)   
                // Without it the view will have a dimension of 0,0 and the bitmap will be null       
                content.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),   
                      MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));  
                content.layout(0, 0, content.getMeasuredWidth(),content.getMeasuredHeight());   
                content.buildDrawingCache(true);  
                Bitmap bitmap = Bitmap.createBitmap(content.getDrawingCache());  
                content.setDrawingCacheEnabled(false);  
 //               Bitmap bitmap = content.getDrawingCache();  
                File file,f = null;            
                if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))   
                  {   
                     file =new File(android.os.Environment.getExternalStorageDirectory(),"TTImages_cache");  
                     if(!file.exists())  
                    {  
                     file.mkdirs();  
                     }   
                     f = new File(file.getAbsolutePath()+file.separator+ "filename"+".png");  
                  }  
                 FileOutputStream ostream = new FileOutputStream(f);                    
                 bitmap.compress(CompressFormat.PNG, 10, ostream);  
                 ostream.close();  
                 Log.v("PRAVEENA","====saved==");  
           } catch (FileNotFoundException e) {  
                // TODO Auto-generated catch block  
                Log.v("PRAVEENA","====failed==107"+e.toString());  
                e.printStackTrace();  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                Log.v("PRAVEENA","====failed 11111=="+e.toString());  
                e.printStackTrace();  
           }  
            }   
To save Layout as pdf to sdcard we need itextpdflib

Friday, September 4, 2015

Display Owners information without unlocking your Phone

We cans see the owners information without unlocking your phone,This will be helpful in emergency cases.

Procedure to set the owners infomation using android mobiles

Goto Settings -->Security -->Owners Info --> Enable show owners info on lock screen and enter information there like emergency contact numbers etc.

Wednesday, May 6, 2015

Android Studio shortcuts like Eclipse

As far we are good to use the shortcut controls in eclipse. 
Now we are migrating to Android studio where the shortcuts are different while comparing Android studio and Eclipse.

 Please follow the below steps to enable the eclipse shortcut controls in Android studio if you want to use the same eclipse controls in Android Studio.
  1. Click on File menu
  2. Navigate to “Settings”
  3. Click on Keymap section which is available in left side panel
  4. You can see the keymaps dropdown on the right side panel. Select “Eclipse” from 
  5. Finally, save the settings by clicking on OK button.
Now you will be able to use the same eclipse controls in Android studio.

 Goto Settings -->Security -->Owners Info --> Enable show owners info on lock screen and enter information there like emergency contact numbers etc.  

Monday, March 10, 2014

Add our application into default chooser

activity
android:name=".WalkieTalkieActivity"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.CALL" />
<data android:scheme="tel" />
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.CALL_PRIVILEGED" />
</intent-filter>
</activity>


By using above code we can add our application to default chooser application in android 

Thursday, January 2, 2014

Finish all activities

 package com.hrupin;  
 import android.app.Activity;  
 import android.content.BroadcastReceiver;  
 import android.content.Context;  
 import android.content.Intent;  
 import android.content.IntentFilter;  
 public abstract class AppBaseActivity extends Activity {  
  public static final String FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION = "com.hrupin.FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION";  
  private BaseActivityReceiver baseActivityReceiver = new BaseActivityReceiver();  
  public static final IntentFilter INTENT_FILTER = createIntentFilter();  
  private static IntentFilter createIntentFilter() {  
  IntentFilter filter = new IntentFilter();  
  filter.addAction(FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION);  
  return filter;  
  }  
  protected void registerBaseActivityReceiver() {  
  registerReceiver(baseActivityReceiver, INTENT_FILTER);  
  }  
  protected void unRegisterBaseActivityReceiver() {  
  unregisterReceiver(baseActivityReceiver);  
  }  
  public class BaseActivityReceiver extends BroadcastReceiver {  
  @Override  
  public void onReceive(Context context, Intent intent) {  
   if (intent.getAction().equals(FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION)) {  
   finish();  
   }  
  }  
  }  
  protected void closeAllActivities() {  
  sendBroadcast(new Intent(FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION));  
  }  
 }  

Monday, September 2, 2013

Custom camera in android

custom camera in android

 public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {  
 private SurfaceHolder mHolder;  
 private Camera mCamera;  
 private Context mContext;  
 public CameraPreview(Context context, Camera camera) {  
 super(context);  
 mContext = context;  
 mCamera = camera;  
 // Install a SurfaceHolder.Callback so we get notified when the  
 // underlying surface is created and destroyed.  
 mHolder = getHolder();  
 mHolder.addCallback(this);  
 // deprecated setting, but required on Android versions prior to 3.0  
 mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);  
 mHolder.setFixedSize(100, 100);  
 }  
 public void surfaceCreated(SurfaceHolder holder) {  
 mCamera.setDisplayOrientation(90);  
 // The Surface has been created, now tell the camera where to draw the  
 // preview.  
 try {  
 mCamera.setPreviewDisplay(holder);  
 mCamera.startPreview();  
 }  
 catch (IOException e) {  
 Log.d(  
 "DG_DEBUG", "Error setting camera preview: " + e.getMessage());  
 }  
 /*try {  
 mCamera.setPreviewDisplay(holder);  
 mCamera.setPreviewCallback(new PreviewCallback() {  
 public void onPreviewFrame(byte[] data, Camera camera) {  
 }  
 });  
 } catch (Exception e) {  
 e.printStackTrace();  
 }*/  
 }  
 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {  
 // If your preview can change or rotate, take care of those events here.  
 // Make sure to stop the preview before resizing or reformatting it.  
 if (mHolder.getSurface() == null) {  
 // preview surface does not exist  
 return;  
 }  
 // stop preview before making changes  
 try {  
 mCamera.stopPreview();  
 }  
 catch (Exception e) {  
 // ignore: tried to stop a non-existent preview  
 }  
 // make any resize, rotate or reformatting changes here  
 // start preview with new settings  
 try {  
 mCamera.setPreviewDisplay(mHolder);  
 mCamera.startPreview();  
 }  
 catch (Exception e) {  
 Log.d(  
 "DG_DEBUG", "Error starting camera preview: " + e.getMessage());  
 }  
 }  
 public void surfaceDestroyed(SurfaceHolder holder) {  
 // empty. Take care of releasing the Camera preview in your activity.  
 }  
 }  
 and use the below method in your activiy which one wants custom camera   
 private  
 void createCamera() {   
 // Create an instance of Camera  
 mCamera = getCameraInstance();  
 // Setting the right parameters in the camera  
 Camera.Parameters params =  
 mCamera.getParameters();  
 // params.setPictureSize(1600, 1200);  
 params.setPictureFormat(PixelFormat.JPEG);  
 params.setJpegQuality(85);  
 mCamera.setParameters(params);  
 // Create our Preview view and set it as the content of our activity.  
 mPreview = new CameraPreview(this, mCamera);  
 FrameLayout preview = (FrameLayout) findViewById(R.id.  
 camera_preview);  
 // Calculating the width of the preview so it is proportional.  
 float widthFloat = (float) (deviceHeight) * 4 / 3;  
 int width = Math.round(widthFloat);  
 // Resizing the LinearLayout so we can make a proportional preview. This  
 // approach is not 100% perfect because on devices with a really small  
 // screen the the image will still be distorted - there is place for  
 // improvment.  
 // LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width, deviceHeight);  
 // preview.setLayoutParams(layoutParams);  
 // Adding the camera preview after the FrameLayout and before the button  
 // as a separated element.  
 preview.addView(  
 mPreview, 0);  
 }  
Take care of releasing the Camera preview in your activity.

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());
        }

Friday, September 16, 2011

store bitmap into sdcard and get it again

/////////////////////////////////////////////////////////////////////////////////

        /////          below code is used to save the bitmap into sdcard   ////////////////////

        /////////////////////////////////////////////////////////////////////////////////

        String extStorageDirectory = Environment.getExternalStorageDirectory().toString();;
        OutputStream outStream = null;
        File file = new File(extStorageDirectory, "SlectImage.PNG");
        try {
            outStream = new FileOutputStream(file);
            picturebitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            outStream.flush();
            outStream.close();

            Toast.makeText(PhotoManipulation.this, "Saved", Toast.LENGTH_LONG).show();

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(PhotoManipulation.this, e.toString(), Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(PhotoManipulation.this, e.toString(), Toast.LENGTH_LONG).show();
        }


        /////////////////////////////////////////////////////////////////////////////////

        /////          below code is used to get the saved image and set to imageview    ////////////////////

        /////////////////////////////////////////////////////////////////////////////////

        final String imageInSD = "/sdcard/SlectImage.PNG";

        Bitmap bitmap = BitmapFactory.decodeFile(imageInSD);

        ImageView myImageView = (ImageView)findViewById(R.id.imageview);
        myImageView.setImageBitmap(bitmap);

Scroll the image both horizontal and vertically


main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent">
    <FrameLayout android:layout_width="90px"
        android:layout_height="90px">
        <RelativeLayout android:id="@+id/container"
            android:layout_width="fill_parent" android:layout_height="fill_parent">
        </RelativeLayout>
    </FrameLayout>
</FrameLayout>


Test.Java

public class Test extends Activity
{
    private RelativeLayout container;
      private int currentX;
      private int currentY;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        container = (RelativeLayout)findViewById(R.id.container);

        int top = 0;
        int left = 0;

        ImageView image1 =new ImageView(this);
        image1.setImageResource(R.drawable.icon);//set the image whatever u scroll
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(left, top, 0, 0);              
        container.addView(image1, layoutParams);

       
      }    

      @Override
      public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                currentX = (int) event.getRawX();
                currentY = (int) event.getRawY();
                break;
            }

            case MotionEvent.ACTION_MOVE: {
                int x2 = (int) event.getRawX();
                int y2 = (int) event.getRawY();
                container.scrollBy(currentX - x2 , currentY - y2);
                currentX = x2;
                currentY = y2;
                break;
            }  
            case MotionEvent.ACTION_UP: {
                break;
            }
        }
          return true;
      }
    }

Check the internet service

Below code is used to check the INTERNET service

 ConnectivityManager connectivityManager;
        NetworkInfo wifiInfo, mobileInfo;
   
      
        public Boolean isNetAvailable(Context con)
        {
   
            try{
                connectivityManager = (ConnectivityManager) con.getSystemService(Context.CONNECTIVITY_SERVICE);
                wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                mobileInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);  
   
                if(wifiInfo.isConnected() || mobileInfo.isConnected())
                {
                    return true;
                }
            }
            catch(Exception e){
               e.printStackTrace();
            }
   
            return false;
        }



and following permissions are required for this


<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>