Android material design Programming Blog

This tutorial demonstrates how to do Android JSON Parsing and display with RecyclerView or ListView. The data may be from JSON file or PHP.

To fetch JSON data in android I used java’s builtin class called AsyncTask and HttpUrlConnection and Android JSON Parsing will be done by using JSONArray and JSONObject class and finally, to display the data we use the RecyclerView(Supported in Android support library v7) widget. Let’s get started.

Note: You need to replace the version of dependency files added except glide dependency, in my case version is 23.3.0. You can find your build tool version on top of the same page.

MainActivity.java: Fetch JSON and Android JSON Parsing

The step by step procedure as follows.

Immediate after the creation of activity, a call to AsyncFetch class is made to carry out the Asynchronous task.

Before the task execution, onPreExecute() method invokes on the UI thread. In this method, we display a loading message.

doInBackground(Params…), invoked on the background thread immediately afteronPreExecute() finishes executing. The receiving of data from JSON file using HttpURLConnection class has done in this function.

onPostExecute(Result), invoked on the UI thread after the background computation finishes. The data received from server/JSON file is stored and JSON Parsing will be done.

Finally, the data is sent to the adapter to display it on RecyclerView.

Hi, I followed your blog post-http://androidcss.com/android/android-php-mysql-login-tutorial/ to log in and it worked very well. Thank you. But when you have logged in and entered a new activity, in this new activity you want to parse JSON data, how will the PHP file look like? I did that with this code initially:

Thank you for replying, Gururaj. I have this code for login (followed fom your tutorial): prepare($sql); $stmt->bindParam(‘:username’, $username, PDO::PARAM_STR); $stmt->bindParam(‘:password’, $password, PDO::PARAM_STR); $stmt->execute(); if($stmt->rowCount()) { $result=”true”; } else if(!$stmt->rowCount()) { $result=”false”; } echo $result; } ?> I just want to get the ID of the user being logged in and pass it to another PHP file through session. I don’t understand how to do that as PHP is not my thing. I’ve had this piece of code for fetching ID, but I don’t know how to adjust this in login.php file: $id = ‘SELECT id FROM cars WHERE name = :username AND password = :password’; $IDresult = mysqli_query($conn, $id); $row = mysqli_fetch_assoc($IDresult); echo “ID: ” . $row[‘id’]; $_SESSION[“Id”] = $row[‘id’];

There are many ways you can add event listener to your RecyclerView. One way is that you can add event listener in onBindViewHolder method like this.myHolder.textFishName.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // do something } });

Great Tutorial 🙂 Thanks before, but i have a small doubt about JSON. Are the image from json must be on same directory? and when i create a detail activity and i want passing data from json text and json image how do i do it? I’m very confused about passing data to detail activity.

Hello ,teacher First I like to thank you for this wonderful tutorial, but had trouble during the application (RecyclerView: No adapter attached; skipping layout) ,and messag Error is org.json.jsonexception:value connection of type java.lang.string cannot be converted to jsonarray whta the soulation

Haii Gururaj, i have a simple question for you, but its so difficult for me. The question is, how i can change the color of textview if (sample) the size name is middle then the color is red, or when the size name is small then the color of textview is green. Can you help me?

Hi, Actually I am receiving an JSON from server and I need to send that data from one fragment to another fragment and show it an recyclerview. As you have shown I have stored it an Arraylist but don’t know how to send it to another fragment. I have been suggested that I have to store that Arraylist in model then send, but I don’t know how to do it. Please help.

Hi, please help me with this Actually I am receiving an JSON from server and I need to send that data from one fragment to another fragment and show it an recyclerview. As you have shown I have stored it an Arraylist but don’t know how to send it to another fragment. I have been suggested that I have to store that Arraylist in model then send, but I don’t know how to do it. And I have already asked this earlier. Please help.

Thank you very nice tutorial it works for me. I tried to put the same code in a fragment class but it doesn’t work and the error message is (E/RecyclerView: No adapter attached; skipping layout) what should i change? Thank you.

Hi, Awesome tutorial. I want to set image for each cardview. Please, Guru Give answer to if “image count for each row is same”. “I noticed the ‘for Loop’ where the data were declared” Thanks in advance

Hi Gururaj.. can you help me? How to use putExtra with this tutorial… example… from MainActivity to DetailFish? because i wanna take this tutorial to my project im sorry for bad language english 😀 thanks

I understand that is great to learn how to do things using only the android apis. But why not use something more modern like retrofit + rxjava or even just retrofit? You could to the exact same thing with a lot less code! When i started using retrofit i decided i would never go back again! 🙂

I just want to voice my opinion in that this is one of the best online android tutorials on how to fetch/retrieve items from MySQL. It’s really well written, clearly understandable and works out of the box.

In my project I have about 100 items that I fetch and I want to implement a favourites feature. I already have my favourite button with an onClick ready to go, can you please guide us to add/remove fetched items (text and images) to a “favorites” activity using SharedPreferences please? There doesn’t seem to be any good online examples of this feature.

I learned about sqlite yesterday (thank you for mentioning it) and then modified the adapter class to include the code (onClick) to insert NAME and URL to sqlite. I used Android Studio to extract the sqlite db onto my computer and then browsed the db, I actually see the values stored in the correct db, table and columns.

..Now the challenge is to actually view the data inside a new Favorites activity using recycle view and cardview.

Gururaj with your suggestion I was able to get a step further, however I’m facing an issue now. I can read/write to sqlite in my adapter class, however I need to read the db and change the color of a textview depending on the value of the url. If the db url matches the current url value inside card view then the color of a textview should be “blue”. If the current url doesn’t match what is inside the db then the color should be “red”. I know I need to do this operation outside the adapter class and away from onBindViewHolder for performence but not sure how yet.

Basically fontFamilyText3.setTextColor(ContextCompat.getColor(context, R.color.dot_dark_screen1)); inside my adapter should be blue if the url matches what is already inside the db, if not it should be blue.

In your code, I din’t see any retrieve of data from SQLite(only Insert and Delete) and little confusion in understanding. It will be good if you host your project on GitHub with necessary files so that i can run on my machine and get you solution.

Hi, lovely tutorial, simple and clean. Very learning a lot and receiving much help from this. But i was wondering, what if the Async method is actually in a fragment, as i am using a fragment. What can i do to achieve the findViewById, currently i cannot do it. Hope you can reply me 🙂

If you don’t know how to test your app with XAMP or WAMP then please follow the below steps.

You need to find the IPV4 address of your computer. If you are using windows system, then you can open command prompt and type ipconfig for ipv4 address.

Make sure XAMP is running, Now open your browser and enter your ipv4 address and go. If you see result same as result when you enter localhost then you can proceed to next step and if some error you see then you may need to map your xamp localhost to your computer ipv4 address. Unfortunately, i don’t know how to do with xamp server but i know how to in wamp server. If you are interested in installing wamp, you can refer How to install and setup PHP and MySql in windows 10 and 7 tutorial and in wamp to map your localhost to ipv4 address, goto menu and click on put online. The following figure depict the same.

In your android code enter address as

http://your-computer-ipv4-address/file-location

For example

http://192.168.1.7/test.php

(please note that which is same as

http://localhost/test.php

and entering address with localhost does not work with android, you should specify ipv4 address only)

Now, run your app in emulator to see result and if you want to run your app on your android mobile then make sure that both of your computer and mobile connected to same wifi router.

JSON file can be created with extension as .json or even .txt(text file) also works. JSON has its own syntax to follow when deal with content, for example if i put some data inside square brackets then it treated as array. If you have your data and you want to organize that data then you can create json file and feed your data appropriately and give it to system(in my case it’s android) that understands your json data.

If you understand what XML files are, i think you understand the purpose of JSON too.