안드로이드 - 실제 휴대폰 연결해서 테스트하기

1.드라이버 설치

 : 휴대폰 제조사엣 driver를 찾아서 설치한다.
   모토로라 같은 외국업체는 미주 사이트에 드라이브가 많다.

2.USB 디버깅 활성화

 : 단말기에서 메뉴 > 설정 > 응용프로그램 또는 애플리케이션 > 개발 > USB 디버깅 허용

3.이클립스에서 테스트

 : 이클립스 DDMS perspective에서 테스트 기기를 확인 할 수 있다.

4.실 행

 : Java perspective 에서 프로젝트명 선택하고

   Run as > Android Application > 테스트 단말기 선택 후 OK
크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 홍반장

2011/05/25 20:46 2011/05/25 20:46
, , , , ,
Response
No Trackback , No Comment
RSS :
http://tcbs17.cafe24.com/tc/rss/response/6186

[phonegap] PhoneGap Android

 

Getting started with Android PhoneGap in Eclipse

http://wiki.phonegap.com/w/page/164947 ··· -eclipse

한글 번역 : http://goodidea.tistory.com/11


Prerequisite Software


PhoneGap requires you have the following software installed:

     1. Eclipse Integrated Design Environment (IDE), a program to write code and manage software development

     2. Java Development Kit (JDK), the Java compiler and support tools

     3. The Android Software Development Kit (SDK), base code and emulators for developing Android apps

     4. Android Development Toolkit (ADT), a plug-in for Eclipse that makes Android development seamless

     5. Apache Ant, a program that automates software build processes (similar to 'make')

     6. Ruby, a programming language

     7. Git Bash, an alternative command program for Windows environments (Windows only)


If you've previously done any development in the Android environment, you probably have 1-4 already installed.  If you have not, it is strongly recommended you visit http://developer.android.com/index.html to better understand Android development and create your own, "Hello, World" example prior to jumping into PhoneGap.  A great resource exists at: http://developer.android.com/sdk/installing.html for new developers.


Step 1: Installing the Prerequisite Software


1A. Eclipse

Install the Eclipse IDE for Java Developers from http://www.eclipse.org/downloads/. This a ZIP archive file, extract the folder “eclipse”. Most other flavors of Eclipse (like Aptana or platform specific builds) will also work, provided that you install all the necessary Eclipse plug-ins.


1B. Java JDK

If you do not already have the java JDK installed on you're system, install the Java SE Development Kit - JDK 6 from here:
http://java.sun.com/javase/downloads/index.jsp


If you're running Windows this is a standard installer file, just follow the on screen instructions for installation.


1C. Android SDK

Install the Android SDK Package from here

http://developer.android.com/sdk/index.html 


Extract the downloaded archive and place it somewhere you'll remember and add the tools sub directory your PATH. Additional information and instructions for adding the Android SDK to your PATH can be found at:
http://developer.android.com/sdk/installing.html


Be sure to do the following (Windows):

  1. If you install into a folder containing a space (c:\Program Files), you must refer to it by its truncated name in the command program.  In this case "c:\progra~1".  The truncated name will be the first six characters + ~ + a sequential number starting with 1 for each instance of the same six characters.
  2. Add android SDK to your Path
  3. Add android sdk tools (\android-sdk-windows\tools) to your path. This is necessary for ruby to find the command "android create project" later on.

1D. ADT Plug-in for Eclipse

Install the ADT Plug-in for Eclipse as described here:

http://developer.android.com/sdk/eclipse-adt.html


To verify your installation of Eclipse, Android SDK, ADT, and Java, you can build a sample “Hello World” application using the instructions located here:

http://developer.android.com/guide/tut ··· rld.html.


1E. Apache ANT

Visit: http://ant.apache.org/index.html

  • Windows -
    • If you install into a folder containing a space (c:\Program Files), you must refer to it by its truncated name in the command program.  In this case "c:\progra~1".  The truncated name will be the first six characters + ~ + a sequential number starting with 1 for each instance of the same six characters.
    • Download and unzip binaries
    • add the unzipped folder path to your PATH
  • OS X - it comes with XCode otherwise "sudo port install apache-ant".

1F. Ruby

Visit: http://rubyinstaller.org for an automatic installation (Windows only)

         Ruby bin 으로 이동해서  'gem install nokogiri' 를 해주면 끝

1G. Git Bash (Windows only) 

     Visit: http://code.google.com/p/msysgit/downloads/list

     Download and install the latest full installer for official Git

     Visit: http://git-scm.com/ for additional information about Git

     Note: During installation, you may select the "Use Git Bash only" option


Step 2: Confirm Environment Variables


Environment variables are data stored by your system; in this case we are interested in the file locations of the various developer tools. You should have these environment variables:

  • ANDROID_HOME, location of the Android SDK (for example: D:/android-sdk-windows)
  • ANT_HOME, location of Android Ant (for example: D:\apache-ant-1.8.1)
  • JAVA_HOME, location of the JDK (for example: C:\Program Files\Java\jdk1.6.0_20)
  • Path, folders where the operating system always looks when given a command (includes these, for example: C:\Ruby191\bin; D:\apache-ant-1.8.1\bin; C:\Program Files\Java\jdk1.6.0_20\bin; D:\android-sdk-windows\tools)

You can confirm the environment variables the following way:

Windows:

2A. Right-click on My Computer (or Computer)

2B. Select Properties -> Advanced tab -> Environment Variables button).

2C.  "Edit..." the Path to include the needed folders.  Use a semicolon (;) to separate folders.

Hint:  You can copy the path from the address bar in Windows Explorer.




If everything looks good in the environment variables, try opening a command prompt (Start > Run > cmd) and typing in "ant", "ruby", "java", or "android".  If you get the error message "x was not recognized as an internal or external command" you need to check your PATH value.  If the program continues to execute you can use ctrl-c to terminate it.


Step 3. Download the PhoneGap Source Code


First you will need to download the latest PhoneGap code.  It is hosted on github.com.  The easier way to get the code is to download it directly from the github website.

3A.  Visit:  http://github.com/phonegap/phonegap-android



Alternatively, you may use a dedicated 'git' client to download the code or you may use Eclipse.  This guide will not cover either of those methods.


3B.  Unzip the files into a folder.


Step 4. Build the Example PhoneGap App


Now we will use Ruby and a script called 'droidgap' that is provided with PhoneGap to package up our example app.  This will create two outputs; a file called 'PhoneGap.jar' and an Android Eclipse project, which we will then import into Eclipse.


4A.  Open a command window and change directory ('cd') to the 'phonegap-android' folder.  In Windows, use git bash as the command window.  In Mac OS, use Terminal.

4B.  Run the following command.  This will create a PhoneGap.jar file and create a basic Android Eclipse project in the output path that can then be opened in Eclipse.


NOTE: The droidgap script has been updated and now there are two methods to create the necessary files. The new script is significantly simpler to use than the old method. For those who prefer the old method, it is still available.


NEW METHOD:

4C. From the 'phonegap-android' folder, run 'ruby bin/droidgap create [path_of_application]'. For the example app, the command would be 'ruby bin/droidgap create example'. If the example folder does not exist inside 'phonegap-android', run 'ruby bin/droidgap gen' first.


The new create command in the droidgap script will generate the Eclipse project, ready to be imported. The results of the script can be found at '[path_of_application]_android'. Example: If [path_of_application] = '~/my_app', then droidgap create will place results at '~/my_app_android'. The for the example app, the results will be placed at '../phonegap-android/example_android'


Skip ahead to Step 5 for Eclipse import instructions.


Run 'droidgap help' to see other new commands including run, log, test and ship.


OLD METHOD:

Previous users of the droidgap script please note that droidgap must now be invoked with the 'classic' command to use this method.


    ruby bin/droidgap classic "[android_sdk_path]" [name] [package_name] "[www]" "[path]"


    android_sdk_path ... The path to your Android SDK install. (Must use forward slashes (/) in path)

    name ...................... The name of your application.

    package_name ....... The name of your package (For example: com.nitobi.demo). Can not be just the app name, must contain at least one "." (i.e. "com.example").

    www ...................... The path to your www folder. (Where your HTML, CSS and JavaScript code is located)

    path ...................... The path to generate the application. (CANNOT be inside ANY Eclipse workspace) (Must use forward slashes (/) in path)

You should get a message in your terminal saying completed!


Example (Windows environment):


$ ruby ./droidgap classic "C:/Progra~1/Androi~1/android-sdk-windows" pgtest com.example.android.pgtest example/ "c:/Progra~1/Androi~1/phonegap-android/output"


In the above Windows example, the following environment settings were used:

android_sdk_path = "c:\Program Files\Android SDK\android-sdk-windows"

name = pgtest

path = "c:\Program Files\Android SDK\phonegap-android\output" (This is the output location where the example files were placed)


Example (Mac environment):


> cd phonegap-android

> ruby ./droidgap classic android/android-sdk-mac_86/ test_app com.mayerdan.testapp example/ ~/projects/test_droid_phonegap


Note if you get errors like:

BUILD FAILED

~/projects/phonegap-android/framework/build.xml:49: taskdef class com.android.ant.SetupTask cannot be found


followed by more errors like:

0:in `stat': No such file or directory - ~/projects/phonegap-android/framework/phonegap.jar


To fix this, just run the command with the full path to the android SDK

"sdk.dir=/andriod/android-sdk-mac_86" => "sdk.dir=/projects/andriod/android-sdk-mac_86"


Then run `ruby ./droidgap classic /Users/danmayer/projects/android/android-sdk-mac_86 test_app com.mayerdan.testapp example/ ~/projects/test_droid_phonegap` again.


Some notes:


  • Your output path should not be inside your Eclipse workspace. *See note in Step 5
  • Make sure the path you set to generate the application doesn't exist
  • For the www folder, phonegap-android comes with a folder called example that includes some sample html, css and js.
  • I found I was getting errors for not having set android or ant in my path. Make sure you followed the earlier steps.
  • When pointing to a directory, you need to have quotes around the path "C:/mobile/......"
  • While in the command prompt, you should manually change all the backslashes ( \ ) to forward slashes ( / ).  This helps the droidgap script with its syntax.  E.g. The android_sdk_path argument must use forward slashes (/).
  • If you install into a folder containing a space (c:\Program Files), you must refer to it by its truncated name in the command program.  In this case "c:\progra~1".  Otherwise, the script will look for "c:\Program" and fail.
    • Note: The truncated name will be the first six characters + '~' + a sequential number starting with 1 for each instance of the same six characters.  For instance if you have two folders c:\PhoneGapA and c:\PhoneGapB, the former's truncated name will become, "c:\phoneg~1" and the latter's will become, "c:\phoneg~2".
  • For Windows users:  The droidgap script is written to expect UNIX-style syntax, which is why you need to use 'git bash' to execute these commands.  'Bash' is a shell language and the 'git bash' application can handle the expected syntax.  Alternatively you may use another bash-style command application, such as 'cygwin', but if you know what that is, you know how to install and use it.
  • Do not have "tools" as a folder in your path to the android sdk folder; C:\Users\Daniel\Dev\tools\android-sdk won't work.
  • If at any point you need to check your PATH variables in git bash you can use the command "echo $PATH"

 


Step 5. Importing Your Example App into Eclipse

Now time to create your project. In Eclipse, go to File > New project > Android > Android Project


Now select create project from existing source and navigate to the new folder that was generated in the last step. Select a build target and press finish.


*NOTE: The folder you specified in the Ruby script will actually be the folder that your Eclipse will save to, and compile from and NOT your current Eclipse Workspace. Saving your folder to a location inside of a Workspace will not allow you to create the project because the .metadata folder. If you have pointed your folder to one of your Eclipse Workspaces, simply cut and paste the folder to a location that is outside of any Workspace.


 



Now, in Eclipse you should see your project


Rightclick phonegap.jar under the libs folder and go to Buildpath -> Add to build path.

Note: Now the folder structure should look like the one shown below.






Click on the project folder again and then the Run button in Eclipse, it is the button that looks like "Play". When you run this project, you should the dialog box to Run As.., choose Android Application.
You may get the unable to launch dialog, this can happen if you have the Android 1.5 or some other file highlighted when you try to run the project. Just select the project folder and click run.


If you have done everything correctly, there should be an Application that loads.  It should be noted that testing with an actual device is preferable to the Emulator for many reasons, namely the fact that it's easier to test the Accelerometer, Geolocation, Beep and Vibrate Functionality.  However, for testing on the actual browser browser events, and various issues with Webkit on Android the Emulator does just as well.



Notes


  • Perhaps JAVA_HOME does not point to the JDK. Or maybe JAVA_HOME doesn't exist. To fix this you must right click on my computer, go to advanced system settings, click the advanced tab, press the environment variables button, Under system variables click new and add JAVA_HOME if it doesn't exist and make the path to the JDK that was installed earlier.
  • ERROR:

          droidgap:48:in ``': No such file or directory
         android create project -t 7 -k be.progone.test -a PG1 -n PG1 -p E:/baud/work/Mobile/Pr_Eclipse/PG1/build (Errno::ENOENT)
          from droidgap:48:in `create_android'


          SOLUTION:

          Add the Android SDK tools path to the system. Follow steps above to get to system environment variables.

          Eg: C:\Program Files\Android SDK\tools


  • ERROR:
    "BUILD FAILED
    C:\phonegap-android\framework\build.xml:49: taskdef class com.android.ant.SetupTask cannot be found"

    SOLUTION:
    Try going to the "framework" folder and check the path in the local.properties file. See if its correct and pointing to your android sdk directory.

          You MUST use a forward slash in the directory (Windows users) otherwise the paths will not match up.

          Eg: C:/Program Files (x86)/Android SDK


 

 

  • ERROR:

 

      "Click on various buttons on the example app, doesn't do anything" or some things are working but I can't tell what is going on, or I want more information how do I view the Android logs?

 
     SOLUTION:
     To get more information about what is going one while phonegap is running, run the Android log viewer. `adb logcat` if adb isn't found you just need to do the full path to it something like `~/projects/andriod/android-sdk-mac_86/tools/adb logcat`. If you have both a device and a Android emulator running use -d and -e like so `adb -e logcat`. This should give you more info about what is going on. Here is a small example clipping form the android logs.


 

D/PhoneGapLog(  291): file:///android_asset/www/phonegap.js: Line 216 : TypeError: Result of expression 'accel' [undefined] is not an object.

E/Web Console(  291): TypeError: Result of expression 'accel' [undefined] is not an object. at file:///android_asset/www/phonegap.js:216

D/dalvikvm(  117): GC_EXPLICIT freed 1727 objects / 91840 bytes in 110ms

D/PhoneGap(  291): The provider network is disabled

D/SntpClient(   61): request time failed: java.net.SocketException: Address family not supported by protocol


    From this we can see that the accel is not working. And some information about the location of the Error. This helps debug problems and also helps you to give more information when asking the PhoneGap community for help. 


크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 홍반장

2011/05/25 19:34 2011/05/25 19:34
,
Response
No Trackback , No Comment
RSS :
http://tcbs17.cafe24.com/tc/rss/response/6185

Tools for developers

Developers

Tools and documentation on how to create Android applications.







크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 홍반장

2011/05/11 06:36 2011/05/11 06:36
,
Response
No Trackback , No Comment
RSS :
http://tcbs17.cafe24.com/tc/rss/response/6155

httpclient 를 사용해서 웹페이지에서 리턴값을 받아오려는데, 그것도 POST 방식으로~ 잘 되지않는다. 온갖 예제를 다 해봤지만 되지 않았었다. 이유는 무엇이었을까나...
말도 안되게 시뮬레이터 문제였다.
android:permission=INTERNET 도 주고 했건만 안되다가...
프로젝트 생성시에 SDK 버전을 8로 주고 만들었었는데, 그것이 화근이었을까?
LOG 를 보니 SDK 8 어쩌고 에러가 있더라.
새로 프로젝트를 생성하며 생성창 제일 아래의 SDK 버전 정보를 입력하지 않고 생성.
그리고, 기존 소스를 입력한 후 실행했더니 왠걸~
바로 실행되버렸다. 어이없음.

디버그 스킬을 익힐 필요를 느끼면, 이클립스는 참 놀라운 툴이지만 쓸줄 모르면 에디트플러스만 못하구나라는걸 새삼.
소스에만 문제가 있을거라는 이 안이한 생각은 어디서 나온 것일까? 요즘  웹브라우저의 다양성으로 인해 웹프로그램 납품에 비상이 걸린지 오래이다.
예전엔 잘 되던 소스들이 이젠 브라우저마다 다르게 보인다는 문제가 생겨버린 것이다.

스마트폰 개발을 해보며 느끼는것도 비슷한 부류다. 디바이스 기준이기 때문에 디바이스의 성격을 잘 알아야 문제없이 만들어 갈수 있다. 이제 문제는 동일 소스가 적용되지 않는다는 것이지. 존재하지 않는 소수는 없지만, 디바이스에 대한 무지가 빗어내는 버그들.

전체를 봐야 할 것이야~
크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 홍반장

2010/11/23 18:35 2010/11/23 18:35
, ,
Response
No Trackback , No Comment
RSS :
http://tcbs17.cafe24.com/tc/rss/response/5670

[Android] 인텐트(Intent) 의 기본

인텐트(Intent)

한 액티비티에서 다른 액티비티를 실행하려면 액티비티 실행을 요청하는 도구가 필요하다. 안드로이드는 브로드캐스팅과 인텐트(Intent)를 제공하는데, 브로드캐스팅은 모든 객체에게 뿌리는 방송과 같은 것이며 인텐트는 이 방송에 실려 전달되는 메시지에 해당된다.

인텐트는 명시적 인텐트와 묵시적 인텐트가 있다.
실행할 액티비티를 직접적으로 정확하게 가리키는 것을 명시적 인텐트라고 하고,
필요한 기능만 설명한 채 직접적으로 액티비티를 가리키지 않는 것을 암시적 인텐트라고 한다.

명시적 인텐트가 가장 빈번히 사용되는 경우는 하나의 패키지 안의 한 액티비티가 또 다른 액티비티를 호출할 때이다. 이것이 가능한 이유는 너무나도 당연한 일이지만 호출하는 쪽에서 호출할 액티비티를 임포트할 수 있기때문이다.
명시적 인텐트를 사용하는 법은 어렵지 않다. 현재 액티비티의 컨텍스트와 실행할 액티비티 클래스를 인텐트 생성자의 인자로 사용하여 인텐트 인스턴스 하나를 생성한 후에 startActivy() 메서드에 생성한 인텐트를 인자로 넘겨서 호출하면 된다.
... (생략)...
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(intent);
... (생략)...
만일 액티비티의 실행 결과를 받아서 추가적인 일을 수행하려면 startActivity() 메서드 대신
startActivityForResult() 메서드를 사용하면 된다.
... (생략)...
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivityForResult(intent, 0);
... (생략)...
startActivityForResult() 메서드가 실행되고 지정한 액티비티가 실행된 후에 실행된 액티비티가 다시 종료되면 액티비티의 onActionResult() 메서드가 호출될 것이다.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
      // 실행한 액티비티가 종료된 후에 필요한 코드를 이곳에 추가합니다.
}
Intent 클래스 생성자의 첫 번째 인자는 현재 액티비티의 컨텍스트이고 두 번째 인자는 실행할 액티비티의 클래스이다.

암시적 인텐트는 앞에서 설명한 것처럼 실행 주제를 정확하게 서술하지 않고 자신의 목적만으로 적합한 액티비티를 실행하는 것이다.  암시적 인텐트를 사용하기 위해서는 두 가지가 필요하다. 하나는 실행하고자 하는 기능을 나타내는 액션(action)이며, 다른 하나는 액션과 함께 액티비티에 넘겨줄 데이터(data)입니다. 액션은 String 객체로 표현되며 데이터는 Uri 클래스의 인스턴스 이다. 예를 들어 가장 많이 사용되는 전화의 경우 액션으로 Intent.ACTION_CALL을, 데이터로 Uri.parse("tel:01012345678") 과 같은 Uri 값을 사용한다. 이를 코드로 구현하면 아래와 같다.
...(생략)...
/* 전화를 걸기 위한 인텐트를 생성합니다. */
Intent intent = new Intent(Intent.ACTION_CALL);
/* 전화를 Uri 인스턴스로 변환합니다.  */
intent.setData(Uri.parse("tel:01012345678"));
/* 생성된 인텐트를 사용해 액티비티를 실행합니다.  */
startActivity(intent);
...(생략)...
전화를 거는 액티비티를 실행하기 위해 Intent.ACTION_CALL 액션을 사용하고 전화번호를 인자로 넘겨줘야 한다는 사실을 어떻게 알 수 있을까? 암시적 인텐트를 사용하기 위해서는 실행될 대상이 어떤 조건의 인텐트를 받는지 문서상으로 알고 있어야 한다. 안드로이드의 기본 애플리케이션 가운데 전화, 브라우저, 맵 등은 액티비티 공유를 위해 필요한 액션과 데이터를 문서로 공유하고 있다.

구글의 개발자 사이트의 http://developer.android.com/guide/appendix/g-app-intents.html 로 들어가서 Intents List : Invoking Google Applications on Android Devices(인텐트 목록: 안드로이드 기기에서 구글의 애플리케이션 호출하기)를 읽어보면 액션과 필요한 데이터를 확인할 수 있다.



크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 홍반장

2010/11/09 16:42 2010/11/09 16:42
, , ,
Response
No Trackback , No Comment
RSS :
http://tcbs17.cafe24.com/tc/rss/response/5633

[Android] Logcat - 로그캣

로그캣
안드로이드에서는 app의 로그를 관리하기 위해 "로그캣"이라는 도구를 제공한다.  액티비티의 생명주기를 직접 눈으로 확인하기 위해 각 콜백 메서드가 호출되는 순간 화면상에 로그를 뿌려준다.
로그캣은 DDMS와 이클립스 양쪽에서 모두 사용할 수 있다.
보기 : [Windows] > [Show View] > [Others]  에서 LogCat 을 선택하면 이클립스 하단에 LogCat 이라는 창이 추가된다.
사용자 삽입 이미지사용자 삽입 이미지사용자 삽입 이미지
각 옵션들은 다음 같은 기준으로 로그를 필터링한다.
▶ V : 장황하다는 Verbose의 약자로 상세 정보를 출력하는 데 사용한다.
▶ D : Debug를 의미하며 말 그대로 디버깅 정보를 출력하는데 사용된다.
▶ I : Information의 약자로 위험성이나 오류가 아닌 단순 정보를 출력하는데 사용된다.
▶ W : Warning의 약자로 경고를 출력하는 데 사용된다.
            경고는 오류는 아니지만 개발자가 체크해야 할 정보로 분류됩니다.
▶ E : Error, 애플리케이션 동작에 있어 심각한 오류를 출력할 때 사용된다.

위의 우선순위는 플랫폼이 알아서 판단하고 분류해 주는 것은 아니다. 각 우선순위는 개발자가 모듈이나 애플리케이션 작성 시 한 중의 로그 출력 코드를 추가할 때, 이 로그는 어느 정도의 위험성을 가지는지 판단하여 그에 맞는 레벨의 로그출력 메서드를 사용함으로써 결정된다.

LogFilter
사용자 삽입 이미지사용자 삽입 이미지
LogFilter 윈도우는 프로세스 아이디(pid)와 로그 태그를 기준으로 로그를 분류한다.
Filter Name 은 생성할 필터의 이름 ,
by Log Tag 는 분류할 로그의 태그 정보를 입력하는 곳.
by pid 는 특정 프로세스의 출력만 보는것으로 프로세스 아이디를 입력한다.
by Log Level 은 위의 다섯가지 우선순위 옵션과 동일한 기능이다.

사용자 삽입 이미지사용자 삽입 이미지
* AALCActivity.java
package com.froglamb.android_application_life_cycle;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class AALCActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        Log.i("AALCActivity", "onCreate");
    }
}


크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 홍반장

2010/11/08 12:00 2010/11/08 12:00
, , , , , ,
Response
No Trackback , No Comment
RSS :
http://tcbs17.cafe24.com/tc/rss/response/5628

DroidDraw 는 안드로이드 화면 구성 코드를 보다 손쉽게 작성할 수 있도록 GUI 를 구현해둔 것이다. 감탄이 절로 나오는걸~
홈페이지에 들어가면 메인에서 바로 적용해볼 수 있어서 접근성을 엄청 높였다.

DroidDraw - Graphical User Interface (UI) designer/editor for programming the Android Cell Phone Platform

URL : http://www.droiddraw.org/

사용자 삽입 이미지
Android Draw : http://www.droiddraw.org/androiddraw.html
사용자 삽입 이미지사용자 삽입 이미지


Tutorial : http://www.droiddraw.org/tutorial.html

사용자 삽입 이미지
Widget Guide : http://www.droiddraw.org/widgetguide.html

사용자 삽입 이미지



크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 홍반장

2010/11/04 20:10 2010/11/04 20:10
, , ,
Response
No Trackback , No Comment
RSS :
http://tcbs17.cafe24.com/tc/rss/response/5619

SQLite
(1)  데이터베이스의 정의
 : Android에서 데이터베이스로 접근하려면, SQLiteOpenHelper 클래스를 상속한 데이터베이스 헬퍼를 정의하고 이것을 이용한다.  이 헬퍼는 데이터베이스의 생성 및 업그레이드를 관리한다.
 SQLiteOpeHelper 클래스를 상혹한 클래느는 다음의 메소드를 오버라이드한다.
오버라이드하는 메소드 메소드의 호출
onCreate() 메소드
onUpgrade() 메소드
데이터베이스 생성 시 호출.
데이터베이스 업그레이드 시 호출.

(2) 데이터베이스 헬퍼 생성자

   SQLiteOpenHepler 클래스

SQLiteOpenHelper(Context context, String fileName, SQLiteDatabase.CursorFactory factory, int version)
기능 : SQLiteOpenHelper 클래스의 생성자
인수 : context     컨텍스트
           fileName 데이터베이스 파일명
          factory      팩토리
          version     버전
  데이터베이스 이름에는 저장할 곳의 파일명을 지정합니다.
  /data/data/패키지명/databases/데이터베이스 파일명 ( test.db) 에 저장됩니다.
  팩토리는 사용하지 않으면 null을 지정하고, 버전은 1을 지정.

(3) 데이터베이스의 생성 : onCreate() 메소드를 호출
   SQLiteOpenHelper 클래스

void onCreate(SQLiteDatabase db)
기능 : 데이터베이스 생성 시 호출
인수 : db 데이터베이스 객체
  onCreate() 메소드 내에서는 SQL명령으로 테이블을 생성하고 있습니다. test 라는 테이블명에서 id 와 info 라는 컬럼을 갖고 있는 테이블을 생성하는 SQL 명령은 아래와 같습니다. 컬럼의 형은 문자열이므로 컬럼명 뒤에 text라고 기술하고, id 는 다른 ID 와 중복되지 않는 기본키이므로 primary key 라고 추가합니다.
create table id not exists text(id text primary key, info text)                                                       

SQL명령을 실행하려면 SQLtestDatabase 클래스의 execSQL()을 사용합니다.
   SQLiteDatabase 클래스

void execSQL(String Sql)
기능 : SQL 명령의 실행
인수 : sql   SQL명령

(4) 데이터베이스의 업그레이드
  : 데이터베이스는 버전업 시 데이터베이스 구조를 변환하지 않으면 업그레이드가 안 되는 경우가 있습니다. 필요로 하는 버전에 이상이 있을 경우 이 onUpdate() 메소드가 불리므로, 이 메소드 내에서 구버전 번호와 신버전 번호의 정보로부터 데이터베이스 구조의 변환을 실행합니다.
  SQLiteOpenHelper 클래스

void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
기능 : 데이터베이스를 업그레이드한 때
인수 : db                 데이터베이스 객체
           oldVersion 구버전 번호
          newVersion 신버전 번호
  다음으로, SQL명령으로 테이블을 삭제한 후 onCreate() 메소드를 호출하여 테이블을 생성합니다. test 라는 이름의 테이블을 삭제할 SQL명령은 다음과 같습니다.
 drop    table   if    exists   test                                                                                                

(5) 데이터베이스 객체의 취득
  : 메인이 되는 SQLiteEx 클래스의 개체에서는 먼저 정의한 데이터베이스 헬퍼를 이용하는 SQLiteDatabase 형 데이터베이스객체를 구합니다. 프로그램 내에서는 이 객체를 사용해서 데이터베이스의 조작을 실행합니다. 데이터베이스 객체를 구하려면 DBHelper 객첼르 생성한 후 getWritableDatabase() 메소드를 호출합니다.
    SQLiteOpenHelper 클래스

SQLiteDatabase getWritableDatabase()
기능 : 데이터베이스 객체의 취득
인수 :데이터베이스 객체

(6) 데이터베이스의 쓰기
   : 데이터베이스의 쓰기를 실행하려면 Content Values 클래스로 갱신하는 레코드 정보를 작성합니다. Content Values 객체를 생성한 후 put() 메소드로 컬럼명과 값을 세트로 추가합니다.
   ContentValues 클래스

void put(String colName, String value)
기능 : 레코드 정보에 컬럼명과 값 추가
인수 : colName   컬럼명
           value         값
이 프로그램에서는 다음의 칼럼을 추가하고 있습니다.
컬러명   
    값                                                       
id
info
0
텍스트 박스의 문자열
데이터 객체의 update() 메소드에 이 레코드 정보를 건네주는 것에 의해서, id[0]을 갖는 레코드의 info가 텍스트 박스의 문자로 덧쓰게 됩니다.
   SQLiteDatabase 클래스

int update(String tableName, ContentValues values, String where, String[] whereArgs)
기능 : 테이블 레코드의 갱신
인수 : tableName   테이블명
           values           레코드 정보
          where           where 파라미터
          whereArgs  where 파라미터
반환값 : 갱신한 레코드 수
  반환값 레코드 수가 0이 될 때는 id[0] 이 존재하지 않는다고 간주하고, insert() 메소드로 테이블에 레코드를 삽입한다.
  SQLiteDatabase 클래스

long insert(String tableName, String nullColumnHack, ContentValues values)
기능 : 테이블의 레코드 추가
인수 : tableName   테이블명
           nullColumnHack   NULL값
          values           레코드 정보
반환값 : 레코드 ID

(7) 데이터베이스로부터 읽기
    : 데이터베이스로부터 읽기를 실행하려면 데이터베이스 객체의 query() 메소드를 사용합니다.
  SQLiteDatabase 클래스

Cursor query(String tableName, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
기능 : 데이터베이스로부터 읽기
인수 : tableName   테이블명
           columns        컬럼명의 배열
           selection       selection parameter
           selectArgs    selection parameter factor
           groupBy        groupBy parameter
           having           having parameter
           orderBy         orderBy parameter
           limit                limit parameter
반환값 : Cursor 객체
    selection, groupBy, having, orderBy, limit 파라미터는 SQLite의 query 명령 파라미터입니다. 이번에는 id가 0 인것만을 취득하고 싶기 때문에 selection 파라미터에 "id=0" 을 지정하고 있습니다.
  반환값은 Cursor 객체로 구해지는데, Cursor 객체는 내부적으로 다수의 레코드를 저장하고 있습니다.  getCount() 메소드로 레코드 수, getColumnCount() 메소드로 컬럼 수를 구할 수 있습니다.

  Cursor 클래스

int getCount()              
기능 : 레코드 수 구하기
반환값 : 레코드 수
Cursor 클래스

int getColumnCount()                  
기능 : 컬럼 수 구하기
반환값 :컬럼 수
    Cursor 객체는, 자장하는 레코드 안의 조작대상을 지시하는 정보(커서)를 갖습니다.
     커서에서 선두의 레코드를 지시하는 때에는 moveToFirst() 메소드를 부릅니다.
Cursor 클래스

boolean moveToFirst()                  
기능 : 커서에서 선두 레코드를 지시한다.
반환값 : 성공 또는 실패
 그리고 나서, getString() 메소드 등을 부르는 것으로 레코드 내의 컬럼이 지시하는 값을 수하는 것이 가능합니다.
Cursor 클래스

String getString(int colIdx)                     
기능 : String 형 값 구하기
인수 : colIdx 컬럼의 위치
반환값 : String 형의 값

double getDouble(int colIdx)                 
기능 : double 형 값 구하기
인수 : colIdx 컬럼의 위치
반환값 : double 형의 값

float getFloat(int colIdx)               
기능 : float 형 값 구하기
인수 : colIdx 컬럼의 위치
반환값 : float 형의 값

int getInt(int colIdx)               
기능 : int 형 값 구하기
인수 : colIdx 컬럼의 위치
반환값 : int 형의 값

long getLong(int colIdx)               
기능 : long 형 값 구하기
인수 : colIdx 컬럼의 위치
반환값 : long 형의 값

short getShort(int colIdx)               
기능 : short 형 값 구하기
인수 : colIdx 컬럼의 위치
반환값 : short 형의 값

여기에서는 컬럼1(0부터 시작하므로 2열 째) 값을 String 형으로 얻고 있습니다.
마지막으로, Cursor 객체의 close() 메소드를 호출하여 Cursor 를 종료합니다.

------------- SQLiteEx.java ------------------------
package com.froglamb.sqliteex;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

public class SQLiteEx extends Activity implements View.OnClickListener{
   
    private final static String DB_NAME = "test.db"; // DB name
    private final static String DB_TABLE = "test";   // table name
    private final static int    DB_VERSION = 1;      // Version
   
    private EditText        editText;
    private Button            btnWrite;
    private Button            btnRead;
    private SQLiteDatabase     db;

    // 초기화
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
       
        // 레이아웃의 생성
        LinearLayout layout = new LinearLayout(this);
        layout.setBackgroundColor(Color.rgb(255, 255, 255));
        layout.setOrientation(LinearLayout.VERTICAL);
        setContentView(layout);
       
        // 텍스트 박스의 생성
        editText = new EditText(this);
        editText.setText("", EditText.BufferType.NORMAL);
        setLLParams(editText, 240, 50);
        layout.addView(editText);
       
        // 쓰기 버튼의 생성
        btnWrite = new Button(this);
        btnWrite.setText("쓰기");
        btnWrite.setOnClickListener(this);
        setLLParams(btnWrite);
        layout.addView(btnWrite);
       
        // 일기 버튼의 생성
        btnRead = new Button(this);
        btnRead.setText("읽 기");
        btnRead.setOnClickListener(this);
        setLLParams(btnRead);
        layout.addView(btnRead);
       
        // 데이터베이스 객체 구하기 (5)
        DBHelper dbHelper = new DBHelper(this);
        db = dbHelper.getWritableDatabase();
    }
   
    // 버튼 클릭 이벤트 처리
    public void onClick(View v){
        if ( v == btnWrite) {
            try {
                String str = editText.getText().toString();
                writeDB(str);
            } catch (Exception e) {
                showDialog(this, "Error", "Write Error");
            }
        } else if ( v == btnRead) {
            try {
                String str = readDB();
                editText.setText(str);
            } catch (Exception e) {
                showDialog(this, "Error", "Read Error");
            }
        }
    }

    // 데이터베이스의 쓰기 (6)
    private void writeDB(String str) throws Exception{
        ContentValues values = new ContentValues();
        values.put("id", "0");
        values.put("info", "info");
        int colNum = db.update(DB_TABLE, values, null, null);
        if( colNum == 0 ) db.insert(DB_TABLE, "", values);
    }
   
    private String readDB() throws Exception{
        Cursor c = db.query(DB_TABLE, new String[] {"id","info"}, "id='0'", null, null, null, null);
        if ( c.getCount() == 0 ) {
            throw new Exception();
        }
        c.moveToFirst();
        String str = c.getString(1);
        c.close();
        return str;
    }

   
    // 데이터베이스 헬퍼 정의 (1)
    private static class DBHelper extends SQLiteOpenHelper{
        // 데이터베이스 헬퍼 생성자 (2)
        public DBHelper(Context context){
            super(context, DB_NAME, null, DB_VERSION);
        }
       
        // 데이터베이스의 생성 (3)
        @Override
        public void onCreate(SQLiteDatabase db){
            db.execSQL(
                    "create table if not exists " +
                    DB_TABLE + " (id text primary key, info text)"
            );           
        }
       
        // 데이터베이스의 업그레이드 (4)
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
            db.execSQL(
                    "drop table if exists " + DB_NAME
            );
            onCreate(db);
        }
    }
   
   
    // 대화상자 표시
    private static void showDialog(final Activity activity, String title, String text){
        AlertDialog.Builder ad = new AlertDialog.Builder(activity);
        ad.setTitle(title);
        ad.setMessage(text);
        ad.setPositiveButton("OK", new  DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int whichButton){
                activity.setResult(Activity.RESULT_OK);
            }
        });
        ad.create();
        ad.show();
    }
   
    // 리니어 레이아웃의 파라미터 지정
    private static void setLLParams(View view){
        view.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    }
   
    // 리니어 레이아웃의 파라미터 지정
    private static void setLLParams(View view, int w, int h){
        view.setLayoutParams(new LinearLayout.LayoutParams(w, h));
    }
   
   
}









