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.
Android JSON Parsing Demo
JSON
The below is an example of fish data I’m using which has some basic info like image URL, fish name, category, size, and price.
example.json
[{"fish_img":"1.jpg","fish_name":"Indian Mackerel","cat_name":"Marine Fish","size_name":"Medium","price":"100"}, {"fish_img":"2.jpg","fish_name":"Manthal Repti","cat_name":"Marine Fish","size_name":"Small","price":"200"}, {"fish_img":"3.jpg","fish_name":"Baby Sole Fish","cat_name":"Marine Fish","size_name":"Small","price":"600"}, {"fish_img":"4.jpg","fish_name":"Silver Pomfret","cat_name":"Marine Fish","size_name":"Large","price":"300"}, {"fish_img":"5.jpg","fish_name":"Squid","cat_name":"Shell Fish","size_name":"Small","price":"800"}, {"fish_img":"6.jpg","fish_name":"Clam Meat","cat_name":"Shell Fish","size_name":"Small","price":"350"}, {"fish_img":"7.jpg","fish_name":"Indian Prawns","cat_name":"Shell Fish","size_name":"Medium","price":"270"}, {"fish_img":"8.jpg","fish_name":"Mud Crab","cat_name":"Shell Fish","size_name":"Medium","price":"490"}, {"fish_img":"9.jpg","fish_name":"Grey Mullet","cat_name":"Backwater Fish","size_name":"Small","price":"670"}, {"fish_img":"10.jpg","fish_name":"Baasa","cat_name":"Backwater Fish","size_name":"Large","price":"230"}, {"fish_img":"11.jpg","fish_name":"Pearl Spot","cat_name":"Backwater Fish","size_name":"Small","price":"340"}, {"fish_img":"12.jpg","fish_name":"Anchovy","cat_name":"Marine Fish","size_name":"Small","price":"130"}, {"fish_img":"13.jpg","fish_name":"Sole Fish","cat_name":"Marine Fish","size_name":"Medium","price":"250"}, {"fish_img":"14.jpg","fish_name":"Silver Croaker","cat_name":"Marine Fish","size_name":"Small","price":"220"}]
Android
The files and steps used in this tutorial as follow.
Adding Dependencies
Open your build.gradle(Module: app) file and add the following dependencies highlighted below and sync your project Gradle.
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.android.support:recyclerview-v7:23.3.0'
compile 'com.github.bumptech.glide:glide:3.5.2'
}
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 after
onPreExecute() 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.
package com.androidcss.jsonexample;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVFishPrice;
private AdapterFish mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Make call to AsyncTask
new AsyncFetch().execute();
}
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
HttpURLConnection conn;
URL url = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
@Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your json file resides
// Even you can make call to php file which returns json data
url = new URL("http://192.168.1.7/test/example.json");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
@Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
List<DataFish> data=new ArrayList<>();
pdLoading.dismiss();
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
DataFish fishData = new DataFish();
fishData.fishImage= json_data.getString("fish_img");
fishData.fishName= json_data.getString("fish_name");
fishData.catName= json_data.getString("cat_name");
fishData.sizeName= json_data.getString("size_name");
fishData.price= json_data.getInt("price");
data.add(fishData);
}
// Setup and Handover data to recyclerview
mRVFishPrice = (RecyclerView)findViewById(R.id.fishPriceList);
mAdapter = new AdapterFish(MainActivity.this, data);
mRVFishPrice.setAdapter(mAdapter);
mRVFishPrice.setLayoutManager(new LinearLayoutManager(MainActivity.this));
} catch (JSONException e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
DataFish.java
package com.androidcss.jsonexample;
public class DataFish {
public String fishImage;
public String fishName;
public String catName;
public String sizeName;
public int price;
}
AdapterFish.java
When the user scrolls through RecyclerView, The binding of data to views and recycling of views will be done.
package com.androidcss.jsonexample;
import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.Collections;
import java.util.List;
public class AdapterFish extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private LayoutInflater inflater;
List<DataFish> data= Collections.emptyList();
DataFish current;
int currentPos=0;
// create constructor to innitilize context and data sent from MainActivity
public AdapterFish(Context context, List<DataFish> data){
this.context=context;
inflater= LayoutInflater.from(context);
this.data=data;
}
// Inflate the layout when viewholder created
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflater.inflate(R.layout.container_fish, parent,false);
MyHolder holder=new MyHolder(view);
return holder;
}
// Bind data
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
// Get current position of item in recyclerview to bind data and assign values from list
MyHolder myHolder= (MyHolder) holder;
DataFish current=data.get(position);
myHolder.textFishName.setText(current.fishName);
myHolder.textSize.setText("Size: " + current.sizeName);
myHolder.textType.setText("Category: " + current.catName);
myHolder.textPrice.setText("Rs. " + current.price + "\\Kg");
myHolder.textPrice.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));
// load image into imageview using glide
Glide.with(context).load("http://192.168.1.7/test/images/" + current.fishImage)
.placeholder(R.drawable.ic_img_error)
.error(R.drawable.ic_img_error)
.into(myHolder.ivFish);
}
// return total item from List
@Override
public int getItemCount() {
return data.size();
}
class MyHolder extends RecyclerView.ViewHolder{
TextView textFishName;
ImageView ivFish;
TextView textSize;
TextView textType;
TextView textPrice;
// create constructor to get widget reference
public MyHolder(View itemView) {
super(itemView);
textFishName= (TextView) itemView.findViewById(R.id.textFishName);
ivFish= (ImageView) itemView.findViewById(R.id.ivFish);
textSize = (TextView) itemView.findViewById(R.id.textSize);
textType = (TextView) itemView.findViewById(R.id.textType);
textPrice = (TextView) itemView.findViewById(R.id.textPrice);
}
}
}
activity_main.xml
The XML file for MainActivity.java
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="@+id/fishPriceList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="10dp"
android:layout_weight="1"
/>
</LinearLayout>
container_fish.xml
The XML file for AdapterFish.java
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:orientation="horizontal"
android:padding="10dp">
<ImageView
android:layout_width="60dp"
android:scaleType="fitXY"
android:layout_height="40dp"
android:id="@+id/ivFish"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="fish name"
android:id="@+id/textFishName"
android:layout_marginLeft="5dp"
android:layout_toRightOf="@id/ivFish"
android:layout_toLeftOf="@+id/textPrice"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="price"
android:id="@+id/textPrice"
android:textColor="@color/colorAccent"
android:layout_alignParentRight="true"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="@+id/textSize"
android:layout_marginLeft="5dp"
android:layout_below="@id/textFishName"
android:layout_toRightOf="@id/ivFish"
android:layout_toEndOf="@id/ivFish"
android:textColor="#666"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="sd"
android:id="@+id/textType"
android:layout_marginLeft="5dp"
android:layout_below="@id/textSize"
android:layout_toRightOf="@id/ivFish"
android:textColor="#666"/>
</RelativeLayout>
AndroidManifest.xml
Don’t forget to add uses-permission for the internet to your AndroidManifest.xml file, otherwise, it will give access denied error.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidcss.jsonexample" >
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
October 21, 2020 at 7:01 am
please add native admob ads inside recycler view
June 2, 2020 at 8:11 am
hello sir i got error that string cannot be converted to jsonarray
but my json looks like same like yours
https://raw.githubusercontent.com/dnzrx/SLC-REPO/master/ISYS6203/E202-ISYS6203-LA01-00.json
how to fix this??
January 1, 2020 at 10:05 am
hi my json type is json array but i get error cannot convert to array list,what should i do?
August 30, 2019 at 10:48 am
not working showing exception that it cannot convert to jsonarray.
January 28, 2019 at 12:47 pm
displaying placeholder image instead of the actual image.
September 7, 2018 at 6:30 am
This is my php file :
$row['Complaints'],
"address"=>$row['address']));
}
echo json_encode($res);
mysqli_close($conn);
This is my php output :
[{"Complaints":"dashboard not working","address":"ville parle"},{"Complaints":"call logs not available","address":"ville parle"}]
Now the problem is when I run the application it shows nothing
September 7, 2018 at 3:23 pm
Please Log/debug your result variable of
onPostExecute()
method to see what is returning. Once you confirm the data then you need to parse data accordingly based on your json format.September 1, 2018 at 11:58 am
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:
$host = 'localhost';
$user = 'root';
$pwd = '';
$db = 'android';
$conn = mysqli_connect($host, $user, $pwd, $db);
if(!$conn){
die("Error in connection : " . $mysqli_connect_error());
}
$response = array();
$sql_query = "select * from users";
$result = mysqli_query($conn, $sql_query);
if(mysqli_num_rows($result) > 0){
$response['success'] = 1;
$heroes = array();
while ($row = mysqli_fetch_assoc($result)) {
array_push($heroes, $row);
}
$response['heroes'] = $heroes;
}
else{
$response['success'] = 0;
$response['message'] = 'No data found';
}
echo json_encode($response);
mysqli_close($conn);
It worked then, but now I don’t know how to modify it after being logged in.
September 2, 2018 at 6:43 am
Hi Zainab, Could you elaborate your question in more details. I’m confused, whether do you really want to call a new service in the new activity or pass data from login activity to new activity.
September 5, 2018 at 6:01 am
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’];
September 5, 2018 at 7:08 am
I mean yes, I want to pass data from login activity to new activity.
August 18, 2018 at 9:55 am
Hi, how add event onClickListener in RecyclerView?
Thanks
August 21, 2018 at 3:42 am
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
}
});
June 11, 2018 at 5:13 pm
how do I create a menu with categories in that application getting the data via JSON?
June 12, 2018 at 3:38 am
Do you mean, how to create menu with RecyclerView?
June 14, 2018 at 2:45 am
Na verdade eu queria saber qual a melhor maneira de criar um menu (Não importa se é menu drop down ou outro), só queria saber como faço para listar as categorias desse projeto em um menu
June 14, 2018 at 2:45 am
Actually I wanted to know what the best way to create a menu (No matter if it’s drop down menu or another), just wanted to know how do I list the categories of that project in a menu
March 15, 2018 at 4:08 pm
This tutorial is great!! Thank you.
March 2, 2018 at 1:16 pm
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.
February 20, 2018 at 6:48 am
Hello,
Actually, in my project, I am using back end as python and Django. This code is working or not.
June 1, 2018 at 3:21 am
You can use any server side scripting language.
August 1, 2017 at 8:22 pm
Big thanks. I want to implement onclick in adapter to open new activity that show details.
April 10, 2017 at 10:19 pm
Great tutorial thanks! I was wondering how I would go about adding a footer to the recyclerview? Thanks
May 20, 2017 at 1:58 am
This inmaofotirn is off the hizool!
April 9, 2017 at 5:03 am
Setting adapter in AsyncTak is creating a problem(No adapter attached,skipping layout),what could be the alternative.
April 7, 2017 at 5:23 pm
Nice tutorial thanks bro…
Very helpful
Can you give a tutorial implement this method on tab layout with fragments ?
Thanks
March 11, 2017 at 10:38 am
Nice tutorial thanks bro…
Very helpful
February 25, 2017 at 6:53 am
Hi Gururaj,
Thanks for the above code. I need a help in populating 2 recycler views from 2 different URLs how do I do that? Is it possible? Because I’m able to populate 2 recycler views with same data.
Thanks in advance!
January 27, 2017 at 9:29 am
Hi Guru,
May I know how should I do if I want to fetch the SQL data from xampp server using php and display in the list view like the example above? Really appreciate your help.
Btw your code were awesome!
January 16, 2017 at 6:36 am
Great post
January 9, 2017 at 4:40 pm
i get this error:
JSONException: Value of type java.lang.String cannot be converted to JSONObject
March 20, 2017 at 9:16 am
The result you are getting is in string format. Try printing it through toast and see what exactly it is.
January 4, 2017 at 5:07 am
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
November 2, 2016 at 6:48 am
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?
October 29, 2016 at 12:45 pm
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.
October 27, 2016 at 5:39 am
Good tutorial…thank you. But its not working,it says No adapter Attached;skipping layout…on the stack trace
October 31, 2016 at 3:43 am
This question is already been answered. Please go through all comments.
November 4, 2016 at 9:13 am
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.
September 9, 2016 at 3:51 am
Thank you for the explanations! A question – what is better, to read my JSON file from a server, or to have it in the raw folder, res directory? If the second case, do I need AsynTask?
Regards
September 1, 2016 at 10:51 am
Hello, We are trying your code, it’s helpful but we got an error “of type JsonObject cannot be converted in JsonArray” and we cannot be able to see our RecyclerView.
September 1, 2016 at 11:13 am
The JSON data you are passing is of type object but you need to pass JsonArray because we written the code to parse JsonArray not object.
June 21, 2017 at 10:14 am
Do you find the solution to this problem? because I have the same problem and I don’t know how to resolve it, thanks.
August 22, 2016 at 7:35 pm
This is the best working example I’ve tried. minimal coding!!!
by the way Gururaj P Kharvi do you have any example for Sorting json values by the use of Spinner? Thanks
August 22, 2016 at 2:44 pm
this helps me in my project SO GREAT TUTORIAL
just follow the steps guys!!!!
August 19, 2016 at 8:56 am
Hello Gururaj P Kharvi, thanks for the tutorial,can you do one for Json parsing using volley
August 18, 2016 at 9:53 pm
Hi, This is the best tutorial ever. It will be more awesome if you do a tutorial on using firebase database instead of the usual http call.
Again, Wonderful tutorial
August 11, 2016 at 7:05 am
dis code will work for if i ll use web api as a service
August 8, 2016 at 6:18 am
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.
August 8, 2016 at 7:06 am
Refer my answer1 and answer2 in other comments.
July 29, 2016 at 12:40 pm
THis is my Main Activity , the app is crashing the error is
FATAL EXCEPTION: AsyncTask #1
Process: com.example.task, PID: 14461
java.lang.RuntimeException: An error occurred while executing doInBackground()
What am i doing wrong ???
// Code stripped out
July 29, 2016 at 1:15 pm
From above code, i found that, you are missed parameter
string
in AsyncTask.July 28, 2016 at 1:18 pm
Thanks Mr.GuruRaj,Your blog save me from the Bottle neck problem, I have a query i.e. How to show the multiple images in each row in recyclerview from the API ?. Do you have any idea please share it, Thanks in advance.
Here is Json String:
“posts”:{
“post”: {
“pm_post_id”: “2655”,
“pm_user_id”: “6022”,
“pm_type”: “1”,
“pm_title”: “”,
“pm_description”: “Mobile Testing post”,
“pm_likes”: “1”,
“pm_comments”: “1”,
“pm_contributors”: “0”,
“pm_report”: “0”,
“pm_views”: “0”,
“pm_created_on”: “2016-07-27 17:21:43”,
“pm_updated_on”: “0000-00-00 00:00:00”,
“pm_shared_type”: “1”,
“pm_shared_with”: “0”,
“pm_tags”: “0,126,0”,
“pm_timeline”: “1”,
“pm_step”: “0”,
“pm_status”: “1”,
“pm_epid”: “0”
},
“images_count”: 5,
“images”: [
{
“pg_gallery_id”: “2975”,
“pg_name”: “iphone.jpeg”,
“pg_link”: “”,
“pg_type”: “1”,
“pg_date”: “2016-07-27 17:21:43”
},
{
“pg_gallery_id”: “2976”,
“pg_name”: “iphone5se (1).jpg”,
“pg_link”: “”,
“pg_type”: “1”,
“pg_date”: “2016-07-27 17:21:43”
},
{
“pg_gallery_id”: “2977”,
“pg_name”: “profile_blue.png”,
“pg_link”: “”,
“pg_type”: “1”,
“pg_date”: “2016-07-27 17:21:43”
},
{
“pg_gallery_id”: “2978”,
“pg_name”: “profile_logo (1).png”,
“pg_link”: “”,
“pg_type”: “1”,
“pg_date”: “2016-07-27 17:21:43”
},
{
“pg_gallery_id”: “2979”,
“pg_name”: “elnb.gif”,
“pg_link”: “”,
“pg_type”: “1”,
“pg_date”: “2016-07-27 17:21:43”
}
],
“post_user”: [
{
“first_name”: “Michelle”,
“last_name”: “Smith”,
“profile_pic”: “tomisima_src1.jpg”
}
]
}
July 28, 2016 at 1:31 pm
Is Image count for each row is same?
August 21, 2016 at 7:28 pm
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
July 5, 2016 at 8:11 am
May I ask a question?
Why the pdloading dialog doesn’t dismiss after load all data?
Thank you
July 5, 2016 at 8:20 am
pdloading.dismiss();
statement ononPostExecute()
is duplicated. May be that causing the problem. Please remove one of them and re run your app.June 30, 2016 at 2:43 pm
I’m just getting the following exception when using this way. Any Ideas?
“org.json.jsonexception value of type java.lang.string cannot be converted to jsonarray”
June 30, 2016 at 5:02 pm
The value coming from your PHP file is string so it’s giving error, you need to pass JSON array. better test your PHP file in browser or display toast message to see what exactly returning.
June 25, 2016 at 4:47 pm
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
June 26, 2016 at 1:07 pm
I already explained here in one of my article comment section.
June 21, 2016 at 12:07 pm
Thank the tutorials is great.But why do too much work on the networking call .Why did you use library like Volley to simplify the network since you also used a library (Glide ) to handle images.
June 21, 2016 at 1:50 pm
That’s right. I possibly use Volley or Retrofit library in upcoming tutorials but some of my tutorials may still contains AsyncTask because they may directly relate to my previous article.
June 21, 2016 at 2:14 am
Hi Guru,
Nice example. Can you help me out with JSON parsing, in my project i stuck with nested JSON array.
June 21, 2016 at 6:14 am
You need to have multiple for loop like this.
June 20, 2016 at 10:29 pm
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! 🙂
June 21, 2016 at 5:51 am
Yes, you are right. I just considered standard approach here.
June 20, 2016 at 6:58 am
Can the recyclerview mix with cardview to make more interactive?
June 20, 2016 at 11:32 am
@Rujaini
You may have recyclerview inside cardview but about mixing of those two, not worked on that.
June 20, 2016 at 1:19 pm
Thanks for you reply, I has test this coding and it works. But I want to change the layout when been view. Not use the fish layout, can i know how to change it? At container fish right.
June 20, 2016 at 4:06 pm
Yes, you are right. Edit your
container_fish.xml
file.June 19, 2016 at 4:06 am
Ty for this code and tutorial
June 16, 2016 at 9:13 am
Bro is there any way I can get data in a filtered range eg. My table contains values from 1000 to 10000 and I want when user clicks on 1000-2000 button only that data will be shown in recycler view
June 16, 2016 at 9:35 am
When user clicks on range button, send those values to PHP(say 1000 and 2000) and apply limit(
select * from table1 limit 1000,2000
) in your query. For example, PHP code look like thisJune 15, 2016 at 1:42 pm
Hi Gururaj,
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.
Much appreciated, thank you.
June 15, 2016 at 6:05 pm
In your scenario, SQLite works well over SharedPreferences. I recommend you to use SQLite(Android inbuilt database engine) and please refer Android SQLite Database tutorial on TutorialsPoint.
June 16, 2016 at 2:45 pm
Gururaj,
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.
June 18, 2016 at 12:28 pm
Sorry for late reply. Hope you done with your problem.
June 19, 2016 at 3:01 am
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.
UsersAdapter.Java = http://pastebin.com/7wYdPNMm
Users.java = http://pastebin.com/0mhbVRXF
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.
I’m stumped in programatically making this.
June 19, 2016 at 6:41 am
Apart from changing color, the favorite(add and display) functionality works perfect right?
June 20, 2016 at 4:58 pm
Gururaj,
You are correct. Apart from changing color, the favorite(add and display) functionality works perfectly.
June 23, 2016 at 4:51 am
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.
May 16, 2016 at 1:15 pm
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 🙂
May 16, 2016 at 3:43 pm
@Bowie
Use following lines of code if you are using Async in fragment. Replace the similar code on
onPostExecute(String result)
method. For your understanding, i marked the changes made in code.May 10, 2016 at 2:01 pm
Hi Guru,
May I know how should I do if I want to fetch the SQL data from xampp server using php and display in the list view like the example above? Really appreciate your help.
Btw your code were awesome!
May 11, 2016 at 1:59 pm
To fetch data from php the method is same as above. The small change you have to do is specify
.php
file in place of.json
file.note: In PHP you need to encode your data to json data. Use json_encode() function in PHP to encode data. See example below.
If you don’t know how to test your app with XAMP or WAMP then please follow the below steps.
For example
(please note that which is same as
and entering address with localhost does not work with android, you should specify ipv4 address only)
May 9, 2016 at 2:25 am
How to create JSON file?
May 9, 2016 at 6:48 am
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.
For more information you can refer json tutorial on w3schools