Android Create Dynamic TextView Using PHP MySQL JSON Data

How to Make TextView at application run time programmatically using Server JSON Parsing MySQL data Example Tutorial.

In this tutorial we would going to create an android application which has contain dynamic TextView, means the text set inside TextView would directly come from our online web hosting server already store in MySQL database and parsed using PHP. So here is the complete step by step tutorial for Android Create Dynamic TextView Using PHP MySQL JSON Data.

Project File Structure :-

List of Java Files in this project :-

  • MainActivity.java

List of layout file in this project :-

  • activity_main.xml

List of php files in this project :-

  • DatabaseConfig.php
  • JSonTextView.php

Contents in this project Android Create Dynamic TextView Using PHP MySQL JSON Data :-

  1. Watch the live demo video.
  2. Create a database on your server including Table.
  3. Create and upload PHP files on your server to parse MySQL data into JSON form.
  4. Start a new android app project.
  5. Add internet permission to your AndroidManifest.xml file.
  6. Add Org.Apache.Http.Legacy library in your project .
  7. Start Coding .

1. Watch Live Demo :


2. Create a database on your server including Table :

After seeing the demo video next step is Create a fresh database on your hosting server, inside that database create a table named as TextViewTable. Inside that table create two columns id and TextViewServerData like i did in below screenshot.

 3. Create and upload PHP files on your server to parse MySQL data into JSON form :

After inserting data into table we need to crate the PHP script which would parse the MySQL data into JSON from. So below is the PHP Code.

PHP Files Source Code for project Dynamic TextView Using PHP MySQL JSON:

Code for DatabaseConfig.php file.

<?php

//Define your host here.
$HostName = "localhost";

//Define your database username here.
$HostUser = "id632449_androidjson";

//Define your database password here.
$HostPass = "kdfjdfdskljomew9ry3873";

//Define your database name here.
$DatabaseName = "id632449_androidjson";

?>

Code for JSonTextView.php file.

<?php
include 'DatabaseConfig.php';

// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);

if ($conn->connect_error) {
 
 die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM TextViewTable";

$result = $conn->query($sql);

if ($result->num_rows >0) {
 
 
 while($row[] = $result->fetch_assoc()) {
 
 $tem = $row;
 
 $json = json_encode($tem);
 
 }
 
} else {
 echo "No Results Found.";
}
 echo $json;
$conn->close();
?>

4. Start a new android app project

Next step is to start a fresh android app development project or open your existing project in which you want to implement dynamic TextView.

5. Add internet permission to your AndroidManifest.xml file :

Open your project’s AndroidManifest.xml file and put the below internet permission inside it. You can find complete AndroidManifest.xml file source code at the last of this page.

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

6. Add Org.Apache.Http.Legacy library in your project :

Open your project’s build.gradle(Module:app) file .

Inside the android scope put useLibrary ‘org.apache.http.legacy’ like i did in below screenshot.

7. Start Coding for project Dynamic TextView Using PHP MySQL JSON :

Code for MainActivity.java file.

package com.androidjson.jsontextview_androidjsoncom;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    HttpResponse httpResponse;
    Button button;
    TextView textView;
    JSONObject jsonObject = null ;
    String StringHolder = "" ;
    ProgressBar progressBar;
    // Adding HTTP Server URL to string variable.
    String HttpURL = "https://androidjsonblog.000webhostapp.com/JSonTextView.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Assigning ID's to button, textView and progressbar.
        button = (Button)findViewById(R.id.button);
        textView = (TextView)findViewById(R.id.textView);
        progressBar = (ProgressBar)findViewById(R.id.progressBar);

        // Adding click lister to button.
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Showing progress bar on button click.
                progressBar.setVisibility(View.VISIBLE);

                //Calling GetDataFromServerIntoTextView method to Set JSon MySQL data into TextView.
                new GetDataFromServerIntoTextView(MainActivity.this).execute();

            }
        });
    }

    // Declaring GetDataFromServerIntoTextView method with AsyncTask.
    public class GetDataFromServerIntoTextView extends AsyncTask<Void, Void, Void>
    {
        // Declaring CONTEXT.
        public Context context;


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

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

        @Override
        protected Void doInBackground(Void... arg0)
        {

            HttpClient httpClient = new DefaultHttpClient();

            // Adding HttpURL to my HttpPost oject.
            HttpPost httpPost = new HttpPost(HttpURL);

            try {
                httpResponse = httpClient.execute(httpPost);

                StringHolder = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");

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

            try{
                // Passing string holder variable to JSONArray.
                JSONArray jsonArray = new JSONArray(StringHolder);
                jsonObject = jsonArray.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 {

                // Adding JSOn string to textview after done loading.
                textView.setText(jsonObject.getString("TextViewServerData"));

            } 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.

<?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"
    android:padding="5dp"
    tools:context="com.androidjson.jsontextview_androidjsoncom.MainActivity">


    <Button
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Load TextView Text From Server And Set JSON data into TextView" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView Text Before Load From Server"
        android:textSize="25dp"
        android:textColor="#000"
        android:gravity="center"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="58dp" />

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="22dp"
        android:visibility="gone"/>


</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.androidjson.jsontextview_androidjsoncom">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        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>

Screenshots :-

Android Create Dynamic TextView Using PHP MySQL JSON Data

Click here to download Android Create Dynamic TextView Using PHP MySQL JSON Data project with source code.

Leave a Reply

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