https://coding-factory.tistory.com/209
'Android' 카테고리의 다른 글
| 안드로이드 db 세팅 table (0) | 2018.09.28 |
|---|---|
| 안드로이드 오픈소스 (0) | 2018.09.28 |
| 안드로이드 스튜드오 실행 에러 INSTALL_FAILED_OLDER_SDK (0) | 2018.09.26 |
| 안드로이드 스튜디오 삭제하기 (0) | 2018.09.24 |
| 안드로이드 스튜디오 avd 설정하기 (0) | 2018.09.10 |
https://coding-factory.tistory.com/209
| 안드로이드 db 세팅 table (0) | 2018.09.28 |
|---|---|
| 안드로이드 오픈소스 (0) | 2018.09.28 |
| 안드로이드 스튜드오 실행 에러 INSTALL_FAILED_OLDER_SDK (0) | 2018.09.26 |
| 안드로이드 스튜디오 삭제하기 (0) | 2018.09.24 |
| 안드로이드 스튜디오 avd 설정하기 (0) | 2018.09.10 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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, this, true);
//어느 변수에 무엇이 어떤값이 들어가야 되는지 각각 설정
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 |
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 |
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 |
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 |
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", null, 1);
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 |
출처 : http://bestkkha.blogspot.com/2015/12/db-table.html
| 안드로이드 오픈 소스 깃허브 url (0) | 2018.11.19 |
|---|---|
| 안드로이드 오픈소스 (0) | 2018.09.28 |
| 안드로이드 스튜드오 실행 에러 INSTALL_FAILED_OLDER_SDK (0) | 2018.09.26 |
| 안드로이드 스튜디오 삭제하기 (0) | 2018.09.24 |
| 안드로이드 스튜디오 avd 설정하기 (0) | 2018.09.10 |
안드로이드 오픈소스 링크입니다
http://coding-factory.tistory.com/209
| 안드로이드 오픈 소스 깃허브 url (0) | 2018.11.19 |
|---|---|
| 안드로이드 db 세팅 table (0) | 2018.09.28 |
| 안드로이드 스튜드오 실행 에러 INSTALL_FAILED_OLDER_SDK (0) | 2018.09.26 |
| 안드로이드 스튜디오 삭제하기 (0) | 2018.09.24 |
| 안드로이드 스튜디오 avd 설정하기 (0) | 2018.09.10 |
안드로이드 스튜디오에서 가상 장치 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 [기린]
| 안드로이드 db 세팅 table (0) | 2018.09.28 |
|---|---|
| 안드로이드 오픈소스 (0) | 2018.09.28 |
| 안드로이드 스튜디오 삭제하기 (0) | 2018.09.24 |
| 안드로이드 스튜디오 avd 설정하기 (0) | 2018.09.10 |
| 안드로이드 프로젝트내 assets 폴더 활용하기 (0) | 2015.02.12 |
프로그램 추가/제거에서 삭제후에 재설치후에도 plugin에러나 동일한 문제들이 발생할경우
완전삭제하고 설치해줘야할 경우가 발생한다.
방법은 비교적 간단하다
C:\User\사용자계정\ 경로에있는 .AndroidStuido해당버젼 파일을 지워주면된다.
나같은경우는 .AndroidStuio3.1 인데 이걸 지우고 재설치하면 문제없이 완전설치가 이뤄진다.
출처: http://831218.com/74 [호구인생]
| 안드로이드 오픈소스 (0) | 2018.09.28 |
|---|---|
| 안드로이드 스튜드오 실행 에러 INSTALL_FAILED_OLDER_SDK (0) | 2018.09.26 |
| 안드로이드 스튜디오 avd 설정하기 (0) | 2018.09.10 |
| 안드로이드 프로젝트내 assets 폴더 활용하기 (0) | 2015.02.12 |
| Webview 사용법 (0) | 2015.02.12 |
안드로이드 프로그램을 작성한 후 테스트를 위해서는
실제 장비에 프로그램을 포팅하여 테스트하는 것이 가장 좋지만,
수많은 사이즈와 성능의 장비들을 모두 준비하여 테스트 하는 것은
현실적으로도 힘들고, 번거롭기도 하다.
그래서, 안드로이드 스튜디오에서는 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 [어제 오늘 내일]
| 안드로이드 오픈소스 (0) | 2018.09.28 |
|---|---|
| 안드로이드 스튜드오 실행 에러 INSTALL_FAILED_OLDER_SDK (0) | 2018.09.26 |
| 안드로이드 스튜디오 삭제하기 (0) | 2018.09.24 |
| 안드로이드 프로젝트내 assets 폴더 활용하기 (0) | 2015.02.12 |
| Webview 사용법 (0) | 2015.02.12 |
프로그램안에서 사용해야 할 다량의 문자열들을 정의하는데 있어서 효율적인 방법은 소스코드에 모든 내용을 포함시키기 보다는 외부에 내용을 저장해 놓고 필요할 때 마다 읽어오는 방법입니다.
안드로이드에서는 문자열로서 사용하기 위한 데이터를 보관하기 위한 기법으로 리소스 XML에 내용을 기술하는 방법과 SQLite를 사용하는 방법, 그리고 assets 디렉토리를 사용하는 방법을 제공해 주고 있습니다.
오늘 소개할 내용은 assets 디렉토리에 저장된 텍스트 파일을 프로그램내로 읽어들이는 내용입니다.
안드로이드 프로젝트를 이클립스 상에서 보면 assets라는 (평소에는 잘 사용하지 않는) 디렉토리에 있습니다. 프로그램과 직접적으로 연관되지 않은 비 리소스 파일들을 저장해 놓고 필요한 경우 스트림을 생성하여 읽어들이기 위한 저장공간입니다.
이 폴더안에 test.txt라는 파일을 넣었다고 가정하고 이 파일의 내용을 프로그램의 Runtime시에 읽어오는 방법을 소개하겠습니다.
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 객체가 생성되면 이 객체의 open() 메소드를 사용하여 InputStream 객체를 얻을 수 있습니다. open() 메소드는 호출 시에 대상 파일의 이름을 문자열로 전달합니다. 파일이 위치한 경로는 이클립스 프로젝트 내의 assets 라는 폴더로 이미 확정이 되어 있는 상태이기 때문에 전달하는 파라미터는 파일의 이름만을 전달합니다. 주의하실 점은 이 메소드를 사용하려면 try { } ~ catch { } 블록으로 묶어 주어야 한다는 점 입니다. 그래서 Asset객체를 통해서 InputStream을 여는 과정은 다음과 같아집니다.
AssetManager am = m_context.getResources().getAssets();
InputStream is = null;
try {
is = am.open("contact.txt");
// 스트림을 사용합니다.
} catch (Exception e) {
// 에러가 발생한 경우의 처리
} finally {
if (is != null) {
try {
is.close();
is = null;
} catch (Exception e) {}
}
}
am = null;
Context객체와 읽어야 할 파일이름을 전달하였을 때, 해당 파일의 내용을 읽어서 문자열로 리턴해 주는 함수를 구현해 본다면 다음과 같이 구현할 수 있겠습니다.
String readAsset(Context context, String file_name) {
AssetManager am = context.getResources().getAssets();
InputStream is = null;
// 읽어들인 문자열이 담길 변수
String result = null;
try {
is = am.open(file_name);
int size = is.available();
if (size > 0) {
byte[] data = new byte[size];
is.read(data);
result = new String(data);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
is = null;
} catch (Exception e) {}
}
}
am = null;
return result;
}
Activity클래스 안에서 사용방법은 다음과 같습니다.
String data = readAsset(this, "test.txt");
| 안드로이드 오픈소스 (0) | 2018.09.28 |
|---|---|
| 안드로이드 스튜드오 실행 에러 INSTALL_FAILED_OLDER_SDK (0) | 2018.09.26 |
| 안드로이드 스튜디오 삭제하기 (0) | 2018.09.24 |
| 안드로이드 스튜디오 avd 설정하기 (0) | 2018.09.10 |
| Webview 사용법 (0) | 2015.02.12 |
웹페이지를 표시하는 뷰이다.
loadData() and loadDataWithBaseURL() for more info.createSnapshot() 현 페이지의 스크린샷 생성
getSettings() 설정을 조정하는 WebSettings 객체 반환
loadData() 브라우저에 주어진 문자열 데이터 로딩
loadDataWithBaseURL() 기준 URL을 사용해 주어진 데이터 로딩
loadUrl() 주어진 URL을 사용해 웹페이지 로딩
setDownloadListener() 사용자가 .zip이나 .apk 파일을 다운받는 경우 등의 다운로드 이벤트의 콜백 등록
setWebChromeClient() 제목이나 진행률 표시줄을 업데이트하거나 자바스크립트 대화상자를 여등 등, WebView 영역밖에서 실행되는 이벤트의 콜백을 등록
setWebViewClient() 리소스 로딩하기, 키 눌림, 인증 요청 등의 이벤트를 방해하도록 애플리케이션이 브라우저에 걸림돌을 설정함.
stopLoading() 현재 페이지 로딩 멈추기
| 안드로이드 오픈소스 (0) | 2018.09.28 |
|---|---|
| 안드로이드 스튜드오 실행 에러 INSTALL_FAILED_OLDER_SDK (0) | 2018.09.26 |
| 안드로이드 스튜디오 삭제하기 (0) | 2018.09.24 |
| 안드로이드 스튜디오 avd 설정하기 (0) | 2018.09.10 |
| 안드로이드 프로젝트내 assets 폴더 활용하기 (0) | 2015.02.12 |