Android JSON parsing Retrieve from URL and set MySQL db data into TextView example tutorial

How to get-fetch data online from server using PHP script and insert into TextView with progress bar loading .

In this tutorial we are simply calling a URL created on server with PHP scripting programming language. This URL will return us some value that is directly coming from our PhpMyAdmin MySQL database. So we fetch this data and parse it using JSON parsing technique inside android application and set into TextView. This will help us to get full control on our android apps so app developer can edit, modify apps title, heading, tag lines directly from server while app is starting and getting data. So here is the complete step by step tutorial for Android JSON parsing Retrieve from URL and set MySQL db data into TextView example tutorial.

android-project-download-code-button

Android JSON parsing Retrieve from URL and set MySQL db data into TextView example tutorial.

List of Main android project files in this project :

  1. MainActivity.java file.
  2. activity_main.xml file.
  3. AndroidManifest.xml file.

List of PHP programming file which is converting MySQL db data into JSON data.

  1. dbconfig.php file .
  2. send-data.php file.

Note: If you are facing The import org.apache.http.HttpResponce cannot resolved error solution then read my this tutorial for solve this problem.

Note : Please add internet permission inside your AndroidManifest.xml file.

<uses-permission android:name="android.permission.INTERNET" />

Code for MainActivity.java file.

 package com.jsonparsingfromurltextview_android_examples.com;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends Activity {

 TextView textview;
 JSONObject json = null;
 String str = "";
 HttpResponse response;
 Context context;
 ProgressBar progressbar;
 Button button;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 progressbar = (ProgressBar)findViewById(R.id.progressBar1);
 textview = (TextView)findViewById(R.id.textView1);
 button = (Button)findViewById(R.id.button1);
 
 progressbar.setVisibility(View.GONE);

 button.setOnClickListener(new View.OnClickListener() {
 
 @Override
 public void onClick(View v) {
 // TODO Auto-generated method stub
 
 progressbar.setVisibility(View.VISIBLE);
 
 new GetTextViewData(context).execute();
 
 }
 }); 
 }

 
 private class GetTextViewData extends AsyncTask<Void, Void, Void> 
 {
 public Context context;
 

 public GetTextViewData(Context context)
 {
 this.context = context;
 }

 @Override
 protected void onPreExecute() 
 {
 super.onPreExecute();
 }

 @Override
 protected Void doInBackground(Void... arg0) 
 {
 
 HttpClient myClient = new DefaultHttpClient();
 HttpPost myConnection = new HttpPost("http://demoblog.16mb.com/send-data.php");
 
 try {
 response = myClient.execute(myConnection);
 str = EntityUtils.toString(response.getEntity(), "UTF-8");
 
 } catch (ClientProtocolException e) {
 e.printStackTrace();
 } catch (IOException e) {
 e.printStackTrace();
 }
 
 
 try{
 JSONArray jArray = new JSONArray(str);
 json = jArray.getJSONObject(0);
 
 
 
 } catch ( JSONException e) {
 e.printStackTrace(); 
 }
 
 catch (Exception e) 
 {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 return null;
 }
 protected void onPostExecute(Void result) 
 {
 try {
 textview.setText(json.getString("ServerData"));
 
 } catch (JSONException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 
 //Hiding progress bar after done loading TextView.
 progressbar.setVisibility(View.GONE);
 
 }
 }
 
 
}

Code for activity_main.xml layout file.

 <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"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.jsonparsingfromurltextview_android_examples.com.MainActivity" >

 <TextView
 android:id="@+id/textView1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignParentTop="true"
 android:layout_centerHorizontal="true"
 android:text="TextView Static Text Before Load"
 android:textAppearance="?android:attr/textAppearanceLarge" 
 android:gravity="center"/>

 <ProgressBar
 android:id="@+id/progressBar1"
 style="?android:attr/progressBarStyleLarge"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_below="@+id/textView1"
 android:layout_centerHorizontal="true"
 android:layout_marginTop="17dp" />

 <Button
 android:id="@+id/button1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_marginTop="150dp" 
 android:text="Click Here to Load TextView data dynamically from MySQL Database Online Using JSON Parsing" />

</RelativeLayout>

Code for AndroidManifest.xml file.

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.jsonparsingfromurltextview_android_examples.com"
 android:versionCode="1"
 android:versionName="1.0" >

 <uses-sdk
 android:minSdkVersion="8"
 android:targetSdkVersion="21" />
 
 <uses-permission android:name="android.permission.INTERNET" />

 <application
 android:allowBackup="true"
 android:icon="@drawable/ic_launcher"
 android:label="@string/app_name"
 android:theme="@style/AppTheme" >
 <activity
 android:name=".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>

PHP files :

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 = "u727224026_demo";
//Define your database password here.
$password = "1234567890";
//Define your database name here.
$dbname = "u727224026_demo";

?>

Code for send-data.php file.

 <?php
include 'dbconfig.php';


// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
 die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM TextViewTable";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
 
 // output data of each row
 while($row[] = $result->fetch_assoc()) {
 
 $json = json_encode($row);
 
 
 }
} else {
 echo "0 results";
}
echo $json;
$conn->close();
?>

Screenshots:

before-load-textview

 

Android JSON parsing Retrieve from URL and set MySQL db data into TextView example tutorial

Android JSON parsing Retrieve from URL and set MySQL db data into TextView example tutorial

PhpMyAdmin Table screenshot :

db-table-screenshot

Click here to download Android JSON parsing Retrieve from URL and set MySQL db data into TextView example tutorial project with source code.

