Friday, 15 May 2015

Android detecting all supported Gestures

Android provides the GestureDetector class for detecting common gestures. Some of the gestures it supports include onDown(), onLongPress(), onFling(), and so on.

 

public class MainActivity extends Activity implements
        GestureDetector.OnGestureListener,
        GestureDetector.OnDoubleTapListener{
   
    private static final String DEBUG_TAG = "Gestures";
    private GestureDetectorCompat mDetector;

    // Called when the activity is first created.
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Instantiate the gesture detector with the
        // application context and an implementation of
        // GestureDetector.OnGestureListener
        mDetector = new GestureDetectorCompat(this,this);
        // Set the gesture detector as the double tap
        // listener.
        mDetector.setOnDoubleTapListener(this);
        // you can set other gesture listeners over here
    }

    @Override
    public boolean onTouchEvent(MotionEvent event){
        this.mDetector.onTouchEvent(event);
        // Be sure to call the superclass implementation
        return super.onTouchEvent(event);
    }

    @Override
    public boolean onDown(MotionEvent event) {
        Log.d(DEBUG_TAG,"onDown: " + event.toString());
        return true;
    }

    @Override
    public boolean onFling(MotionEvent event1, MotionEvent event2,
            float velocityX, float velocityY) {
        Log.d(DEBUG_TAG, "onFling: " + event1.toString()+event2.toString());
        return true;
    }

    @Override
    public void onLongPress(MotionEvent event) {
        Log.d(DEBUG_TAG, "onLongPress: " + event.toString());
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
            float distanceY) {
        Log.d(DEBUG_TAG, "onScroll: " + e1.toString()+e2.toString());
        return true;
    }

    @Override
    public void onShowPress(MotionEvent event) {
        Log.d(DEBUG_TAG, "onShowPress: " + event.toString());
    }

    @Override
    public boolean onSingleTapUp(MotionEvent event) {
        Log.d(DEBUG_TAG, "onSingleTapUp: " + event.toString());
        return true;
    }

    @Override
    public boolean onDoubleTap(MotionEvent event) {
        Log.d(DEBUG_TAG, "onDoubleTap: " + event.toString());
        return true;
    }

    @Override
    public boolean onDoubleTapEvent(MotionEvent event) {
        Log.d(DEBUG_TAG, "onDoubleTapEvent: " + event.toString());
        return true;
    }

    @Override
    public boolean onSingleTapConfirmed(MotionEvent event) {
        Log.d(DEBUG_TAG, "onSingleTapConfirmed: " + event.toString());
        return true;
    }
}

Android working with Volley Library - Http GET , POST , PUT , DELETE Request

Android volley is a networking library was introduced to make networking calls much easier, faster without writing tons of code. By default all the volley network calls works asynchronously, so we don’t have to worry about using asynctask anymore.

Volley offers the following benefits:

  • Automatic scheduling of network requests.
  • Multiple concurrent network connections.
  • Transparent disk and memory response caching with standard HTTP cache coherence
  •  Support for request prioritization.
  • Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel.
  • Ease of customization, for example, for retry and backoff.
  • Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network.
  • Debugging and tracing tools.

 Following are the important class of volley:

  • RequestQueue: A Queue containing the Network/HTTP Requests that needs to be made.
  • Request: A Base Class which contains Network related information like HTTP Methods.
  • StringRequest: HTTP Request where the response is parsed a String. 
  • JsonObjectRequest: HTTP Request where the response is JSONObject.    

To use Volley, you must add the android.permission.INTERNET permission to your app's manifest. Without this, your app won't be able to connect to the network. 

Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url = "Url goes here"

Making GET Requests

// prepare the Request
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
    new Response.Listener<JSONObject>() 
    {
        @Override
        public void onResponse(JSONObject response) {   
                        // display response     
            Log.d("Response", response.toString());
        }
    }, 
    new Response.ErrorListener() 
    {
         @Override
         public void onErrorResponse(VolleyError error) {
              //error
             Log.d("Error.Response", response);
       }
    }
);
 
// add it to the RequestQueue   
queue.add(getRequest);
 

