Ctrl + Shift + F : 자동 정렬

Ctrl + Shift + O : 자동 import


MAC은 Ctrl 대신 Command를 누르면 됩니다.

준비물 : 이클립스, 다운받은 javax 라이브러리, 라이브러리를 추가할 프로젝트


1. 프로젝트를 오른쪽 클릭 후 Properties에 들어간다.

2. Java Build Path를 누른다.

3. Libraries를 누른다.

4. Add External JARs 를 누른다.

5. 다운받은 javax 라이브러리를 추가한다.


이후 코드내에서 추가한 라이브러리를 import할 수 있다.

JSR(Java Specification Requests)은 자바 플랫폼에 대한 규격을 제안하거나 기술한 것을 말한다.


https://jcp.org/en/jsr/all




두 EditText에 있는 값을 아래의 5개 버튼을 누르면 계산결과가 TextView에 나오는 프로그램

실수 끼리 연산했을 경우 결과는 실수, 정수끼리 연산했을 경우 정수로 처리함.
문자가 들어가있을 경우, 0으로 나눌경우 예외처리가 되있음


MainActivity.class

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package com.calculater;
 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
 
public class MainActivity extends AppCompatActivity {
    EditText edt1, edt2;
    Button btAdd, btSub, btMul, btDiv,btNa;
    TextView tvOutput;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        edt1 = (EditText) findViewById(R.id.edt1);
        edt2 = (EditText) findViewById(R.id.edt2);
        btAdd = (Button) findViewById(R.id.btAdd);
        btSub = (Button) findViewById(R.id.btSub);
        btMul = (Button) findViewById(R.id.btMul);
        btDiv = (Button) findViewById(R.id.btDiv);
        btNa=(Button) findViewById(R.id.btNa);
 
        tvOutput = (TextView) findViewById(R.id.tvOutput);
        btAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                double iTemp1 = 0, iTemp2 = 0;
                try {
                    iTemp1 = Double.valueOf(edt1.getText().toString());
                    iTemp2 = Double.valueOf(edt2.getText().toString());
                    double result = iTemp1 + iTemp2;
                    if(result == (int)result) {
                        int iChange = (int) result;
                        tvOutput.setText("계산 결과 : "+String.valueOf(iChange));
                    }
                    else
                    {
                        tvOutput.setText("계산 결과 : "+String.valueOf(result));
                    }
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "입력에 문자가 있습니다.", Toast.LENGTH_SHORT).show();
                }
 
            }
        });
        btSub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                double iTemp1 = 0, iTemp2 = 0;
                try {
                    iTemp1 = Double.valueOf(edt1.getText().toString());
                    iTemp2 = Double.valueOf(edt2.getText().toString());
                    double result = iTemp1 - iTemp2;
                    if(result == (int)result) {
                        int iChange = (int) result;
                        tvOutput.setText("계산 결과 : "+String.valueOf(iChange));
                    }
                    else
                    {
                        tvOutput.setText("계산 결과 : "+String.valueOf(result));
                    }
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "입력에 문자가 있습니다.", Toast.LENGTH_SHORT).show();
                }
 
            }
        });
        btMul.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                double iTemp1 = 0, iTemp2 = 0;
                try {
                    iTemp1 = Double.valueOf(edt1.getText().toString());
                    iTemp2 = Double.valueOf(edt2.getText().toString());
                    double result = iTemp1 * iTemp2;
                    if(result == (int)result) {
                        int iChange = (int) result;
                        tvOutput.setText("계산 결과 : "+String.valueOf(iChange));
                    }
                    else
                    {
                        tvOutput.setText("계산 결과 : "+String.valueOf(result));
                    }
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "입력에 문자가 있습니다.", Toast.LENGTH_SHORT).show();
                }
            }
 
        });
        btDiv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                double iTemp1 = 0, iTemp2 = 0;
                try {
                    iTemp1 = Double.valueOf(edt1.getText().toString());
                    iTemp2 = Double.valueOf(edt2.getText().toString());
                    double result = iTemp1 / iTemp2;
                    if(result == (int)result) {
                        int iChange = (int) result;
                        tvOutput.setText("계산 결과 : "+String.valueOf(iChange));
                    }
                    else
                    {
                        tvOutput.setText("계산 결과 : "+String.valueOf(result));
                    }
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "입력에 문자가 있거나 0으로 나눌수 없습니다", Toast.LENGTH_SHORT).show();
                }
 
            }
 
        });
        btNa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int iTemp1 = 0, iTemp2 = 0;
                try {
                    iTemp1 = Integer.parseInt(edt1.getText().toString());
                    iTemp2 = Integer.parseInt(edt2.getText().toString());
                    int result = iTemp1 % iTemp2;
                    tvOutput.setText(String.valueOf(result));
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "입력에 문자가 있습니다.", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
 
}
cs


activity_main.xml

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:orientation="vertical">
 
    <EditText
        android:id="@+id/edt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:singleLine="true"/>
    <EditText
        android:id="@+id/edt2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:singleLine="true"/>
    <Button
        android:id="@+id/btAdd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="더하기"/>
    <Button
        android:id="@+id/btSub"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="빼기"/>
    <Button
        android:id="@+id/btMul"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="곱하기"/>
    <Button
        android:id="@+id/btDiv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="나누기"/>
    <Button
        android:id="@+id/btNa"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="나머지 값"/>
    <TextView android:id="@+id/tvOutput"
        android:text="계산결과"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
 
</LinearLayout>
cs


Calculater 2.zip


Listener에 등록을 하여 이벤트 처리를 하는 것.




MainActivity.java
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.button4test;
 
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
 
public class MainActivity extends Activity {
    Button btn_naver,btn_911,btn_gallery,btn_end;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_naver=(Button)findViewById(R.id.btn_naver);
        btn_911=(Button)findViewById(R.id.btn_911);
        btn_gallery=(Button)findViewById(R.id.btn_gallery);
        btn_end=(Button)findViewById(R.id.btn_end);
        btn_naver.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent mIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("http://naver.com"));
                startActivity(mIntent);
            }
        });
        btn_911.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent mIntent=new Intent(Intent.ACTION_VIEW,Uri.parse("tel:/911"));
                startActivity(mIntent);
            }
        });
        btn_gallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent mIntent = new Intent(Intent.ACTION_VIEW,Uri.parse("content://media/internal/images/media"));
                startActivity(mIntent);
            }
        });
        btn_end.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
 
}
cs



activity_main.xml

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
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
 
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn_naver"
        android:text="네이버 홈페이지 열기"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn_911"
        android:text="911 응급 전화 걸기"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn_gallery"
        android:text="갤러리 열기"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn_end"
        android:text="끝내기"/>
</LinearLayout>
cs


1.AndroidManifest.xml 클릭

2.좌측하단에 적용시킬 Activity 선택

3.Screen orientation 선택

Screen orientation의 속성

portrit 세로만 보기

landscape 가로만 보기

nosensor 화면전환 막음

sensor 화면전환 가능 (휴대폰의 화면전환 적용 X)

4.저장



또는 AndroidManifest.xml 코드에서 직접적으로
1
2
android:screenOrientation="portrait" //세로고정
android:screenOrientation="landscape" //가로고정
cs
을 추가하면 된다.


이전 포스트에 이어 파일처리를 응용한 간단한 다이어리 에플리케이션이다.


자신이 저장한 파일을 보고싶을 땐 이클립스 기준으로

오른쪽 상단에 Open perstective를 클릭 후 DDMS를 추가한다음 File Explorer를 눌러서 확인할 수 있다.

내부 메모리에 저장된 파일은 /data/data/패키지이름/file에 저장된다.



 




▲ 쓰기를 통해 문자열을 txt형태로 저장한뒤 읽기로 불러들여 TextView에 넣은 스크린샷

안드로이드에서 파일 저장 및 불러오는 프로그램이다.


FileInputStream fis = openFileInput("test.txt");

openFileInput은 저장된 파일을 불러올때 사용하며 FileInputStream타입 변수에 저장한다.

FileOutputStream fos = openFileOutput("test.txt",Context.MODE_WORLD_WRITEABLE);

openFileOutput은 읽기,쓰기 등의 관리에 사용되는데 FileOutputStream 타입 변수에 저장한다.

▲ openFileOutput의 각종 모드들이다.

MODE_WORLD_READABLE  : 읽기

MODE_WORLD_WRITEABLE : 쓰기

MODE_PRIVATE              : 단독으로 읽을때(close()메소드를 통해 끝내지않는한 다른 곳에서 파일                                  을 읽을수 없다.


데이터를 읽을 땐 read() 메소드를 사용하고, 데이터를 넣을 때는 write()메소드를 사용하는데, 데이터를 불러들이거나 저장할 때 byte타입으로 저장해야한다.


FileTest.zip


▲쓰레드 3개를 사용하여 각각 숫자 3000까지 올라가는 프로그램


작업환경 : Eclipse, Android Virtual Device

xml코드를 사용하지않고 java코드로만 만들어서 View 클래스를 상속받은 클래스에서 제작하였다.

그리고 처음부터라는 회색영역을 클릭하는 이벤트가 발생하면 각 쓰레드를 null로 처리하여 제거하고 새로 인스턴스화 하여 구현하였다.

각 클래스 짤막 설명

MainActivity : setContentView에서 xml로 짜여진 layout을 뿌려주는것이 아닌 View를 상속받은 TestView를 화면에 뿌려준것(이때 이 에플리케이션에 대한 정보를 파라미터로 넘겨줌)


TestView : View클래스를 상속받은 클래스로 UI부분과 이벤트를 담당하는 클래스


Thread1 : 랜덤으로 수를 증가하여(그 수들은 TestView안에 있는 변수에 저장한다) 3000을 넘어가면 종료되는 클래스


MultiThread.zip


프로그램을 실행하면 하나의 동작을 할수있지만 동작을 여러번 할 수 있도록 하는 것이 쓰레드이다.


자바에서는 Thread를 상속받거나 Runnable 인터페이스로 구현하는 방법도 존재한다.


public class 클래스명 extends Thread

public class 클래스명 implements Runnable


공통적으로 쓰레드를 구동하였을때 동작하는 부분은 run()메쏘드 안에 넣어서 사용한다.

그리고 쓰레드를 구동하는데는 start()메소드를 사용하고 한번 start메쏘드를 사용하면 그 쓰레드는 더이상 사용할 수 없게 된다.

(Thread를 사용했을 때는 run() 메쏘드를 오버라이딩 한것이고 Runnable 인터페이스를 사용할때는 추상클래스에서 구현한 것이다.)


객체를 생성할 때는 Thread a = new "쓰레드로 구현된 클래스의 생성자" 로 할수도 있고

"쓰레드가 구현된 클래스" a = new "쓰레드가 구현된 클래스의 생성자"로 할수도있다.(다른 메소드나 맴버변수 접근가능)

인터페이스로 구현된 쓰레드는 "Runnable로 구현된 클래스명" = new Thread(new "Runnable로 구현된 클래스 생성자") 로 하면된다.


start()메소드를 사용하여 객체인 쓰레드를 구동시키면 그 쓰레드가 끝났을때 다시 start()메소드를 써도 다시 시작되지않고 새로 객체로만들어서 써야합니다

+ Recent posts