Wednesday, August 2, 2017

Circular Percentage view representation on Android and iOS using Xamarin Forms


This Sample one contains the Circular percentage view drawing using Skiasharp.
I have seen that there are some controls available but they have licence and not free.
Hence I came up with this option and designed accordingly

Steps:
1) Create the Xamarin forms project with PCL, .iOS and .Droid Modules.

2)  Add the NuGet package by searching with SkiaSharp.Views.Forms package and add it to your solution. If you check the References section of each project after adding SkiaSharp, you can see that various SkiaSharp libraries have been added to each of the projects in the solution.
If your Xamarin.Forms application targets iOS, use the project properties page to change the minimum deployment target to iOS 8.0.
3) Crete the Xaml Page  and add the Below code
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:CircularPercentageSample"
                                      xmlns:skia="clrnamespace:SkiaSharp.Views.Forms;assembly=SkiaSharp.Views.Forms"
             x:Class="CircularPercentageSample.MainPage">
        <Grid  Grid.Row="0">
            <skia:SKCanvasView x:Name="canvasView"
                               PaintSurface="OnCanvasViewPaintSurface" />

            <StackLayout HorizontalOptions="Center" VerticalOptions="Center">
                <Label Text="50%" TextColor="Black"/>
            </StackLayout>
        </Grid>
    
 </ContentPage>

4) In Code behind Class add the below code
     public partial class MainPage: ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }
       SKPaint outlinePaint = new SKPaint
        {
            Style = SKPaintStyle.Stroke,
            StrokeWidth = 15,
            Color = SKColors.Gray
        };

        SKPaint arcPaint = new SKPaint
        {
            Style = SKPaintStyle.Stroke,
            StrokeWidth = 15,
            Color = SKColors.Blue
        };
        void sliderValueChanged(object sender, ValueChangedEventArgs args)
        {
            if (canvasView != null)
            {
                canvasView.InvalidateSurface();
            }
        }

        void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
        {
            SKImageInfo info = args.Info;
            SKSurface surface = args.Surface;
            SKCanvas canvas = surface.Canvas;

            canvas.Clear();

            SKRect rect = new SKRect(100, 100, info.Width - 100, info.Height - 100);

            canvas.DrawOval(rect, outlinePaint);

            using (SKPath path = new SKPath())
            {
                path.AddArc(rect, 270, 90);
                canvas.DrawPath(path, arcPaint);
            }
        }
    }
5) Set the MainPage as CirclePageSample  and select the target application and launch.

This will show the Circular percentage representation in the Page.

Thank you,

Wednesday, July 24, 2013

Android Getting Device Size in MB Programatically

     This Post helps to get the device Internal storage space,Freespace and Used Space


 // Return size is in Megabytes
     public class DeviceMemory {

        public static long getInternalStorageSpace()
        {
            StatFs statFs = new StatFs(Environment.getDataDirectory().getAbsol             utePath());
            //StatFs statFs = new StatFs("/data");
            long total = ((long)statFs.getBlockCount() * (long)statFs.getBlock            Size()) / 1048576;
            return total;
        }

        public static long getInternalFreeSpace()
        {
            StatFs statFs = new StatFs(Environment.getDataDirectory().getAbsol            utePath());
            //StatFs statFs = new StatFs("/data");
            long free  = ((long)statFs.getAvailableBlocks() * (long)statFs.get            BlockSize()) / 1048576;
            return free;
        }

        public static long getInternalUsedSpace()
        {
            StatFs statFs = new StatFs(Environment.getDataDirectory().getAbsol            utePath());
            //StatFs statFs = new StatFs("/data");
            long total = ((long)statFs.getBlockCount() * (long)statFs.getBlock            Size()) / 1048576;
            long free  = ((long)statFs.getAvailableBlocks() * (long)statFs.get            BlockSize()) / 1048576;
            long busy  = total - free;
            return busy;
        }
     }

Wednesday, May 15, 2013

Android Studio

Introducing Android Studio .

Android Studio is a new Android development environment based on IntelliJ IDEA. Similar to Eclipse with the ADT Plugin, Android Studio provides integrated Android developer tools for development and debugging. On top of the capabilities you expect from IntelliJ, Android Studio offers:

http://developer.android.com/sdk/installing/studio.html#side-nav

For Tips and Tricks

http://developer.android.com/sdk/installing/studio-tips.html

The Complete keymap about Intellij Idea as follows below

http://www.jetbrains.com/idea/documentation/index.jsp

Wednesday, May 8, 2013

REST and SOAP


SOAP - "Simple Object Access Protocol"
SOAP is a method of transferring messages, or small amounts of information, over the Internet. SOAP messages are formatted in XML and are typically sent using HTTP (hypertext transfer protocol).

  • SOAP builds an XML protocol on top of HTTP or sometimes TCP/IP.
  • SOAP describes functions, and types of data.
  • SOAP is a successor of XML-RPC and is very similar, but describes a standard way to communicate.
  • Several programming languages have native support for SOAP, you typically feed it a web service URL and you can call its web service functions without the need of specific code.
  • Binary data that is sent must be encoded first into a format such as base64 encoded.
  • Has several protocols and technologies relating to it: WSDL, XSDs, SOAP, WS-Addressing


Rest - Representational state transfer
Rest is a simple way of sending and receiving data between client and server and it doesn't have any much standards defined. You can send and receive data as JSON, XML or even plain text. It's light weighted compared to SOAP.
  • REST need not be over HTTP but most of my points below will have an HTTP bias.
  • REST is very lightweight, it says wait a minute, we don't need all of this complexity that SOAP created.
  • Typically uses normal HTTP methods instead of a big XML format describing everything. For example to obtain a resource you use HTTP GET, to put a resource on the server you use HTTP PUT. To delete a resource on the server you use HTTP DELETE.
  • REST is a very simple in that it uses HTTP GET, POST and PUT methods to update resources on the server.
  • REST typically is best used with Resource Oriented Architecture (ROA). In this mode of thinking everything is a resource, and you would operate on these resources.
  • As long as your programming language has an HTTP library, and most do, you can consume a REST HTTP protocol very easily.
  • Binary data or binary resources can simply be delivered upon their request.


enter image description here

Tuesday, May 7, 2013

Announcing OkHttp for Open source Android and Java


Android has two HTTP clients built-in:
  • Apache HTTP Client is stable yet basic.
  • HttpURLConnection supports advanced features, but suffers a few annoying bugs on older devices.
At Square, we want it all: advanced features that work right on every device. We also want to ship new tech without waiting for new Android releases.
OkHttp is our new open source HTTP client for Android and Java. Our goal is to build the most robust, most efficient HTTP client.



Robust

Flaky networks are a fact of life, especially on mobile. OkHttp employs a few strategies to automatically recover should a connection fail.
For example, if your web service is hosted in multiple data centers for redundancy, OkHttp will attempt each IP address until it finds one that works. It also recovers from failed TLS handshakes and troublesome proxy servers.
The code is based on the latest version of Android’s HttpURLConnection, which has been battle-tested against real-world web servers.

Efficient

The fastest download is the one you don’t have to make. OkHttp includes an integrated response cache. Unlike an application-level cache, the integrated cache uses conditional requests to extend the life of stale resources.
When OkHttp does hit the network, it uses transparent response compression and a sophisticated connection pool. These on-by-default optimizations save bandwidth and reduce latency.
My favorite feature is the SPDY backend. This is Google’s efficient new wire transport layer that is the starting point for the new HTTP 2.0 draft. SPDY enables multiple concurrent requests to share a single socket. This lowers the cost of HTTPS so you no longer have to choose between security and performance.

Give it a try!

