Sunday, 3 February 2013

Mapview :Drag and drop marker on Google map view with pop-up.


Here in this blog i implement Itemized-overlay with handling onTap and onTouchevent.
As shown below onTap method is  used for pop-up and onTouch method is used for drag and drop pin at particular location.

public class MapDemoActivity extends MapActivity {
private MapView map = null;
private MyLocationOverlay me = null;
List<Overlay> mapOverlays;
boolean flag;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_demo);

map = (MapView) findViewById(R.id.map);

map.getController().setCenter(
getPoint(40.76793169992044, -73.98180484771729));
map.getController().setZoom(17);
map.setBuiltInZoomControls(true);

mapOverlays = map.getOverlays();

Drawable marker = getResources().getDrawable(R.drawable.mekr);

marker.setBounds(0, 0, marker.getIntrinsicWidth(),
marker.getIntrinsicHeight());

map.getOverlays().add(new SitesOverlay(marker, map));

me = new MyLocationOverlay(this, map);
map.getOverlays().add(me);
}

@Override
public void onResume() {
super.onResume();

me.enableCompass();
}

public MapView getMapView() {
return this.map;
}

@Override
public void onPause() {
super.onPause();

me.disableCompass();
}

@Override
protected boolean isRouteDisplayed() {
return (false);
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_S) {
map.setSatellite(!map.isSatellite());
return (true);
} else if (keyCode == KeyEvent.KEYCODE_Z) {
map.displayZoomControls(true);
return (true);
}

return (super.onKeyDown(keyCode, event));
}

private GeoPoint getPoint(double lat, double lon) {
return (new GeoPoint((int) (lat * 1000000.0), (int) (lon * 1000000.0)));
}

private class SitesOverlay extends ItemizedOverlay<OverlayItem> {
private List<OverlayItem> items = new ArrayList<OverlayItem>();
private Drawable marker = null;
private OverlayItem inDrag = null;
private ImageView dragImage = null;
private int xDragImageOffset = 0;
private int yDragImageOffset = 0;
private int xDragTouchOffset = 0;
private int yDragTouchOffset = 0;
private Context c;
public int selectedIndex = -1;
private final Bitmap bitMap;
private View view = null;
private boolean   isPinch  =  false;


public SitesOverlay(Drawable marker, MapView mapView) {
super(boundCenter(marker));
this.marker = marker;
c = mapView.getContext();
dragImage = (ImageView) findViewById(R.id.drag);
xDragImageOffset = dragImage.getDrawable().getIntrinsicWidth() / 2;
yDragImageOffset = dragImage.getDrawable().getIntrinsicHeight();

items.add(new OverlayItem(getPoint(40.748963847316034,
-73.96807193756104), "UN", "United Nations"));
items.add(new OverlayItem(getPoint(40.76866299974387,
-73.98268461227417), "Lincoln Center",
"Home of Jazz at Lincoln Center"));
items.add(new OverlayItem(getPoint(40.765136435316755,
-73.97989511489868), "Carnegie Hall",
"Where you go with practice, practice, practice"));
items.add(new OverlayItem(getPoint(40.70686417491799,
-74.01572942733765), "The Downtown Club",
"Original home of the Heisman Trophy"));

bitMap = BitmapFactory.decodeResource(getResources(),
R.drawable.mekr);
populate();
}

@Override
protected OverlayItem createItem(int i) {
return (items.get(i));
}

@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
super.draw(canvas, mapView, shadow);

boundCenterBottom(marker);
}

@Override
public int size() {
return (items.size());
}

public void refresh() {
populate();
}

public void clear() {
items.clear();
resetLastFocuesIndex();
}

public void resetLastFocuesIndex() {
setLastFocusedIndex(-1);
selectedIndex = -1;
}

