2. 기본문법2(class, object and variables)

IT(Old)/RubyOnRails 2008. 1. 15. 14:23

1. Class, Object and Variables(루비)

class Song
  def initialize(name, artist, duration)
     @name = name
     @artist = artist
     @duration = duration
  end
end

initialize는 Ruby에서 특별한 method다. Song.new로 객체를 생성할때 new뒤에 붙는 파라미터들은
initialize메소드로 들어가게된다.

aSong = Song.new{"Bicylops", "Fleck", 260}

예제)
class Song
  def initialize(name, artist, duration)
    @name = name
    @artist = artist
    @duration = duration
  end
 
  def to_s
    "Song:
#{@name}--#{@artist} (#{@duration})"
  end
end

aSong = Song.new("Bicylops", "Fleck", 260)
aSong.to_s
>> Song: Bicylops--Fleck (260)



2. Inheritance and Messages

class KaraokeSong < Song
  def initialize(name, artist, duration, lyrics)
     super(name, artist, duration)
     @lyrics = lyrics
  end
end

"< Song" 은 KaraokeSong이 Song의 sub클래스임을 의미한다.
다시한번

class Song
  def initialize(name, artist, duration)
    @name = name
    @artist = artist
    @duration = duration
  end
 
  def to_s
    "Song:
#{@name}--#{@artist} (#{@duration})"
  end
end

class KaraokeSong < Song
  def initialize(name, artist, duration, lyrics)
    super(name, artist, duration)
    @lyrics = lyrics
  end
 
  def to_s
    "Song:
#{@name}--#{@artist} (#{@duration}) #{@lyrics}"
  end
end

aSong = Song.new("Bicylops", "Fleck", 260)
puts aSong.to_s

bSong = KaraokeSong.new("My Way", "Sinatra", 225, "And new, the...")
puts bSong.to_s

>>
Song: Bicylops--Fleck (260)
Song: My Way--Sinatra (225) And new, the...

이것을 다시 Ruby 문법으로 간단하게 바꿔보자

KaraokeSong의 to_s를
"Song: #{@name}--#{@artist} (#{@duration}) #{@lyrics}"  => super + " #{@lyrics}"
로 바꾸면 더욱 간단해 진다.

3. Inheritance and Mixins

ruby는 단일상속만 지원하지만 많은수의 mixins기능을 포함할 수 잇따
(몬말인지는 나중에 설명한다... ㅡ.ㅡ)

4. Object and Attributes

앞서 작성한 song객체의 state는 private상태이다. 다른 곳에서 부를수가 없다는 말이겠지

class Song
 
  attr_reader :name, :artist, :duration
  def initialize(name, artist, duration)
    @name = name
    @artist = artist
    @duration = duration
  end
 
  def name
    @name
  end
   
  def artist
    @artist
  end
   
  def duration
    @duration
  end
end

aSong = Song.new("Bicylops", "Fleck", 260)
puts aSong.artist
puts aSong.name
puts aSong.duration


로칼변수를 write하기 위해서는

  def duration=(newDuration)
    @duration = newDuration
  end
또는
  attr_writer :duration

을 사용해라(주의 def duration=(newDuration) 에 스페이스는 없어야된다.)

5. Virtual Attributes

class Song
  def durationInMinutes
     @duration/60.0
  end
end

aSong.durationInMinues

처럼 가상의 변수를 만들어 사용할 수 잇따.

6. Class Variables and Class Methods

- class variables

class Song
  @@plays = 0
  def initialize(name, artist, duration)
    @name     = name
    @artist   = artist
    @duration = duration
    @plays    = 0
  end
  def play
    @plays += 1
    @@plays += 1
    "This  song: #@plays plays. Total #@@plays plays."
  end
end


s1 = Song.new("Song1", "Artist1", 234)  # test songs..
s2 = Song.new("Song2", "Artist2", 345)
s1.play » "This  song: 1 plays. Total 1 plays."
s2.play » "This  song: 1 plays. Total 2 plays."
s1.play » "This  song: 2 plays. Total 3 plays."
s1.play » "This  song: 3 plays. Total 4 plays."


- class methods

class SongList
  MaxTime = 5*60           #  5 minutes
  def SongList.isTooLong(aSong)
    return aSong.duration > MaxTime
  end
end
song1 = Song.new("Bicylops", "Fleck", 260)
SongList.isTooLong(song1) » false
song2 = Song.new("The Calling", "Santana", 468)
SongList.isTooLong(song2) » true


7. Singletons and Other Constructors

singletons를 사용하기 위해서는 new의 사용을 막고,
create같은 method를 사용해라.

class Logger
  private_class_method :new
  @@logger = nil
  def Logger.create
    @@logger = new unless @@logger
    @@logger
  end
end

puts Logger.create.id
puts Logger.create.id
>>
22918100
22918100

class Shape
  def Shape.triangle(sideLength)
    Shape.new(3, sideLength*3)
  end
  def Shape.square(sideLength)
    Shape.new(4, sideLength*4)
  end