If you’ve written an Android app, OkHttp may improve the speed & reliability of your networking. It supports both the HttpURLConnection and HttpClient APIs so you can upgrade painlessly.
If you’re writing a new app, the project website has code examples to get you started.
Get OkHttp from Maven or download it from the project website.

Friday, April 26, 2013

Uploading Image to Server Path Using MultipartEntity Library

Here the fallowing will explains how to upload the image to server.
using multipartentity using     httpmime-4.1.2.jar


The following code will help to acheives without loosing the Image quality




public class ImageUpload extends Activity {
private static final int PICK_IMAGE = 1;
private ImageView imgView;
private Button upload;
private EditText caption;
private Bitmap bitmap;
private ProgressDialog dialog;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imageupload);

imgView = (ImageView) findViewById(R.id.ImageView);
upload = (Button) findViewById(R.id.Upload);
caption = (EditText) findViewById(R.id.Caption);
upload.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
if (bitmap == null) {
Toast.makeText(getApplicationContext(),
"Please select image", Toast.LENGTH_SHORT).show();
} else {
dialog = ProgressDialog.show(ImageUpload.this, "Uploading",
"Please wait...", true);
new ImageUploadTask().execute();
}
}
});

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.imageupload_menu, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.ic_menu_gallery:
try {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"),
PICK_IMAGE);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_IMAGE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = data.getData();
String filePath = null;

try {
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();

// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);

if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}

if (filePath != null) {
decodeFile(filePath);
} else {
bitmap = null;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
break;
default:
}
}

class ImageUploadTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... unsued) {
try {

Date now = new Date(); // java.util.Date, NOT java.sql.Date or java.sql.Timestamp!
String format = new SimpleDateFormat("yyyyMMddHHmmss").format(now);
String fileName =format+".jpg";
String pID = "1000";
Log.i("Timestamp",fileName);
String url = "http://test.uspdhub.com/muspdhub1.0/m_service/Handler.ashx?PhotoCaption="+fileName+"&PID="+pID;

HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);

MultipartEntity entity = new MultipartEntity();

ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
Log.i("Bytes are",""+data.toString());
// entity.addPart("returnformat", new StringBody("json"));
entity.addPart("uploaded", new ByteArrayBody(data,"image/jpeg","image.jpg"));
// entity.addPart("photoCaption", new StringBody(caption.getText().toString()));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,
localContext);
String sResponse = EntityUtils.getContentCharSet(response.getEntity());
/*BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));

String sResponse = reader.readLine();*/
return sResponse;
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}

// (null);
}

@Override
protected void onProgressUpdate(Void... unsued) {

}

@Override
protected void onPostExecute(String sResponse) {
try {
if (dialog.isShowing())
dialog.dismiss();

if (sResponse != null) {

Toast.makeText(getApplicationContext(),
sResponse+" Photo uploaded successfully",
Toast.LENGTH_SHORT).show();
/*JSONObject JResponse = new JSONObject(sResponse);
int success = JResponse.getInt("SUCCESS");
String message = JResponse.getString("MESSAGE");
if (success == 0) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Photo uploaded successfully",
Toast.LENGTH_SHORT).show();
caption.setText("");
}*/
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}

public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}

public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);

// The new size we want to scale to
final int REQUIRED_SIZE = 1024;

// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}

// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);

imgView.setImageBitmap(bitmap);

}
}



Tuesday, April 2, 2013

Handling OutOfMemory Exception When Sending or Uploading Large Images to the Server From Android Activity

This Post provides the solution for OutOfMemoryException for large image uploades or server requests as Base64 encoded String format.

The code as follows.

1) The image which I am picking from either camera or from gallery .

 Dialog for pick the image.