36 Comments

  1. Sir, i’m very newbie in programming. how to make this application without button? so it will get data when application opened.

    cheers

  2. DIAN its very easy to get data without button all you have to do is call the new GetTextViewData(context).execute(); function just after setContentView(R.layout.activity_main);

    • Thanks for your answer sir. and sorry for late response from me because i have problem with my connection. may i have your contact sir?

  3. may i ask once again? how to put value into togglebutton? so if 0 togglebutton will off then if 1 togglebutton will on.

    thanks

  4. i’m done with all of your tutorial. thank you very much.
    but now, my application has stopped because i did modification 😀

    but thank you so much sir for your help

    Cheers

  5. Welcome DIAN

  6. Thanks sir it,s working ,but i have one question. There is displaying only one row, but i want to display all data in my database…
    Thanks in advance

  7. Thank you very much……
    Really helpful example..I solved my problem.

  8. I got problem of “No value for ServerData “…and it will not display on textview

  9. I want to display all data in my database in TextView. And also use last entry in My future.But if I run this code for my case.It will not display any data on the Text view.And gave me an error “No value for ServerData “.

  10. Urvashi sondagar

    hello sir,
    your all tutorial is very helpful.. i have developed 50% app my referring your tutorial. now my problem is i have to retrieve data from mysql database and display in receipt format. Can you please help me out how i can i create receipt structure to display data.

  11. Hello sir , How to retrieve data by id and display in listview .

  12. Im getting this error when i click the button. How can i fix this?
    Mylogcat
    07-18 11:34:24.617 1961-1961/com.example.lightning.phpmyurlandroid E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.lightning.phpmyurlandroid, PID: 1961
    java.lang.NullPointerException: Attempt to invoke virtual method ‘java.lang.String org.json.JSONObject.getString(java.lang.String)’ on a null object reference
    at com.example.lightning.phpmyurlandroid.MainActivity$GetTextViewData.onPostExecute(MainActivity.java:114)
    at com.example.lightning.phpmyurlandroid.MainActivity$GetTextViewData.onPostExecute(MainActivity.java:60)
    at android.os.AsyncTask.finish(AsyncTask.java:660)
    at android.os.AsyncTask.-wrap1(AsyncTask.java)
    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
    at android.os.Handler.dispatchMessage(Handler.java:110)
    at android.os.Looper.loop(Looper.java:203)
    at android.app.ActivityThread.main(ActivityThread.java:6364)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)

    • This is my code
      TextView textview;
      JSONObject json = null;
      String str = “”;
      HttpResponse response;
      Context context;
      ProgressBar progressbar;
      Button button;
      @Override
      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      progressbar = (ProgressBar)findViewById(R.id.progressBar1);
      textview = (TextView)findViewById(R.id.textView1);
      button = (Button)findViewById(R.id.button1);

      progressbar.setVisibility(View.GONE);

      button.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
      // TODO Auto-generated method stub

      progressbar.setVisibility(View.VISIBLE);

      new GetTextViewData(context).execute();

      }
      });
      }

      private class GetTextViewData extends AsyncTask
      {
      public Context context;

      public GetTextViewData(Context context)
      {
      this.context = context;
      }

      @Override
      protected void onPreExecute()
      {
      super.onPreExecute();
      }

      @Override
      protected Void doInBackground(Void… arg0)
      {

      HttpClient myClient = new DefaultHttpClient();
      HttpPost myConnection = new HttpPost(“http://demoblog.16mb.com/send-data.php”);

      try {
      response = myClient.execute(myConnection);
      str = EntityUtils.toString(response.getEntity(), “UTF-8”);

      } catch (ClientProtocolException e) {
      e.printStackTrace();
      } catch (IOException e) {
      e.printStackTrace();
      }

      try{
      JSONArray jArray = new JSONArray(str);
      json = jArray.getJSONObject(0);

      } catch ( JSONException e) {
      e.printStackTrace();
      }

      catch (Exception e)
      {
      // TODO Auto-generated catch block
      e.printStackTrace();
      }
      return null;
      }
      protected void onPostExecute(Void result)
      {
      try {
      textview.setText(json.getString(“ServerData”));

      } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      }

      //Hiding progress bar after done loading TextView.
      progressbar.setVisibility(View.GONE);

      }
      }

    • Madara just download and import the whole project into Studio.

      • You are using eclipse in this project. Can you updated the project using android studio i cant import it properly in the android studio. Sorry newbie here.

      • Im already import it properly but the crash still there once i click the button. Can you check it?
        Here is my logcat
        07-20 11:12:25.065 30281-30281/? E/AndroidRuntime: FATAL EXCEPTION: main
        Process: com.jsonparsingfromurltextview_android_examples.com, PID: 30281
        java.lang.NullPointerException: Attempt to invoke virtual method ‘java.lang.String org.json.JSONObject.getString(java.lang.String)’ on a null object reference
        at com.jsonparsingfromurltextview_android_examples.com.MainActivity$GetTextViewData.onPostExecute(MainActivity.java:114)
        at com.jsonparsingfromurltextview_android_examples.com.MainActivity$GetTextViewData.onPostExecute(MainActivity.java:60)
        at android.os.AsyncTask.finish(AsyncTask.java:660)
        at android.os.AsyncTask.-wrap1(AsyncTask.java)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
        at android.os.Handler.dispatchMessage(Handler.java:110)
        at android.os.Looper.loop(Looper.java:203)
        at android.app.ActivityThread.main(ActivityThread.java:6364)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)

        ——— beginning of system

  13. Hi Juned ,
    I really like your tutorial, it helped me a lot.

    I have a question and was wondering if you can help.

    lest say my sql was “SELECT * FROM TextViewTable Where id=” ‘$id’.
    and my $id = $_Post[“id”];

    how do I specify the id from the java file.

    Thank you, and I hope to hear from you soon.

Leave a Reply

Your email address will not be published. Required fields are marked *