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/

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
47 [Android SDK] 동기와 비동기 처리의 이해 및 안드로이드에서의 적용 file 졸리운_곰 2024.05.01 120
46 [Android SDK] [Android] 안드로이드에서 Delay 구현 - Thread 졸리운_곰 2024.05.01 99
45 [Android SDK] How to implement Do nothing for a certain period of time in Android 졸리운_곰 2024.05.01 134
44 [Android SDK] Android handle을 이용한 지연처리: postDelayed 등 졸리운_곰 2024.05.01 132
43 [Android SDK] [안드로이드 스튜디오] 로딩창 구현 (ProgressBar) file 졸리운_곰 2024.05.01 126
42 [Android SDK] [Android] 안드로이드 Alert 창 띄우기 file 졸리운_곰 2024.05.01 124
41 [Android SDK] Android thread에서 Toast 호출하기 file 졸리운_곰 2024.05.01 88
40 [Android SDK] runOnUiThread란? (개념과 사용법) file 졸리운_곰 2024.05.01 165
39 [Android SDK] How to enable/disable WiFi from an application? 안드로이드 와이파이 켜고 끄기 java 졸리운_곰 2024.05.01 138
38 [Android SDK] 안드로이드 화면꺼짐 방지 코드 졸리운_곰 2024.05.01 108
37 Android WebView javascriptInterface 사용하기 file 졸리운_곰 2018.03.26 656
36 안드로이드 에서 JSON 읽어오기 (JSON parser) file 가을의곰 2017.06.18 827
35 Android Basic JSOUP Tutorial file 졸리운_곰 2017.03.27 349
34 [Android] 안드로이드 웹페이지 파싱하기 - jsoup 이용하기 file 졸리운_곰 2017.03.27 724
33 Android에서 jsoup를이용하여 HTML 파서(Parser) file 졸리운_곰 2017.03.27 764
32 윈도우즈에서 IntelliJ IDEA + android 개발환경 만들기 file 졸리운_곰 2016.12.05 488
31 단말기 내부에 폴더 및 txt파일 생성하기 file 졸리운_곰 2016.05.01 171
30 wifi 연결시 알림 android source 졸리운_곰 2016.05.01 250
29 How to use Broadcast Receiver in Android – Send and Receive SMS file 졸리운_곰 2016.05.01 292
28 [Android] Layout XML - layout_weight file 졸리운_곰 2016.04.30 23630
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED