Wednesday, 13 July 2016

Convert 24 hours format to 12 hours format


change date format : 24 to 12 hours


 public static String Convert24to12(String time) {
        String convertedTime = "";
        try {
            SimpleDateFormat displayFormat = new SimpleDateFormat("hh:mm a",Locale.US);
            SimpleDateFormat parseFormat = new SimpleDateFormat("HH:mm:ss",Locale.US);
            Date date = parseFormat.parse(time);
            convertedTime = displayFormat.format(date);
            System.out.println("convertedTime : " + convertedTime);
        } catch (final ParseException e) {
            e.printStackTrace();
        }
        return convertedTime;
        //Output will be 10:23 PM
    }

Android underline in Textview


display underline with textview in android


 public static void mekeUnderLine(Context context, TextView textView) {
        Paint p = new Paint();
        p.setColor(context.getResources().getColor(R.color.app_pink));
        textView.setPaintFlags(p.getColor());
        textView.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
    }

Android - get Bitmap from url


 get image bitmap from web url


public static Bitmap getBitmapFromURL(String imageUrl) {
    try {
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

Tuesday, 28 June 2016

Android View Disappearing When Go Outside Of Parent



 Android: Animation gets clipped by parent view,


set android:clipChildren="false" android:clipToPadding="false"  to ALL parents of view


in xml code

android:clipChildren="false"
android:clipToPadding="false"

in code

iewGroup.setClipChildren(false);


http://stackoverflow.com/questions/18048997/android-view-disappearing-when-go-outside-of-parent

Saturday, 11 June 2016

Play GIF File in android




  Play GIF file in android very smoothly,


Download Demo here :

 https://drive.google.com/open?id=0B7De_mE7QNdOd2FVRlpTM0tYcUU

Custome Calendar (get whole days of month)


Create custome calendar in android

   // variables

    private static final int DAY_OFFSET = 1;
    private final String[] weekdays = new String[]{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
    private final String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
    private final int[] daysOfMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    private int daysInMonth;
    private int currentDayOfMonth;
    private int currentWeekDay;

    String tag = "tag";
    List<String> list;



//methods
private void printMonth(int mm, int yy) {
        Log.d(tag, "==> printMonth: mm: " + mm + " " + "yy: " + yy);
        int trailingSpaces = 0;
        int daysInPrevMonth = 0;
        int prevMonth = 0;
        int prevYear = 0;
        int nextMonth = 0;
        int nextYear = 0;
        int currentMonth = mm - 1;
        String currentMonthName = getMonthAsString(currentMonth);
        daysInMonth = getNumberOfDaysOfMonth(currentMonth);
        Log.d(tag, "Current Month: " + " " + currentMonthName + " having " + daysInMonth + " days.");
        GregorianCalendar cal = new GregorianCalendar(yy, currentMonth, 1);
        Log.d(tag, "Gregorian Calendar:= " + cal.getTime().toString());
        if (currentMonth == 11) {
            prevMonth = currentMonth - 1;
            daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
            nextMonth = 0;
            prevYear = yy;
            nextYear = yy + 1;
            Log.d(tag, "*->PrevYear: " + prevYear + " PrevMonth:" + prevMonth + " NextMonth: " + nextMonth + " NextYear: " + nextYear);
        } else if (currentMonth == 0) {
            prevMonth = 11;
            prevYear = yy - 1;
            nextYear = yy;
            daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
            nextMonth = 1;
            Log.d(tag, "**--> PrevYear: " + prevYear + " PrevMonth:" + prevMonth + " NextMonth: " + nextMonth + " NextYear: " + nextYear);
        } else {
            prevMonth = currentMonth - 1;
            nextMonth = currentMonth + 1;
            nextYear = yy;
            prevYear = yy;
            daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
            Log.d(tag, "***---> PrevYear: " + prevYear + " PrevMonth:" + prevMonth + " NextMonth: " + nextMonth + " NextYear: " + nextYear);
        }
        int currentWeekDay = cal.get(Calendar.DAY_OF_WEEK) - 1;
        trailingSpaces = currentWeekDay;
        Log.d(tag, "Week Day:" + currentWeekDay + " is " + getWeekDayAsString(currentWeekDay));
        Log.d(tag, "No. Trailing space to Add: " + trailingSpaces);
        Log.d(tag, "No. of Days in Previous Month: " + daysInPrevMonth);
        if (cal.isLeapYear(cal.get(Calendar.YEAR))) if (mm == 2) ++daysInMonth;

        else if (mm == 3)
            ++daysInPrevMonth; // Trailing Month days
        for (int i = 0; i < trailingSpaces; i++) {
            Log.d(tag, "PREV MONTH:= " + prevMonth + " => " + getMonthAsString(prevMonth) + " " + String.valueOf((daysInPrevMonth - trailingSpaces + DAY_OFFSET) + i));
            list.add(String.valueOf((daysInPrevMonth - trailingSpaces + DAY_OFFSET) + i) + "-GREY" + "-" + getMonthAsString(prevMonth) + "-" + prevYear);
        }
        /* Current Month Days*/
        for (int i = 1; i <= daysInMonth; i++) {
            Log.d(currentMonthName, String.valueOf(i) + " " + getMonthAsString(currentMonth) + " " + yy);
            if (i == getCurrentDayOfMonth()) {
                list.add(String.valueOf(i) + "-BLUE" + "-" + getMonthAsString(currentMonth) + "-" + yy);
            } else {
                list.add(String.valueOf(i) + "-WHITE" + "-" + getMonthAsString(currentMonth) + "-" + yy);
            }
        }
        /* Leading Month days*/
        for (int i = 0; i < list.size() % 7; i++) {
            Log.d(tag, "NEXT MONTH:= " + getMonthAsString(nextMonth));
            list.add(String.valueOf(i + 1) + "-GREY" + "-" + getMonthAsString(nextMonth) + "-" + nextYear);
        }
    }

    private String getMonthAsString(int i) {
        return months[i];
    }

    private String getWeekDayAsString(int i) {
        return weekdays[i];
    }

    private int getNumberOfDaysOfMonth(int i) {
        return daysOfMonth[i];
    }

    public String getItem(int position) {
        return list.get(position);
    }

    public int getCurrentDayOfMonth() {
        return currentDayOfMonth;
    }

    private void setCurrentDayOfMonth(int currentDayOfMonth) {
        this.currentDayOfMonth = currentDayOfMonth;
    }

    public void setCurrentWeekDay(int currentWeekDay) {
        this.currentWeekDay = currentWeekDay;
    }

    public int getCurrentWeekDay() {
        return currentWeekDay;
    }



   /// just call from activity
/////////////
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        list = new ArrayList<String>();
        printMonth(01, 90);// just pass month and year
    }

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

Download demo here : http://www.androidhub4you.com/2012/10/custom-calendar-in-android.html

Wednesday, 8 June 2016

Convert dptopx and pxtodp

Convert dptopx and pxtodp 

Convert dp to pixel:

public int dpToPx(int dp) {
    DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
    int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));       
    return px;
}


