Wednesday 10 September 2014

Custom listview using volley


Custom listview using volley

Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster. Volley is available through the open AOSP repository.
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.
Json parsing using volley example
1.Create new project.
2.add volley.jar in your libs.clickhere to download vollery.jar.
3.Create AppController.java Singleton class where we initialize all the volley core libs.


public class AppController extends Application {
    public static final String TAG = AppController.class.getSimpleName();
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private static AppController mInstance;
    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }
    public static synchronized AppController getInstance() {
        return mInstance;
    }
    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }
        return mRequestQueue;
    }
    public ImageLoader getImageLoader() {
        getRequestQueue();
        if (mImageLoader == null) {
            mImageLoader = new ImageLoader(this.mRequestQueue,
                    new LruBitmapCache());
        }
        return this.mImageLoader;
    }
    public <T> void addToRequestQueue(Request<T> req, String tag) {
        // set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }
    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }
    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}
4.add the LruBitmapCache.java for store the image into the cache for fast image access.
public class LruBitmapCache extends LruCache<String, Bitmap> implements
        ImageCache {
    public static int getDefaultLruCacheSize() {
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize = maxMemory / 8;
        return cacheSize;
    }
    public LruBitmapCache() {
        this(getDefaultLruCacheSize());
    }
    public LruBitmapCache(int sizeInKiloBytes) {
        super(sizeInKiloBytes);
    }
    @Override
    protected int sizeOf(String key, Bitmap value) {
        return value.getRowBytes() * value.getHeight() / 1024;
    }
    @Override
    public Bitmap getBitmap(String url) {
        return get(url);
    }
    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        put(url, bitmap);
    }
}
5.add the AppController.java into the Application tag in manifest.xml to execute this at app launch.and also add internet permission.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.customlistviewusingvolley"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>   
    <application
        android:name="com.example.customlistviewusingvolley.AppController"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
6.Create listview in the MainActivity layout to set the custom items into the listview.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >
    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>
</LinearLayout>
7.get the json array requst URL.
Here I am using follow URL.
Json Array request URL:
private String jsonArrayUrl=
"http://www.androidtoppers.com/VolleyExample/ws_API/get_array.php";

Response:
[
{
"id": "1",
"Name": "Bentley",
"image": "http://www.androidtoppers.com/photos/webservice/image1.jpg",
"dec": "Car 1"
},
{
"id": "2",
"Name": "Bentley",
"image": "http://www.androidtoppers.com/photos/webservice/image2.jpg",
"dec": "car 2"
},
{
"id": "4",
"Name": "Bentley",
"image": "http://www.androidtoppers.com/photos/webservice/image3.jpg",
"dec": "car 3 "
},
{
"id": "6",
"Name": "Bentley",
"image": "http://www.androidtoppers.com/photos/webservice/image4.jpg",
"dec": "car 4"
},
{
"id": "7",
"Name": "BMW",
"image": "http://www.androidtoppers.com/photos/webservice/image5.jpg",
"dec": "Car 5"
},
{
"id": "10",
"Name": "BMW",
"image": "http://www.androidtoppers.com/photos/webservice/image6.jpg",
"dec": "car 6"
},
{
"id": "12",
"Name": "BMW",
"image": "http://www.androidtoppers.com/photos/webservice/image8.jpg",
"dec": "car 8"
}
]
7.Create listview and set the adapter into the listview in MainActivity.java
listview=(ListView)findViewById(R.id.listview);
adapter=new listviewAdapter();
listview.setAdapter(adapter);
listviewAdapter:
private class listviewAdapter extends BaseAdapter{

private LayoutInflater inflater;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
@Override
public int getCount() {
// TODO Auto-generated method stub
return modelList.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return modelList.get(arg0);
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
// TODO Auto-generated method stub
if(inflater ==null)
inflater=(LayoutInflater)getLayoutInflater();
if(view==null)
view=inflater.inflate(R.layout.list_item, null);
if(imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView imageview=(NetworkImageView)view.findViewById(R.id.imageview);
TextView textview=(TextView)view.findViewById(R.id.header);
ItemModel itemmodel=modelList.get(position);
imageview.setImageUrl(itemmodel.getImage(), imageLoader);
textview.setText(itemmodel.getName());
return view;
}
}
ItemModel:
private class ItemModel{
private String name;
private String image;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
callJsonArrayRequest:
pdialog=new ProgressDialog(this);
pdialog.setMessage("Loading data..");
pdialog.show();
JsonArrayRequest arrayReq=new JsonArrayRequest(URL, new Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
// TODO Auto-generated method stub
dissmissDialog();
for(int i=0;i<response.length();i++){
try {
JSONObject obj=response.getJSONObject(i);
ItemModel model=new ItemModel();
model.setImage(obj.getString("image"));
model.setName(obj.getString("Name"));
modelList.add(model);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
VolleyLog.d(TAG, "ERROR"+error.getMessage());
}
});
finally add the request url to the requestQueue,
AppController.getInstance().addToRequestQueue(arrayReq);
the full code of mainactivity is,
MainActivity.java
public class MainActivity extends Activity {
private String TAG=MainActivity.class.getSimpleName();
private ListView listview;
private ProgressDialog pdialog;
private listviewAdapter adapter;
private List<ItemModel> modelList=new ArrayList<ItemModel>();
private String URL="http://www.androidtoppers.com/VolleyExample/ws_API/get_array.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview=(ListView)findViewById(R.id.listview);
adapter=new listviewAdapter();
listview.setAdapter(adapter);
pdialog=new ProgressDialog(this);
pdialog.setMessage("Loading data..");
pdialog.show();
JsonArrayRequest arrayReq=new JsonArrayRequest(URL, new Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
// TODO Auto-generated method stub
dissmissDialog();
for(int i=0;i<response.length();i++){
try {
JSONObject obj=response.getJSONObject(i);
ItemModel model=new ItemModel();
model.setImage(obj.getString("image"));
model.setName(obj.getString("Name"));
modelList.add(model);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
VolleyLog.d(TAG, "ERROR"+error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(arrayReq);
}
private void dissmissDialog() {
// TODO Auto-generated method stub
if(pdialog !=null){
if(pdialog.isShowing()){
pdialog.dismiss();
}
pdialog=null;
}
}
private class listviewAdapter extends BaseAdapter{
private LayoutInflater inflater;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
@Override
public int getCount() {
// TODO Auto-generated method stub
return modelList.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return modelList.get(arg0);
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
// TODO Auto-generated method stub

if(inflater ==null)
inflater=(LayoutInflater)getLayoutInflater();
if(view==null)
view=inflater.inflate(R.layout.list_item, null);
if(imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView imageview=(NetworkImageView)view.findViewById(R.id.imageview);
TextView textview=(TextView)view.findViewById(R.id.header);
ItemModel itemmodel=modelList.get(position);
imageview.setImageUrl(itemmodel.getImage(), imageLoader);
textview.setText(itemmodel.getName());
return view;
}
}
private class ItemModel{
private String name;
private String image;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
@Override
    public void onDestroy() {
        super.onDestroy();
        dissmissDialog();
    }
}
Screenshot:

No comments: