My previous article Customized ListView with Image and Text gives you a good overview of customizing a list view which contains a thumbnail image and few text fields. All the list data will be downloaded by making a network calls. The main challenge in that tutorial is downloading the images asynchronously and caching them. Because of lack of good tools I used a third party library (it is a good library though) to download the listview data and caching the images.
Today I am going to explain the same, but this time with a different approach by using an another library called volley. By using volley you can see decent improvement in listview performance without much effort.
Final Output
The list view we are going to build contains list of movies information where each list row defines single movie. The row layout is customized that contains movie poster as thumbnail image on the left and the movie title, rating, genre and release date on the right. Below is the final output.
1. Example JSON
I am going to use this example json to load the list data. This json contains array of objects where the each object contains information like movie name, rating, genre and release date.
JSON Url: https://api.androidhive.info/json/movies.json
[ { "title": "Dawn of the Planet of the Apes", "image": "https://api.androidhive.info/json/movies/1.jpg", "rating": 8.3, "releaseYear": 2014, "genre": ["Action", "Drama", "Sci-Fi"] }, .... .... ]
2. Downloading Volley Library (volley.jar)
If you are coming across volley for the first time, I would suggest you go through my previous article Android working with Volley Library which gives you enough knowledge about volley and other things like building the volley library to generate volley.jar. It is up to you that you want to generate volley.jar on your own or just download the the volley.jar
3. Planning The Layout Design
To achieve this customized layout I choose the RelativeLayout as parent element. All the child elements are aligned using relative properties like align below, align right, align parent bottom etc.,
Now let’s start by creating a new project.
4. Creating New Project
1. In Eclipse create a new project by navigating to File ⇒ New ⇒ Android Application Project and fill required details. I gave my project package name as
info.androidhive.customlistviewvolley
2. Once the project is created paste the volley.jar in libs folder.
3. I am creating required packages first just to keep the project organised. This step is optional but it is recommended. Create four packages named adapter, app, model and util. So after creating packages my project contains following.
info.androidhive.customlistviewvolley.adater
info.androidhive.customlistviewvolley.app
info.androidhive.customlistviewvolley.model
info.androidhive.customlistviewvolley.util
4. Open colors.xml under res ⇒ values and add below colors. If you don’t see colors.xml file, create a new file and add these color values.
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="genre">#666666</color> <color name="year">#888888</color> <color name="list_divider">#d9d9d9</color> <color name="list_row_start_color">#ffffff</color> <color name="list_row_end_color">#ffffff</color> <color name="list_row_hover_start_color">#ebeef0</color> <color name="list_row_hover_end_color">#ebeef0</color> </resources>
5. Also add below dimensions in dimens.xml file located under res ⇒ values.
<resources> <dimen name="title">17dp</dimen> <dimen name="rating">15dip</dimen> <dimen name="genre">13dip</dimen> <dimen name="year">12dip</dimen> </resources>
6. Before start writing java code, I would like to complete the UI part first. Create list_row_bg.xml, list_row_bg_hover.xml and list_row_selector.xml with below respective codes under res ⇒ drawable folder. If you don’t see drawable folder under res, create a new folder and name it as drawable.
list_row_bg.xml – Default style for list view row.
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <gradient android:startColor="@color/list_row_start_color" android:endColor="@color/list_row_end_color" android:angle="270" /> </shape>
list_row_bg_hover.xml – Style for list view row when row is selected
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > <gradient android:angle="270" android:endColor="@color/list_row_hover_end_color" android:startColor="@color/list_row_hover_start_color" /> </shape>
list_row_selector.xml – Selector file to toggle the row states.
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/list_row_bg" android:state_pressed="false" android:state_selected="false"/> <item android:drawable="@drawable/list_row_bg_hover" android:state_pressed="true"/> <item android:drawable="@drawable/list_row_bg_hover" android:state_pressed="false" android:state_selected="true"/> </selector>
7. Now open your layout file of main activity(in my case activity_main.xml) and add a ListView element.
<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" tools:context=".MainActivity" > <ListView android:id="@+id/list" android:layout_width="fill_parent" android:layout_height="wrap_content" android:divider="@color/list_divider" android:dividerHeight="1dp" android:listSelector="@drawable/list_row_selector" /> </RelativeLayout>
8. We need to create another layout file for list view row. This is the main design component in this project as we define actual custom list design here. I am naming this file as list_row.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/list_row_selector" android:padding="8dp" > <!-- Thumbnail Image --> <com.android.volley.toolbox.NetworkImageView android:id="@+id/thumbnail" android:layout_width="80dp" android:layout_height="80dp" android:layout_alignParentLeft="true" android:layout_marginRight="8dp" /> <!-- Movie Title --> <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/thumbnail" android:layout_toRightOf="@+id/thumbnail" android:textSize="@dimen/title" android:textStyle="bold" /> <!-- Rating --> <TextView android:id="@+id/rating" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/title" android:layout_marginTop="1dip" android:layout_toRightOf="@+id/thumbnail" android:textSize="@dimen/rating" /> <!-- Genre --> <TextView android:id="@+id/genre" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/rating" android:layout_marginTop="5dp" android:layout_toRightOf="@+id/thumbnail" android:textColor="@color/genre" android:textSize="@dimen/genre" /> <!-- Release Year --> <TextView android:id="@+id/releaseYear" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:textColor="@color/year" android:textSize="@dimen/year" /> </RelativeLayout>
Here we completed the design part. Let’s move to java part.
9. Create LruBitmapCache.java under util package. This class takes care of caching images on disk.
package info.androidhive.customlistviewvolley.util; import com.android.volley.toolbox.ImageLoader.ImageCache; import android.graphics.Bitmap; import android.support.v4.util.LruCache; 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); } }
10. Create AppController.java under app package. This class is a singleton class which initializes core objects of volley library.
package info.androidhive.customlistviewvolley.app; import info.androidhive.customlistviewvolley.util.LruBitmapCache; import android.app.Application; import android.text.TextUtils; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.Volley; 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); } } }
11. Now add the AppController.java class in AndroidManifest.xml to your <application> tag using name property to execute this class on application start. Also add INTERNET permission as we are going to make network calls.
<application android:name="info.androidhive.customlistviewvolley.app.AppController" ../>
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="info.androidhive.customlistviewvolley" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="18" /> <uses-permission android:name="android.permission.INTERNET" /> <application android:name="info.androidhive.customlistviewvolley.app.AppController" android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="info.androidhive.customlistviewvolley.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>
12. Now create Movie.java under model package. This model class will be used to provide movie objects data to list view after parsing the json.
package info.androidhive.customlistviewvolley.model; import java.util.ArrayList; public class Movie { private String title, thumbnailUrl; private int year; private double rating; private ArrayList<String> genre; public Movie() { } public Movie(String name, String thumbnailUrl, int year, double rating, ArrayList<String> genre) { this.title = name; this.thumbnailUrl = thumbnailUrl; this.year = year; this.rating = rating; this.genre = genre; } public String getTitle() { return title; } public void setTitle(String name) { this.title = name; } public String getThumbnailUrl() { return thumbnailUrl; } public void setThumbnailUrl(String thumbnailUrl) { this.thumbnailUrl = thumbnailUrl; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public double getRating() { return rating; } public void setRating(double rating) { this.rating = rating; } public ArrayList<String> getGenre() { return genre; } public void setGenre(ArrayList<String> genre) { this.genre = genre; } }
13. Create a class named CustomListAdapter.java with below code. This is a custom list adapter class which provides data to list view. In other words it renders the layout_row.xml in list by pre-filling appropriate information.
package info.androidhive.customlistviewvolley.adater; import info.androidhive.customlistviewvolley.R; import info.androidhive.customlistviewvolley.app.AppController; import info.androidhive.customlistviewvolley.model.Movie; import java.util.List; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.NetworkImageView; public class CustomListAdapter extends BaseAdapter { private Activity activity; private LayoutInflater inflater; private List<Movie> movieItems; ImageLoader imageLoader = AppController.getInstance().getImageLoader(); public CustomListAdapter(Activity activity, List<Movie> movieItems) { this.activity = activity; this.movieItems = movieItems; } @Override public int getCount() { return movieItems.size(); } @Override public Object getItem(int location) { return movieItems.get(location); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (inflater == null) inflater = (LayoutInflater) activity .getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (convertView == null) convertView = inflater.inflate(R.layout.list_row, null); if (imageLoader == null) imageLoader = AppController.getInstance().getImageLoader(); NetworkImageView thumbNail = (NetworkImageView) convertView .findViewById(R.id.thumbnail); TextView title = (TextView) convertView.findViewById(R.id.title); TextView rating = (TextView) convertView.findViewById(R.id.rating); TextView genre = (TextView) convertView.findViewById(R.id.genre); TextView year = (TextView) convertView.findViewById(R.id.releaseYear); // getting movie data for the row Movie m = movieItems.get(position); // thumbnail image thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader); // title title.setText(m.getTitle()); // rating rating.setText("Rating: " + String.valueOf(m.getRating())); // genre String genreStr = ""; for (String str : m.getGenre()) { genreStr += str + ", "; } genreStr = genreStr.length() > 0 ? genreStr.substring(0, genreStr.length() - 2) : genreStr; genre.setText(genreStr); // release year year.setText(String.valueOf(m.getYear())); return convertView; } }
14. Now open your main activity class (MainActivity.java) and do the below changes. Here I created volley’s JsonArrayRequest to get the json from url. Upon parsing the json, I stored all the json data into an ArrayList as Movie objects. Finally I called notifyDataSetChanged() on CustomListAdapter instance to render the list view with updated information.
package info.androidhive.customlistviewvolley; import info.androidhive.customlistviewvolley.adater.CustomListAdapter; import info.androidhive.customlistviewvolley.app.AppController; import info.androidhive.customlistviewvolley.model.Movie; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.ProgressDialog; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.widget.ListView; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.JsonArrayRequest; public class MainActivity extends Activity { // Log tag private static final String TAG = MainActivity.class.getSimpleName(); // Movies json url private static final String url = "https://api.androidhive.info/json/movies.json"; private ProgressDialog pDialog; private List<Movie> movieList = new ArrayList<Movie>(); private ListView listView; private CustomListAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) findViewById(R.id.list); adapter = new CustomListAdapter(this, movieList); listView.setAdapter(adapter); pDialog = new ProgressDialog(this); // Showing progress dialog before making http request pDialog.setMessage("Loading..."); pDialog.show(); // changing action bar color getActionBar().setBackgroundDrawable( new ColorDrawable(Color.parseColor("#1b1b1b"))); // Creating volley request obj JsonArrayRequest movieReq = new JsonArrayRequest(url, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Log.d(TAG, response.toString()); hidePDialog(); // Parsing json for (int i = 0; i < response.length(); i++) { try { JSONObject obj = response.getJSONObject(i); Movie movie = new Movie(); movie.setTitle(obj.getString("title")); movie.setThumbnailUrl(obj.getString("image")); movie.setRating(((Number) obj.get("rating")) .doubleValue()); movie.setYear(obj.getInt("releaseYear")); // Genre is json array JSONArray genreArry = obj.getJSONArray("genre"); ArrayList<String> genre = new ArrayList<String>(); for (int j = 0; j < genreArry.length(); j++) { genre.add((String) genreArry.get(j)); } movie.setGenre(genre); // adding movie to movies array movieList.add(movie); } catch (JSONException e) { e.printStackTrace(); } } // notifying list adapter about data changes // so that it renders the list view with updated data adapter.notifyDataSetChanged(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); hidePDialog(); } }); // Adding request to request queue AppController.getInstance().addToRequestQueue(movieReq); } @Override public void onDestroy() { super.onDestroy(); hidePDialog(); } private void hidePDialog() { if (pDialog != null) { pDialog.dismiss(); pDialog = null; } } @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; } }
Now run the project and test it once. Please do comment below if you ran into any issue.
Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk: ravi@androidhive.info
Hey,
It worked! I’m trying to solve a little problem with the image only!
Thank you so much!
Cheers!
Your Tutorial is so much fine
how to put this code and activity and method name:
updateimageurl = obj.getString(“image”).replace(“http”, “https”);
movie.setThumbnailUrl(updateimageurl);
Paste your json parsing code.
Thanks, Lastly Its work.
Great. Have you found out the problem?
Yeah. Dear
Lots of thanks
Hello sir, I am PHP developer. For the first time i am developing android app. I saw your article and developed the app almost. But i am facing a problem in null pointer exception sometimes when i click listview.. suggest me what can i do? Check below screenshot
It seems you are not checking for null response from http call, but accessing the response.
thanks sir its working
i have succeded making a app (working very nice)with many fragments in which one fragment is having a custom listview loading images from network and caching them in memory ,without any external library but the problem is the bitmap is taking to much of memory around 70-100 mb ,i have released memory at approriate cycles of fragments and activity, everything is fine, my memory allocation tracker tells that “onbitmapcreate” method is taking 80 % of apps memory,because of this 4% users have reported outofmemory crashreport ,so can you suggest any method for bitmap memory optimization ??or using the above volley library will clear the memory issue?? help ? thank you very much for your tutorials it really helped a lot till now
Why are not using Image Caching libraries like Glide, Picasso or Fresco?
good Aternoon ! Sir today ii tested the app with glide library but the memory allocation is almost the same.
In the library you can mention the max cache size somewhere.
Thanks Sir,for all your Help, i will test the library again !!!Keep Posting ! Helping Android community a lot
where do we have to place volley.jar file
use this
https://www.androidhive.info/2014/09/android-json-parsing-using-volley/
i have done everything you have mentioned above, there were no errors. but still why is the app getting stopped without even starting? can you please help me solving it
Awesome Ravi! This isn’t the first guide from you that helps me, there have been other using Material Design but this one I just loved It!
I have just finished your guide and it’s working really great!, some minor problems with the new HTTPS from your blog but nothing that a little gist can’t handle haha.
Thanks a lot!! Your blog is one of the best ones!

Yeah updating all the articles to https is a big task for me. I modify them one day.
Thanks for your appreciation.
Happy Coding 😀
Hi,
I downloaded code and run ‘app’ to install it. I run app but it shows empty slots. There aren’t films and other things.
I run it on android studio.
Hi
Could you try the changing the url to https in the code?
From
http://api.androidhive.info/json/movies.json
to
https://api.androidhive.info/json/movies.json (note: this is https)
Yes, it worked but it doesnt show images. I guess it is because of image url. If I change url to image: “https…”, it will work. I have a question, how can I change url in this code. I want to add “s” after “http”.
Thanks
I have to modify the image url in the json and update on the server.
A quick fix can be replace the
http
tohttps
in image url before passing it to Glide library.there is only one place where u mentioned http in Mainactivity, Where else to change http to https? I m not getting images. Where is Glide lib? pls guide
worked, by replacing string being passed to image url like this String updateimageurl = obj.getString(“image”).replace(“http”, “https”);
movie.setThumbnailUrl(updateimageurl);
Thanks Ankur.
Hi ravi, i got this error,
Unexpected response code 301
Hi ravi,
The application is not opened.?
In the code could you try to change the json url to https?
Hello Ravi Sir can you please suggest a tutorial that show how we can implement detailView in the above tutorial when listitem is clicked??? Please Sir this is urgent i couldnt find good tutorial. if possible mail me in.
mebinodlamichhane123@gmail.com
Hi Ravi,
In the first step you said to create 4 packages. I did create a package but it didn’t show up in my project structure.
What I did is I right-clicked on the app directory, and click new Package.
When I tried to create new Package under the same name, it says “adapter with the same name already exist”.
Where does the package exist or what did I do wrong.
Thanks
Hi
You need to toggle the project view from Android to Project. Also it hides the empty packages. Please explore in this area.
Hi Ravi,
I am beginner in Android development .Your tutorial is very useful for reference.
Thank you so much 🙂
You are welcome 🙂
Hi Ravi,
Can you give me source code php and database?
Thank you, sir
It’s just static json created. Not fetched from db.
oh okay,

and why image not appaear in my emulator, sir?
thanks
Yup, recently the site is moved to https. You have to replace http with https in image urls in json.
Try this
updateimageurl = obj.getString("image").replace("http", "https");
movie.setThumbnailUrl(updateimageurl);
okay, sir thats work perfectly
Thank you for your help and lessons
Cheers!
how to put the code in method or Activity name
Hi Ravi, How can I have the list view to auto refresh and get the data again every 10 seconds? Thank you so much. Do you have any source?
Add the following as the last thing in your onCreate:
//Runs volley request every 10 seconds
Runnable runnable = new Runnable() {
@Override
public void run() {
if (movieList != null) {
movieList.clear();
}
adapter.notifyDataSetChanged();
AppController.getInstance().addToRequestQueue(movieReq);
handler.postDelayed(this, 10000);
}
};
handler.postDelayed(runnable, 10000);
This works, but every time it refreshes the list blinks. I can’t figure out how to prevent this. Anyone have any ideas?
I have replaced the image url then also the images are not displaying.
what to do?
Please help me
did u get it?
Have you replaced http with https?
i pasted the code in android studio but it is showing several errors i rectified some errors.still there are errors.can you please help me to rectify those errors.R.”menu”.this is in red color last line in main activity java class.
hi ravi
this is my image pickup. How to clickon this open full image on new window
thumb_image = (NetworkImageView) findViewById(R.id.image_my);
hi ravi,
how to make it can acces data from database?
what about if its from json Object? help me please.
Refer this article
https://www.androidhive.info/2014/05/android-working-with-volley-library-1/
what IDE you work on , this doesn’t open with android studio !!
It’s older Eclipse project. Try adding one by one file (by reading the article) in android studio.
While i run the code , this problem was appear !!
Seems the value in a variable is null at line #50 in MainActivity. Could you post the code of MainActivity?
I follow your tutorial. But now I need to add search functionality. Can some please help me with this please. Phuzz!!
Hi Ravi,
In custom list adapter.. i have the following error in Android Studio.
import customlistviewvolley.R;
cannot resolve symbol R.
What am i missing or what did i not do right.
its affecting everything below.
convertView = inflater.inflate(com.namteens.lb.R.list_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView rating = (TextView) convertView.findViewById(R.id.rating);
TextView genre = (TextView) convertView.findViewById(R.id.genre);
TextView year = (TextView) convertView.findViewById(R.id.releaseYear);
thank u
🙂
You need to learn about writing REST APIs. Check the below article
https://www.androidhive.info/2014/01/how-to-create-rest-api-for-android-app-using-php-slim-and-mysql-day-12-2/
i want to create this list in a navigation drawer please ansewr me ravi
Have you added AppController to AndroidManifest.xml?
AppController is not assigned to an Activity??
Hi,
I get a DeadObjectException whenever I run the app. It worked in the beginning but now nothing works.
Can somebody help?
Please can you clarify why menu can not be resolved ?
You need to have a file in res -> menu -> main.xml or remove the
onCreateOptionsMenu
completely.Hi Ravi,
thanks for the tutorial it works perfectly and i want to make a detail page when onclick to show the detail on another activity i did this but my question how to can i pass selected movie id to detail activity so i can show detail data on another activity
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView arg0, View arg1, int position, long arg3)
{
Intent intent = new Intent(getApplicationContext(),MovieDetailsActivity.class);
startActivity(intent);
}
});
com.android.volley.ParseError: org.json.JSONException: Value {“data”:[{“ID”:”2″,”Name”:”test1″,”Path”:”image/1″,”Comment”:””,”GroupID”:”6″},{“ID”:”3″,”Name”:”test2″,”Path”:”image/2″,”Comment”:””,”GroupID”:”6″}],”success”:”1″} of type org.json.JSONObject cannot be converted to JSONArray
please im getting this error how can i fix it?? (I’m getting this error in this function : “new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {” )
May be you are making Json Array?
JsonArrayRequest movieReq = new JsonArrayRequest(imagesurl,
new Response.Listener() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
I’m using this function how can i make it JsonArrayObject? its not working. thank you
You can find the JsonObjectRequest code sample here.
https://www.androidhive.info/2014/05/android-working-with-volley-library-1/
ok will check it. thank you
I’m Sorry I mean JsonObjectRequest not JsonArrayObject
Hello Ravi, I have been referring your posts since long and they are truely usefull, whenever I have any new functionality I first of all refer your post..I referred this code but I am facing issues when I replace your Json url with my php web service ..so can you please help me in fetching images into listview from my database through web service.
Post your json response along with parsing code. I can verify once.
Hello Ravi, Im getting this message how can I fix it please?
java.lang.ClassCastException: android.support.v7.widget.AppCompatImageView cannot be cast to com.android.volley.toolbox.NetworkImageView
Post your layout file of list row.
Hi Ravi, Im having problems with cached images in my custom listview. In my project I have the option to update images, but I keep the same URL, when I load my listview after updating the image, it shows the previous cached URL image and not the updated image. I have to close the app completely to see the new image I uploaded. How would you manage updated images with the same URL without eliminating the cache functionality completely? (I tried eliminating the put(url, bitmap); from putBitmap method in LruBitmapCache class but that only makes the list redownload the image every time you want to display it on the listview)
I’ve been searching everywhere but can’t find a solution it would be greatly appreciated if you could help me with this!
bhai mera app data load nhi krr rha h bss loading.. hi show krta rehta h please kuch solution btao…
Check the LogCat to see the errors.
Bhai please ye bta do ki list view item per click hone per item ka data new activity me open krke kse show krwana h
If you understood this tutorial, I suggest you to learn RecyclerView as ListView is deprecated.
https://www.androidhive.info/2016/01/android-working-with-recycler-view/
Hello Ravi Tamada! First, thanks alot for your great and easy understandable tutorials!
Secondly i got some questions regarding the listview example here.
I converted the project to use it with a sidebar and fragments, right now i want to click an item from the listview and open another fragment with detailed information.
First question, can you recommend me a good method to parse the data from the arraylist to the second fragment?
The Second question i have is the following: When i go back from the detail fragment to the listview fragment, it will refresh automatically, adding the same items it already fetched before a second time.
So first thing i tried is to clear the list on every oncreate, but i think it would be more practicable to leave the already fetched information on back button pressed, but i dont know how to implement this. Do you have an idea?
Hi Andy
Thanks for your appreciation.
1. First question, can you recommend me a good method to parse the data from the arraylist to the second fragment?
If you using POJO objects, extend the POJO class from Parcelable and pass the selected object to second activity via Intents.
https://stackoverflow.com/questions/10107442/android-how-to-pass-parcelable-object-to-intent-and-use-getparcelable-method-of
2. The Second question i have is the following: When i go back from the detail fragment to the listview fragment, it will refresh automatically, adding the same items it already fetched before a second time.
This can be solved by storing data in local database and load it from there. Also you can use savedInstanceState method to check whether activity is newly created or resumed.
https://stackoverflow.com/questions/151777/saving-android-activity-state-using-save-instance-state
Awesome! Thanks for your fast reply 🙂 I’m gonna look into it and hope that i’ll get it to work =) Wish you all the best, keep on your fantastic work 🙂
All the best Andi 🙂
sir, when i run application it doesnt show any response only progress bar run for a second and vanish but it doesnt show any response please help me…
thanks for your valuable tutorials..
Use https instead of http.
thanks..done..thanks for your great tutorials and your valuable time
You are welcome 🙂
Consider reading RecyclerView next.
https://www.androidhive.info/2016/01/android-working-with-recycler-view/
Why we have to use https in this case?
Because http on my blog redirects to https throwing 301 code and JSON won’t be received.
code run nai hota bhsdk
sahi bole tum bhau ekdm baklol code likha hai
sahi bola tu baka. kya baat hai
jethaji sahi baat hai
Hi world:
When I imported this project into AS (Android Studio), it wasn’t recognized as an Android project (play button didn’t turn on); does anybody know what’s I am doing wrong? I just downloaded it and imported into AS. :thinking_face:
Any help would be welcome.

Brs and thanks in advance.
Hello, is this still active? I am having a hard time because I think the adapter is not working. Thanks in advance
the attached image is the output when i run the program
Download the code, generate the apk and install it into your phone.
Look for the differences. 🙂
Hello, Sir
I using using your code in my application it’s work perfect but when i add new data in my site and try to load new data in application its not show new data every time its show old. Sir help me in this how load all new data when i m refresh page in application
Make sure the new data appears in your JSON first.
When I try to call link in browser its show new data, but in the application, its not appear
Hello, Thanks for sharing!
Can I use Picasso instead?
How can I do this for a pdf? (i’m working on books example)
Thanks in advance
Hello sir,
I’m using your code but error occur :
Error:Execution failed for task ‘:app:transformDexArchiveWithExternalLibsDexMergerForDebug’.
> java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
please help me to solve this..
You need to enable MultiDex support in your project. Search accordingly.
I enable MultiDex support …but now when i try to run app
$ adb push G:AndroidFundraiserBuyForFundappbuildoutputsapkdebugapp-debug.apk /data/local/tmp/com.android.buyforfund
$ adb shell pm install -t -r “/data/local/tmp/com.android.buyforfund”
Failure [INSTALL_FAILED_USER_RESTRICTED: Invalid apk]
$ adb shell pm uninstall com.android.buyforfund
DELETE_FAILED_INTERNAL_ERROR
Error while Installing APK
These errors occur..
I also disable Instant Run.
Then i again run app but same error occurs.
Clean data cache (your mobile phone -> settings -> apps -> (name of your app) , clean project…(in Android Studio)…
Hi,
can you please explain where did you stored the images of movie posters and how did you create path for the images ,i didnt understand this ,pls explain
Images are on my server and the path is created using the folder name on the server.
how Bro i tried didnt getting please explain with steps if you dnt mine
Have you ever run a server like Apache or Nginx in your local machine?
Thanx a lot for this amazing tutorial, this saved my day while giving a interview test.
Cheers!
HI
Im new to android ,how to parse the same api using volley with recycleview and glide.
Thanks in advance.
This article resembles the same (Glide, RecyclerView and Volley). You can read and modify the code accordingly.
https://www.androidhive.info/2017/09/android-recyclerview-swipe-delete-undo-using-itemtouchhelper/
Thank you SO much
You are welcome 🙂
Hello sir, while parsing JSON i want to parse JSON from array. here is the JSON view:: Here is my code that i am using ::
try {
// Retrieves first JSON object in outer array
JSONObject obj = response.getJSONObject(“_embedded”);
JSONArray array = obj.getJSONArray(“events”);
// Iterates through the JSON Array getting objects and adding them
//to the list view until there are no more objects in colorArray
for (int i = 0; i < array.length(); i++) {
//gets each JSON object within the JSON array
JSONObject obj2 = array.getJSONObject(i);
//to receive city name
JSONObject obj3 = obj2.getJSONObject("_embedded");
JSONArray array1 = obj3.getJSONArray("venues");
JSONObject obj4 = array1.getJSONObject(i);
JSONObject obj5 = obj4.getJSONObject("city");
//to receive country name
JSONObject obj6 = obj4.getJSONObject("country");
//to receive genre name
JSONArray array2 = obj2.getJSONArray("classifications");
JSONObject obj7 = array2.getJSONObject(i);
JSONObject obj8 = obj7.getJSONObject("segment");
Event event = new Event();
event.setName(obj2.getString("name"));
event.setInfo(obj2.getString("info"));
event.setVenues(); //here i want to parse from the Venues array
How can i do it? I have no idea about it….
Have you ever used Gson? Read these article that uses Volley and Gson to parse the JSON.
https://www.androidhive.info/2017/11/android-recyclerview-with-search-filter-functionality/
https://www.androidhive.info/2017/09/android-recyclerview-swipe-delete-undo-using-itemtouchhelper/
Once you are comfortable using Gson, the below thread can help you parsing your json.
https://stackoverflow.com/questions/37813797/deserialize-json-containing-links-and-embedded-using-spring-hateoas
https://stackoverflow.com/questions/27405637/meaning-and-usage-of-embedded-in-hateoas/27424771?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
HELLO,how to cache all the information from the volley
request
Hello Sir, this tutorial is really helpful. I have a question, what if a certain image url has no file existed, what can we do to catch this error?
nice tutorial
Hi, Ravi
Can you help me please see this thread…
https://stackoverflow.com/questions/54751856/android-listview-onclicklistener-returns-only-single-json-item-value