Creating PHP Script – Android JSON Parsing

Creating PHP Script – Android JSON Parsing

  • First we will create a php script that will fetch the data from the database.
  •  Now we will create an array.
  • Push the fetched data in the array as key=>value format (associative array).
  • Key would be the column name.
  • Print the array in JSON format with the function json_encode().
  • Close the database.

The final PHP Script

You can copy the above code. Save the code with some name (Extension must be .php). Upload the file to your server and try executing it.

Our JSON is now ready at this URL => http://www.simplifiedcoding.16mb.com/get-data.php

The above link will give JSON String. Itt has an array of objects name result. In result we have objects containing all the value. Each object has three values id, name and address.

Creating Android App for Parsing JSON

  • Open Android Studion => Create a New Project
  • I named my project as FetchJSON
  • Go to your activity_main.xml
  • Change the layout to LinearLayout and vertical orientation
  • Create a ListView for displaying the details that will be fetched
  • Create a new layout for our list items.
  • Right click on Layout -> New -> Layout Resource File
  • Name it list_item.xml
  • Copy the following code and paste in the layout file list_item.xml
  •  Come to the MainActivity.java
  • myJSON is the string where we will store the JSON string from server.
  • We have declared some final String TAGS for getting the values from JSON String and
  • A JSONArray peoples for storing the JSON Array and
  • An array list for creating a list from JSON and
  • A ListView for displaying the list in the Activity
  • Come to onCreate method
  • We have initialized our list object and personList.
  • Finally we called the getData() method which will fetch the JSON string from the server.
  •  getData is executing an AsyncTask. In the AyncTask class the doInBackgroundMethod will return the JSON String.
  • In onPostExecute method we will store that String to myJSON. Then we will call a new showList() method to show the JSON string in the ListView after parsing.
  •  Finally just add the internet permission to your manifest.xml

 

 

  •  Execute your application, you will see the following output.
Fetch JSON Output
https://www.simplifiedcoding.net/android-json-parsing-retrieve-from-mysql-database/#
4 سال پیش

دیدگاهتان را بنویسید

نشانی ایمیل شما منتشر نخواهد شد. بخش‌های موردنیاز علامت‌گذاری شده‌اند *

این سایت از اکیسمت برای کاهش هرزنامه استفاده می کند. بیاموزید که چگونه اطلاعات دیدگاه های شما پردازش می‌شوند.