Convert pixel to dp:

public int pxToDp(int px) {
    DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
    int dp = Math.round(px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
    return dp;

}


Sunday, 29 May 2016

Blur image(image load from url) 


make image blur which is load from url


implement imageloader code with listener like......


imageLoader.displayImage(img1, imgCover, options1, new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String imageUri, View view) {
            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                Bitmap blurbmp = blur(loadedImage);

                //imgCover.setImageBitmap(blurbmp);
            }

            @Override
            public void onLoadingCancelled(String imageUri, View view) {
            }
        }, new ImageLoadingProgressListener() {
            @Override
            public void onProgressUpdate(String imageUri, View view, int current, int total) {

            }
        });


write method for blur image

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    public Bitmap blur(Bitmap image) {
        if (null == image) return null;

        Bitmap outputBitmap = Bitmap.createBitmap(image);
        final RenderScript renderScript = RenderScript.create(this);
        Allocation tmpIn = Allocation.createFromBitmap(renderScript, image);
        Allocation tmpOut = Allocation.createFromBitmap(renderScript, outputBitmap);

        //Intrinsic Gausian blur filter
        ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));
        theIntrinsic.setRadius(BLUR_RADIUS);
        theIntrinsic.setInput(tmpIn);
        theIntrinsic.forEach(tmpOut);
        tmpOut.copyTo(outputBitmap);
        return outputBitmap;
    }


// if issue of GC, or large bitmap(extra method)

public Bitmap blur(Bitmap image) {

    if (null == image)
        return null;

    final float BITMAP_SCALE = 0.4f;
    final float BLUR_RADIUS = 15f;

    int width = Math.round(image.getWidth() * BITMAP_SCALE);
    int height = Math.round(image.getHeight() * BITMAP_SCALE);

    Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
    Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);

    RenderScript rs = RenderScript.create(context);
    ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
    Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
    Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
    theIntrinsic.setRadius(BLUR_RADIUS);
    theIntrinsic.setInput(tmpIn);
    theIntrinsic.forEach(tmpOut);
    tmpOut.copyTo(outputBitmap);

    return outputBitmap;
}


Saturday, 28 May 2016

Change Time format 24 hours to 12 hours

Change Time format 24 hours to 12 hours



public static String convertToEventFormat(String date) {
    String finaldate = null;
    try {
           SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.US);
        Date date1 = fmt.parse(date);
        SimpleDateFormat fmtOut = new SimpleDateFormat("dd-MM-yyyy hh:mm aa",Locale.US);
        finaldate = fmtOut.format(date1);

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

    return finaldate;

}

Friday, 8 April 2016

Download file using default download functionality

Download file using default download functionality

Download from url
in this just send file url.


public void startDownload(Context context,String url) {


    String fullurl = url;
    String title = "title";
    String fileName = "title";
    try {

        String servicestring = Context.DOWNLOAD_SERVICE;
        DownloadManager downloadmanager;
        downloadmanager = (DownloadManager) context.getSystemService(servicestring);
        Uri uri = Uri.parse(fullurl);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setTitle(title);
        request.setDestinationInExternalPublicDir("/Download/MP3/",
                fileName + ".mp3");
        Long reference = downloadmanager.enqueue(request);

    } catch (Exception e) {

    }

}


Friday, 25 March 2016

Custome Graph View

Custome Graph View

custome line chart

//
add class to project

public class CustomeGraphview extends View {

   private Paint centerLinePaint;
   private GestureDetector gestureDetector;
   private Scroller scroller;
   private float nextX;
   private int maxX;
   private float currentX;
   private Paint tickPaint;
   private Paint tickTextPaint;
   private int startDistance;
   private int bitweenDistance;
   private int totalDistance;
   private int noOfMonth;
   ArrayList<Integer> arrListRates;
   ArrayList<String> arrListMonths;
   private int Line0, Line1, Line2, Line3, Line4, Line5, LineForText;
   private int lastX, lastY;
   boolean iScall = true;
   private int circleRadius = 3;

   @Override   protected void onSizeChanged(int w, int h, int oldw, int oldh) {
      super.onSizeChanged(w, h, oldw, oldh);
      Log.d("TAG", "onsize");
      bitweenDistance = (getWidth() / 6);
      startDistance = (getWidth() / 12);
      totalDistance = (bitweenDistance * (noOfMonth - 1))
            + (startDistance * 2);
      maxX = totalDistance - getWidth();

      Line5 = getHeight() / 7;
      Line4 = (getHeight() / 7) * 2;
      Line3 = (getHeight() / 7) * 3;
      Line2 = (getHeight() / 7) * 4;
      Line1 = (getHeight() / 7) * 5;
      Line0 = (getHeight() / 7) * 6;

      LineForText = Line0 + ((getHeight() / 7) / 2);
   }

   public void setDetail(ArrayList<Integer> arrListRates,
         ArrayList<String> arrListMonths, int noOfMonth) {

      this.arrListMonths = arrListMonths;
      this.arrListRates = arrListRates;
      this.noOfMonth = noOfMonth;
   }

   private Runnable requestLayoutRunnable = new Runnable() {
      public void run() {
         requestLayout();
      }
   };

   public CustomeGraphview(Context context, ArrayList<Integer> arrListRates,
         ArrayList<String> arrListMonths, int noOfMonth) {
      super(context);
      Log.d("TAG", "contstructor");
      this.arrListMonths = arrListMonths;
      this.arrListRates = arrListRates;
      if (arrListMonths.size() < 6) {
         this.noOfMonth = 6;
      } else {
         this.noOfMonth = arrListMonths.size();
      }
      initView();
   }

   private void initView() {
      Log.d("TAG", "init view");
      if (centerLinePaint != null) {
         return;
      }

      centerLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
      centerLinePaint.setStrokeWidth(5.0f);
      centerLinePaint.setColor(Color.argb(255, 38, 189, 190));

      tickPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
      tickPaint.setStrokeWidth(1.0f);
      tickPaint.setColor(Color.argb(200, 181, 181, 181));

      tickTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
      tickTextPaint.setStrokeWidth(1.0f);
      tickTextPaint.setColor(Color.argb(255, 181, 181, 181));

      nextX = getWidth();
      currentX = 0;

      scroller = new Scroller(getContext());
      gestureDetector = new GestureDetector(getContext(),
            new GestureDetector.SimpleOnGestureListener() {
               @Override               public boolean onDown(MotionEvent e) {
                  return CustomeGraphview.this.onDown(e);
               }

               @Override               public boolean onFling(MotionEvent e1, MotionEvent e2,
                     float velocityX, float velocityY) {
                  return true;
               }

               @Override               public boolean onScroll(MotionEvent e1, MotionEvent e2,
                     float distanceX, float distanceY) {
                  synchronized (CustomeGraphview.this) {
                     nextX += (int) distanceX;
                  }
                  requestLayout();

                  return true;
               }
            });
   }

   @Override   public boolean dispatchTouchEvent(MotionEvent event) {
      boolean handled = super.dispatchTouchEvent(event);
      handled |= gestureDetector.onTouchEvent(event);
      return handled;
   }

   protected boolean onDown(MotionEvent e) {
      scroller.forceFinished(true);
      return true;
   }

   @Override   protected void onLayout(boolean changed, int left, int top, int right,
         int bottom) {
      super.onLayout(changed, left, top, right, bottom);

      if (scroller.computeScrollOffset()) {
         int scrollx = scroller.getCurrX();
         nextX = scrollx;
      }

      if (nextX <= 0) {
         nextX = 0;
         scroller.forceFinished(true);
      }
      if (nextX >= maxX) {
         nextX = maxX;
         scroller.forceFinished(true);
      }

      currentX = nextX;

      if (!scroller.isFinished()) {
         post(requestLayoutRunnable);
      } else {
         postInvalidate();
      }
   }