Making POST Requests 

 
StringRequest postRequest = new StringRequest(Request.Method.POST, url, 
    new Response.Listener<String>() 
    {
        @Override
        public void onResponse(String response) {
            // response
            Log.d("Response", response);
        }
    }, 
    new Response.ErrorListener() 
    {
         @Override
         public void onErrorResponse(VolleyError error) {
             // error
             Log.d("Error.Response", response);
       }
    }
) {     
    @Override
    protected Map<String, String> getParams() 
    {         // Adding parameters
            Map<String, String>  params = new HashMap<String, String>();  
            params.put("parameter1", "value1");  
            params.put("parameter2", "value2");
             
            return params;  
    }
};
queue.add(postRequest);
 

Making PUT Requests 

 
StringRequest putRequest = new StringRequest(Request.Method.PUT, url, 
    new Response.Listener<String>() 
    {
        @Override
        public void onResponse(String response) {
            // response
            Log.d("Response", response);
        }
    }, 
    new Response.ErrorListener() 
    {
         @Override
         public void onErrorResponse(VolleyError error) {
                         // error
             Log.d("Error.Response", response);
       }
    }
) {
 
    @Override
    protected Map<String, String> getParams() 
    {  
            Map<String, String>  params = new HashMap<String, String> ();  
            params.put("parameter1", "value1");  
            params.put("parameter2", "value2");
             
            return params;  
    }
 
};
 
queue.add(putRequest);
 

Making DELETE Requests

 
StringRequest deleteRequest = new StringRequest(Request.Method.DELETE, url, 
    new Response.Listener<String>() 
    {
        @Override
        public void onResponse(String response) {
            // response
            Log.d("Response", response);
        }
    }, 
    new Response.ErrorListener() 
    {
         @Override
         public void onErrorResponse(VolleyError error) {
             // error.
               Log.d("Error.Response", response);
       }
    }
);
queue.add(deleteRequest);
 
 
 








Sunday, 12 April 2015

Display Animated Gif Android

 
Step1)put a Gif image in drawable folder 
 
Step2)Make GifViewActivity and GifViewClass as follows

public class GifViewActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new GifViewClass(this));
    }

    private class GifViewClass extends View {
        Movie movie;

        GifViewClass(Context context) {
            super(context);
            //Gif image from drawable folder
            movie = Movie.decodeStream(
                    context.getResources().openRawResource(
                            R.drawable.gif_image));
        }
        @Override
        protected void onDraw(Canvas canvas) {   
            if (movie != null) {
                movie.setTime(
                    (int) SystemClock.uptimeMillis() % movie.duration());
                movie.draw(canvas, 0, 0);
                invalidate();
            }
        }
    }
}

Android animation using xml

Step to perform animation in android apps

Step 1) Create XML which define animation
create a xml file which define the animation in  res ⇒ anim ⇒ animation.xml , If you dont have anim folder then create it in res directory

blink.xml
<?xml version="1.0" encoding="utf-8"?>
    <alpha android:fromAlpha="0.0"
        android:toAlpha="1.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:duration="800"
        android:repeatMode="reverse"
        android:repeatCount="infinite"/>
</set>
   
Step 2) Load the animation and set to view in acitvity to see blink effect

public class BlinkActivity extends Activity{
 
    TextView textMessage;
 
    // Animation
    Animation animBlink;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blink);
 
        textMessage = (TextView) findViewById(R.id.textMessage);
               textMessag.setText(Welcome to Android Code Portal);
        // load the animation
        animBlink = AnimationUtils.loadAnimation(getApplicationContext(),
                R.anim.blink);  
       // start the animation
       textMessage.startAnimation(animBlink);
     
    }
}
 
Some other useful animations as follows
  
1)Blink
blink.xml
<?xml version="1.0" encoding="utf-8"?>
    <alpha android:fromAlpha="0.0"
        android:toAlpha="1.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:duration="800"
        android:repeatMode="reverse"
        android:repeatCount="infinite"/>
</set>
 
2)ZoomIn
zoomin.xml
<?xml version="1.0" encoding="utf-8"?>
    android:fillAfter="true" >
 
    <scale
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="1000"
        android:fromXScale="1"
        android:fromYScale="1"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toXScale="3"
        android:toYScale="3" >
    </scale>
 
