Android Tutorial For beginners: How to communicate with a server using httputils2 (Part 3: php, MySql & JSON)

Part 2 see here: http://www.b4x.com/android/forum/th...a-server-using-httputils2-part-2-mysql.42456/

Well. Today we want to:

- make an app which calls different functions in our php script
- the app will be able to insert new persons, retrieve & count them into/from a database
- we will learn a bit about formatting the data (for lazy people like me - but it's more efficient)


Setting up the app

To keep it easy I have attached the project and the php file this time. I have tested all functions.

Keeping in mind what functions we want the app to have

- insert (a new person)
- retrieve all persons to show them
- count them (just to show how we work with single parms and a list of)

In tutorial 2 I have created a table with two culumns: name and age (all lowercase). The app will use it, too.

I made 3 buttons (insert, retrieve and count), 2 Edittext views (to input name and age) and a listview to display the data.

Insert:

B4X:
Dim InsertNewPerson As HttpJob
    InsertNewPerson.Initialize("InsertNewP", Me)
    InsertNewPerson.download2("http://www.yourdomain.com/myscript.php", Array As String ("action", "InsertNewPerson", "name", NameET.Text, "age", AgeET.Text))

We call our php script and send "name" and "age". As you see, we send the field name AND it's value. So in the script we can use the get-method to retrieve the fields we need (at the moment we need it).

To let the script know what we want to do (remember: we have 3 functions) I've added an "action field" as the first parameter. Here it is "InsertNewPerson". Guess what it does? Even the jobname ist called "InsertNewPerson".



Send and receive data to/from the php script

We will send and receive the data as an JSON formatted string. JSON is not a member of a boygroup. It helps us to handle the data very simple.

In my example there is a function to retrieve all persons from the table. The result we be a list of rows (n rows with name and age of a person):

B4X:
name      age
Klaus    30
Michael    40
test    23
Peter    59
Thomas    54


So here we have the 5 rows with 2 culumns which format is very similar to the way we send data to the script (field name, field value, field name, field value, .....)

JSON stands for "JavaScript Object Notation" and is a "ready to use function" to format data in a standard way. You will find the documentation here: http://www.json.org/

At first sight you will recognize the form we send and receive data. JSON help us to format the data.

And this is the formatted string the php sends to the app (JSON format):

B4X:
[{"name":"Klaus","age":"30"},{"name":"Michael","age":"40"},{"name":"test","age":"23"},{"name":"Peter","age":"59"},{"name":"Thomas","age":"54"}]

The meaning is simple:

Each content inside the brackets = {} is an object which is quite abstract. As we know, we handle persons with our app. So let's call it person.

So we simple get a list with persons. That's it.

In our app we use
B4X:
Dim parser As JSONParser
parser.Initialize(res)

to initialise the JSON parser.

As I said, we know to get a list with persons. So why not have a list to handle it?

B4X:
Dim ListOfPersons As List

Now we let the parser work:

B4X:
ListOfPersons = parser.NextArray

The JSON parser takes a look at the data and extracts the list for us. And remember: The list is a map with field name, field value, field name, field value, ..... and every map is a person (name and age).

So we need a map:

B4X:
Dim Person As Map

Inside the map we can address each value by (= culum of our table):

B4X:
PersonName = Person.Get("name")
PersonAge = Person.Get("age")

Wow. Now we have the "get" statement we used in our php script to get the data. Sending and getting maps with data.

The equivalent in the php script:

Getting the data from the app

B4X:
$name = $_GET["name"];
$age = $_GET["age"];

Sending back data to the app

B4X:
$q = mysql_query("SELECT name, age FROM persons");
        $rows = array();
        while($r = mysql_fetch_assoc($q))
        {
            $rows[] = $r;
        }
        print json_encode($rows);

"mysql_fetch_assoc" will get the values AND the culumn names. The rows are stored in an array and at the end we convert it into a JSON string.

B4X:
[{"name":"Klaus","age":"30"},{"name":"Michael","age":"40"},{"name":"test","age":"23"},{"name":"Peter","age":"59"},{"name":"Thomas","age":"54"}]

But what if we only want to send back one single value?

In another function I just count the persons stored. The php script will then just send a number. JSON will do that for us, too.

B4X:
$q = mysql_query("SELECT * FROM Persons");
$count = mysql_num_rows($q);
print json_encode($count);

In our app we need to tell the parser to expect a single value:

B4X:
parser.NextValue

Here we have an array with just one value and JSON gets it for us.

Now take a look at the b4a project and the php script. The include statement includes another php script which contains the database names and the login parameters. This is used to protect your login parameters and passwords from being known.
 

Attachments

  • Example_B4A.zip
    8.6 KB · Views: 2,881
  • php_example.zip
    552 bytes · Views: 2,478

alienhunter

Active Member
Licensed User
Longtime User
oRecord is a Map
hi ,
thanks for your answer , i anticipated this , but it does not work would you be so kind and post the complete php and b4a code or a sample for images ? .
It is kind of strange i cannot find this as complete demo in the whole forum , just bits and pieces and they do not fit together ... similar to IKEA :)
As Remote.Database.Connector. user i do not know how , and i need this project to work over PHP do not have any posibility of RDC
thanks AH
 

agus mulyana

Member
Licensed User
Longtime User
Dear all

i still have an error, like this, when i debug it, till fethind data from PHP is ok, but after that, json error,..please help me

thank you
 

Attachments

  • error JSON.png
    error JSON.png
    133.5 KB · Views: 361

KMatle

Expert
Licensed User
Longtime User
Top