크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 홍반장

2010/11/03 18:00 2010/11/03 18:00
, , ,
Response
No Trackback , No Comment
RSS :
http://tcbs17.cafe24.com/tc/rss/response/5614

Android Architecture

Android Architecture

The following diagram shows the major components of the Android operating system. Each section is described in more detail below.



크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기

Posted by 홍반장

2010/09/03 16:15 2010/09/03 16:15
,
Response
No Trackback , No Comment
RSS :
http://tcbs17.cafe24.com/tc/rss/response/5494

안드로이드 개발환경 설치

* 안드로이드 커뮤니티 - 개발 강좌.
http://www.androidpub.com/

* 회색의 구글 안드로이드 개발 - 개발자 블로그
http://graynote.tistory.com/


안드로이드 강좌 1 - 어플리케이션 개발 시작하기. SDK 설치 및 실행

안드로이드 강좌 2 - 이클립스 개발환경 사용법 및 프로젝트 생성

안드로이드 강좌 3 - 프로젝트 실행과 디버깅 그리고 단말 세팅

안드로이드 강좌 4 - 액티비티(Activity), 뷰(View), 레이아웃(Layout)

안드로이드 강좌 5 - XML에서의 TextView, ImageView, LinearLayout

안드로이드 강좌 6 - Java 코드(Code)에서 뷰(View)  다루기
크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기

Posted by 홍반장

2010/03/02 14:17 2010/03/02 14:17
, ,
Response
No Trackback , No Comment
RSS :
http://tcbs17.cafe24.com/tc/rss/response/5017


블로그 이미지

- 홍반장

Archives

Recent Trackbacks

Calendar

«   2024/04   »
  1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30        
Statistics Graph

Site Stats

Total hits:
183065
Today:
454
Yesterday:
607