SMALL

https://coding-factory.tistory.com/209

LIST
블로그 이미지

SeoHW

,
SMALL


안도르이드 스튜디오는 OS안에서 DB와 TABLE 을 핸들링 할 수 있습니다 그래서 간단한 쿼리문으로 응용해서 예제를 작성해보도록 할텐데요 자바클래스와 xml이 너무 많은 관계로 주석으로 대체 설명이 되어있으니 참고하시고 읽어주세요 첫 순서는 DB생성과 TABLE 생성과 검색기능이 있고 그 다음 로그인화면으로 이동을 하는 버튼이 있습니다 그 이후에 로그인을 하게되면 게시판형식의 listView가 뜨고 거기에 글을 쓰거나 읽을 수 있는 기능을 구현해봤습니다

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
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
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.ntsysmac01.sampledatabase.MainActivity">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearLayout">
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="customer.db"
            android:id="@+id/editText"
            android:layout_weight="1" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="DB 생성"
            android:id="@+id/button" />
    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/linearLayout"
        android:id="@+id/linearLayout2">
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="employee"
            android:id="@+id/editText2"
            android:layout_weight="1" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Table 생성"
            android:id="@+id/button2" />
    </LinearLayout>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="상태 : "
        android:id="@+id/textView"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_below="@+id/linearLayout2"
        android:layout_marginTop="95dp"
        android:layout_alignParentBottom="true" />
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/linearLayout2"
        android:layout_marginBottom="52dp"
        android:weightSum="1">
        <EditText
            android:layout_width="204dp"
            android:layout_height="wrap_content"
            android:id="@+id/editText3"
            android:layout_weight="1.25" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="검색하기"
            android:id="@+id/button3" />
    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </LinearLayout>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="로그인하기"
        android:id="@+id/button4"
        android:layout_marginTop="46dp"
        android:layout_below="@+id/linearLayout2"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>
cs

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
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
package com.example.ntsysmac01.sampledatabase;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
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 org.w3c.dom.Text;
public class MainActivity extends AppCompatActivity {
    SQLiteDatabase db;
    //db를 커넥션 해주기 위해 필요한 메소드
    MySQLiteOpenHelper helper;
    String databaseName;
    String tableName;
    String searchName;
    Button button;
    EditText editText;
    Button button2;
    EditText editText2;
    Button button3;
    EditText editText3;
    Button button4;
    TextView textView;
    boolean databaseCreated = false;
    boolean tableCreated = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //첫번째는 현재화면의 context를 지정
        //두번째는 db 파일명
        //세번째는 버전 번호
        helper = new MySQLiteOpenHelper(MainActivity.this,
                "customer.db",
                null,
                1);
        button = (Button)findViewById(R.id.button);
        editText = (EditText)findViewById(R.id.editText);
        button2 = (Button)findViewById(R.id.button2);
        editText2 = (EditText)findViewById(R.id.editText2);
        button3 = (Button)findViewById(R.id.button3);
        editText3 = (EditText)findViewById(R.id.editText3);
        button4 = (Button)findViewById(R.id.button4);
        textView = (TextView)findViewById(R.id.textView);
        //첫번째 버튼은 db를 생성하거나 열어주는 역할
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //editText를 받아서 변수에 넣어줌
                databaseName = editText.getText().toString();
                //그 변수를 실행
                createDatabase(databaseName);
            }
        });
        //두번째 버튼은 db에 테이블을 생성하는 역할
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //editText를 받아서 변수에 넣어줌
                tableName = editText2.getText().toString();
                //그 변수를 실행
                createTable(tableName);
                //레코드 입력 메소드를 호출함
                int count = insertRecord();
                println(count + "records inserted.");
            }
        });
        //세번째 버튼은 테이블을 검색 하는 역할
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //editText를 받아서 변수에 넣어줌
                searchName = editText3.getText().toString();
                //그 변수를 실행
                searchTable(searchName);
            }
        });
        //네번째 버튼은 로그인 화면으로 이동해주는 역할
        button4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), login.class);
                startActivity(intent);
            }
        });
    }
    //현재 상태가 어떻게 되는지 textview에 표현해주는 기능
    private void println(String s) {
        textView.append("\n" + s);
    }
    //데이터베이스를 만들어주는 기능
    private void createDatabase(String name) {
        //현재 상태가 어떻게 되는지 textview에 뿌려줌
        println("creating database [" + name + "].");
            //db를 name값으로 생성해줌 (name값은 위에 databaseName 값을 가져옴)
            db = openOrCreateDatabase(name, MODE_WORLD_WRITEABLE, null);
            databaseCreated = true;
    }
    //테이블을 만들어주는 기능
    private void createTable(String name) {
        //현재 상태가 어떻게 되는지 textview에 뿌려줌
        println("creating table [" + name + "].");
        //위에 tableName값을 name으로 받아와서 테이블을 생성
        db.execSQL("create table "
                + name
                + "("
                + " _id integer PRIMARY KEY autoincrement, "
                + " name text, "
                + " age integer, "
                + " phone text);");
        tableCreated = true;
    }
    //테이블을 검색해주는 기능
    private void searchTable(String searchName) {
        //db객체를 얻어옴(읽기)
        db = helper.getReadableDatabase();
        //db에 들어있는 값들은 Cursor로 받아줘야됨
        //Cursor c = db.query(searchName, null, null, null, null, null, null); <<이렇게 해줘도됨 하지만 밑에게 더 간단함
        Cursor c = db.rawQuery("select * from " + searchName, null);
        //받아와서 뿌려주는 작업은 while문을 이용해야됨
        //while문 안의 조건에 들어가있는 c.moveToNext()는 위에 담아온 Cursor에 다음 값이 있으면 계속 실행
        //만약에 다음값이 없다면 멈춘다는 뜻
        while (c.moveToNext()){
            //각자의 값을 맡는 타입의 변수를 만들어 넣어줌
            String name = c.getString(c.getColumnIndex("name"));
            int age = c.getInt(c.getColumnIndex("age"));
            String phone = c.getString(c.getColumnIndex("phone"));
            //그리고 값을 뿌려줌
            println(searchName+" 테이블의 값 =\n이름 : " + name + " 나이 : " + age + " 번호 : " + phone);
        }
    }
    //테이블에 값을 넘어줌 insert (테이블 검색기능을 테스트해보기 위해서)
    private int insertRecord(){
        println("inserting records.");
        int count = 3;
        db.execSQL("insert into employee(name, age, phone) values ('john', 20, '010-1234-5678');");
        return count;
    }
}
cs