@Override
protected boolean onTap(final int index) {
 if ( isPinch ){
       return false;
 }else{
// getMapView().setOnTouchListener(new OnTouchListener() {
// @Override
// public boolean onTouch(View arg0, MotionEvent arg1) {
// if (!items.isEmpty()) {
// if (view != null) {
// view.setVisibility(View.GONE);
// getMapView().invalidate();
// }
// }
// getMapView().invalidate();
// return true;
// }
// });
if (view != null) {
view.setVisibility(View.GONE);
getMapView().removeView(view);
getMapView().invalidate();
flag = false;
view = null;
}
view = getLayoutInflater().inflate(R.layout.balloon_overlay, null);
LinearLayout layout = (LinearLayout) view
.findViewById(R.id.balloon_main_layout);
layout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
view.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
view.setBackgroundResource(R.drawable.balloon_overlay_bg_selector);
ImageView image = (ImageView) view
.findViewById(R.id.balloon_disclosure);
TextView text = (TextView) view
.findViewById(R.id.balloon_item_title);
text.setText(items.get(index).getTitle());

if (items.get(index).getTitle() != null
&& items.get(index).getTitle().equals("Me") == false) {
image.setImageResource(R.drawable.mekr);
}

Projection projection = getMapView().getProjection();
Point point = new Point();
projection.toPixels(items.get(index).getPoint(), point);

int x = (int) (view.getWidth() / 2f);
int y = -bitMap.getHeight() - 3;

MapView.LayoutParams lp = new MapView.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, items.get(index)
.getPoint(), x, y,
MapView.LayoutParams.BOTTOM_CENTER);
    getMapView().removeView(view);
getMapView().invalidate();
    getMapView().addView(view, lp);
getMapView().invalidate();

view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (!items.isEmpty()) {
if (view != null) {
view.setVisibility(View.GONE);
getMapView().invalidate();
}
}
getMapView().invalidate();
}
});
selectedIndex = index;
           return true;        
 }
}

@Override
public boolean onTouchEvent(MotionEvent event, MapView mapView) {
final int action = event.getAction();
final int x = (int) event.getX();
final int y = (int) event.getY();
boolean result = false;

if (action == MotionEvent.ACTION_DOWN) {
for (OverlayItem item : items) {
Point p = new Point(0, 0);

map.getProjection().toPixels(item.getPoint(), p);

if (hitTest(item, marker, x - p.x, y - p.y)) {
result = true;
inDrag = item;
items.remove(inDrag);
populate();

xDragTouchOffset = 0;
yDragTouchOffset = 0;

setDragImagePosition(p.x, p.y);
dragImage.setVisibility(View.VISIBLE);

xDragTouchOffset = x - p.x;
yDragTouchOffset = y - p.y;
isPinch=false;
break;
}
}
} else if (action == MotionEvent.ACTION_MOVE && inDrag != null) {

if (view != null) {
if (view.getVisibility() != 0) {
Log.e("touch", " out move");
setDragImagePosition(x, y);
result = true;
isPinch=true;
}else{
setDragImagePosition(x, y);
isPinch=false;
}
}else{
setDragImagePosition(x, y);
result = true;
isPinch=true;
}
} else if (action == MotionEvent.ACTION_UP && inDrag != null) {
dragImage.setVisibility(View.GONE);

GeoPoint pt = map.getProjection().fromPixels(
x - xDragTouchOffset, y - yDragTouchOffset);
OverlayItem toDrop = new OverlayItem(pt, inDrag.getTitle(),
inDrag.getSnippet());

Log.e("touch", " out last" + pt.getLatitudeE6());
items.add(toDrop);
populate();
inDrag = null;
result = true;
isPinch = false;
}
return (isPinch || super.onTouchEvent(event,mapView));
}

private void setDragImagePosition(int x, int y) {
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) dragImage.getLayoutParams();

lp.setMargins(x - xDragImageOffset - xDragTouchOffset, y
- yDragImageOffset - yDragTouchOffset, 0, 0);
dragImage.setLayoutParams(lp);
}
}
}
Here as shown in image that first one in which user can drag and drop pin.

here when the pop is shown that time user cant drag and drop pin.

Wednesday, 30 January 2013

Android Tutorial: Countdown Timer Code


Countdown Timer Code for the end of date as you want.



public class CountDown  extends Activity {
/** Called when the activity is first created. */
TextView tv;
long diff;
long milliseconds;
long endTime;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

tv = new TextView(this);
this.setContentView(tv);
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy, HH:mm");
formatter.setLenient(false);


String oldTime = "1.2.2013, 12:00";
Date oldDate;
try {
oldDate = formatter.parse(oldTime);
milliseconds = oldDate.getTime();

//long startTime = System.currentTimeMillis();
   // do your work...
   long endTime=System.currentTimeMillis();
   
    diff = endTime-milliseconds;       

Log.e("day", "miliday"+diff);
long seconds = (long) (diff / 1000) % 60 ;
Log.e("secnd", "miliday"+seconds);
long minutes = (long) ((diff / (1000*60)) % 60);
Log.e("minute", "miliday"+minutes);
long hours   = (long) ((diff / (1000*60*60)) % 24);
Log.e("hour", "miliday"+hours);
long days = (int)((diff / (1000*60*60*24)) % 365);
Log.e("days", "miliday"+days);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


Long serverUptimeSeconds = (System.currentTimeMillis() - milliseconds) / 1000;


String serverUptimeText = String.format("%d days %d hours %d minutes %d seconds",
serverUptimeSeconds / 86400,
( serverUptimeSeconds % 86400) / 3600 ,
((serverUptimeSeconds % 86400) % 3600 ) / 60,
((serverUptimeSeconds % 86400) % 3600 ) % 60
);


Log.v("jjj", "miliday"+serverUptimeText);
MyCount counter = new MyCount(milliseconds,1000);
counter.start();


}


// countdowntimer is an abstract class, so extend it and fill in methods
public class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}

@Override
public void onFinish() {
tv.setText("done!");
}

@Override
public void onTick(long millisUntilFinished) {
//tv.setText("Left: " + millisUntilFinished / 1000);

long diff = endTime - millisUntilFinished; 
Log.e("left", "miliday"+diff);
long seconds = (long) (diff / 1000) % 60 ;
//Log.e("secnd", "miliday"+seconds);
long minutes = (long) ((diff / (1000*60)) % 60);
//Log.e("minute", "miliday"+minutes);
long hours   = (long) ((diff / (1000*60*60)) % 24);
//Log.e("hour", "miliday"+hours);
int days = (int)((diff / (1000*60*60*24)) % 365);
Log.v("days", "miliday"+days);


Long serverUptimeSeconds = 
   (System.currentTimeMillis() - millisUntilFinished) / 1000;


String serverUptimeText = 
String.format("%d days %d hours %d minutes %d seconds",
serverUptimeSeconds / 86400,
( serverUptimeSeconds % 86400) / 3600 ,
((serverUptimeSeconds % 86400) % 3600 ) / 60,
((serverUptimeSeconds % 86400) % 3600 ) % 60
);  

Log.v("new its", "miliday"+serverUptimeText);

// tv.setText(days +":"+hours+":"+minutes + ":" + seconds);
 
tv.setText(serverUptimeText);
}
}

Saturday, 26 January 2013

Create Database using Xml in android

Here in this blog i create database using of xml file such as (res / xml / tables.xml).
Create xml folder in res directory and create file like tables.xml.


<?xml version="1.0" encoding="ISO-8859-1"?>
<database name="andando_db" version="5">
<table name="categories" to-string="%name%" backup="no"> 
   <field name="name" obligatory="true" type="string-identifier" size="128"/>
<field name="default_time_gps" type="integer" obligatory="true" default="1" />
<field name="default_distance_gps" type="integer" obligatory="true" default="5" />
<field name="position" type="integer" obligatory="true" default="1" new-in-version="2" />
  </table>
 <table name="types_resource" to-string="%name%" backup="no"> 
  <field name="name" obligatory="true" type="name" size="128"/> 
 </table>
  
 </database>
As above code i create two simple table.

Monday, 21 January 2013

Custom seek-bar like Circle (pie chart) using bitmap.

Here's something I came up with using clip path. I'm using following images (coder colours) out of which background is a solid one and foreground one contains only blue circle on transparent background. First background image is drawn onto screen, then clip path is set so that progress image, foreground one, is drawn properly on top of it.


private class ProgressView extends View {

    private Bitmap bgBitmap;
    private Bitmap fgBitmap;
    private RectF fullRect = new RectF();
    private Path clipPath = new Path();

    public ProgressView(Context context) {
        super(context);
        bgBitmap = BitmapFactory.decodeResource(
                                   context.getResources(), R.drawable.bg);
        fgBitmap = BitmapFactory.decodeResource(
                                   context.getResources(), R.drawable.fg);
    }

    @Override
    public void onDraw(Canvas c) {
        fullRect.right = getWidth();
        fullRect.bottom = getHeight();

        c.drawBitmap(bgBitmap, null, fullRect, null);

        float angle = SystemClock.uptimeMillis() % 3600 / 10.0f;

        clipPath.reset();
        clipPath.setLastPoint(getWidth() / 2, getHeight() / 2);
        clipPath.lineTo(getWidth() / 2, getHeight());
        clipPath.arcTo(fullRect, -90, angle);
        clipPath.lineTo(getWidth() / 2, getHeight() / 2);
        c.clipPath(clipPath);

        c.drawBitmap(fgBitmap, null, fullRect, null);

        invalidate();
    }   
}

also we can achieved like as seek-bar on touch event of this custom view.

@Override
public boolean onTouchEvent(MotionEvent event) {
int touchX = (int) event.getX();
int touchY = (int) event.getY();

if (outerCircle == null) {
 return true; // ignore all events until the canvas is drawn
}
float x1 = bgBitmap.getWidth(), x2 = bgBitmap.getHeight(), y1 = bgBitmap
    .getWidth(), y2 = bgBitmap.getHeight();
if ((touchX <= x1 && touchX <= x2)
  && (touchY <= y1 && touchY <= y2)) {
int angle = pointToAngle(touchX, touchY);
// model.rotate(Integer.valueOf(""+Math.round((angle / 3.6))));
angle = 360 + angle - startAngle;
int angleX2 = angle * 2;
angleX2 = roundToNearest15(angleX2);
if (angleX2 > 720) {
 angleX2 = angleX2 - 720; // avoid mod because we prefer 720 over
 }
 
 setMinutes(angleX2);
model.rotate(Integer.valueOf("" + Math.round((angleX2 / 7.2))));
 return true;
} else {
 return false;
 }
}

Tuesday, 8 January 2013

Tab with scroll

Basically when we are using Tab-bar with number of tabs then all the tabs show in one screen not identify for particular tab click, can't scroll it.Here i implement  Tab-bar with horizontal scroll by using HorizontalScrollView in tab-host as show in XML file,In below code i added  tab as dynamically on button click.And easily control tabs.

public class MyTabActivity extends TabActivity {
private static int tabIx = 0;
private TabHost tabHost;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab);
tabHost = getTabHost();

addTab();

((Button) findViewById(R.id.add_tab))
.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
tabIx++;
addTab();
}
});
}

private void addTab() {
LayoutInflater layoutInflate = LayoutInflater.from(MyTabActivity.this);

Button tabBtn = (Button) layoutInflate.inflate(R.layout.newtab_event, null);
tabBtn.setText("Tab " + tabIx);
Intent tabIntent = new Intent(TabActivity.this, NewActivity.class);
setupTab(tabBtn, tabIntent, "Tab " + tabIx);
}

protected void setupTab(View tabBtn, Intent setClass, String tag) {
TabSpec setContent = tabHost.newTabSpec(tag).setIndicator(tabBtn)
.setContent(setClass);
tabHost.addTab(setContent);
}
}

activity_tab.xml file

<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:padding="5dp" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <HorizontalScrollView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:fillViewport="true"
                android:scrollbars="none" >

                <TabWidget
                    android:id="@android:id/tabs"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="0dip"
                    android:layout_marginRight="0dip" />
            </HorizontalScrollView>

            <Button
                android:id="@+id/add_tab"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="0.1"
                android:text="Add" />
        </LinearLayout>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:padding="2dp" />
    </LinearLayout>

</TabHost>

Copy and share your useful data from Google chrome browser to your application in android.

Here In this blog I explain that how to copy and share your useful data from chrome browser in android. 1) How to show your applic...