   @Override   protected void onDraw(Canvas canvas) {
      super.onDraw(canvas);

      canvas.drawLine(0, Line0, getWidth(), Line0, tickPaint);
      canvas.drawLine(0, Line1, getWidth(), Line1, tickPaint);
      canvas.drawLine(0, Line2, getWidth(), Line2, tickPaint);
      canvas.drawLine(0, Line3, getWidth(), Line3, tickPaint);
      canvas.drawLine(0, Line4, getWidth(), Line4, tickPaint);
      canvas.drawLine(0, Line5, getWidth(), Line5, tickPaint);

      if (arrListMonths.size() < 6) {
         for (float mm = 0.0f; mm < 6; mm++) {

            int x = getXFromMillimeters(mm);
            // canvas.drawLine(x, centerY - 100, x, centerY, tickPaint);
            try {

               if (mm == 0.0) {
                  if (arrListRates.get((int) mm) == 0) {
                     lastY = Line0;
                  } else if (arrListRates.get((int) mm) == 1) {
                     lastY = Line1;
                  } else if (arrListRates.get((int) mm) == 2) {
                     lastY = Line2;
                  } else if (arrListRates.get((int) mm) == 3) {
                     lastY = Line3;
                  } else if (arrListRates.get((int) mm) == 4) {
                     lastY = Line4;
                  } else if (arrListRates.get((int) mm) == 5) {
                     lastY = Line5;
                  }
                  lastX = x;
               } else {
                  if (arrListRates.get((int) mm) == 0) {
                     canvas.drawLine(lastX, lastY, x, Line0,
                           centerLinePaint);
                     lastY = Line0;
                  } else if (arrListRates.get((int) mm) == 1) {
                     canvas.drawLine(lastX, lastY, x, Line1,
                           centerLinePaint);
                     lastY = Line1;
                  } else if (arrListRates.get((int) mm) == 2) {
                     canvas.drawLine(lastX, lastY, x, Line2,
                           centerLinePaint);
                     lastY = Line2;
                  } else if (arrListRates.get((int) mm) == 3) {
                     canvas.drawLine(lastX, lastY, x, Line3,
                           centerLinePaint);
                     lastY = Line3;
                  } else if (arrListRates.get((int) mm) == 4) {
                     canvas.drawLine(lastX, lastY, x, Line4,
                           centerLinePaint);
                     lastY = Line4;
                  } else if (arrListRates.get((int) mm) == 5) {
                     canvas.drawLine(lastX, lastY, x, Line5,
                           centerLinePaint);
                     lastY = Line5;
                  }
                  lastX = x;
               }

               if (arrListRates.get((int) mm) == 0) {
                  RectF rectF = new RectF(x - circleRadius, Line0                        - circleRadius, x + circleRadius, Line0                        + circleRadius);
                  canvas.drawOval(rectF, centerLinePaint);
               } else if (arrListRates.get((int) mm) == 1) {
                  RectF rectF = new RectF(x - circleRadius, Line1                        - circleRadius, x + circleRadius, Line1                        + circleRadius);
                  canvas.drawOval(rectF, centerLinePaint);
               } else if (arrListRates.get((int) mm) == 2) {
                  RectF rectF = new RectF(x - circleRadius, Line2                        - circleRadius, x + circleRadius, Line2                        + circleRadius);
                  canvas.drawOval(rectF, centerLinePaint);
               } else if (arrListRates.get((int) mm) == 3) {
                  RectF rectF = new RectF(x - circleRadius, Line3                        - circleRadius, x + circleRadius, Line3                        + circleRadius);
                  canvas.drawOval(rectF, centerLinePaint);
               } else if (arrListRates.get((int) mm) == 4) {
                  RectF rectF = new RectF(x - circleRadius, Line4                        - circleRadius, x + circleRadius, Line4                        + circleRadius);
                  canvas.drawOval(rectF, centerLinePaint);
               } else if (arrListRates.get((int) mm) == 5) {
                  RectF rectF = new RectF(x - circleRadius, Line5                        - circleRadius, x + circleRadius, Line5                        + circleRadius);
                  canvas.drawOval(rectF, centerLinePaint);
               }

               // for text
               drawHvAlignedText(canvas, x, LineForText,
                     arrListMonths.get((int) mm), tickTextPaint,
                     Paint.Align.CENTER, TextVertAlign.Middle);

            } catch (Exception e) {
            }
         }

      } else {

         for (float mm = 0.0f; mm < arrListMonths.size(); mm++) {

            int x = getXFromMillimeters(mm);
            // canvas.drawLine(x, centerY - 100, x, centerY, tickPaint);
            try {

               if (mm == 0.0) {
                  if (arrListRates.get((int) mm) == 0) {
                     lastY = Line0;
                  } else if (arrListRates.get((int) mm) == 1) {
                     lastY = Line1;
                  } else if (arrListRates.get((int) mm) == 2) {
                     lastY = Line2;
                  } else if (arrListRates.get((int) mm) == 3) {
                     lastY = Line3;
                  } else if (arrListRates.get((int) mm) == 4) {
                     lastY = Line4;
                  } else if (arrListRates.get((int) mm) == 5) {
                     lastY = Line5;
                  }
                  lastX = x;
               } else {
                  if (arrListRates.get((int) mm) == 0) {
                     canvas.drawLine(lastX, lastY, x, Line0,
                           centerLinePaint);
                     lastY = Line0;
                  } else if (arrListRates.get((int) mm) == 1) {
                     canvas.drawLine(lastX, lastY, x, Line1,
                           centerLinePaint);
                     lastY = Line1;
                  } else if (arrListRates.get((int) mm) == 2) {
                     canvas.drawLine(lastX, lastY, x, Line2,
                           centerLinePaint);
                     lastY = Line2;
                  } else if (arrListRates.get((int) mm) == 3) {
                     canvas.drawLine(lastX, lastY, x, Line3,
                           centerLinePaint);
                     lastY = Line3;
                  } else if (arrListRates.get((int) mm) == 4) {
                     canvas.drawLine(lastX, lastY, x, Line4,
                           centerLinePaint);
                     lastY = Line4;
                  } else if (arrListRates.get((int) mm) == 5) {
                     canvas.drawLine(lastX, lastY, x, Line5,
                           centerLinePaint);
                     lastY = Line5;
                  }
                  lastX = x;
               }

               if (arrListRates.get((int) mm) == 0) {
                  RectF rectF = new RectF(x - circleRadius, Line0                        - circleRadius, x + circleRadius, Line0                        + circleRadius);
                  canvas.drawOval(rectF, centerLinePaint);
               } else if (arrListRates.get((int) mm) == 1) {
                  RectF rectF = new RectF(x - circleRadius, Line1                        - circleRadius, x + circleRadius, Line1                        + circleRadius);
                  canvas.drawOval(rectF, centerLinePaint);
               } else if (arrListRates.get((int) mm) == 2) {
                  RectF rectF = new RectF(x - circleRadius, Line2                        - circleRadius, x + circleRadius, Line2                        + circleRadius);
                  canvas.drawOval(rectF, centerLinePaint);
               } else if (arrListRates.get((int) mm) == 3) {
                  RectF rectF = new RectF(x - circleRadius, Line3                        - circleRadius, x + circleRadius, Line3                        + circleRadius);
                  canvas.drawOval(rectF, centerLinePaint);
               } else if (arrListRates.get((int) mm) == 4) {
                  RectF rectF = new RectF(x - circleRadius, Line4                        - circleRadius, x + circleRadius, Line4                        + circleRadius);
                  canvas.drawOval(rectF, centerLinePaint);
               } else if (arrListRates.get((int) mm) == 5) {
                  RectF rectF = new RectF(x - circleRadius, Line5                        - circleRadius, x + circleRadius, Line5                        + circleRadius);
                  canvas.drawOval(rectF, centerLinePaint);
               }

               // for text
               drawHvAlignedText(canvas, x, LineForText,
                     arrListMonths.get((int) mm), tickTextPaint,
                     Paint.Align.CENTER, TextVertAlign.Middle);

            } catch (Exception e) {
            }
         }

      }

   }

   private int getXFromMillimeters(float mm) {
      int centerX = startDistance;
      int scrollLeftX = (int) (currentX - centerX);
      int temp = (int) (mm * bitweenDistance) - scrollLeftX;
      return temp;
   }

   public enum TextVertAlign {
      Top, Middle, Baseline, Bottom   };

   public static void drawHvAlignedText(Canvas canvas, float x, float y,
         String s, Paint p, Paint.Align horizAlign, TextVertAlign vertAlign) {

      float testTextSize = canvas.getWidth() / 30;
      p.setTextSize(testTextSize);
      p.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.NORMAL));
      // Set horizontal alignment      p.setTextAlign(horizAlign);

      // Get bounding rectangle - we need its attribute and method values      Rect r = new Rect();
      p.getTextBounds(s, 0, s.length(), r); // Note: r.top will be negative
      // Compute y-coordinate we'll need for drawing text for specified      // vertical alignment      float textX = x;
      float textY = y;
      switch (vertAlign) {
      case Top:
         textY = y - r.top;
         break;
      case Middle:
         textY = y - r.top - r.height() / 2;
         break;
      case Baseline: // Default behavior - do nothing         break;
      case Bottom:
         textY = y - (r.height() + r.top);
         break;
      }
      canvas.drawText(s, textX, textY, p);
   }

}


// call from activiy

LinearLayout linear_graphlayout  = (LinearLayout) findViewById(R.id.linear_graphlayout);
CustomeGraphview cgv = new CustomeGraphview(getParent(), arrListRates, arrListMonths, arrListRates.size());
linear_graphlayout.addView(cgv);




Wednesday, 23 March 2016

(Latest Code ) Android check internet connectivity Check with broadcast.

Download demo from here:-  https://drive.google.com/open?id=1SbrzrDvEvW2OsGHV-LpY4TQXPAetDpjV

Note:- extent base activity where require internet connectivity functionality. and implement below override methods from base actrivity

@Overridepublic void onNetworkConnectionChanged(boolean isConnected) {

    if(isConnected) {
        Toast.makeText(MainActivity.this, "Got Internet connectivity", Toast.LENGTH_SHORT).show();
    }else{
        Toast.makeText(MainActivity.this, "Lost Internet connectivity", Toast.LENGTH_SHORT).show();
    }
}
 
 

Android check internet connection (Simple Oldtype Demo)

CheckIetConnection cic = new CheckInternetConnection(context);

if(cic.checkInternet(0))
{
    // available}
else{
    // not available}
//class
public class CheckInternetConnection {
    public Context context = null;
    public Activity mActivity;
    Dialog dialog;
    int TYPE_DIALOG = 0;


    // TYPE_DIALOG = 0   : no dialog (Default)    // TYPE_DIALOG = 1   : toast    // TYPE_DIALOG = 2   : dialog display    //if(checkInternet(TYPE_DIALOG))
    public CheckInternetConnection(Context context) {
        this.context = context;
    }

    public CheckInternetConnection(Activity context) {
        this.TYPE_DIALOG = 1;
        this.context = context;
        this.mActivity = context;
        initAlertDialog(context, context.getResources().getString(R.string.msg_nointernet));
    }

    public boolean checkInternet() {
        this.TYPE_DIALOG = 0;
        return isOnline();
    }

    public boolean checkInternet(int checkType) {

        this.TYPE_DIALOG = checkType;

        return isOnline();
    }

    public Boolean isOnline() {
        if (isNetAvailable(context))
            return true;
        else {
            try {
                URL url = new URL("http://www.google.com");
                HttpURLConnection urlc = (HttpURLConnection) url
                        .openConnection();
                urlc.setRequestProperty("User-Agent", "Test");
                urlc.setRequestProperty("Connection", "close");
                urlc.setConnectTimeout(3000); // This is time limit if the                // connection time limit                urlc.connect();
                if (urlc.getResponseCode() == 200) {
                    return true;
                }
            } catch (MalformedURLException e1) {
                e1.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (TYPE_DIALOG == 0) {

        } else if (TYPE_DIALOG == 1) {

            showToast(context, context.getResources().getString(R.string.msg_nointernet));

        } else if (TYPE_DIALOG == 2) {

            showDialog();
        }

        return false;
    }

    public void showToast(Context context, String message) {
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();

    }


    public synchronized static boolean isNetAvailable(Context context) {

        try {
            boolean isNetAvailable = false;
            if (context != null) {
                ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                if (mgr != null) {
                    boolean mobileNetwork = false;
                    boolean wifiNetwork = false;
                    boolean wiMaxNetwork = false;

                    boolean mobileNetworkConnecetd = false;
                    boolean wifiNetworkConnecetd = false;
                    boolean wiMaxNetworkConnected = false;

                    NetworkInfo mobileInfo = mgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                    NetworkInfo wifiInfo = mgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                    NetworkInfo wiMaxInfo = mgr.getNetworkInfo(ConnectivityManager.TYPE_WIMAX);

                    if (mobileInfo != null)
                        mobileNetwork = mobileInfo.isAvailable();

                    if (wifiInfo != null)
                        wifiNetwork = wifiInfo.isAvailable();

                    if (wiMaxInfo != null)
                        wiMaxNetwork = wiMaxInfo.isAvailable();

                    if (wifiNetwork == true)
                        wifiNetworkConnecetd = wifiInfo.isConnectedOrConnecting();
                    if (mobileNetwork == true)
                        mobileNetworkConnecetd = mobileInfo.isConnectedOrConnecting();
                    if (wiMaxNetwork == true)
                        wiMaxNetworkConnected = wiMaxInfo.isConnectedOrConnecting();

                    isNetAvailable = (mobileNetworkConnecetd || wifiNetworkConnecetd || wiMaxNetworkConnected);
                }
            }
            return isNetAvailable;
        } catch (NullPointerException e) {
            return false;
        } catch (Exception e) {
            return false;
        }
    }


    public void showDialog() {
        try {
            if (dialog != null && (!dialog.isShowing())) {
                Log.d("TAG", "SHOW DIALOG");
                dialog.show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void initAlertDialog(Context context, String message) {

        AlertDialog.Builder builder = new AlertDialog.Builder(context);

        builder.setTitle(context.getResources().getString(R.string.app_name));
        builder.setMessage(message);

        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

            @Override            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });


        dialog = builder.create();

    }

}

android - How to create my own Preference class



// call from class
PreferencesHelper prefs = new PreferencesHelper(context);prefs.setString("hello");prefs.getString();

// class
public class PreferencesHelper {
    private SharedPreferences prefs;
    private SharedPreferences.Editor editor;

    private String KEY_ONE;
    private String KEY_TWO;
    private String KEY_THREE;

    // Class constants.
    public PreferencesHelper(Context context) {
        prefs = PreferenceManager.getDefaultSharedPreferences(context);
        editor = prefs.edit();
    }

    public static PreferencesHelper getInstance(Context context) {
        return new PreferencesHelper(context);
    }

    public Boolean getBoolean() {
        return prefs.getBoolean(KEY_ONE, false);
    }

    public void setBoolean(Boolean value) {
        editor.putBoolean(KEY_ONE, value);
        editor.commit();
    }

    public String getString() {
        return prefs.getString(KEY_TWO, "");
    }

    public void setString(String value) {
        editor.putString(KEY_TWO, value);
        editor.commit();
    }

    public int getInt() {
        return prefs.getInt(KEY_THREE, 0);
    }

    public void setInt(int value) {
        editor.putInt(KEY_THREE, value);
        editor.commit();
    }

}





Android_SharedPreferences_Basics

Run/install/debug Android applications over Wi-Fi ?

Open Teminal/cmd --------------- Below steps is for Android 10 or lower Step 1 - Connect the device via USB and make sure debugging is work...