MySQLiteOpenHelper.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
package com.example.ntsysmac01.sampledatabase;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
 * Created by ntsysMac01 on 2015-12-21.
 */
//이 클래스는 helper로 db를 커넥션 연동 시키기 위해서 꼭 필요한 클래스 이다
public class MySQLiteOpenHelper extends SQLiteOpenHelper{
    public MySQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}
cs

login.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
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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="I D"
            android:id="@+id/textView2"
            android:textAlignment="center" />
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText4" />
    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="P W"
            android:id="@+id/textView3"
            android:textAlignment="center" />
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText5" />
    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="ID는 이름 PW는 나이로 입력해주세요."
            android:id="@+id/textView4" />
    </LinearLayout>
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="확인"
            android:id="@+id/button5" />
    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="상태 : "
            android:id="@+id/textView5" />
    </LinearLayout>
</LinearLayout>
cs

login.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.example.ntsysmac01.sampledatabase;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class login extends AppCompatActivity {
    SQLiteDatabase db;
    MySQLiteOpenHelper helper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        //db를 사용해야되기 때문에 helper에 연결시켜준다
        helper = new MySQLiteOpenHelper(login.this,
                "customer.db",
                null,
                1);
        final EditText id = (EditText)findViewById(R.id.editText4);
        final EditText pw = (EditText)findViewById(R.id.editText5);
        Button button = (Button)findViewById(R.id.button5);
        final TextView textView = (TextView)findViewById(R.id.textView5);
        //버튼을 클릭하게 됨과 동시에 db에서 확인을하게 된다
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                db = helper.getReadableDatabase();
                String name = id.getText().toString();
                String age = pw.getText().toString();
                String db_name = null;
                String db_age = null;
                //쿼리문 설정
                Cursor c = db.rawQuery("select * from employee" , null);
                //while문으로 역시 원하는값을 변수에 넣어줌
                while (c.moveToNext()){
                    db_name = c.getString(c.getColumnIndex("name"));
                    db_age = c.getString(c.getColumnIndex("age"));
                }
                //그다음 조건문을 걸어줘서 조건에 부합하다면 성공 메세지와 함께 다음 화면으로 이동
                if(name.equals(db_name) && age.equals(db_age)){
                    textView.append("\n로그인 성공!!!");
                    Intent intent = new Intent(getApplicationContext(), listview.class);
                    startActivity(intent);
                }else if(TextUtils.isEmpty(name) || TextUtils.isEmpty(age)){//유효성검사 해당 변수에 안에 값의 null이거나 비어 있는지를 체크
                    Toast.makeText(login.this,"ID와 PW를 입력하세요",Toast.LENGTH_LONG).show();
                }else{
                    //아니라면 실패라는 메세지와 함께 화면 이동은 발생하지 않음
                    textView.append("\n실패");
                }
            }
        });
    }
}
cs

list.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
50
51
52
53
54
55
56
57
58
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#009cc3">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="번호"
            android:id="@+id/textView23"
            android:layout_weight="1"
            android:textAlignment="center" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="제목"
            android:id="@+id/textView24"
            android:layout_weight="1"
            android:textAlignment="center" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="작성자"
            android:id="@+id/textView25"
            android:layout_weight="1"
            android:textAlignment="center" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="날짜"
            android:id="@+id/textView26"
            android:layout_weight="1"
            android:textAlignment="center" />
    </LinearLayout>
    <ListView
        android:layout_width="match_parent"
        android:layout_height="430dp"
        android:id="@+id/listView" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="글쓰러가기"
        android:id="@+id/button7"
        android:layout_gravity="center_horizontal" />
</LinearLayout>
cs

Item.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
package com.example.ntsysmac01.sampledatabase;
/**
 * Created by ntsysMac01 on 2015-12-22.
 */
public class Item {//listView에 데이터가 들어갈 공간을 정의함
    private String[] borditem;//String 배열 타입에 데이터를 넣기위해 선언
    public Item(String[] obj02){
        borditem = obj02;//다른곳에서 값을 넣어줄 수 있게함
    }
    public String[] borditemdate(){
        return borditem;
    }//다른곳에서 이 값을 쓸수있게 설정
    public String borditemdate(int index){//배열 값을 받아쓸때 if문을 한번거침 값이 없거나 인덱스 값이 배열이 가지고 있는 데이터 갯수보다 같거나 크면 null값을 return 해줌
        if (borditem == null || index >= borditem.length) {
            return null;
        }
        return borditem[index];
    }
}
cs

ItemView.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
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
package com.example.ntsysmac01.sampledatabase;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
 * Created by ntsysMac01 on 2015-12-22.
 */
public class ItemView extends LinearLayout {//ItemView는 보여지는 역할을 해주는 클래스
    //값을 보여줘야 하기 때문에 보여줄때 필요한 타입을 변수로 선언
    private TextView numtext;//번호
    private TextView subtext;//제목
    private TextView nametext;//이름
    private TextView daytext;
    public ItemView(Context context, Item date) {
        super(context);
        LayoutInflater inflater = (LayoutInflater)//컨텐츠가 보여질 xml을 내가만든 xml로 설정하기 위해 inflater을 설정
                context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.bordlist_content, thistrue);
        //어느 변수에 무엇이 어떤값이 들어가야 되는지 각각 설정
        numtext = (TextView)findViewById(R.id.textView6);
        numtext.setText(date.borditemdate(0));
        subtext = (TextView)findViewById(R.id.textView7);
        subtext.setText(date.borditemdate(1));
        nametext = (TextView)findViewById(R.id.textView8);
        nametext.setText(date.borditemdate(2));
        daytext = (TextView)findViewById(R.id.textView9);
        daytext.setText(date.borditemdate(3));
    }
    //배열로 처리된 값들을 setText로 쪼개줌
    //위에서 쓰게되는것을 보면 이해가 쉬움
    public void setText(int index, String data){
        if (index == 0 ){
            numtext.setText(data);
        } else if (index == 1 ){
            subtext.setText(data);
        } else if (index == 2){
            nametext.setText(data);
        } else if (index == 3){
            daytext.setText(data);
        } else {
            throw new IllegalArgumentException();
        }
    }
    public ItemView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public ItemView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public ItemView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }
}
cs

itemListAdapter.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.example.ntsysmac01.sampledatabase;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by ntsysMac01 on 2015-12-22.
 */
//BaseAdapter에 상속받기 때문에 extends 해줌
public class itemListAdapter extends BaseAdapter{
    private Context mContext;
    //어댑터를 사용할것이기 때문에 리스트를 생성해줌
    private List<Item> mItems = new ArrayList<Item>();
    itemListAdapter(Context context){
        mContext = context;
    }
    void additem(Item it){
        mItems.add(it);
    }
    private void setListItems(List<Item> list){
        mItems = list;
    }
    @Override
    public int getCount() {
        return mItems.size();
    }
    @Override
    public Object getItem(int position) {
        return mItems.get(position);
    }
    @Override
    public long getItemId(int position) {
        return position;
    }
    @Override
    //저번 예제에서 살펴봤던거와 동일하게 작업해주면 됨
    //퍼포먼스역할과 View 보여주는 역할을 해주는 기능
    public View getView(int position, View convertView, ViewGroup parent) {
        ItemView itemView;
        if(convertView == null) {
            itemView = new ItemView(mContext, mItems.get(position));
        } else {
            itemView = (ItemView) convertView;
            itemView.setText(0, mItems.get(position).borditemdate(0));
            itemView.setText(1, mItems.get(position).borditemdate(1));
            itemView.setText(2, mItems.get(position).borditemdate(2));
            itemView.setText(3, mItems.get(position).borditemdate(3));
        }
        return itemView;
    }
}
cs

listview.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
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
package com.example.ntsysmac01.sampledatabase;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
public class listview extends AppCompatActivity {
    SQLiteDatabase db;
    MySQLiteOpenHelper helper;
    ListView listView;
    itemListAdapter adapter;
    String num;
    String sub;
    String name;
    String day;
    String content;
    Button writebtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list);
        //list를 불러와야하기 때문에 db를 연결시켜준다
        helper = new MySQLiteOpenHelper(listview.this,
                "customer.db",
                null,
                1);
        //그리고 listview와 adapter를 설정해준다
        listView = (ListView)findViewById(R.id.listView);
        adapter = new itemListAdapter(this);
        String[] arr= new String[5];
        //쿼리문을 설정해주고
        db = helper.getReadableDatabase();
        Cursor c = db.rawQuery("select * from bord"null);
        //while문으로 원하는값을 변수에 담아준다
        //그리고 곧바로 뿌려준다
        while (c.moveToNext()){
            arr[0= num = c.getString(c.getColumnIndex("Num"));
            arr[1= sub = c.getString(c.getColumnIndex("Subject"));
            arr[2= name = c.getString(c.getColumnIndex("Name"));
            arr[3= day = c.getString(c.getColumnIndex("Day"));
            arr[4= content = c.getString(c.getColumnIndex("Content"));
            adapter.additem(new Item(arr));
            arr = new String[5];
        }
        listView.setAdapter(adapter);
        //해당 listView를 클릭하게 되면 상세보기 화면으로 넘어가게끔 설정
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getApplicationContext(), look.class);
                Item curItem = (Item)adapter.getItem(position);
                String[] curData = curItem.borditemdate();
                intent.putExtra("Item",curData);
                startActivity(intent);
            }
        });
        //글쓰기 버튼을 클릭하게 되면 글쓰기 화면으로 넘어게가끔 설정
        writebtn = (Button)findViewById(R.id.button7);
        writebtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), write.class);
                startActivity(intent);
                finish();
            }
        });
    }
}
cs

write.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="제목"
            android:id="@+id/textView10" />
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/editText6" />
    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="작성자"
            android:id="@+id/textView11" />
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/editText7" />
    </LinearLayout>
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="내용 : "
            android:id="@+id/textView12" />
        <EditText
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/editText8" />
    </LinearLayout>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="확인"
        android:id="@+id/button6"
        android:layout_gravity="center_horizontal" />
</LinearLayout>
cs

write.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.example.ntsysmac01.sampledatabase;
import android.app.Application;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
//글쓰기페이지 역할
public class write extends AppCompatActivity {
    SQLiteDatabase db;
    MySQLiteOpenHelper helper;
    EditText sub;
    EditText name;
    EditText content;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.write);
        sub = (EditText)findViewById(R.id.editText6);
        name = (EditText)findViewById(R.id.editText7);
        content = (EditText)findViewById(R.id.editText8);
        Button button = (Button)findViewById(R.id.button6);
        //사용할 db를 연동 시켜준다
        helper = new MySQLiteOpenHelper(write.this"customer.db"null1);
        db = helper.getWritableDatabase();
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //글을 다 입력하고 클릭하는 동시에
                GregorianCalendar calendar = new GregorianCalendar();
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH);
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                int hour = calendar.get(Calendar.HOUR_OF_DAY);
                int min = calendar.get(Calendar.MINUTE);
                int sec = calendar.get(Calendar.SECOND);
                //변수에 각각의 값을 담아주고
                String now = year + "-" + month + "-" + day + "\n" + hour + ":" + min + ":" + sec; //글쓴시간을 저장
                db.execSQL("insert into bord values(null,'"+sub.getText().toString()+"','" +name.getText().toString()+ "','"+now+"','" +content.getText().toString()+ "');");
                //db에 insert시켜준다
                Intent intent = new Intent(getApplicationContext(), listview.class);
                startActivity(intent);
                finish();
                //그다음 값을 intent에 실어주고 intent를 실행시켜준후 finish로 페이지를 닫아준다
            }
        });
    }
}
cs

예제 실행화면은 아래와 같습니다


초기화면에서 db와 테이블의 기능을 사용했고
그 다음 테이블에 담긴 값들을 검색해봤습니다
그리고 로그인버튼을 누르게 되면 아래로 이동하게 됩니다


ID와 PW는 db에 저장되어있는 이름값과 나이값으로 설정해뒀습니다
그래서 db에 연결후 확인하고 값과 동일하다면 다음페이지로 이동이 가능합니다
(상태에서 로그인 성공이 뜬 후 곧바로 자동으로 페이지 이동)


초기화면에 list가 보입니다 모두 db에 저장된 게시글 들이구요
작성시간 또한 저장되어 있습니다 글쓰러가기 버튼을 클릭한 후


제목과 작성자 내용을 입력하게 되면


다시 list로 넘어가게 되면서 밑에 금방 쓴 글이 추가된것을 확인할 수 있습니다


그 다음 그 글을 클릭하게되면 상세보기 페이지로 넘어가서
해당 글을 볼 수 있습니다

출처 : http://bestkkha.blogspot.com/2015/12/db-table.html

LIST
블로그 이미지

SeoHW

,
SMALL

안드로이드 오픈소스 링크입니다


http://coding-factory.tistory.com/209

LIST
블로그 이미지

SeoHW

,
SMALL

안드로이드 스튜디오에서 가상 장치 AVD 가 아니라 실제 기기로 다운로드 하여 개발할때 아래와 같은 에러가 나온다.


Installation failed with message INSTALL_FAILED_OLDER_SDK.

It is possible that this issue is resolved by uninstalling an existing version of the apk if it is present, and then re-installing.


WARNING: Uninstalling will remove the application data!


Do you want to uninstall the existing application?


화면을 캡쳐하면 아래와 같다.



이런 INSTALL_FAILED_OLDER_SDK 에러는 최저 SDK 사양이 맞지 않아서 발생한다. 우선 

최저 SDK 사양에 맞는 SDK를 설치 하는데 Tools->Android->SDK Manager에서 SDK를 설치하고,

개발중인 프로젝트의 minSDK 버전을 변경해준다. 여기서는 minSDK 가 22 로 되어있고 갤럭시 3에 다운로드 하려니 위와 같은 에러가 계속 발생되었다.


아래와 같은 프로젝트 화면에서 



프로젝트 이름에서, 여기서는 app 에서 마우스 오른쪽 버튼을 눌러 메뉴에서 Open Module Setting 을 선택한다.





열리는 창에서 Flavors 탭을 클릭하여 Min Sdk Version 에 아래와 같이 API19 를 선택주고 빠져나오면 된다.




그러면 AndroidMenifesto.xml 파일은 아무 변화 가 없고,  Bulild Gradle(Module : App) 파일의 minsdk 버전이 22 에서 19로 바뀐다.



apply plugin: 'com.android.application'

android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
defaultConfig {
applicationId "com.huins.androidsample"
minSdkVersion 19
targetSdkVersion 22
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
}

와 같이 변경하면 실제 안드로이드 기기에서 잘 실행될 것이다.

개발자의 공유는 삽질을 멈추게 한다.ㅎㅎ



출처: http://fishpoint.tistory.com/1669 [기린]

LIST
블로그 이미지

SeoHW

,
SMALL

프로그램 추가/제거에서 삭제후에 재설치후에도 plugin에러나 동일한 문제들이 발생할경우

완전삭제하고 설치해줘야할 경우가 발생한다.


방법은 비교적 간단하다


C:\User\사용자계정\ 경로에있는 .AndroidStuido해당버젼 파일을 지워주면된다.



나같은경우는 .AndroidStuio3.1 인데 이걸 지우고 재설치하면 문제없이 완전설치가 이뤄진다.



출처: http://831218.com/74 [호구인생]

LIST
블로그 이미지

SeoHW

,
SMALL

안드로이드 프로그램을 작성한 후 테스트를 위해서는 

실제 장비에 프로그램을 포팅하여 테스트하는 것이 가장 좋지만,

수많은 사이즈와 성능의 장비들을 모두 준비하여 테스트 하는 것은 

현실적으로도 힘들고, 번거롭기도 하다.

그래서, 안드로이드 스튜디오에서는 AVD(Android Virtual Device)라는 가상의 애뮬레이터를 제공하고,

우리는 이 애뮬레이터를 통해서 다양한 디바이스에서의 테스트를 해볼 수 있다.

(물론, 당연히 실제 디바이스와 100% 동일하지는 않지만..)


여기서는 AVD 설정과 실행방법을 소개한다.

(참고로, 나는 여기서 AVD 설정 실패...내 PC에서는 돌지 않는다. ㅠㅠㅠㅠㅠㅠㅠ

하지만, 이건 나의 PC사양의 문제이므로 이 글을 보는 다른 이들은 모두 성공하실 것임..ㅠㅠ)



AVD를 설정하고, 실행시키기 위해


1. Tools > Android > AVD Manager를 선택한다.


2. 'Create Virtual Device' 버튼을 클릭한다.


3. 여러가지 Device 중 원하는 하드웨어 스펙을 선택한다.

Category를 선택하고 나면 해당 카테고리에서 기본으로 제공하는 Device 정보중 하나를 선택해도 되고, 하단의 'New Hardware Profile'을 선택하여 상세한 하드웨어 정보를 설정할 수도 있다.

여기서는 Phone category를 선택하고, 그중 해상도 480*800의 Nexus S를 선택하였다.


4. 하드웨어에 들어갈 System Image를 선택한다.

Recommended 탭에서 추천한 Marshmallow x86이미지를 선택하려고 하니, 오른쪽에 뜨는 빨간 메세지 ㅠㅠ

(아마 나 빼고 다른 분들은 안날거에요...ㅠㅠ)

일단 진행이 되니 패스하고, 이 빨간 메세지에 대해서는 다음 포스팅에서 ...


5. Virtual Device의 상세 스펙을 설정한다.

AVD Name은 여러개의 Virtual Device를 구분하기 위한 이름이므로 자유롭게 기술한다.

'Show Advanced Settings'를 클릭하여 기타 상세사항들을 자유롭게 조정한다.

여기서는 일단 변경없이 그대로 생성한다.

이 설정들은 나중에도 변경할 수 있다.

Finish 버튼을 클릭한다.


6. Android Virtual Device Manager에 새로운 Device가 생성된 것을 볼 수 있다.


7. AVD Manager의 화살표 버튼을 클릭하거나, 

화면 상단의 화살표 버튼을 클릭하면 생성된 Virtual Device가 실행된다.


요렇게 실행되면 되는데,

사실 아래 캡쳐는 제대로 실행이 안된 상태이다.

원인은 아까 중간에 스킵했던 빨간 오류 메세지..

이 내용에 대해서는 다음 포스팅에...하휴...


여기 까지 하면 애뮬레이터 설치 및 실행 완료!



출처: http://hianna.tistory.com/144 [어제 오늘 내일]

LIST
블로그 이미지

SeoHW

,
SMALL

프로그램안에서 사용해야 할 다량의 문자열들을 정의하는데 있어서 효율적인 방법은 소스코드에 모든 내용을 포함시키기 보다는 외부에 내용을 저장해 놓고 필요할 때 마다 읽어오는 방법입니다.

안드로이드에서는 문자열로서 사용하기 위한 데이터를 보관하기 위한 기법으로 리소스 XML에 내용을 기술하는 방법과 SQLite를 사용하는 방법, 그리고 assets 디렉토리를 사용하는 방법을 제공해 주고 있습니다.

오늘 소개할 내용은 assets 디렉토리에 저장된 텍스트 파일을 프로그램내로 읽어들이는 내용입니다.

assets 디렉토리

안드로이드 프로젝트를 이클립스 상에서 보면 assets라는 (평소에는 잘 사용하지 않는) 디렉토리에 있습니다. 프로그램과 직접적으로 연관되지 않은 비 리소스 파일들을 저장해 놓고 필요한 경우 스트림을 생성하여 읽어들이기 위한 저장공간입니다.

이 폴더안에 test.txt라는 파일을 넣었다고 가정하고 이 파일의 내용을 프로그램의 Runtime시에 읽어오는 방법을 소개하겠습니다.


AssetManager의 객체 생성

Context 클래스 내에 보면 getResource()라는 메소드가 있습니다. getResource()라는 메소드는 Resources 라는 클래스의 객체를 리턴합니다. 이 객체는 App이 갖고 있는 자원에 접근할 수 있는 객체입니다. 이 객체를 통해서 AssetManager라는 객체를 얻을 수 있습니다.

<strong>Context 클래스</strong>
<strong>Resources getResource();</strong><br />리소스 객체를 얻어옵니다.


만약 Activity안에서 AssetManager객체를 얻고자 한다면 다음과 같이 사용할 수 있습니다.

Resources r = getResource();


Context 클래스는 Activity 클래스의 상위 클래스이기 때문에 Activity 안에서는 Context클래스 내의 기능들을 자기것인양 사용할 수 있습니다.

리소스 객체를 얻은 후에는 이 리소스 객체를 통해서 AssetManager 객체를 얻어옵니다.

<strong>Resources클래스</strong>
<strong>AssetManager getAssets();</strong><br />AssetManager 객체를 얻어옵니다.




 

AssetManager를 통하여 파일 열기

AssetManager 객체가 생성되면 이 객체의 open() 메소드를 사용하여 InputStream 객체를 얻을 수 있습니다. open() 메소드는 호출 시에 대상 파일의 이름을 문자열로 전달합니다. 파일이 위치한 경로는 이클립스 프로젝트 내의 assets 라는 폴더로 이미 확정이 되어 있는 상태이기 때문에 전달하는 파라미터는 파일의 이름만을 전달합니다. 주의하실 점은 이 메소드를 사용하려면 try { } ~ catch { } 블록으로 묶어 주어야 한다는 점 입니다. 그래서 Asset객체를 통해서 InputStream을 여는 과정은 다음과 같아집니다.

  1. AssetManager am = m_context.getResources().getAssets();  
  2. InputStream is = null;  
  3.   
  4. try {  
  5.     is = am.open("contact.txt");  
  6.     // 스트림을 사용합니다.  
  7. catch (Exception e) {  
  8.     // 에러가 발생한 경우의 처리  
  9. finally {  
  10.     if (is != null) {  
  11.         try {  
  12.             is.close();  
  13.             is = null;  
  14.         } catch (Exception e) {}  
  15.     }  
  16. }  
  17.   
  18. am = null;  




 

test.txt 파일을 읽기

Context객체와 읽어야 할 파일이름을 전달하였을 때, 해당 파일의 내용을 읽어서 문자열로 리턴해 주는 함수를 구현해 본다면 다음과 같이 구현할 수 있겠습니다.

  1. String readAsset(Context context, String file_name) {  
  2.     AssetManager am = context.getResources().getAssets();  
  3.     InputStream is = null;  
  4.     // 읽어들인 문자열이 담길 변수  
  5.     String result = null;  
  6.   
  7.     try {  
  8.         is = am.open(file_name);  
  9.         int size = is.available();  
  10.   
  11.         if (size > 0) {  
  12.             byte[] data = new byte[size];  
  13.             is.read(data);  
  14.             result = new String(data);  
  15.         }  
  16.     } catch (Exception e) {  
  17.         e.printStackTrace();  
  18.     } finally {  
  19.         if (is != null) {  
  20.             try {  
  21.                 is.close();  
  22.                 is = null;  
  23.             } catch (Exception e) {}  
  24.         }  
  25.     }  
  26.   
  27.     am = null;  
  28.     return result;  
  29. }  


Activity클래스 안에서 사용방법은 다음과 같습니다.

String data = readAsset(this, "test.txt");
LIST
블로그 이미지

SeoHW

,

Webview 사용법

Android 2015. 2. 12. 13:21
SMALL

웹페이지를 표시하는 뷰이다.


상속구조는 아래와 같다.

   ↳ android.view.View 
         ↳ android.webkit.WebView

웹브라우저에서 하는 역할을 모두 할 수 있으며 액티비티내에서 화면의 일부로 온라인컨텐츠를 표시할수 있다.
WebKin render engine을 사용하며 이전페이지, 다음페이지, 확대/축소, 텍스트검색등의 기능을 포함한다.

zoom기능을 활성화하려면 WebSettings.setBuiltInZoomControls(boolean)을 사용하라.

액티비티에서 인터넷을 억세스하고 웹페이지를 WebView에 표시하려면 아래 퍼미션을 매니페스트 파일에 추가하라.

<uses-permission android:name="android.permission.INTERNET"/>

기본적인 사용법
기본적으로 WebView는 브라우져와 유사한 위젯을 제공하지는 않는다. 자바스크립트는 비활성화되어 있으며 웹페이지에러는 무시된다. 그냥 UI의 일부로 HTML을 표시하고자 한다면 이정도면 충분하다. 만일 full-blown 웹브라우져를 원한다면 WebView를 이용하는것보다 그냥 인텐트를 날려서 브라우져에서 표시하고자 할것이다. 아래와 같이...

   Uri uri = Uri.parse("http://www.example.com");
   
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
   startActivity
(intent);
 
액티비티에서 WebView를 제공하고자 한다면 layout에 <WebView>를 추가하거나 onCreate()에서 액티비티자체를 WebView로 지정하면 된다.
   WebView webview = new WebView(this);
   setContentView
(webview);
 
이어서 원하는 웹페이지를 로드한다.

// Simplest usage: note that an exception will NOT be thrown
 
// if there is an error loading this page (see below).
 webview
.loadUrl("http://slashdot.org/");

 
// OR, you can also load from an HTML string:
 
String summary = "<html><body>You scored <b>192</b> points.</body></html>";
 webview
.loadData(summary, "text/html", "utf-8");
 
// ... although note that there are restrictions on what this HTML can do.
 
// See the JavaDocs for loadData() and loadDataWithBaseURL() for more info.

WebView는 원하는 동작을 구현하기 위해 몇가지 수정가능한 방법을 제공한다.
 - WebChromeClient의 subclass를 생성하고 설정한다. 이 클래스는 브라우져UI에서 어떤 동작이 발생하면 호출된다. 예를 들어 update과정이나 자바스크립트 경고같은 것들이 이 클래스로 전달된다.
 - WebViewClient의 서브클래스를 생성하고 설정한다. 콘텐츠의 렌더링과 연관된 동작이 발생하면 호출된다. 예를 들어 에러나 폼서브미션시(form submission)에 호출된다. shouldOverrideUrlLoading()함수를 통해 URL이 로드되기전에 원하는 작업을 할 수도 있다.
 - WebSettings의 변경가능, setJavaScriptEnabled()로 자바스크립트를 활성화할 수 있다.
 - JavaScript-to-Java 인터페이스를 추가할 수 있다. addJavascriptInterface(Object, String)메소드로 가능하다. 이 함수는 자바오브젝트를 WebView에 바인드할 수 있다. 이렇게 하여 웹페이지의 자바스크립트를 제어할 수 있다.

아래 좀더 복잡한 예제가 있다, 에러핸들링의 표시, 셋팅, 진행상태 통지등의 예를 볼수 있다.

// Let's display the progress in the activity title bar, like the
 
// browser app does.
 getWindow
().requestFeature(Window.FEATURE_PROGRESS); // 타이틀바에 진행상태 아이콘표시모드로 변경한다.

 webview
.getSettings().setJavaScriptEnabled(true); // 자바스크립트를 활성화한다.

 
final Activity activity = this;
 webview
.setWebChromeClient(new WebChromeClient() { // WebChromeClient를 설정하고 진행상태 변동상태를 화면에 반영한다.
   
public void onProgressChanged(WebView view, int progress) {
     
// Activities and WebViews measure progress with different scales.
     
// The progress meter will automatically disappear when we reach 100%
     activity
.setProgress(progress * 1000);
   
}
 
});

 webview
.setWebViewClient(new WebViewClient() { // WebViewClient를 설정하여 에러발생시 토스트로 표시한다.
   
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
     
Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
   
}
 
});

 webview
.loadUrl("http://slashdot.org/"); // 원하는 웹페이지를 연다.
 
쿠키와 윈도우관리
보안상의 이유로 당신의 애플리케이션은 자체 캐시와 쿠키 등의 저장소들을 가지고 있다. 이것은 브라우져애플리케이션의 데이터와 공유되지 않는다. 쿠키의 경우 스래드로 분리되어 관리된다. 그래서 UI thread에 의해 블럭되지 않는다. 애플리케이션에서 쿠리정보를 참조하고 싶다면 CookieSyncManager를 사용하라.

기본적으로 HTML에서 새로운 창에 여는기능은 무시된다. 이는 자바스크립트나 링크의 대상의 속성에의해 가능해진다. WebChromeClient를 수정하여 여러개의 윈도우로 페이지를 여는것을 당신 마음대로 변경할 수 있다.

액티비티의 기본동작은 configuration이 변경되면 destroy되었다가 다시 create되는것이다. 이 경우 WebView는 웹페이지를 다시 로딩하게 된다. 이게 싫다면 orientation과 keyboardHidden값을 변경하면 다시로드하지 않고 처리된다.

자주 사용된느 WebView관련 함수들
addJavascriptInterface() 자바스크립트의 자바 객체 접근 허용

createSnapshot() 현 페이지의 스크린샷 생성

getSettings() 설정을 조정하는  WebSettings 객체 반환 

loadData() 브라우저에 주어진 문자열 데이터 로딩

loadDataWithBaseURL() 기준 URL을 사용해 주어진 데이터 로딩

loadUrl() 주어진 URL을 사용해 웹페이지 로딩

setDownloadListener() 사용자가 .zip이나 .apk 파일을 다운받는 경우 등의 다운로드 이벤트의 콜백 등록

setWebChromeClient() 제목이나 진행률 표시줄을 업데이트하거나 자바스크립트 대화상자를 여등 등, WebView 영역밖에서 실행되는 이벤트의 콜백을 등록

setWebViewClient() 리소스 로딩하기, 키 눌림, 인증 요청 등의 이벤트를 방해하도록 애플리케이션이 브라우저에 걸림돌을 설정함.

stopLoading() 현재 페이지 로딩 멈추기

LIST
블로그 이미지

SeoHW

,