Umesh

Untitled Document

Tuesday, 27 November 2012

Android CookBook and Some android learning links


Hello friends, these are some links for android learners. I will always update this page and will add more useful links for android beginners. It is also helpful for me too. 


1. Android CookBook....
2. 41post
3. android-er.blogspot.in
4. http://www.androidhub4you.com  --this is my fav one

Wednesday, 21 November 2012

Android : Application force closed after changing screen orientation



If Android detects change in your phone configuration, it destroys your phone current orientation view and try to reload it in new orientation view. Between these process, one of the  two things will happened : Either the new oriented screen will be loaded or the application will be forced closed. This issue can be fixed, you have to follow bellow steps :


Write this line of code in manifest file for your activity :

       android:configChanges="keyboardHidden|orientation"

Your complete activity code looks like this :


       <activity
            android:name=".PoiDetailActivity"
            android:configChanges="keyboardHidden|orientation"
            android:theme="@android:style/Theme.Light.NoTitleBar" >
        </activity>


Tuesday, 6 November 2012

Android : ADB Command Line Tricks

1. Open the AVD Manager and launch a virtual device 

    From your SDK's platform-tools/ directory, execute the android tool 

    with the avd options :

    android avd 

    In the Virtual Device view, Select an AVD and click Start. 

2. Install your application


    From your SDK's tools/ directory, install the .apk on the emulator : 


    adb install apkfilename.apk

3. If there is more than one emulator running, you must specify the emulator

    which to install the application, by its serial number, with the -s option. :


    adb -s emulator -5554 install apkfilename.apk

4. To see a list of available device serial numbers use : 

     adb devices


5. Install already installed app through adb command
    without uninstalling it in android emulator. 

     abd install -r test.apk

     It updates and keeps databases and stored preferences

6. Run your app directly on your attached device :


  1. Enable USB Debugging on your device. Use this way : Settings > Applications >         Development > USB debugging
  2. Check whether device connected or not. 
  3. Once your device connected, use fallowing command line 
    adb -d install apkfilename.apk

   -d flag specifies that you want to run your app on connected device....

Android: Show Google Map, Zooming Control And Marker On Map

umesh_map_view.xml : 


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#008000"
    android:orientation="vertical" >

    <com.google.android.maps.MapView
         android:id="@+id/mapView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:enabled="true"
        android:clickable="true"
        android:apiKey="0twJXMQDHBfxjMnb77nwRzKs29kGZdRkcG3_Z8Q" />
    
    <LinearLayout android:id="@+id/zoom" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_alignParentBottom="true" 
        android:layout_centerHorizontal="true" 
        /> 
    
</RelativeLayout>


In above xml file, you should generate your own apiKey. For more reference fallow this link : get google map api key

GPSLocation.java :


import java.util.List;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.os.Bundle;
import com.redorange.c4mh.R;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.MapView.LayoutParams;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;


public class GPSLocation extends MapActivity {

MapView mapView;
MapController mc;
GeoPoint p;
public static String latitude,longitude;

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

mapView = (MapView) findViewById(R.id.mapView);
mapView.setSatellite(false);
LinearLayout zoomLayout = (LinearLayout) findViewById(R.id.zoom);
View zoomView = mapView.getZoomControls();

zoomLayout.addView(zoomView, new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mapView.displayZoomControls(true);
// Show particular location in Mapview
mc = mapView.getController();
   String coordinates[] = {latitude, longitude};
       //String coordinates[] = {"1.352566007", "103.78921587"};
       double lat = Double.parseDouble(coordinates[0]);
       double lng = Double.parseDouble(coordinates[1]);
 
       p = new GeoPoint(
           (int) (lat * 1E6), 
           (int) (lng * 1E6));
 
       mc.animateTo(p);
      // mc.setZoom(17); 
       
       //---Add a location marker---
       
       MapOverlay mapOverlay = new MapOverlay();
       List<Overlay> listOfOverlays = mapView.getOverlays();
       listOfOverlays.clear();
       listOfOverlays.add(mapOverlay); 
       
       //================================
 
       mapView.invalidate();
       
//=====================================
}

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

// Below is the code when the user presses the number 3 on the keyboard the
// map
// will zoom in into the next level. Pressing number 1 will zoom out one
// level.

public boolean onKeyDown(int keyCode, KeyEvent event) {
MapController mc = mapView.getController();
switch (keyCode) {
case KeyEvent.KEYCODE_3:
mc.zoomIn();
break;
case KeyEvent.KEYCODE_1:
mc.zoomOut();
break;
}
return super.onKeyDown(keyCode, event);
}

// ----------------------------------------------------
// Class that point out the perticular location using push pin image
class MapOverlay extends com.google.android.maps.Overlay
   {
       @Override
       public boolean draw(Canvas canvas, MapView mapView, 
       boolean shadow, long when) 
       {
           super.draw(canvas, mapView, shadow);                   
 
           //---translate the GeoPoint to screen pixels---
           Point screenPts = new Point();
           mapView.getProjection().toPixels(p, screenPts);
 
           //---add the marker---
           Bitmap bmp = BitmapFactory.decodeResource(
               getResources(), R.drawable.pushpin);            
           canvas.drawBitmap(bmp, screenPts.x, screenPts.y-42, null);         
           return true;
       }
   } 
 
}

In above java file, it uses pushpin as an image. You can download it from Google and store it in your drawable folder





Android: Draw Route From Current Location To Destination Location On Google Map

In order to show route on Google Map, Just call an intent which passes current and destination latitude and longitude. You may also pass address in any case if don't know lat-long. After doing this, its Google Map's job to show location. You may also show street view.

In below code, there are three parameters : current_lat, current_longi, dest_address

 final Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?" 
+ "saddr="+ current_lat+","+current_longi + "&daddr="+dest_address ));

intent.setClassName("com.google.android.apps.maps","com.google.android.maps.MapsActivity");
startActivity(intent);

If you have current address and destination address, then you can write like this :

Uri.parse("http://maps.google.com/maps?" 
+ "saddr="+curr_address+ "&daddr="+dest_address ));

If you have current and destination latitude and longitude both then you can write like this :

Uri.parse("http://maps.google.com/maps?" 
+ "saddr="+ current_lat+","+current_longi + "&daddr="+ destt_lat+","+dest_longi  ));


When you call this intent, Google Map shows option whether to draw route by bus or by walk.

Android : Open Restricted Websites In Webview And Also Shows How To Use ProgressDialog For Loading Web Data


Hello guys, there are some websites which are not opening in webview. Even if you try to open it on android default browser it seems error. Fallowing code also shows how to use progress dialog.


try this website as sample one on your android browser : https://secure.questdiagnostics.com/hcp/psc/jsp/SearchLocation.do


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public void onCreate(Bundle savedInstanceState) 

{
  super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);   //layout file i.e main.xml
mWebView = (WebView) findViewById(R.id.umesh_webview);  // webview 
mWebView.getSettings().setJavaScriptEnabled(true);
dialog = ProgressDialog.show(this, null, "Please wait..", true);
mWebView.loadUrl("https://secure.questdiagnostics.com/hcp/psc/jsp/SearchLocation.do");
mWebView.setWebViewClient(new WebViewClient() 
{
 
     public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error)
{
handler.proceed();
}

public void onPageFinished(WebView view, String url) 
{
super.onPageFinished(view, url);
if (dialog != null && dialog.isShowing())
dialog.dismiss();
}
});
//LoadData();
}
Fallowing code handle such restricted sites : 

 public void onReceivedSslError(WebView view,SslErrorHandler handler, SslError error)
{
     handler.proceed();
}


Android : Check Internet Connection availability


Hello guys this is nice code to check internet availability. If you are testing it on android emulator then

1. go to Window menu
2. Show view
3. other
4. Emulator control
5. Set value for Data as home (means network available)
6. Test application(it shows internet available)
7. Not set value for Data as denied ( means network connection denied)
8. Test application ( It shows internet not available)

All the above steps is just for emulator. If you are testing it on device no need to fallow these steps.


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;


public class NetworkStatus extends Activity {

Intent i;
//public WebView mWebView;
protected ProgressDialog dialog;
static boolean value = false;
int DELAY = 1000;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);

LoadData();
}

        public void LoadData()
{

   dialog = ProgressDialog.show(this, null, "Please wait..", true);
   Handler handler = new Handler();
   handler.postDelayed(new Runnable()
      {          
       public void run()
               {
             checkConnection();
       }

   }, DELAY);

}
        public void checkConnection()
         {
// TODO Auto-generated method stub
if(isOnline())
{
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Internet Available", 3000).show();
// INTERNET IS AVAILABLE, DO STUFF..
}
else
{
// NO INTERNET AVAILABLE, DO STUFF..

dialog.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
           builder.setTitle("Info");
        builder.setMessage("Internet not available");
                        builder.setPositiveButton("Try again", new DialogInterface.OnClickListener()
                     {
                             public void onClick(DialogInterface dialog2, int which)
                            {
                    // Do nothing but close the dialog
           dialog2.dismiss();
           LoadData();
            }

   });

   builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
                    {

       public void onClick(DialogInterface dialog2, int which)
                       {
           // Do nothing
           dialog2.dismiss();
       }
   });

   builder.create();
   builder.show();
}

}

// To check internet connection
protected boolean isOnline()
        {
   ConnectivityManager cm =
           (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
   NetworkInfo netInfo = cm.getActiveNetworkInfo();
   if (netInfo != null && netInfo.isConnected())
            {
       return true;
   }
           else
           {
       return false;
   }
}
}

Android: View previous web page using webview


 If your are loading webpage on android webview and need to go on previously  loaded webpage on webview, then this is nice trick to go to the previous page over a webview. Just add following method in your java file. 


public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (event.getAction() == KeyEvent.ACTION_DOWN)
{
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mWebView.canGoBack() == true)
{
mWebView.goBack();
}
else
{
finish();
}
return true;
}

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

Android :Open webpage in browser through intent

Open web page in android default browser through intent

Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://www.google.com"));
startActivity(i);

Play youtube video in full screen in default device youtube player by passing youtube video id


Hello friends, If you want to play youtube video in full screen  in default  youtube player from your device by passing youtube video id , use following code. I hope it will work for you.


Button watch=(Button)findViewById(R.id.btn_watchnow);

watch.setOnClickListener(new OnClickListener()
 {
@Override
public void onClick(View v)
{
String id="IqZf2pj4oj8";   //Youtube video id
    Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:" +id));
    startActivity(i);

}
});

Try it. It works fine for me. Again in order to give option to open in browser, just use


Uri.parse("ytv://"+id)

Animate android list items. Rotate Listview items

main.xml :


<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Hello Umesh Suryawanshi"
    android:textColor="#959AE8"
    />
<ListView
    android:id = "@+id/umesh_list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#EBC38F"
    />
</LinearLayout>


ListAnimation.java :



package com.umesh.ListAnimation;

import com.umesh.ListAnimation.*;
import com.umesh.ListAnimation.Rotate3dAnimation;

import android.app.Activity;
import android.os.Bundle;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LayoutAnimationController;
import android.view.animation.TranslateAnimation;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ListAnimation extends Activity {

String[] items={"Umesh", "Suryawanshi", "Sunil", "Pradip", "Sachin",
         "Milind", "Puja", "Monika", "Diksha", "Mayur",
         "Shivam", "Deepali", "Lokesh", "Anshul", "Vasant",
         "Shivani", "Vishal", "Pravin", "Manisha", "Chetan",
         "Komal", "Vicky", "Tushar"};
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ListView flightlist = (ListView)findViewById(R.id.umesh_list);
        flightlist.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,items));
        //setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
        //items));
        AnimationSet set = new AnimationSet(true);

        Animation animation = new AlphaAnimation(0.0f, 1.0f);
        animation.setDuration(80);
        set.addAnimation(animation);

        animation = new TranslateAnimation(
            Animation.RELATIVE_TO_SELF, 0.0f,Animation.RELATIVE_TO_SELF, 0.0f,
            Animation.RELATIVE_TO_SELF, -1.0f,Animation.RELATIVE_TO_SELF, 0.0f
        );
        animation.setDuration(500);
        set.addAnimation(applyRotation(0,0,360));

        LayoutAnimationController controller =
                new LayoutAnimationController(set, 0.5f);
        controller.setDelay(1.0f);
        flightlist.setLayoutAnimation(controller);
        //flightlist.de
    }
   
 
    private Rotate3dAnimation applyRotation(int position, float start, float end) {
        // Find the center of the container
        final float centerX = 100.0f;//view.getWidth()/2.0f;
        final float centerY = 20.0f;//view.getHeight()/2.0f;

        // Create a new 3D rotation with the supplied parameter
        // The animation listener is used to trigger the next animation
        final Rotate3dAnimation rotation =
                new Rotate3dAnimation(start, end, centerX, centerY, 310.0f, true);
        rotation.setDuration(500);
        rotation.setFillAfter(true);
        rotation.setInterpolator(new AccelerateInterpolator());
        rotation.setAnimationListener(new DisplayNextView(position));

        return rotation;
    }
 
    private final class DisplayNextView implements Animation.AnimationListener {
        private final int mPosition;

        private DisplayNextView(int position) {
            mPosition = position;
        }

        public void onAnimationStart(Animation animation) {
        }

        public void onAnimationEnd(Animation animation) {

        }

        public void onAnimationRepeat(Animation animation) {
        }
    }
}


Rotate3dAnimation.java  :



package com.umesh.ListAnimation;

import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.graphics.Camera;
import android.graphics.Matrix;

public class Rotate3dAnimation extends Animation {
    private final float mFromDegrees;
    private final float mToDegrees;
    private final float mCenterX;
    private final float mCenterY;
    private final float mDepthZ;
    private final boolean mReverse;
    private Camera mCamera;

   
    public Rotate3dAnimation(float fromDegrees, float toDegrees,
            float centerX, float centerY, float depthZ, boolean reverse) {
        mFromDegrees = fromDegrees;
        mToDegrees = toDegrees;
        mCenterX = centerX;
        mCenterY = centerY;
        mDepthZ = depthZ;
        mReverse = reverse;
    }

    @Override
    public void initialize(int width, int height, int parentWidth, int parentHeight) {
        super.initialize(width, height, parentWidth, parentHeight);
        mCamera = new Camera();
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        final float fromDegrees = mFromDegrees;
        float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);

        final float centerX = mCenterX;
        final float centerY = mCenterY;
        final Camera camera = mCamera;

        final Matrix matrix = t.getMatrix();

        camera.save();
        if (mReverse) {
            camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime));
        } else {
            camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime));
        }
        camera.rotateX(degrees);
        camera.getMatrix(matrix);
        camera.restore();

        matrix.preTranslate(-centerX, -centerY);
        matrix.postTranslate(centerX, centerY);
    }
}





Monday, 5 November 2012

Android : Simple splash screen code


Hello friends, here is simple splash screen code :



public class SplashScreen extends Activity
{

public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_splashscreen);

new CountDownTimer(3000, 1000)
{

public void onTick(long arg0)
{

}

        public void onFinish()
       {

Intent i = new Intent(getApplicationContext(), LoginA.class);
startActivity(i);
SplashScreen.this.finish();
 
}
}.start();
}
}

"splash_splashscreen" is an xml file.  splash_splashscreen.xml code is shown below.




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/splash_image" >

</RelativeLayout>


 LoginA.class" is another class which is called after specific time interval