end


8. Access Control

- public methods : 누구나 호출가능
- protected methods : 상속받은 sub class만 호출가능
- private methods : 외부에서는 호출할 수 없음

하지만 Ruby는 다른 OO언어들과는 다르다. Access control은 프로그램이 실행될 때 동적으로 결정된다.
당신은 제한된 mothod를 실행하기 시도할때만 당신은 이 규칙을 위반할 수 있다.

Specifying Access Control
public, protected, private를 사용하여 class나 module정의할때 access level을 정의할 수 있다.

class MyClass

      def method1    # default is 'public'
        #...
      end

  protected          # subsequent methods will be 'protected'

      def method2    # will be 'protected'
        #...
      end

  private            # subsequent methods will be 'private'

      def method3    # will be 'private'
        #...
      end

  public             # subsequent methods will be 'public'

      def method4    # and this will be 'public'
        #...
      end
end


다른 방법으로는

class MyClass

  def method1
  end

  # ... and so on

  public    :method1, :method4
  protected :method2
  private   :method3
end


클래스의 initialize method는 자동으로 private로 선언된다.

class Accounts

  private

    def debit(account, amount)
      account.balance -= amount
    end
    def credit(account, amount)
      account.balance += amount
    end

  public

    #...
    def transferToSavings(amount)
      debit(@checking, amount)
      credit(@savings, amount)
    end
    #...
end



class Account
  attr_reader :balance       # accessor method 'balance'

  protected :balance         # and make it protected

  def greaterBalanceThan(other)
    return @balance > other.balance
  end
end


9. Variables

person = "Tim"
puts person.id
puts person.type
puts person
>>
22918640
String
Tim



person1 = "Tim"
person2 = person1
person1[0] = 'J'
puts person1
puts person2
>>
Jim
Jim

person1 = "Tim"
person2 = person1.dup
person1[0] = 'J'
puts person1
puts person2
>>
Jim
Tim

