Tuesday, August 26, 2014

Volley Network Image Loader

Hi All,

Volley is a library that handles the processing and caching of network requests. It helps to download the imaged from web asynchronously. We do not worry  about the Async Task to download the image from network because Volley library now can able to handle the image download asynchronously.

We already had known the famous library Universal Image Loder and Piccaso. Both are easy to handle to download the image in a thread pool and maintained the cache management.

Volley simplify everything and increases the app performances. - See more at: http://www.survivingwithandroid.com/2013/11/android-volley-tutorial-post-download.html#sthash.ATBAtGr2.dpuf
 Volley have lot of advantages:






  • Efficient network management
  • Easy to use request managements
  • Disk and memory cache management
  • Easy to extend and customize to our needs
  • - See more at: http://www.survivingwithandroid.com/2013/11/android-volley-tutorial-post-download.html#sthash.ATBAtGr2.dpuf
    • Automatic scheduling of network requests.
    • Multiple concurrent network connections.
    • Transparent disk and memory response caching
    • 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.
    • Application performance
    There are two available cache implementations. The recommended approach uses a basic in memory LRU cache. For the disk cache implementation I chose to use the DiskLruCache written by Jake Wharton. I chose this implementation because it is frequently used in the Android community and represents a common use case for someone trying to retrofit their application for Volley. Using a disk based L1 cache may cause i/o blocking issues. Volley already has an implicit disk L2 cache. The disk L1 cache is included because I was originally unaware of how Volley handled image request caching. 

    For download or clone of Volley library you have to run predefined command in your system, In your system should have installed the git.

    1. git clone https://android.googlesource.com/platform/frameworks/volley
    2. android update project -p .
    3. ant jar
    Once you done this commond you can get the volley clone library in your directory.
    Only thing you have to use the  NetworkImageView in place of ImageView. I have share code for GridView image loader with volley that manage the cache management for network processing.



      






  • Efficient network management
  • Easy to use request managements
  • Disk and memory cache management
  • Easy to extend and customize to our needs
  • - See more at: http://www.survivingwithandroid.com/2013/11/android-volley-tutorial-post-download.html#sthash.ATBAtGr2.dpuf






  • Efficient network management
  • Easy to use request managements
  • Disk and memory cache management
  • Easy to extend and customize to our needs
  • - See more at: http://www.survivingwithandroid.com/2013/11/android-volley-tutorial-post-download.html#sthash.ATBAtGr2.dpuf






  • Efficient network management
  • Easy to use request managements
  • Disk and memory cache management
  • Easy to extend and customize to our needs
  • - See more at: http://www.survivingwithandroid.com/2013/11/android-volley-tutorial-post-download.html#sthash.ATBAtGr2.dpuf






  • Efficient network management
  • Easy to use request managements
  • Disk and memory cache management
  • Easy to extend and customize to our needs
  • - See more at: http://www.survivingwithandroid.com/2013/11/android-volley-tutorial-post-download.html#sthash.ATBAtGr2.dpuf
    Volley simplify everything and increases the app performances. - See more at: http://www.survivingwithandroid.com/2013/11/android-volley-tutorial-post-download.html#sthash.ATBAtGr2.dpuf
    Volley simplify everything and increases the app performances. - See more at: http://www.survivingwithandroid.com/2013/11/android-volley-tutorial-post-download.html#sthash.ATBAtGr2.dpuf

    activity_main.xml

    < RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="comsunil.volleygridexample.MainActivity" >




    < /RelativeLayout>

    grid_image_item.xml

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






    MainActivity.java

    package comsunil.volleygridexample;

    import android.os.Bundle;
    import android.support.v7.app.ActionBarActivity;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.GridView;
    import android.widget.ImageView;

    import com.android.volley.toolbox.ImageLoader;
    import com.android.volley.toolbox.NetworkImageView;

    public class MainActivity extends ActionBarActivity {

    ImageLoader mImageLoader;
    NetworkImageView mNetworkImageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    mImageLoader = MyVolleySingleton.getInstance(this).getImageLoader();

    final GridView gridView = (GridView) findViewById(R.id.gridView);
    gridView.setAdapter(new MyImageAdapter());


    }

    static class ViewHolder {
    ImageView imageView;
    }

    class MyImageAdapter extends BaseAdapter {

    @Override
    public int getCount() {
    return ImageUrlArray.IMAGES.length;
    }

    @Override
    public Object getItem(int position) {
    return null;
    }

    @Override
    public long getItemId(int position) {
    return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

    View view = convertView;
    final ViewHolder gridViewImageHolder;
    // check to see if we have a view
    if (view == null) {
    view = getLayoutInflater().inflate(R.layout.grid_image_item, parent, false);
    gridViewImageHolder = new ViewHolder();
    gridViewImageHolder.imageView = (ImageView) view.findViewById(R.id.networkImageView);
    view.setTag(gridViewImageHolder);
    } else {
    gridViewImageHolder = (ViewHolder) view.getTag();
    }

    mNetworkImageView = (NetworkImageView) gridViewImageHolder.imageView;
    mNetworkImageView.setDefaultImageResId(R.drawable.no_image);
    mNetworkImageView.setErrorImageResId(R.drawable.error);
    mNetworkImageView.setAdjustViewBounds(true);
    mNetworkImageView.setImageUrl(ImageUrlArray.IMAGES[position], mImageLoader);

    return view;
    }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
    return true;
    }
    return super.onOptionsItemSelected(item);
    }
    }

    MyVolleySingleton.java

    package comsunil.volleygridexample;

    import android.content.Context;

    import com.android.volley.Request;
    import com.android.volley.RequestQueue;
    import com.android.volley.toolbox.ImageLoader;
    import com.android.volley.toolbox.Volley;

    /**
    * copied from the official documentation
    */
    public class MyVolleySingleton {

    private static MyVolleySingleton mVolleyInstance;
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private static Context mContext;

    private MyVolleySingleton(Context context) {
    mContext = context;
    mRequestQueue = getRequestQueue();
    mImageLoader = new ImageLoader(mRequestQueue,
    new MyLruBitmapCache(MyLruBitmapCache.getCacheSize(context))
    );
    }

    public static synchronized MyVolleySingleton getInstance(Context context) {
    if (mVolleyInstance == null) {
    mVolleyInstance = new MyVolleySingleton(context);
    }
    return mVolleyInstance;
    }

    public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
    // use the application context
    mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
    }
    return mRequestQueue;
    }

    public void addToRequestQueue(Request req) {
    getRequestQueue().add(req);
    }

    public ImageLoader getImageLoader() {
    return mImageLoader;
    }
    }

    MyLruBitmapCache.java

    package comsunil.volleygridexample;

    import android.content.Context;
    import android.graphics.Bitmap;
    import android.support.v4.util.LruCache;
    import android.util.DisplayMetrics;

    import com.android.volley.toolbox.ImageLoader;

    /**
    * copied from official documentation
    */
    public class MyLruBitmapCache extends LruCache
    implements ImageLoader.ImageCache {

    public MyLruBitmapCache(int maxSize) {
    super(maxSize);
    }

    public MyLruBitmapCache(Context ctx) {
    this(getCacheSize(ctx));
    }

    @Override
    protected int sizeOf(String key, Bitmap value) {
    return value.getRowBytes() * value.getHeight();
    }

    @Override
    public Bitmap getBitmap(String url) {
    return get(url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
    put(url, bitmap);
    }

    // Returns a cache size equal to approximately three screens worth of images.
    public static int getCacheSize(Context ctx) {
    final DisplayMetrics displayMetrics = ctx.getResources().
    getDisplayMetrics();
    final int screenWidth = displayMetrics.widthPixels;
    final int screenHeight = displayMetrics.heightPixels;
    // 4 bytes per pixel
    final int screenBytes = screenWidth * screenHeight * 4;

    return screenBytes * 3;
    }
    }

    For network operation I recommended to use this library instead of AsynTask.


    package com.sunil.volleynetworkoperation;

    import org.json.JSONObject;

    import android.app.Activity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.TextView;

    import com.android.volley.Request;
    import com.android.volley.RequestQueue;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.JsonObjectRequest;
    import com.android.volley.toolbox.Volley;

    public class MainActivity extends Activity {

    private TextView txtDisplay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    txtDisplay = (TextView) findViewById(R.id.txtDisplay);

    RequestQueue queue = Volley.newRequestQueue(this);
    String url = "http://echo.jsontest.com/key/value/one/two";

    JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener() {

    @Override
    public void onResponse(JSONObject response) {
    // TODO Auto-generated method stub
    txtDisplay.setText("Response => "+response.toString());
    findViewById(R.id.progressBar1).setVisibility(View.GONE);
    }
    }, new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError error) {
    // TODO Auto-generated method stub

    }


    })


    /*{ // if you have any key value request
    @Override
    protected Map getParams()
    {
    Map params = new HashMap();
    params.put("name", "sunil");
    params.put("domain", "http://sunil.info");

    return params;
    }
    }*/;

    queue.add(jsObjRequest);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
    return true;
    }
    return super.onOptionsItemSelected(item);
    }
    }

    Here you can dwonload the source code VolleyGridview

    Monday, July 14, 2014

    CalenderView Example

    Hi Guys,

    Today I am sharing the code for CalenderView. This class is a calendar widget for displaying and selecting dates. The range of dates supported by this calendar is configurable. A user can select a date by taping on it and can scroll and fling the calendar to a desired date.

    activity_main.xml







    MainActivity.java

    package com.sunil.calenderexample;

    import android.support.v7.app.ActionBarActivity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.CalendarView;
    import android.widget.CalendarView.OnDateChangeListener;
    import android.widget.Toast;

    public class MainActivity extends ActionBarActivity implements OnDateChangeListener {

    private CalendarView calenderview=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    calenderview=(CalendarView)findViewById(R.id.calendarView_cl);
    calenderview.setOnDateChangeListener(this);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
    return true;
    }
    return super.onOptionsItemSelected(item);
    }

    @Override
    public void onSelectedDayChange(CalendarView arg0, int arg1, int arg2, int arg3) {

    Toast.makeText(getBaseContext(), arg1+"/"+arg2+"/"+arg3, Toast.LENGTH_LONG).show();
    }
    }


    Result is:
    Here you can download the source code CalenderView Example

    Saturday, June 21, 2014

    Check Network Connectivity

    Hi Guys,

    I am sharing the code for check the internet connectivity of your device either mobile or wifi connectivity.
    More detail Here 
    Java Code:

    private void checkNetworkConnection() {
    ConnectivityManager connMgr =
    (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
    if (activeInfo != null && activeInfo.isConnected()) {
    wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
    mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
    if(wifiConnected) {
    Log.i(TAG, "WIFI connected");
    } else if (mobileConnected){
    Log.i(TAG, "Mobile Connected");
    }
    } else {
    Log.i(TAG,"Neither Mobile nor WIFi connected.");
    }
    }
    or second way

    public static boolean isInternetOn(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context
    .getSystemService(Context.CONNECTIVITY_SERVICE);
    // test for connection
    if (cm.getActiveNetworkInfo() != null
    && cm.getActiveNetworkInfo().isAvailable()
    && cm.getActiveNetworkInfo().isConnected()) {
    Log.v("Util", "Internet is working");
    // txt_status.setText("Internet is working");
    return true;
    } else {
    // txt_status.setText("Internet Connection Not Present");
    Log.v("Util", "Internet Connection Not Present");
    return false;
    }
    }
    Please do not forget to add the permission in AndroidMenifest file.




     

    Copyright @ 2013 Android Developers Tipss.