Android Programming

Hands On No. 6 : Data Passing using JSON

Resources

API Code in PHP - showDetails.php
                                        
<?php 
//0 for record not found
//-1 for Not Get Error
//-2 for Parameter Error

$s2 = array();
class Subject {
          public $cno = "";
          public $ccode  = "";
          public $cname  = "";
          public $cincharge = "";
       }
 $s = new Subject();
if($_GET)
{
    $a = isset($_GET['id'])?$_GET['id']:0;
    
    
    if($a==0)
    {
    $con = mysqli_connect("localhost","root","","tybca2018");
    if (!$con)
      {
      echo "Error";
      }
    
    
    
    $res = mysqli_query($con,"select * from subject where sno='$a'");
    
    $n = mysqli_num_rows($res);
    //echo $n;
    if($n==0)
    {
           $s->cno = "0";
           $s->ccode = "0";
           $s->cname = "0";
           $s->cincharge = "0";
           $s1 = array('subject' => $s);
           array_push($s2,$s1);
    }
    else
    {
        while ($row = mysqli_fetch_assoc($res))
        {
           
           
           
          
           $s->cno = $row['sid'];
           $s->ccode = $row['sno'];
           $s->cname = $row['sname'];
           $s->cincharge = $row['cincharge'];
           $s1 = array('subject' => $s);
           array_push($s2,$s1);
            
        }
    }
    
    
    mysqli_close($con);
    }
    else
    {
        $s->cno = "-2";
        $s->ccode = "-2";
        $s->cname = "-2";
        $s->cincharge = "-2";
        $s1 = array('subject' => $s);
        array_push($s2,$s1);
        
        
    }
    
}
else
{
    $s->cno = "-1";
    $s->ccode = "-1";
    $s->cname = "-1";
    $s->cincharge = "-1";
    $s1 = array('subject' => $s);
    array_push($s2,$s1);
}
echo json_encode($s1);
?>

Table Schema of subject in MYSQL
                                        
CREATE TABLE `subject` (
  `sid` bigint(20) UNSIGNED NOT NULL,
  `sno` varchar(10) NOT NULL,
  `sname` varchar(50) NOT NULL,
  `cincharge` varchar(50) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
 
INSERT INTO `subject` (`sid`, `sno`, `sname`, `cincharge`) VALUES
(1, 'CA312', 'Andorid', 'Dhaval Mehta'),
(2, 'CA101', 'Web Design', 'Yash Karanke');
 
ALTER TABLE `subject`
  ADD UNIQUE KEY `sid` (`sid`);
ALTER TABLE `subject`
  MODIFY `sid` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
COMMIT;

Source Code of ActivityMain.java
mport androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {

    Button mButton;
    TextView tv1,tv2;
    AlertDialog.Builder builder;
    String s;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mButton = (Button)findViewById(R.id.load_data);
        tv1 = (TextView) findViewById(R.id.txtcname);
        final EditText et1 = (EditText) findViewById(R.id.txtcode);

        builder = new AlertDialog.Builder(this);
        builder.setMessage("Are You Sure to Exit").setTitle("W3TechBlog");

        builder.create();
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo nInfo = cm.getActiveNetworkInfo();
                boolean connected = nInfo != null && nInfo.isAvailable() && nInfo.isConnected();

                if(connected) {

                    s = et1.getText().toString().trim();
                    String url = "https://w3techblog.com/tybca_example/showDetails.php?id=" + s;

                    JsonObjectRequest jsonRequest = new JsonObjectRequest
                            (Request.Method.GET, url, null, new Response.Listener() {
                                @Override
                                public void onResponse(JSONObject response) {
                                    // the response is already constructed as a JSONObject!
                                    try {

                                        response = response.getJSONObject("subject");

                                        String sname = response.getString("cname"),
                                                cname = response.getString("cincharge");
                                        if (sname.equals("0")) {
                                            tv1.setText("Record Not Found");

                                        } else if (sname.equals("-1")) {
                                            tv1.setText("Not using GET method");

                                        } else if (sname.equals("-2")) {
                                            tv1.setText("Error in Parameter");

                                        } else {
                                            tv1.setText("Course Name " + sname + "\nCourse Incharge Name : " + cname);

                                        }


                                    } catch (JSONException e) {
                                        tv1.setText(e.toString());
                                        System.out.println(e.toString());

                                    }
                                }
                            }, new Response.ErrorListener() {

                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    builder.setMessage("Server is not Responding...").setTitle("W3TechBlog");
                                    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int id) {

                                        }
                                    });


                                    builder.show();

                                }
                            });

                    Volley.newRequestQueue(MainActivity.this).add(jsonRequest);
                }
                else
                {
                    builder.setMessage("Internet is Off").setTitle("W3TechBlog");
                    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {

                        }
                    });


                    builder.show();

                }
                }

        });

    }

    @Override
    public void onBackPressed() {
        builder.setMessage("Are You Sure to Exit").setTitle("W3TechBlog");

        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                System.exit(0);
            }
        });
        builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User cancelled the dialog
            }
        });

        builder.show();



    }


}
                                    

Add following line in build.gradle of app
implementation 'com.android.volley:volley:1.1.1'
                                    

Source Code of activity_main.xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">


<TableRow android:layout_marginTop="50dp">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:layout_marginLeft="40dp"
android:text="Course Code"
android:textAppearance="@style/TextAppearance.AppCompat.Body2"

android:textColor="@android:color/holo_blue_light"
android:textSize="25sp" />

<EditText
android:id="@+id/txtcode"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_marginLeft="20dp"
android:width="150dp"
android:ems="20" />
</TableRow>


<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<Button
android:id="@+id/load_data"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:background="@color/colorAccent"
android:text="Submit"
android:textColor="@android:color/white"

android:textSize="25sp" />

</TableRow>

<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/txtcname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:layout_span="2"

android:text="Course Code"

android:textColor="@android:color/holo_blue_light" />
</TableRow>

</TableLayout>

Add following code in AndroidManifest.xml File
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />