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

How to use Singleton Class ?



The ClassicSingleton class maintains a static reference to the lone singleton instance and returns that reference from the static getInstance() method.

//call from java class 
Singleton singleton = Singleton.getInstance();

//class
public class Singleton {


    private static Singleton mInstance = null;

    private String mString;

    private Singleton() {
        mString = "Hello";
    }

    public static Singleton getInstance() {
        if (mInstance == null) {
            mInstance = new Singleton();
        }
        return mInstance;
    }

    // for clear instance    public static void clearInstance() {
        mInstance = null;
    }

    public String getString() {
        return this.mString;
    }

    public void setString(String value) {
        mString = value;
    }


}


Tuesday, 22 March 2016

Change Media volume in Android?



Easiest way to handle System Volume



// Get System Volume

public static int getSystemMusicorRingVolume(Context context) {

   int volume = 0, volumeMusic = 0;

   AudioManager am = (AudioManager) context
         .getSystemService(Context.AUDIO_SERVICE);

   volume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
   volumeMusic = am.getStreamVolume(AudioManager.STREAM_RING);

   Log.d("tag", "music volume---> " + volume);
   Log.d("tag", "ring volume---> " + volumeMusic);

   if (volume == 0 || volumeMusic == 0) {

      return 0;

   } else {

      return 1;
   }

// set System volue
public static void setSystemVolumeRingOrMusic(Context context) {
   try {

      int volume = 0, volumeMusic = 0;


      AudioManager am;
      am = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);

      volume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
      volumeMusic = am.getStreamVolume(AudioManager.STREAM_RING);


      if (volume == 0) {

         volume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
         am.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);
      }
      if (volumeMusic == 0) {
         volumeMusic = am.getStreamMaxVolume(AudioManager.STREAM_RING);
         am.setStreamVolume(AudioManager.STREAM_RING, volumeMusic, 0);
      }

      Log.d("TAG", "SET VOLUME SUCCESS");

   } catch (Exception e) {

   }
}

more link
http://stackoverflow.com/questions/4593552/how-do-you-get-set-media-volume-not-ringtone-volume-in-android

Monday, 21 March 2016

Android Static map


This is use for enerate static map images easily.

Download here.




Android Runtime_Permissions


 This demo is for Runtime permission, this is use for 6.0 and above android version


Download here

https://github.com/teegarcs/Runtime_Permissions

Also another nice library

https://github.com/ParkSangGwon/TedPermission?utm_source=android-arsenal.com&utm_medium=referral&utm_campaign=3238

// Latest

Android Material Icon Generator


Create simple icons for android with that loooong material shadow!

Easy way to create shadow icons

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...