private void startDialog() {

AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
myAlertDialog.setTitle("Upload Pictures Option");
myAlertDialog.setMessage("How do you want to set your picture?");

myAlertDialog.setPositiveButton("Gallery",
new DialogInterface.OnClickListener() {

public void onClick(DialogInterface arg0, int arg1) {
pictureActionIntent = new Intent(
Intent.ACTION_GET_CONTENT, null);
pictureActionIntent.setType("image/*");
pictureActionIntent.putExtra("return-data", true);
// Intent intent = new Intent(Intent.ACTION_PICK,
// android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(
pictureActionIntent, "Select Picture"),
GALLERY_PICTURE);
}
});

myAlertDialog.setNegativeButton("Camera",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {

pictureActionIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File f = null;
try {
f = setUpPhotoFile();
mCurrentPhotoPath = f.getAbsolutePath();
pictureActionIntent.putExtra(
MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));

} catch (IOException e) {
e.printStackTrace();
f = null;
mCurrentPhotoPath = null;
}
startActivityForResult(pictureActionIntent,
CAMERA_PICTURE);
}
});
myAlertDialog.show();
}



2)  Next I will set the image to image view in OnActivityresult() method as follows.



public void onActivityResult(int requestCode, int resultCode, Intent data) {

if (resultCode == RESULT_OK) {

switch (requestCode) {

case GALLERY_PICTURE:

Log.i(TAG, "INSIDE GALLERY PICTURE>>>>>>>>>>>>>>>>>>>>");
if (data != null) {

Uri imageUri = data.getData();

if(bitmap != null && !bitmap.isRecycled()){
attachImage.setImageBitmap(bitmap);
bitmap.isRecycled();
bitmap = null;
}
try {
bitmap = MediaStore.Images.Media.getBitmap(
this.getContentResolver(), imageUri);
attachImage.setImageBitmap(bitmap);
attachImage.setVisibility(View.VISIBLE);
// getImageByteAsString(bitmap);

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

break;

case CAMERA_PICTURE:
Log.i(TAG, "INSIDE CAMERAPICTURE>>>>>>>>>>>>>>>>>>>>");
if (mCurrentPhotoPath != null) {
setPic();
// galleryAddPic();

} else {
if (data != null) {
Uri imageUri = data.getData();
if(bitmap != null && !bitmap.isRecycled()){
attachImage.setImageBitmap(null);
bitmap.recycle();
bitmap = null;
}
try {
bitmap = MediaStore.Images.Media.getBitmap(
this.getContentResolver(), imageUri);
attachImage.setImageBitmap(bitmap);
attachImage.setVisibility(View.VISIBLE);
// getImageByteAsString(bMap);

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
break;
}
}
}

3) I will decode the bitmap as follows.


private void setPic() {

/* There isn't enough memory to open up more than a couple camera photos */
/* So pre-scale the target bitmap into which the file is decoded */

/* Get the size of the ImageView */
int targetW = 200;
int targetH = 200;

/* Get the size of the image */
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;

/* Figure out which way needs to be reduced less */
int scaleFactor = 1;
if ((targetW > 0) || (targetH > 0)) {
scaleFactor = Math.min(photoW / targetW, photoH / targetH);
}

/* Set bitmap options to scale the image decode target */
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;

if (bitmap != null && !bitmap.isRecycled()) {
attachImage.setImageBitmap(null);
bitmap.recycle();
bitmap = null;
}

/* Decode the JPEG file into a Bitmap */
bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);

/* Associate the Bitmap to the ImageView */
attachImage.setImageBitmap(bitmap);
attachImage.setVisibility(View.VISIBLE);

// getImageByteAsString(bitmap);
}


4) Scaling the Image to overcome the out of memory exception while converting Base64 encoding format.


call the below method as requst of your image bytes in the form of Base64 encoded string.


private String getImageByteAsString(Bitmap bitmap) {
String bitmapStr = null;
try {

Bitmap bmap = Bitmap.createScaledBitmap(bitmap, 100, 100, true);

ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();

// here chance to get Out Of Memory Exception
bitmapStr = Base64.encodeToString(b, Base64.DEFAULT);

baos.close();
baos = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return bitmapStr;
}


the above scaled and recycled bitmap will solves the issue.