Create an API (PHP) 앱 인벤터와 php 통합

 

TinyWebDB is an App Inventor component that allows you to access the web from an Android app. You can use TinyWebDB to access a data source (API) or to store the app’s data persistently in a web database. These notes show you how to do the former– create an App-Inventor-compliant API that returns data to an App Inventor app. Often, the service you write will just serve as a proxy and call some other existing data service (e.g., Twitter, Amazon, Yahoo Finance).  

Though you can create an App-Inventor-compliant API in many languages and environments, these instructions describe an API written in PHP.  

To follow these instructions, you’ll need to have some programming expertise and be familiar with PHP and web services (APIs).  

 
App Inventor TinyWebDB Protocol  

TinyWebDB provides two key functions: StoreValue(tag,value) and GetValue(tag) which allow an app to store and retrieve tag-value pairs.

In this tutorial we shall create a small app that allows us to store a result, and recall what we stored. 

Although you can do that with standard TinyWebDB / App Engine usage in App Inventor,  so we’ll do a little extra.

If the value we store is the string ‘two times table’ then let’s actually return the two times table. 1×2=2, 2×2=4 etc etc when we recall it. In other words, showing we’re processing data ahead of returning it, not just returning static items parrot fashion.  

App Inventor Part

OK, so start a new project and call it ‘PHPTest’, and set the title of Screen1 to ‘PHP TinyWebDB demo’.  Add the following components:

 Textbox1 

  • Empty the Text, so it’s blank
  • Set Hint to “Enter the text to be sent and stored. Send ‘two table table’ without the quotes to get the two times table”
  • Set Width to Fill Parent

 Button1 

  • Set Text to Submit

 Button2 

  • Set Text to Retrieve

 Label1 

  • Empty the Text, so it’s blank.

  TinyWebDB1 

OK, now open the Blocks Editor and let’s make the magic happen. 

Define two global variables: 

  

Wire up the two buttons. Start with Button1, which was ‘Submit’. Set it up as below:

   

Basically it’s going to make a call to StoreValue in the TinyWebDB component, passing in the tag ‘testPHP’ and the text contents of the textbox.

 Now Button2, which was ‘Retrieve’. Set it up as below: 

  

Passing in the same tag as we used to store the value, so we can use it (if we want) to identify which StoreValue is related to which GetValue.

Now let’s set up the TinyWebDB component.

First, let’s be good and catch errors that may be reported, that we can push to the users screen in Label1.  

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

Now the guts of it. Set is up as follows:

   

Basically, this simply builds up a string called theText that is ultimately set to be displayed via Label1.  

The guts of this is a while loop while there is still data to be read (items in the list), get each one out, and add it to theText. If you’ve set the TinyWebDB component to point to our PHP servers as mentioned above then you should be able to store and retrieve values to your hearts content without doing anything else. Don’t forget, store ‘two times table’ (case sensitive, without the quotes) and retrieve it to see the two times table and not just a straight text retrieval. 

TRY IT. Scan the barcode to your Android phone:
CUSTOMIZE IT. Download the source code blocks to create your own PHPTest app.

 

  1. save the source file to your computer
  2. open the My Projects page in App Inventor
  3. select Upload Source
  4. choose this file
   
   

PHP Part

Well, the PHP for this is remarkably simple. 

   
CUSTOMIZE THE API. Are you a programmer? If so, download the source code for the PHP  Part

What does it actualy do? First, get the Post string: 

 $postUrl=$_SERVER["REQUEST_URI"];

 and see if it is a store request:

 if(strpos($postUrl,'storeavalue')){

then get the variables that were passed in: 

  // Get that tag
  $tag = trim($tag);
  // Get the value
  $value = trim($value);

then do your processing, or whatever. If it’s a get request this will result in you creating an array of all the data you want to return: 

 $resultData = array("VALUE",$tag,array($theData));

where $tag is supplied by default, and $theData is the data you wish to return. Then prime a JSON formatted string using json_encode(), and return it:

$resultDataJSON = json_encode($resultData);
echo $resultDataJSON;

A simple string would return something like: 

["VALUE","tagname",["stored string"]]

Or a more complex array (like our two times table) could result something like: 

["VALUE","tagname",{"1 x 2 = ":2,"2 x 2 = ":4,"3 x 2 = ":6,
"4 x 2 = ":8,"5 x 2 =":10}]

So as you can see, strings in quotes. Numbers not in quotes. Be careful of Gotchas!! A couple of things that stumped me during this:

  1. Cutting/pasting text into PHP caused odd line breaks which upset PHP. Make sure all lines are valid.
  2. json_encode is PHP5 only. If you can’t use that, construct the string manually, so long as it is a valid JSON string as shown in the examples above.

Also, don’t forget to point your TinyWebDB component to your correct PHP file.

I strongly recommend while you start playing to dump out to a MySQL database or a flat file, the contents of $_SERVER[“REQUEST_URI”], $tag and $value so you can see what is being passed in etc. It makes debugging a lot easier.

The world is open to pull data into App Inventor. All you need is to format it as a valid JSON string as shown in the examples above.

Have fun!!

This sample was inspired by the post ‘TinyWebDB php example’ on the official App Inventor for Android Google Groups, and thanks to the author of that post (martin12345) for his help and input.

Next steps:

I’m working on a tutorial that will do this all slightly different, and not use TinyWebDB.StoreValue any more, and rather have an App Inventor Procedure that compiles a JSON string that is sent in as the tag on a TinyWebDB.GetValue, deconstructed in PHP, does some jiggery pokery and returns another JSON string. I’ll have this out very very soon.   

Martin Keywood

 

[출처] https://appinventorapi.com/program-an-api-php/

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
93 Android Studio Build시 failed linking references 해결방법 file 졸리운_곰 2020.05.05 648
92 [안드로이드 스튜디오] COULD NOT FIND COM.ANDROID.TOOLS.BUILD:GRADLE:3.0.0-BETA6 file 졸리운_곰 2020.05.05 125
91 Android Sync SQLite Database with Server using PHP and MySQL file 졸리운_곰 2019.02.25 7762
90 안드로이드의 MVC, MVP, MVVM 종합 안내서 file 졸리운_곰 2019.01.06 370
89 Getting Started: WebView-based Applications for Web Developers file 졸리운_곰 2018.09.03 410
88 App Inventor - MySQL interface 앱 인벤터 mysql 연결 file 졸리운_곰 2018.04.07 7995
87 Connect App Inventor to MySQL Database 앱 인벤터와 mysql 데이터베이스 연결 file 졸리운_곰 2018.04.07 7273
» Create an API (PHP) 앱 인벤터와 php 통합 file 졸리운_곰 2018.04.07 630
85 Android WebView javascriptInterface 사용하기 file 졸리운_곰 2018.03.26 656
84 Using the WebViewer Control in App Inventor 앱인터에서 웹뷰 컨트롤 사용 file 졸리운_곰 2018.03.24 512
83 WebView Javascript Processor for App Inventor 앱 인벤터 웹뷰 자바스크립트 인터페이스 file 졸리운_곰 2018.03.24 505
82 android webview로 javascript 호출 및 이벤트 받기(연동하기) file 졸리운_곰 2018.03.19 1405
81 Android Asynchronous Http Client file 졸리운_곰 2017.07.03 709
80 안드로이드 에서 JSON 읽어오기 (JSON parser) file 가을의곰 2017.06.18 827
79 Creating a digital wallet application in App Inventor 2 file 졸리운_곰 2017.05.01 287
78 Android Basic JSOUP Tutorial file 졸리운_곰 2017.03.27 349
77 [Android] 안드로이드 웹페이지 파싱하기 - jsoup 이용하기 file 졸리운_곰 2017.03.27 724
76 Android에서 jsoup를이용하여 HTML 파서(Parser) file 졸리운_곰 2017.03.27 764
75 Android : Keystore 정보확인 및 패스워드 변경 졸리운_곰 2017.03.23 235
74 android studio 2.3 의 안드로이드 레이아웃 배치 법 : Layout Editor로 UI 빌드 file 졸리운_곰 2017.03.09 534
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED