How to retrieve + fill Php URL JSON parsing multiple records one by one into CardView inside RecyclerView.
RecyclerView is the upgraded version of ListView with multiple more extended features and it can also be created by dynamic data. Here dynamic data means the data( All the records ) directly coming from online server with the use of PHP scripting code that is also coming from MySQL database. So here is the complete step by step tutorial for Android Create RecyclerView using JSON parsing online server data example tutorial.
Note : Project download folder contain all the source code with whole android project and all the php scripting files with MySQL database included.
List of All the Java programming files inside this project :
- MainActivity.java .
- GetDataAdapter.java .
- RecyclerViewAdapter.java .
List of all layout files inside this project :
- activity_main.xml .
- recyclerview_items.xml .
List of All PHP scripting files, which help us to convert MySQL database data into JSON format.
- jsonData.php .
- dbconfig.php .
Note: Read below steps very carefully to add Volley,RecyclerView and CardView library inside your current project.
1. Open your project’s build.gradle ( Module : app ) file.
2. Please add below code inside your build.gradle ( Module : app ) file.
compile 'com.android.support:appcompat-v7:23.4.0' compile 'com.android.support:cardview-v7:23.0.+' compile 'com.android.support:recyclerview-v7:23.0.+' compile 'com.mcxiaoke.volley:library:1.0.19'
3. Screenshot of build.gradle ( Module : app ) file after adding above code.
Next step is to add Internet permission inside AndroidManifest.xml file.
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Here your go friends, Now start coding .
Android Create RecyclerView using JSON parsing online server data example tutorial.
Code for MainActivity.java file.
package com.android_examples.dynamicrecyclerviewjson_android_examplescom; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.Volley; public class MainActivity extends AppCompatActivity { List<GetDataAdapter> GetDataAdapter1; RecyclerView recyclerView; RecyclerView.LayoutManager recyclerViewlayoutManager; RecyclerView.Adapter recyclerViewadapter; ProgressBar progressBar; String GET_JSON_DATA_HTTP_URL = "http://androidblog.esy.es/jsonData.php"; String JSON_ID = "id"; String JSON_NAME = "name"; String JSON_SUBJECT = "subject"; String JSON_PHONE_NUMBER = "phone_number"; Button button; JsonArrayRequest jsonArrayRequest ; RequestQueue requestQueue ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); GetDataAdapter1 = new ArrayList<>(); recyclerView = (RecyclerView) findViewById(R.id.recyclerView1); progressBar = (ProgressBar) findViewById(R.id.progressBar1); button = (Button)findViewById(R.id.button) ; recyclerView.setHasFixedSize(true); recyclerViewlayoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(recyclerViewlayoutManager); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { progressBar.setVisibility(View.VISIBLE); JSON_DATA_WEB_CALL(); } }); } public void JSON_DATA_WEB_CALL(){ jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { progressBar.setVisibility(View.GONE); JSON_PARSE_DATA_AFTER_WEBCALL(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); requestQueue = Volley.newRequestQueue(this); requestQueue.add(jsonArrayRequest); } public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){ for(int i = 0; i<array.length(); i++) { GetDataAdapter GetDataAdapter2 = new GetDataAdapter(); JSONObject json = null; try { json = array.getJSONObject(i); GetDataAdapter2.setId(json.getInt(JSON_ID)); GetDataAdapter2.setName(json.getString(JSON_NAME)); GetDataAdapter2.setSubject(json.getString(JSON_SUBJECT)); GetDataAdapter2.setPhone_number(json.getString(JSON_PHONE_NUMBER)); } catch (JSONException e) { e.printStackTrace(); } GetDataAdapter1.add(GetDataAdapter2); } recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this); recyclerView.setAdapter(recyclerViewadapter); } }
Code for GetDataAdapter.java file.
package com.android_examples.dynamicrecyclerviewjson_android_examplescom; import java.util.ArrayList; /** * Created by JUNED on 6/16/2016. */ public class GetDataAdapter { int Id; String name; String phone_number; String subject; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return Id; } public void setId(int Id1) { this.Id = Id1; } public String getPhone_number() { return phone_number; } public void setPhone_number(String phone_number1) { this.phone_number = phone_number1; } public String getSubject() { return subject; } public void setSubject(String subject1) { this.subject = subject1; } }
Code for RecyclerViewAdapter.java file.
package com.android_examples.dynamicrecyclerviewjson_android_examplescom; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; /** * Created by JUNED on 6/16/2016. */ public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> { Context context; List<GetDataAdapter> getDataAdapter; public RecyclerViewAdapter(List<GetDataAdapter> getDataAdapter, Context context){ super(); this.getDataAdapter = getDataAdapter; this.context = context; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_items, parent, false); ViewHolder viewHolder = new ViewHolder(v); return viewHolder; } @Override public void onBindViewHolder(ViewHolder holder, int position) { GetDataAdapter getDataAdapter1 = getDataAdapter.get(position); holder.NameTextView.setText(getDataAdapter1.getName()); holder.IdTextView.setText(String.valueOf(getDataAdapter1.getId())); holder.PhoneNumberTextView.setText(getDataAdapter1.getPhone_number()); holder.SubjectTextView.setText(getDataAdapter1.getSubject()); } @Override public int getItemCount() { return getDataAdapter.size(); } class ViewHolder extends RecyclerView.ViewHolder{ public TextView IdTextView; public TextView NameTextView; public TextView PhoneNumberTextView; public TextView SubjectTextView; public ViewHolder(View itemView) { super(itemView); IdTextView = (TextView) itemView.findViewById(R.id.textView2) ; NameTextView = (TextView) itemView.findViewById(R.id.textView4) ; PhoneNumberTextView = (TextView) itemView.findViewById(R.id.textView6) ; SubjectTextView = (TextView) itemView.findViewById(R.id.textView8) ; } } }
Code for activity_main.xml layout file.
<?xml version="1.0" encoding="utf-8"?> <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="com.android_examples.dynamicrecyclerviewjson_android_examplescom.MainActivity"> <android.support.v7.widget.RecyclerView android:id="@+id/recyclerView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="@+id/button"> </android.support.v7.widget.RecyclerView> <ProgressBar android:id="@+id/progressBar1" style="?android:attr/progressBarStyleLarge" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:visibility="gone"/> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Click Here to load JSON data into RecyclerView" android:id="@+id/button" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" /> </RelativeLayout>
Code for recyclerview_items.xml layout file.
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto" android:id="@+id/cardview1" android:layout_width="match_parent" android:layout_height="wrap_content" card_view:cardElevation="7dp" card_view:contentPadding="7dp" card_view:cardCornerRadius="7dp" card_view:cardMaxElevation="7dp" > <TableLayout android:layout_width="fill_parent" android:layout_height="wrap_content"> <TableRow> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="ID : " /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="ID Show Here" /> </TableRow> <TableRow> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Name : " /> <TextView android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Name Show Here" /> </TableRow> <TableRow> <TextView android:id="@+id/textView5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Phone Number : " /> <TextView android:id="@+id/textView6" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Phone Number Show" /> </TableRow> <TableRow> <TextView android:id="@+id/textView7" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Subject : " /> <TextView android:id="@+id/textView8" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Subject Show Here" /> </TableRow> </TableLayout> </android.support.v7.widget.CardView>
Code for AndroidManifest.xml layout file.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android_examples.dynamicrecyclerviewjson_android_examplescom"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <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>
Code for PHP files which converts MySQL database data into JSON data.
Code for jsonData.php file.
<?php include 'dbconfig.php'; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT * FROM JsonDataTable"; $result = $conn->query($sql); if ($result->num_rows >0) { // output data of each row while($row[] = $result->fetch_assoc()) { $tem = $row; $json = json_encode($tem); } } else { echo "0 results"; } echo $json; $conn->close(); ?>
Code for dbconfig.php file.
<?php //This script is designed by Android-Examples.com //Define your host here. $servername = "mysql.hostinger.in"; //Define your database username here. $username = "u288012116_and"; //Define your database password here. $password = "GArpOsx4KVa0GJDquJ"; //Define your database name here. $dbname = "u288012116_and"; ?>
Screenshots of Application :
can u help me plz how can i put onclick function in this example on cklick take me to mainactivity????
Just put a button in this activity then read my this tutorial it will help you : https://www.android-examples.com/open-new-activity-on-button-click-in-android-by-existing-activity/
thanx alot can i ask you another q??
how can i put post method to my requset i want to send astring value to my php
Read this tutorial it will explain you every thing : https://www.android-examples.com/send-insert-edittext-data-online-to-mysql-db-server-in-android/
Sorry, for annoying
first of all thanx for every thing
i want to make like this request
jsonArrayRequest = new JsonArrayRequest( Request.Method.POST,GET_JSON_DATA_HTTP_URL,new JSONObject(params),new Response.Listener() {
how can i read the params in my php code, Do you have any idea about this
Thanks in advance
Help me please, how to coding if we select data base on subject and phone numberwhere we input text from form ( xml ) form
Riswan please explain your question more briefly .
Dear Juned, when i run this example, i found this message on app : “RecyclerView: No adapter attached; skipping layout”, And when i clicked the button on my android emulator it won’t show the records… what did i miss? thank you
RAIS just download the whole project and then import it in Studio.
It Works Juned… Thanks You are the best… You just save me…
Welcome Rais .
Hi junned. Amazing tutorial. just one problem. if i click button second time, the previous data is not deleted and the data is populated twice/ HOw to delete the pool.
Just disable the button after first load or delete all the values of RecyclerView .
i cannot use clear() or removeall() for recyclerview. can you help me how to delete all data?
Then just disable the button after first load.
I have an error
com.android.volley.ParseError: org.json.JSONException: Value {“queue_names”:”queue1,queue2,queue3″} of type org.json.JSONObject cannot be converted to JSONArray
Camille did you import the volly library into your project, or i would say just download and import the project into your Android Studio.
Yes I already import the library to my gradle, I cant also run your project too many errors like ” Error:Execution failed for task ‘:app:mergeDebugResources’.
> C:\Users\Camille\Downloads\DynamicRecyclerViewJSON-Android-Examples.com_\DynamicRecyclerViewJSON-Android-Examples.com\app\build\intermediates\exploded-aar\com.android.support\appcompat-v7\23.4.0\res\drawable-mdpi-v4\abc_btn_switch_to_on_mtrl_00012.9.png: Error: File path too long on Windows, keep below 240 characters : C:\Users\Camille\Downloads\DynamicRecyclerViewJSON-Android-Examples.com_\DynamicRecyclerViewJSON-Android-Examples.com\app\build\intermediates\exploded-aar\com.android.support\appcompat-v7\23.4.0\res\drawable-mdpi-v4\abc_btn_switch_to_on_mtrl_00012.9.png “
Camille send me your project on [email protected] i will solve your error.
Thank You alott. After lot of efforts. At last.. Made it.
Welcome Jitander .
hye, can you help me..
i just wanna make my data from cardview become onclick to other activity that i can update my data..
Read my this tutorial on my new blog this would surely help you: https://androidjson.com/multiple-json-parsing-data-recyclerview/ after getting the click item you could send that item into new activity.
tq very much
Welcome
I want to ask, you know not how to do two types of login, login admin and user. just ask . . .
You can do both type of login by just putting a simple it condition in your php code.
Dear Mr. Juned
i want to ask you something. went we click on the listview over there , it will show all the detail from listview in another activity. and that new activity I can update the data from database?
by the way, thank you for sharing knowledge. you save me
Yes AFIQ read my this tutorial on my new blog this would help you : https://androidjson.com/filter-json-data-using-php-mysql/
Thank you Bro..
Thank You so much . . .
Welcome Afiq .
do yo have tutorial for login and logout?
Yes Hanif you can read my this tutorial on Login and Logout including registration online with PHP MySQL on my new Website : https://androidjson.com/android-server-login-registration-php-mysql/
am nearly new to Android development , I want to ask about two things:
1- I want to parse JSON from Youtube API V3 , which has object then Array to read from, how can I get String response from URL this parse it in JSON_DATA_WEB_CALL().
2- I want to attach a click Listener to items retrieved how to make this ?
OsaMa just set your path here on this variable GET_JSON_DATA_HTTP_URL then below this variable put all your data column names which is coming from server .
thank you so much 🙂
Welcome Niveditha .
Please how can I add search function to this
Samuel you can read my this tutorial : https://www.android-examples.com/implement-filter-using-search-box-on-json-listview/
Hey Junaid, I am trying to implement the onClickListener, from the blog https://androidjson.com/multiple-json-parsing-data-recyclerview/, I am stuck at this line over here, can you assist.
Toast.makeText(MainActivity.this, SubjectNames.get(RecyclerViewClickedItemPOS), Toast.LENGTH_LONG).show();
What should I replace with the SubjectNames.get(RecyclerViewClickedItemPOS) ?
It will be very helpful!
Btw, this is a great tutorial, thanks!
how to use mysql database in project and why and where
Can you please show me how to implement a searchview to this example, I have seen your article with the searchview for a listview, but I am unable to apply it to this recyclerview. If you could just write another article or just comment the code where I need to implement the searchview methods Kindly add it, it’ll be a great help. As I am stuck for days.
Heh Junaid please reply, I am waiting. Please look at this question
https://stackoverflow.com/questions/47049152/setting-the-dataset-for-recyclerview-after-filter/47049332?noredirect=1#comment81056720_47049332
Hey Fayaz currently i am working to this tutorial and i will soon publish my new tutorial regarding to your query.