person1 = "Tim"
person2 = person1
person1.freeze    # prevent modifications to the object
person2[0] = "j"
>>
Logger.rb:4:in `[]=': can't modify frozen string (TypeError)
















1. 기본문법1 (Ruby.new)

IT(Old)/RubyOnRails 2008. 1. 15. 11:15

1 .객체 생성
생성자라는 것에 의해 객체가 생성됨. new가 standard constructor

song1 = Song.new("Ruby Tuesday")
song2 = Song.new("Enveloped in Python")
# and so on

2. method call

"gin joint".length     >> 9
"Rick".index("c")    >> 2
-1942.abs              >> 1942
sam.play(aSong)    >> "duh dum, da dum de dum ..."

3. A method that return a string

def sayGoodnight(name)
  result  = "Goodnight, " + name
  return result
end

# Time for bed ...
puts sayGoodnight("John-Boy")
puts sayGoodnight("Mary-Ellen")

>> Goodnight, John-Boy
>> Goodnight, Mary-Ellen

puts sayGoodnight "John-Boy1"
puts sayGoodnight("John-Boy2")
puts (sayGoodnight "John-Boy3")
puts (sayGoodnight ("John-Boy4"))

>> Goodnight, John-Boy1
>> Goodnight, John-Boy2
>> Goodnight, John-Boy3
>> Goodnight, John-Boy4

4. double-quoted strings

- ""안에서 개행문자는 \n을 사용한다.
puts "And Goodnight, \nGrandma"

>> And Goodnight,
>> Grandma

- ""안에서 변수는 #{expression} 을사용한다
def sayGoodnight(name)
  result = "Goodnight, #{name}:
  return result
end


5. 명명규칙

Local variables, method paramethers 그리고 method names은 소문자로 시작되어야 한다.
class, module , constants는 대문자로 시작하자.
global variables$를 이름앞에 붙인다.
instance variables@을 이름앞에 붙인다.
class variables@@을 이름앞에 붙인다.

local : name, fishAndChips, x_axis, thx1138, _26
global : $debug, $CUSTOMER, $_, $plan9, $Global
instance : @name, @point_1, @X, @_, @plan9
Class : @@total, @@symtab, @@N, @@x_pos, @@SINGLE
Constatns and Class Names : PI, FeetPerMile, String, MyClass, Jazz_Song


6. 배열과 해쉬

배열과 해쉬는 indexed collections이다. 둘다 key를 사용하여 접근 가능하다.
배열은 정수를 키로, 해쉬는 객체를 키로 사용한다.
이것들은 서로 다른타입을(integer, string, floating point number) 객체로 가질수 있다.

a = [1, 'cat', 3.14] # array with three elements
# access the first element
a[0]     >> 1
# set the third element
a[2] = nil
# dump out the array
a         >>  [ 1, "cat", nil]

Array.new를 사용하여 생성할 수도 있다.
empty1 = []
empty2 = Array.new

때때로 단어들을 사용하는 배열은 귀찮을 수가 있다. 왜냐 모두 quote로 묶어야 돼니까.
그걸위해 %w를 사용해라

a = %w{ ant bee cat dog elk }
a[0]    >> "ant"
a[3]    >> "dog"

해쉬를 사용하는 것은 배열과 비슷하다.

instSection = {
  'cello' => 'string',
  'clarinet' => 'woodwind',
  'drum => 'percussion',
  'oboe'  => 'woodwind',
  'trumpet' =>'brass',
  'violin'  => 'string'
}

instSection['oboe']  >> "woodwind:
instSection['cello']  >> "string"
instSection['bassoon'] >> nil

세번째 nil은 존재하지 않는다는 것을 의미한다.
nil은 조건식에서 false를 의미할 때 사용한다. 이 기본값을 바꾸길 원할것이다.
그거시 기본값으로 0을 가지긴 쉽다. 생성자로 생성할때 empty경우 기본값을 세팅하면 되거든

histogram = Hash.new(0)
histogram['key1']               >> 0
histogram['key1'] = histogram['key1'] + 1
histogram['key1']               >> 1

7. 조건문 반복문

일반적인 사용예)

if count > 10
  puts "Try again"
elsif tries == 3
  puts "You lose"
else
  puts "Enter a number"
end

while weight < 100 and numPallets <= 30
  pallet = nextPallet()
  weight += pallet.weight
  numPallets += 1
end

간단히 바꾸기
if radiation > 3000
  puts "Danger, Will Robinson"
end
=>
puts "Danger, Will Robinson" if radiation > 3000

while square < 1000
  square = square * square
end
=>
square = square*square while square < 1000


8. 정규표현식(Regualr Expressions)

/Perl|Python/  => /P(erl|ython)/
/\d\d:\d\d:\d\d/   # a time such as 12:34:56
/Perl.*Python/              # Perl, zero or more other chars, then Python
/Perl\s+Python/          # Perl, one or more spaces, then Python
/Ruby (Perl|Python)/    # Ruby, a space, and either Perl or Python

만약 해당되는 문자열이 =~ 다음에 포함되어 있으면(같은것이 아니고 포함) true, 아니면 false(nil)

line = 'Perl1'
if line =~ /Perl|Python/
  puts "aaa"
else
  puts "bbb"
end

>> aaa

문자열 변환

line = 'Perl123'
puts line.sub(/Perl/, 'Ruby')
>> Ruby123

9. Blocks and Iterators

{puts "Hello" }           # this is a block

do                            #
  club.enroll(person)  # and so is this
  person.socialize     #
end                         #

yield를 사용해서 method는 한번이상 invoke될수 있다.

def callBlock
  yield
  yield
end

callBlock { puts "In the block" }
>>
In the block
In the block

In the block이 두번 실행되엇다.
yield는 "|" 사이에 있는 파라미터를 받을수 있다.

def callBlock
  yield ,
end
callBlock { |, | ... }

Iterator사용
a = %w(ant bee cat dog elk)     # create an array
a.each {|animal| puts animal } # iterate over the contents
>>
ant
bee
cat
dog
elk


['cat','dog','horse'].each do |animal|
   print animal, " -- "
end
>> cat -- dog -- horse --

5.times {print "*"}
3.upto(6) {|i| print i}
('a'..'e').each{|char| print char}
>> *****3456abcde


10. Reading and 'Riting

printf "Number: %5.2f, String:%s", 1.23, "hello"
>> Number:  1.23, String:hello
C와 비슷

line = gets
print line

gets는 콘솔로부터 값을 받는구나


while gets
   if /Ruby/
     print
   end
end

이건 Ruby라는 단어를 치면 Ruby를 출력
>>
asdf
fds
sdf
g
Ruby
Ruby
asdf
Ruby
Ruby
ruby
Ruby
Ruby

The Apache Tomcat Connector - Generic HowTo

IT(Old)/Tomcat 2008. 1. 10. 08:43

The Apache Tomcat Connector - Generic HowTo

Quick Start HowTo

Printer Friendly Version
print-friendly
version
Introduction

This document describes the configuration files used by JK on the Web Server side for the 'impatients':

  • workers.properties is a mandatory file used by the webserver and which is the same for all JK implementations (Apache/IIS/NES).
  • web server add-ons to be set on the webserver side.

We'll give here minimum servers configuration and an example workers.properties to be able to install and check quickly your configuration.

Minimum workers.properties

Here is a minimum workers.properties, using just ajp13 to connect your Apache webserver to the Tomcat engine, complete documentation is available in Workers HowTo.

  # Define 1 real worker using ajp13
  worker.list=worker1
  # Set properties for worker1 (ajp13)
  worker.worker1.type=ajp13
  worker.worker1.host=localhost
  worker.worker1.port=8009

Minimum Apache web server configuration

Here is a minimun informations about Apache configuration, a complete documentation is available in Apache HowTo.

You should first have mod_jk.so (unix) or mod_jk.dll (Windows) installed in your Apache module directory (see your Apache documentation to locate it).

Usual locations for modules directory on Unix:

  • /usr/lib/apache/
  • /usr/lib/apache2/
  • /usr/local/apache/libexec/

Usual locations for modules directory on Windows :

  • C:\Program Files\Apache Group\Apache\modules\
  • C:\Program Files\Apache Group\Apache2\modules\

You'll find a link to prebuilt binaries here

Here is the minimum which should be set in httpd.conf directly or included from another file:

Usual locations for configuration directory on Unix:

  • /etc/httpd/conf/
  • /etc/httpd2/conf/
  • /usr/local/apache/conf/

Usual locations for configuration directory on Windows :

  • C:\Program Files\Apache Group\Apache\conf\
  • C:\Program Files\Apache Group\Apache2\conf\

  # Load mod_jk module
  # Update this path to match your modules location
  LoadModule    jk_module  libexec/mod_jk.so
  # Declare the module for <IfModule directive> (remove this line on Apache 2.x)
  AddModule     mod_jk.c
  # Where to find workers.properties
  # Update this path to match your conf directory location (put workers.properties next to httpd.conf)
  JkWorkersFile /etc/httpd/conf/workers.properties
  # Where to put jk shared memory
  # Update this path to match your local state directory or logs directory
  JkShmFile     /var/log/httpd/mod_jk.shm
  # Where to put jk logs
  # Update this path to match your logs directory location (put mod_jk.log next to access_log)
  JkLogFile     /var/log/httpd/mod_jk.log
  # Set the jk log level [debug/error/info]
  JkLogLevel    info
  # Select the timestamp log format
  JkLogStampFormat "[%a %b %d %H:%M:%S %Y] "
  # Send everything for context /examples to worker named worker1 (ajp13)
  JkMount  /examples/* worker1

Minimum IIS web server configuration

A complete documentation is available in IIS HowTo.

This paragraph has not been written yet, but you can contribute to it.

Minimum NES/iPlanet web server configuration

A complete documentation is available in Netscape/iPlanet HowTo.

This paragraph has not been written yet, but you can contribute to it.

Test your configuration

(Re)start the web server and browse to the http://localhost/examples/

activity life cycle 시작과 끝

IT(Old)/Android 2007. 12. 10. 16:52

Method Description Killable? Next
onCreate() Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one.

Always followed by onResume()

No onResume()
    onStart() Called when the activity is becoming visible to the user.

Followed by onResume() if the activity is being first created, or onRestart() if it is being shown again after previously being stopped.

No onRestart() or onResume()
onRestart() Called after your activity has been stopped, prior to it being resumed again.

Always followed by onResume().

No onResume()
    onResume() Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it.

Followed by either onFreeze() if another activity is being resumed in front of it, or onPause() if this activity is being finished.

No onFreeze() or
onPause()
onFreeze() Allows you to save away your current state, when your activity is being paused and another one resuming to interact with the user. After being paused, the system may at any time need to stop (or even outright kill) your application in order to claim resources for the current foreground activity. If this should happen, the state you supply here will later be given back to you onCreate() when a new instance of your activity is started to interact with the user.

Always followed by onPause().

No onPause()
onPause() Called when the system is about to start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, etc. Implementations of this method must be very quick because the next activity will not be resumed until this method returns.

Followed by either onResume() if the activity returns back to the front, or onStop() if it becomes invisible to the user.

Yes onResume() or
onStop()
onStop() Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one. This may happen either because a new activity is being started, an existing one is being brought in front of this one, or this one is being destroyed.

Followed by either onRestart() if this activity is coming back to interact with the user, or onDestroy() if this activity is going away.

Yes onStart() or
onDestroy()
onDestroy() The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method. Yes nothing

Note the "Killable" column in the above table -- for those methods that are marked as being killable, after that method returns the process hosting the activity may killed by the system at any time without another line of its code being executed. Thus you should take advantage of onFreeze() (for saving your current UI state) and onPause() (for writing any edits to persistent storage) so that the activity will be correctly restored to its current state in the event that it is killed. See the Process Lifecycle section for more information on how the lifecycle of a process is tied to the activities it is hosting.

For those methods that are not marked as being killable, the activity's process will not be killed by the system starting from the time the method is called and continuing after it returns. Thus an activity is in the killable state, for example, between after onPause() to the start of onResume().

android GUI vs XML (android/samples/app)

IT(Old)/Android 2007. 12. 4. 12:23

forwarding.xml

사용자 삽입 이미지
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:padding="4dip"
    android:gravity="center_horizontal"
    android:layout_width="fill_parent" android:layout_height="fill_parent">

    <TextView
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_weight="0"
        android:paddingBottom="4dip"
        android:text="@string/forwarding"/>

    <Button id="@+id/go"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:text="@string/go">
        <requestFocus />
    </Button>

</LinearLayout>
-----------------------------------------------------------------------------------------------------
2. hello_world.xml

사용자 삽입 이미지

<TextView xmlns:android="http://schemas.android.com/apk/res/android" id="@+id/text"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:gravity="center_vertical" android:textAlign="center"
    android:text="@string/hello_world"/>

-----------------------------------------------------------------------------------------------------
3. save_restore_state.xml

사용자 삽입 이미지
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:padding="4dip"
    android:layout_width="fill_parent" android:layout_height="fill_parent">

    <TextView id="@+id/msg"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_weight="0"
        android:paddingBottom="4dip" />

    <TextView
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_weight="0"
        android:paddingBottom="4dip"
        android:text="@string/saves_state"/>

    <EditText id="@+id/saved"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@drawable/green"
        android:text="@string/initial_text">
        <requestFocus />
    </EditText>

    <TextView
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_weight="0"
        android:paddingTop="8dip"
        android:paddingBottom="4dip"
        android:text="@string/no_saves_state"/>

    <EditText
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@drawable/red"
        android:text="@string/initial_text">
    </EditText>

</LinearLayout>

-----------------------------------------------------------------------------------------------------
4. receive_result.xml

사용자 삽입 이미지

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:padding="4dip"
    android:gravity="center_horizontal"
    android:layout_width="fill_parent" android:layout_height="fill_parent">

    <TextView
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_weight="0"
        android:paddingBottom="4dip"
        android:text="@string/receive_result_instructions"/>

    <TextView id="@+id/results"
        android:layout_width="fill_parent" android:layout_height="10dip"
        android:layout_weight="1"
        android:paddingBottom="4dip"
        android:background="@drawable/green">
    </TextView>

    <Button id="@+id/get"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_weight="0"
        android:text="@string/receive_result_result">
        <requestFocus />
    </Button>

</LinearLayout>
-----------------------------------------------------------------------------------------------------
5. redirect_enter.xml

사용자 삽입 이미지

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:padding="4dip"
    android:gravity="center_horizontal"
    android:layout_width="fill_parent" android:layout_height="fill_parent">

    <TextView
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_weight="0"
        android:paddingBottom="4dip"
        android:text="@string/redirect_enter"/>

    <Button id="@+id/go"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:text="@string/go">
        <requestFocus />
    </Button>

</LinearLayout>

-----------------------------------------------------------------------------------------------------
6. translucent_background.xml

사용자 삽입 이미지
<TextView xmlns:android="http://schemas.android.com/apk/res/android" id="@+id/text"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:gravity="center_vertical" android:textAlign="center"
    android:text="@string/translucent_background"/>

-----------------------------------------------------------------------------------------------------
7. TranslucentFancyActivity.java

사용자 삽입 이미지

protected void onCreate(Bundle icicle)
    {
        // Be sure to call the super class.
        super.onCreate(icicle);

        // Have the system blur any windows behind this one.
        getWindow().setFlags(WindowManager.LayoutParams.BLUR_BEHIND_FLAG,
                WindowManager.LayoutParams.BLUR_BEHIND_FLAG);
       
        // Apply a tint to any windows behind this one.  Doing a tint this
        // way is more efficient than using a translucent background.  Note
        // that the tint color really should come from a resource.
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.tintBehind = 0x60000820;
        getWindow().setAttributes(lp);
       
        // See assets/res/any/layout/translucent_background.xml for this
        // view layout definition, which is being set here as
        // the content of our screen.
        setContentView(R.layout.translucent_background);
    }

android adb shell 및 sd card setting 법

IT(Old)/Android 2007. 12. 3. 20:28
도스건 shell이건 android tools path는 잡혀 있다고 가정하고 작업을 하십시오..

* sd카드 잡는법 1
  1) mksdcard 2048M mysdcard (일단 만들고)
  2) emulator -sdcard mysdcard (에뮬레이터 옵션에 -sdcard mysdcard 를 넣고)
  3) adb push local_file sdcard/remote_file(컴퓨터에 있는 파일을 가상의 sdcard로 넣는다)

넘 간단한가...

나같은 경우는 다른 방법으로 잡았다.

* SD카드 잡는법 2
  1) mksdcard.exe 256M c:\android_music (위치를 만든다)
  2) 아래와 같이 이클립스 실행 옵션에 -sdcard C:\android_music 를 넣었다.
사용자 삽입 이미지
   
android emulator 실행후
  3) adb push c:\a.mp3 c:\android_music\a.mp3
로 실행하니.... SDcard 위치에 새로운 mp3가 생겼겟찌?
    




퀴즈.
다음 이미지의 출처는 어디일까요?
사용자 삽입 이미지

좀더 자세히 보여드릴까요?
사용자 삽입 이미지

눈치 빠르신분은 알겠지만.. android emulator 내부 모습입니다.
도스창에서 간단한 명령어
adb shell 을 치면 바로 android로 들어갈 수 있네요
마치 핸드폰을 해킹 했다는 그런 기분...이 드는거 나만 그런가? -_-

일단 팁이었습니다.

그럼 이만.

android emulator limitations(안드로이드 에뮬레이터 제한사항) 삽질금지

IT(Old)/Android 2007. 11. 30. 16:45

무턱대고 android에 덤벼들지 말자
아래와 같은 하드웨어적인 지원이 아주 약하다.

Emulator Limitations

이번 릴리즈에는. 에뮬레이터의 제약조건은 다음을 포함함다.

  • 실제 전화통화를 주고 받을 수 없다. 그러나 에뮬레이터 콘솔 화면을 통해서 전화통화(보내고 받는것)을 시뮬레이션 할수 있다.
  • USB연결에 대한 지원이 안된다.
  • 카메라나 비디오 캡쳐 지원이 안된다.(입력)
  • 음성 입력에 대한 지원이 안된다. 하지만 음성출력은 지원된다.
  • 장치에 부착된 헤드폰을 지원 안한다.
  • 연결된 상태를 알수 없다.
  • 배터리 충전 level과 AC 충전중인 상태를 알 수 없다.
  • SD카드를 끼웠는지 뺐는지를 알수 없다.
  • 블루투스를 지원하지 않는다.


출처 : http://code.google.com/android/reference/emulator.html#limitations

Designing Your Screen in XML(andorid XML디자인)

IT(Old)/Android 2007. 11. 28. 17:42

Designing Your Screen in XML

소스코드 안에다 화면 디자인하는것이 성가신 작업이 될 수 있기에, Android는 XML문법으로 화면 디자인하는 것을 지원한다. Android는 아주 많은수의 custom elements를 정의하고 있고, 그것들은 독특한 Android View subclass를 대표한다. 당신은 일련의 태그기반의 HTML파일을 생성한것과 같은 방법으로 화면을
디자인할수 있고, 그 파일은 application의 res/layout 디렉토리 안에 XML 파일로 저장된다. 어떤 elements가 표현되는지 그리고 XML파일 포맷을 배우기 위해서 Layout Resources를 보아라. 각 파일은 single android.view.View를 설명하고 있다. 하지만 이 element는 단순한 visual element 또는 자식 객체들의 collection을 포함하는 layout element가 될수도 있다(screen 또는 screen의 일부). Android가 당신의 application을 compiles 할때, 그것은 android.view.View 리소스로 complie하고, 당신의  Activity.onCreate() 안에 구현된 setContentView(R.layout.layout_file_name)을 호출하는 것으로 당신의 코드안에서 그것을 load할 수 있다.

각 XML파일은 android GUI classes에 상응하는 태그들로 구성된다. 이 태그들은 class안에 있는 methods에 상응하는 attributes를 가지고 있다.(예를 들면, EditText는 text attibute를 가지고 그것은 EditText.setText와 같다.)

class와 method 이름들 그리고 element와 attribute 이름들이 정확하게 일치하는 것은 아니라는걸 명심해라. - 거의 비슷하다, 하지만 항상 1대1 관계는 아니다.

또한 Android는 XML안에 그들이 나타나는 순서대로 elements를 그리는 경향이 있다. 그래서 elements가 겹치게 되면, XML파일안에 마지막놈이 같은 공간에 있는 이전에 listing된 elements들중 1순위로 그려지게 될 것이다.

각 XML파일은 single View 또는 ViewGroup 객체에 기반을 둔 tree로 컴파일된다. 그래서 single root 태그를 포함해야 한다. 다음 예제에서, 그것은 가장 바깥에 있는 LinearLayout 객체를 evaluate한다.

layout_somthing이라 이름 붙여진 Attriutes는 객체의 LayoutParams멤버로 적용된다.  Layout Resources는 또한 LayoutParams의 peroperties를 상세하기 위한 문법을 어떻게 배우는지 설명한다.

다음 값들은 치수를 지원한다.(TypedValue에 설명되어 있음)

  • px (pixels)
  • dip (device independent pixels)
  • sp (scaled pixels — best for text size)
  • pt (points)
  • in (inches)
  • mm (millimeters)

Example: android:layout_width="25px"

이 dimensions에 대한 더많은 정보를 원한다면, Dimension Values를 보아라.

다음 XML파일은 (오른쪽과같이)보여지는 screen을 생성한다. screen의 상단에 위치한 text는 Activity.setTitle라 불리는 것에 의해 set되는 것을 기억해라. 관련된 elements(layout_toLeft)를 가리키는 attributes는 연관된 resource의 문법을 사용하는 ID를 참조한다.(@id/id_number)

The following XML file creates the screen shown. Note that the text on the top of the screen was set by calling Activity.setTitle. Note that the attributes that refer to relative elements (i.e., layout_toLeft) refer to the ID using the syntax of a relative resource (@id/id_number).

<?xml version="1.0" encoding="utf-8"?>
<!-- Demonstrates using a relative layout to create a form -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android
                android:layout_width="fill_parent" 
                android:layout_height="wrap_content"
                android:background="@drawable/blue"
                android:padding="10px">

    <TextView id="@+id/label" 
              android:layout_width="fill_parent" 
              android:layout_height="wrap_content" 
              android:text="Type here:"/>

    <EditText id="@+id/entry" 
              android:layout_width="fill_parent" 
              android:layout_height="wrap_content" 
              android:background="@android:drawable/editbox_background"
              android:layout_below="@id/label"/>
  
    <Button id="@+id/ok" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:layout_below="@id/entry"
            android:layout_alignParentRight="true"
            android:layout_marginLeft="10px"
            android:text="OK" />

    <Button android:layout_width="wrap_content" 
            android:layout_height="wrap_content"
            android:layout_toLeft="@id/ok"
            android:layout_alignTop="@id/ok"
            android:text="Cancel" />
</RelativeLayout>
Screen shot showing how this layout XML file is rendered.

Loading the XML Resource

컴파일된 layout resource를 loading하는 것은 매우 쉽고 application의 onCreate()를 호출하는것에 의해 실행된다. 아래와같다

protected void onCreate(Bundle savedValues)
{
   // Be sure to call the super class.
   super.onCreate(savedValues);

   // Load the compiled layout resource into the window's
   // default ViewGroup.
   // The source file is res/layout/hello_activity.xml
    setContentView(R.layout.hello_activity);
  
   // Retrieve any important stored values.
   restoreValues(savedValues);
} 

android 계산기 한번 만들어 보자꾸나

IT(Old)/Android 2007. 11. 27. 23:24

난 개발자다.
근데.,,월요일 화요일 회사 세바뀌를 돌았다.
고정자산이다, OA자산 실사 준비다
이것저것 때문에... 소스분석하고 개선할 시간이 진짜 없었다.
개발자는 개발만 할 수 있으면 좋겠다. 흐흐흐...

오늘 화요일 현장을 돌아다니면서.. 요놈의 android가 계속 생각난다.
진짜 내가 맘에 들어하는 놈인거 가따.

일단 안드로이드 분석은 이쯤 하면 됐다 싶고....
계산기란 놈을 함 만들어보고 싶었다.

사용자 삽입 이미지

일단 기본android 프로젝트를 생성했다 .Calc라는 놈으로


프로젝트 생성을 마치고...젤 먼저 생각해야 될 것이..
UI이다.
일단 계산하는 값 2개를 받고
연산자 선택하고
결과 같 표시를 해야 될 듯 싶어
다음과 같이 만들었다.

res/layout/main.xml

-------------------------------------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
   
 <TextView id="@+id/result"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="@string/result" />
 
 <LinearLayout android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    >
 
 <EditText id="@+id/leftBox" android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:layout_weight="1" />
 
 <TextView id="@+id/operator"
  android:layout_height="fill_parent"
  android:layout_width="wrap_content"
  android:text="@string/operator"/>
 
 <EditText id="@+id/rightBox" android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:layout_weight="1" />
 </LinearLayout>
 <LinearLayout android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
     >
     <Button id="@+id/operatorPlus"
   android:text="@string/operatorPlus"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" />
 
  <Button id="@+id/operatorMinus"
   android:text="@string/operatorMinus"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" />
 
  <Button id="@+id/operatorMulti"
   android:text="@string/operatorMulti"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" />
 
  <Button id="@+id/operatorDivide"
   android:text="@string/operatorDivide"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" />
   
    </LinearLayout>
 
 <Button id="@+id/calculate"
   android:text="@string/calculate"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" />

</LinearLayout>
----------------------------------------------------------------------------------------------

두번째로는 text값을 저장하고 있는 string.xml생성
/res/values/string.xml
----------------------------------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">calculator</string>
    <string name="result">Calculation Result</string>
    <string name="calculate">calculate</string>
    <string name="operator">oper</string>
    <string name="operatorPlus">+</string>
    <string name="operatorMinus">-</string>
    <string name="operatorMulti">*</string>
    <string name="operatorDivide">/</string>
</resources>
---------------------------------------------------------------------------------------------

세번째로 각 버튼마다 이벤트를 넣었다.
src/com.tistory.jolaking/CalcActivity.java
----------------------------------------------------------------------------------------------
package com.tistory.jolaking;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class CalcActivity extends Activity {
 
 private TextView tv;
 
 private Button operatorPlus;
 private Button operatorMinus;
 private Button operatorMulti;
 private Button operatorDivide;
 
 private TextView operView;
 
 String oper;
 
 String  [] operations = {"+", "-", "*", "/"};
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
       
        Button calculate = (Button) findViewById(R.id.calculate);
        tv = (TextView) findViewById(R.id.result);
       
        operatorPlus = (Button) findViewById(R.id.operatorPlus);
        operatorMinus= (Button) findViewById(R.id.operatorMinus);
        operatorMulti= (Button) findViewById(R.id.operatorMulti);
        operatorDivide= (Button) findViewById(R.id.operatorDivide);
       
        operView = (TextView) findViewById(R.id.operator);
       
       
        operatorPlus.setOnClickListener(new View.OnClickListener(){

   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    oper = "+";
    operView.setText("+");
   }
         
        });
       
        operatorMinus.setOnClickListener(new View.OnClickListener(){

   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    oper = "-";
    operView.setText("-");
   }
         
        });
       
        operatorMulti.setOnClickListener(new View.OnClickListener(){

   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    oper = "*";
    operView.setText("*");
   }
         
        });
       
        operatorDivide.setOnClickListener(new View.OnClickListener(){

   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    oper = "/";
    operView.setText("/");
   }
         
        });
       
        calculate.setOnClickListener(new View.OnClickListener(){
         
   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
   
    try{
     EditText leftBox = (EditText) findViewById(R.id.leftBox);
     EditText rightBox = (EditText) findViewById(R.id.rightBox);
     
     String leftValue = leftBox.getText().toString();
     String rightValue = rightBox.getText().toString();
     String operator = oper;
     double result = calculate(leftValue, rightValue, operator);
     tv.setText(String.valueOf(result));
     
    }catch(Exception e){
         
     tv.setText("Incorrect String");
    }
   }
         
        });
    }
   
    public double calculate(String leftValue, String rightValue, String operator) throws Exception{
     
     double result = 0;
     int operIndex = 99;
     
     
     // operation 검사
     for(int i = 0 ; i < operations.length ; i++){
     
      if(operations[i].equals(operator)){
       
       operIndex = i;
       break;
      }
     }
     
     if(operIndex == 99)
      throw new Exception();
       
     double leftV = Double.parseDouble(leftValue);
     double rightV = Double.parseDouble(rightValue);
     
     if(operator.equals("+")){
     
      result = leftV + rightV;
     }else if(operator.equals("-")){
     
      result = leftV - rightV;
     }else if(operator.equals("*")){
     
      result = leftV * rightV;
     }else if(operator.equals("/")){
     
      result = leftV / rightV;
     }
     
     return result;   
    }
}
---------------------------------------------------------------------------------------------------

이게 끝...

생각보다 간단히 만들었다...간만에 오류 없이 컴파일까지 되더라..
역시 JAVA는 깊게 들어갈 수록 어렵지만...초반엔 적응하기 싶더라...

일단 여기까지 하면 R.java는 자동으로 생성이 될 것이고 ...실행을 해봤더니..ㅡ.ㅡ

사용자 삽입 이미지

계산기 실행화면.. 단순하다 ㅡ.ㅡ



에게 줄맞춤도 그렇고.. 디자인은 진짜 허접하다 흐흐흐
이래도 사칙연산을 실행해보면 아래와 같이 잘 되는군..후훗
사용자 삽입 이미지
사용자 삽입 이미지
사용자 삽입 이미지
사용자 삽입 이미지


에혀.. 다시봐도 맘에 안드는게.. 역시 UI는 이뻐야 된다는 거..

layout 관련 API좀 더 자세히 봐야겠다..

담에는 내 핸폰에 있는 PGM UI 똑같이 만드는거 연습좀 하자..

그럼 끝.

Android 몇가지 데모 실행 성공 -__-

IT(Old)/Android 2007. 11. 22. 19:35

처음에 Hello Android 를 실행시켜보고
자동으로 만들어진 소스를 보면서
Framework을 처음 접했을 때의 기분을 느꼈다.

ejb나 spring처럼 눈에 전혀 들어오지도 않았고

activity, intent, bundle 등의 용어도 생소하였기에 ..
그냥 소스만 계속 보고 또 보고  또 봤다. 진짜 몇일동안 내내 본거 같다.
그리고 드뎌.. 이제 왠만한 소스는 이해가 잘 되었다.

그래서 처음엔..sample 소스라고 제공된 놈들을 어뜨케 실행해야 될찌 막막했지만
지금에야 다시 보니. 삘이 왔따.

그럼 거거싱

사용자 삽입 이미지

Notepad v2 따라 작성하고 실행한 모습 단순하다


사용자 삽입 이미지

제목과 내용을 입력하고 confirm을 하면 저장이 된다.


사용자 삽입 이미지

저장된 리스트가 보인다.


사용자 삽입 이미지

추억의 뱀 게임


사용자 삽입 이미지

그냥 방향키로 게임가능


사용자 삽입 이미지

재미없어서 이건 빨리 끝냈다.


사용자 삽입 이미지

인터넷에서 보던 그 정체불명의 게임

사용자 삽입 이미지

스페이스바를 누르면 에너지 남아 있는 만큼 부스터(?)를 쓸수 있다.

사용자 삽입 이미지

쩜 재미 없었다. 빨리끝나고