</set>
 
 3)ZoomOut
zoomout.xml
<?xml version="1.0" encoding="utf-8"?>
    android:fillAfter="true" >
 
    <scale
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="1000"
        android:fromXScale="1.0"
        android:fromYScale="1.0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toXScale="0.5"
        android:toYScale="0.5" >
    </scale>
 
</set>
 
4)FadeIn
fadein.xml
<?xml version="1.0" encoding="utf-8"?>
    android:fillAfter="true" >
 
    <alpha
        android:duration="1000"
        android:fromAlpha="0.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:toAlpha="1.0" />
 
</set> 
 
5)FadeOut
fadeout.xml
<?xml version="1.0" encoding="utf-8"?>
    android:fillAfter="true" >
 
    <alpha
        android:duration="1000"
        android:fromAlpha="1.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:toAlpha="0.0" />
 
</set>
 
6)Rotate
rotate.xml
<?xml version="1.0" encoding="utf-8"?>
    <rotate android:fromDegrees="0"
        android:toDegrees="360"
        android:pivotX="50%"
        android:pivotY="50%"
        android:duration="700"
        android:repeatMode="restart"
        android:repeatCount="infinite"
        android:interpolator="@android:anim/cycle_interpolator"/>
 
</set>
 
7)Move
 move.xml
<?xml version="1.0" encoding="utf-8"?>
<set
    android:interpolator="@android:anim/linear_interpolator"
    android:fillAfter="true">
 
   <translate
        android:fromXDelta="0%p"
        android:toXDelta="80%p"
        android:duration="1000" />
</set>
 
8)SlideDown
slidedown.xml
<?xml version="1.0" encoding="utf-8"?>
    android:fillAfter="true">
 
    <scale
        android:duration="800"
        android:fromXScale="1.0"
        android:fromYScale="0.0"
        android:interpolator="@android:anim/linear_interpolator"
        android:toXScale="1.0"
        android:toYScale="1.0" />
 
</set>
 
 9)SlideUp
slideup.xml
<?xml version="1.0" encoding="utf-8"?>
    android:fillAfter="true" >
 
    <scale
        android:duration="800"
        android:fromXScale="1.0"
        android:fromYScale="1.0"
        android:interpolator="@android:anim/linear_interpolator"
        android:toXScale="1.0"
        android:toYScale="0.0" />
 
</set>
 
10)Bounce
 bounce.xml
<?xml version="1.0" encoding="utf-8"?>
    android:fillAfter="true"
    android:interpolator="@android:anim/bounce_interpolator">
 
    <scale
        android:duration="800"
        android:fromXScale="1.0"
        android:fromYScale="0.0"
        android:toXScale="1.0"
        android:toYScale="1.0" />
 
</set>
 
 
 

Save Activity State in Android

Save activity state in android apps (for example when we rotate our device portrait to landscape or landscape to portrait the values which we had filled in EditText gone away)

You need to override onSaveInstanceState(Bundle savedInstanceState) and write the application state values you want to change to the Bundle parameter like this

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  // Save UI state changes to the savedInstanceState.
  // This bundle will be passed to onCreate if the process is
  // killed and restarted.
  savedInstanceState.putBoolean("BooleanValueKey", true);
  savedInstanceState.putDouble("DoubleValueKey", 1.9);
  savedInstanceState.putInt("IntValueKey", 1);
  savedInstanceState.putString("StringValueKey", "Welcome to Android Code Portal");
  // etc.
}
 
The Bundle is essentially a way of storing a NVP ("Name-Value Pair") map, and it will 
get passed in to onCreate() and also onRestoreInstanceState() where you'd extract 
the values like this: 

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  // Restore UI state from the savedInstanceState.
  // This bundle has also been passed to onCreate.
  boolean booleanValue = savedInstanceState.getBoolean("BooleanValueKey");
  double doubleValue = savedInstanceState.getDouble("DoubleValueKey");
  int intValue = savedInstanceState.getInt("IntValueKey");
  String stringValue = savedInstanceState.getString("StringValueKey");
}