package my.note.app;

public class MyObj {

public String myname = "okgosu";
public String getMyHome() {
return "okgosu.net";
}
}

package my.note.app;

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

public class MyNote1 extends Activity {

private Button btn1; // 멤버변수
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Button btn2; // 로컬변수
setContentView(R.layout.my_note1);
btn1 = (Button)findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// MyObj클래스를 인스턴스화(그 클래스의 변수나 함수를 사용 )
MyObj me = new MyObj();
Toast.makeText(MyNote1.this, me.myname, 1000).show();// myname 변수값 출력
Toast.makeText(MyNote1.this, me.getMyHome(), 1000).show();// getMyHome()리턴값 출력
}
});
}
}


package my.note.app;

public class MyObj {
// 멤버변수
public String myname = "okgosu";
public char mygrade = 'A';  // char 타입
public int myage = 19; // int 타입
public double myeye = 1.5; // double타입
public boolean mywed = true;   // boolean타입
public int num1;
public int num2 = 10;
public String getMyGrade(int point) {
      String res = "A";
      // if - else를 써서 point값에 따라 학점출력
      if(point <60) {
     res = "F";  
      } else if(point>=60 && point <70) {
     res = "D";
      } else if(point>=70 && point <80) {
      res = "C"; 
      } else if(point>=80 && point <90) {
      res = "B";
      } else {
      res = "A";
      }
      //point가 60 미만이면 res = "F" 
      //point가 60 이상 70 미만이면 res="D"
      //point가 70 이상 80 미만이면 res="C"
      //point가 80 이상 90 미만이면 res="B"
      //point가 90 이상 이면 res="A"
      return res;
}
public int getSum() {
int res;
res = num1 + num2;
return res;
}
public String getMyHome() {
// 함수 안에 선언하는 변수는 로컬변수
String myname = "okgosu";
char mygrade = 'A';  // char 타입
int myage = 19; // int 타입
double myeye = 1.5; // double타입
boolean mywed = true;   // boolean타입
return "okgosu.net";
}
}

package my.note.app;

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

public class MyNote1 extends Activity {

private Button btn1; // 멤버변수
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Button btn2; // 로컬변수
setContentView(R.layout.my_note1);
btn1 = (Button)findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// MyObj클래스를 인스턴스화(그 클래스의 변수나 함수를 사용 )
MyObj me = new MyObj();
//Toast.makeText(MyNote1.this, "" + me.mywed, 1000).show();// myname 변수값 출력
Toast.makeText(MyNote1.this, me.getMyGrade(78), 1000).show();// myname 변수값 출력
}
});
}
}

my_second_app.xml
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent"&gt;
&lt;EditText android:id="@+id/ed1" android:text="아무거나 입력하세요" android:layout_width="wrap_content"
android:layout_height="wrap_content"&gt;&lt;/EditText&gt;
&lt;Button android:id="@+id/btn1" android:text="EditText값 확인"  android:layout_width="wrap_content"
android:layout_height="wrap_content"&gt;&lt;/Button&gt;
&lt;/LinearLayout&gt;

MySecondApp 자바 소스

package android.edu;

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

public class MySecondApp extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_second_app);
Button btn1 = (Button)findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText ed = (EditText)findViewById(R.id.ed1);
String msg = ed.getText().toString();
Toast.makeText(MySecondApp.this, msg, 1000).show();
}
});
}
}

my_web_view.xml

&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent"&gt;
&lt;LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent" android:layout_height="wrap_content"&gt;
&lt;EditText android:id="@+id/url" android:layout_height="wrap_content"
android:layout_width="wrap_content" android:lines="1"
android:layout_weight="1" android:text="http://okgosu.net" /&gt;
&lt;Button android:id="@+id/go_button" android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="Go" /&gt;
&lt;/LinearLayout&gt;
&lt;WebView android:id="@+id/webkit" android:layout_width="fill_parent"
android:layout_height="fill_parent" /&gt;
&lt;/LinearLayout&gt;


MyWebView.java

package android.edu;

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

public class MyWebView extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_web_view);
Button btn = (Button)findViewById(R.id.go_button);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
WebView browser = (WebView)findViewById(R.id.webkit);
EditText ed = (EditText)findViewById(R.id.url);
// 에디트텍스트에 입력된 사이트로 이동
browser.loadUrl(ed.getText().toString());
}
});
}
}

[실습]MyWebView에 현재 브라우저에서 웹페이지 로딩하도록 설정

browser.setWebViewClient(new WebViewClient() {
  public boolean shouldOverrideUrlLoading(WebView view, String url)  { 
     view.loadUrl(url); 
     return true;
 }
});


[my_text_style.xml]
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent"&gt;
&lt;TextView android:id="@+id/tv1" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="This is a TextView Style test!"
android:typeface="sans" android:textColor="#FF0000"
android:background="#FFFF00" android:textSize="20sp"
android:layout_gravity="left"&gt;&lt;/TextView&gt;
&lt;LinearLayout android:layout_width="fill_parent"
android:orientation="horizontal" android:layout_height="wrap_content"&gt;
&lt;CheckBox android:text="bold" android:textStyle="bold"
android:id="@+id/CheckBox01" android:layout_weight="1"
android:layout_width="wrap_content" android:layout_height="wrap_content"&gt;&lt;/CheckBox&gt;
&lt;CheckBox android:text="italic" android:textStyle="italic"
android:id="@+id/CheckBox02" android:layout_weight="1"
android:layout_width="wrap_content" android:layout_height="wrap_content"&gt;&lt;/CheckBox&gt;
&lt;/LinearLayout&gt;
&lt;View android:background="#CCCCCC" android:layout_width="fill_parent"
android:layout_height="2sp"&gt;&lt;/View&gt;
&lt;RadioGroup android:id="@+id/rdg" android:layout_width="wrap_content"
android:layout_height="wrap_content"&gt;
&lt;RadioButton android:text="sans" android:id="@+id/rb1"
android:checked="true" android:layout_width="wrap_content"
android:layout_height="wrap_content"&gt;&lt;/RadioButton&gt;
&lt;RadioButton android:text="serif" android:id="@+id/rb2"
android:layout_width="wrap_content" android:layout_height="wrap_content"&gt;&lt;/RadioButton&gt;
&lt;RadioButton android:text="monospace" android:id="@+id/rb3"
android:layout_width="wrap_content" android:layout_height="wrap_content"&gt;&lt;/RadioButton&gt;
&lt;/RadioGroup&gt;
&lt;/LinearLayout&gt;

MyTextStyle.java

package android.edu;

import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioGroup;
import android.widget.TextView;

public class MyTextStyle extends Activity {
private int tvStyle1;
private int tvStyle2;
private String mytype="sans";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_text_style);
final TextView tv1 = (TextView)findViewById(R.id.tv1);
CheckBox cb1 = (CheckBox)findViewById(R.id.CheckBox01);
CheckBox cb2 = (CheckBox)findViewById(R.id.CheckBox02);
RadioGroup rdg = (RadioGroup)findViewById(R.id.rdg);
// cb1, cb2에 대해 CompoundButton.OnCheckedChangListener
cb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
tvStyle1 = Typeface.BOLD;
} else {
tvStyle1 = Typeface.NORMAL;
}
Typeface face=Typeface.create(mytype, tvStyle1|tvStyle2);
tv1.setTypeface(face, tvStyle1|tvStyle2);
}
});
cb2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
tvStyle2 = Typeface.ITALIC;
} else {
tvStyle2 = Typeface.NORMAL;
}
Typeface face=Typeface.create(mytype, tvStyle1|tvStyle2);
tv1.setTypeface(face, tvStyle1|tvStyle2);
}
});
// rdg에 대해 RadioGroup.OnCheckedChangListener
rdg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.rb1:
mytype = "sans";
break;
case R.id.rb2:
mytype = "serif";
break;
case R.id.rb3:
mytype = "monospace";
break;
}
Typeface face=Typeface.create(mytype, 0);
tv1.setTypeface(face);
}
});
}
}

my_image_view.xml
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content"&gt;
&lt;ImageView android:id="@+id/img" android:src="@drawable/snk10"
android:layout_weight="1" android:layout_width="wrap_content"
android:layout_height="fill_parent" /&gt;
&lt;ImageButton android:id="@+id/imgBtn" android:src="@drawable/my_image_btn"
android:layout_gravity="bottom|center" android:layout_width="48px"
android:layout_height="48px" /&gt;
&lt;/LinearLayout&gt;

MyImageView.java

package android.edu;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;

public class MyImageView extends Activity {
private ImageView iv;
private ImageButton imgBtn;
private int imageNum = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_image_view);
imgBtn = (ImageButton)findViewById(R.id.imgBtn);
iv = (ImageView)findViewById(R.id.img);
iv.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// 웹사이트 이미지 로딩 [시작]
try {
URL url = new URL("http://okgosu.net/pds/blackgg/" + imageNum + ".jpg");
URLConnection conn = url.openConnection();
conn.connect();
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
iv.setImageBitmap(bm); // 로딩한 이미지의 비트맵을 iv의 이미지로 설정
if(++imageNum>9) imageNum = 1;
} catch (IOException e) {
e.printStackTrace();
}
// 웹사이트 이미지 로딩 [종료]
return false;
}
});
}
}

my_edit_text.xml
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="10dp" android:layout_width="fill_parent"
android:layout_height="wrap_content"&gt;
&lt;TextView android:id="@+id/label" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="입력한글자수:" /&gt;
&lt;EditText android:id="@+id/entry" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_below="@id/label" /&gt;
&lt;Button android: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="10dip"
android:text="OK" /&gt;
&lt;Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_toLeftOf="@id/ok"
android:layout_alignTop="@id/ok" android:text="CANCEL" /&gt;
&lt;/RelativeLayout&gt;

MyEditText.java
package android.edu;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;

public class MyEditText extends Activity {
private TextView tv;
private EditText ed;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_edit_text);
tv = (TextView)findViewById(R.id.label);
ed = (EditText)findViewById(R.id.entry);
ed.addTextChangedListener(new TextWatcher() {
// 텍스트 입력중 변화
public void onTextChanged(CharSequence s, int start, int before, int count) {
tv.setText("입력한 글자수:" + ed.getText().length());
}
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
}
public void afterTextChanged(Editable s) {
}
});
}
}

[SMS수신]
1. 퍼미션 추가: &lt;uses-permission android:name="android.permission.RECEIVE_SMS" /&gt;

2. MySMSReceiver 클래스 작성: MySMSReceiver extends BroadcastReceiver 

3. 매니페스트에 MySMSReceiver 추가
&lt;receiver android:name="MySMSReceiver "&gt; 
     &lt;intent-filter&gt; 
           &lt;action android:name="android.provider.Telephony.SMS_RECEIVED" /&gt; 
       &lt;/intent-filter&gt; 
&lt;/receiver&gt;

4. MySMSReceiver onReceive(Context context, Intent intent) 오버라이딩
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
   Bundle bundle = intent.getExtras();   
   if(bundle != null) {
         Toast.makeText(context, "문자 왔음", 1000).show();
   }
}

5. bundle객체로부터 문자내용 파싱 
1) import android.telephony.SmsMessage; 추가
2) SmsMessage 파싱
Object[] pdusObj = (Object[]) bundle.get("pdus"); 
StringBuilder sb = new StringBuilder();
SmsMessage[] messages = new SmsMessage[pdusObj.length]; 
    for (int i = 0; i&lt;pdusObj.length; i++) { 
             messages[i] = SmsMessage.createFromPdu ((byte[])pdusObj[i]); 
             sb.append("보낸사람:");
             sb.append(messages[i].getDisplayOriginatingAddress());                  
             sb.append("메시지내용:");
             sb.append(messages[i].getDisplayMessageBody());
    } 


// 설치된 안드로이드 애플리케이션 목록 추출
package android.edu;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.ListActivity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class MyAppList extends ListActivity {

private ArrayList<String> items = new ArrayList<String>();
private List<ApplicationInfo> appList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
appList = getPackageManager().getInstalledApplications(0);// List객체
Iterator<ApplicationInfo> itr = appList.iterator();
while(itr.hasNext()) {
ApplicationInfo info = (ApplicationInfo)itr.next();
items.add(info.packageName);
}
//setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items));
//setListAdapter(new ArrayAdapter<String>(this, R.layout.my_app_row, R.id.text1, items));
setListAdapter(new MyAdapter(this, R.layout.my_app_row, R.id.text1, appList));
} // onCreate 끝
// ArrayAdapter를 상속한 커스텀 어댑터 --> 데이터를 보기좋게 커스터마이징
class MyAdapter extends ArrayAdapter {

public MyAdapter(Context context, int resource, int textViewResourceId,
List objects) {
super(context, resource, textViewResourceId, objects);
}
// 데이터가 화면에 렌더링될 때 호출
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// XML레이아웃 읽어오기
View row = getLayoutInflater().inflate(R.layout.my_app_row, null);
ApplicationInfo info = (ApplicationInfo)getItem(position);
TextView tv1 = (TextView)row.findViewById(R.id.text1);
tv1.setText(info.packageName);
ImageView img = (ImageView)row.findViewById(R.id.img);
img.setImageDrawable(info.loadIcon(getPackageManager()));
return row;
}
}
} // Activity 끝


// SD카드로 파일 입출력
package android.edu;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

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

public class MyReadBin extends Activity {
private final static String BIN_FILE_NAME = "okgosu.txt";// 저장할 파일 이름
private EditText edit_text;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_read_bin);
edit_text = (EditText) findViewById(R.id.edit_text);
Button btn = (Button) findViewById(R.id.btn_close);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();// 액티비티 종료
}
});
}
@Override
protected void onResume() {
super.onResume();
try {
// InputStream in = openFileInput(BIN_FILE_NAME);// okgosu.txt 파일 읽기
File f = new File("/sdcard/okgosu.txt");
InputStream in = new FileInputStream(f);
InputStreamReader ins = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(ins);
String str;
StringBuffer buf = new StringBuffer();
while ((str = reader.readLine()) != null) { // 파일을 1줄씩 처리
buf.append(str + "\n");
}
in.close();
edit_text.setText(buf.toString()); // 에디트텍스트에 내용 설정
} catch (IOException e) {
Log.d("okgosu", BIN_FILE_NAME + "doesn't exist");
}
}
@Override
protected void onPause() {
super.onPause();
try {
// 파일 내용 저장
// OutputStreamWriter out = new OutputStreamWriter(openFileOutput(BIN_FILE_NAME, 0));
File f = new File("/sdcard/okgosu.txt");
if (!f.exists()) f.createNewFile();
OutputStream os = new FileOutputStream(f);
OutputStreamWriter out = new OutputStreamWriter(os);
out.write(edit_text.getText().toString());// 에디트텍스트의 내용을 파일로 출력
out.close();
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
}

[RSS 목록 추출]
package android.edu;
import java.io.StringReader;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class MyRSSReader extends ListActivity {
ArrayList&lt;String&gt; items = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String uri = "http://okgosu.net/zbxe/deveng/rss"; // RSS 주소
HttpClient hc = new DefaultHttpClient();
HttpGet req = new HttpGet(uri);
try {
ResponseHandler&lt;String&gt; res = new BasicResponseHandler();
String resXML = hc.execute(req, res);// RSS XML 리턴
// RSS 구조 rss - channel - item(반복) - title - CDATA:  XML 파싱
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = builder.parse(new InputSource( new StringReader(resXML)));// XML파싱
NodeList list = doc.getElementsByTagName("title"); // title태그 목록 추출
for (int i = 0; i &lt; list.getLength(); i++) {
Element el = (Element) list.item(i);
String data = (String) el.getFirstChild().getNodeValue();
items.add(data);
}
setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, items));
} catch (Exception e) {
e.printStackTrace();
}
}// onCreate 종료
}// ListActivity 종료

[SQLite DB 입력 수정 삭제 조회]
package android.edu;

import android.app.ListActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class MyDBExam extends ListActivity {
Button btn;
EditText ed_prod_code;
EditText ed_prod_name;
MyProdDBHelper dbhelper;
SQLiteDatabase sdb;
String prod_id = "0";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_db_exam);
ed_prod_code = (EditText)findViewById(R.id.ed_prod_code);
ed_prod_name = (EditText)findViewById(R.id.ed_prod_name);
dbhelper = new MyProdDBHelper(MyDBExam.this, 
MyProdDBCons.DB_NAME, null, MyProdDBCons.DB_VERSION); // DB접속
// DB 건수 조회
btn = (Button)findViewById(R.id.btn1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sdb = dbhelper.getReadableDatabase();// SQLite 쓰기모드로 접속
Cursor c = sdb.query(MyProdDBCons.TABLE_NAME, null, null, null, null, null, null);
startManagingCursor(c);
int count = c.getCount(); // 건수
c.close();
sdb.close();
Toast.makeText(MyDBExam.this, "DB건수:" + count, 1000).show();
}
});
// DB쿼리결과를ListView에보여줌
btn = (Button)findViewById(R.id.btn2);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sdb = dbhelper.getReadableDatabase();// SQLite 쓰기모드로 접속
Cursor c = sdb.query(MyProdDBCons.TABLE_NAME, null, null, null, null, null, null); 
startManagingCursor(c);
String[] db_column_arr = new String[]{MyProdDBCons.PROD_CODE, MyProdDBCons.PROD_NAME};
int[] view_id_arr = new int[] {android.R.id.text1, android.R.id.text2};
SimpleCursorAdapter myAdapter = new SimpleCursorAdapter(MyDBExam.this, android.R.layout.simple_list_item_2, c, db_column_arr, view_id_arr );
setListAdapter(myAdapter);
//c.close();
//sdb.close();
}
});
// DB에 데이터 1건 입력
btn = (Button)findViewById(R.id.btn3);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sdb = dbhelper.getWritableDatabase();// SQLite 쓰기모드로 접속
ContentValues values = new ContentValues();
values.put(MyProdDBCons.PROD_CODE, ed_prod_code.getText().toString());
values.put(MyProdDBCons.PROD_NAME, ed_prod_name.getText().toString());
sdb.insert(MyProdDBCons.TABLE_NAME, null, values);
sdb.close();
Toast.makeText(MyDBExam.this, "입력되었습니다", 1000).show();
}
});
// DB에 데이터 1건 수정
btn = (Button)findViewById(R.id.btn4);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sdb = dbhelper.getWritableDatabase();// SQLite 쓰기모드로 접속
String whereClause = MyProdDBCons.PROD_ID+ "= ? ";
String[] whereArgs = {prod_id};
ContentValues values = new ContentValues();
values.put(MyProdDBCons.PROD_CODE, ed_prod_code.getText().toString());
values.put(MyProdDBCons.PROD_NAME, ed_prod_name.getText().toString());
sdb.update(MyProdDBCons.TABLE_NAME, values, whereClause, whereArgs);
sdb.close();
}
});
// DB에 데이터 1건 삭제
btn = (Button)findViewById(R.id.btn5);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sdb = dbhelper.getWritableDatabase();// SQLite 쓰기모드로 접속
String whereClause = MyProdDBCons.PROD_ID+ "= ? ";
String[] whereArgs = {prod_id};
sdb.delete(MyProdDBCons.TABLE_NAME, whereClause, whereArgs);
sdb.close();
}
});
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
prod_id = "" + id;
Cursor c = (Cursor)getListAdapter().getItem(position);
ed_prod_code.setText(c.getString(1));
ed_prod_name.setText(c.getString(2));
}
}

package android.edu;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MyCSVReader extends Activity {
private EditText edit_text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_read_bin);
edit_text = (EditText) findViewById(R.id.edit_text);
Button btn = (Button) findViewById(R.id.btn_close);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();// 액티비티 종료
}
});
}
@Override
protected void onResume() {
super.onResume();
try {
File f = new File("/sdcard/students.csv");
InputStream in = new FileInputStream(f);
InputStreamReader ins = new InputStreamReader(in, "EUC-KR");
BufferedReader reader = new BufferedReader(ins);
String str;
StringBuffer buf = new StringBuffer();
boolean parse_begin = false;
while ((str = reader.readLine()) != null) { // 파일을 1줄씩 처리
StringTokenizer st = new StringTokenizer(str, ",");
int cnt = 0;
while(st.hasMoreTokens()) {
String col = st.nextToken();
if(col.equals("번호")) {
parse_begin = true;
}
cnt++;
if(cnt>2) break;
}
if(parse_begin) {
buf.append(str + "\n");
}
}
in.close();
edit_text.setText(buf.toString()); // 에디트텍스트에 내용 설정
} catch (IOException e) {
e.printStackTrace();
}
}
}


[MyCPExam.java]
package android.edu;

import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

public class MyCPExam extends ListActivity {
Button btn;
EditText ed_prod_code;
EditText ed_prod_name;
String prod_id = "0";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_db_exam);
ed_prod_code = (EditText)findViewById(R.id.ed_prod_code);
ed_prod_name = (EditText)findViewById(R.id.ed_prod_name);
// DB 건수 조회
btn = (Button)findViewById(R.id.btn1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
// DB쿼리결과를ListView에보여줌
btn = (Button)findViewById(R.id.btn2);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
// DB에 데이터 1건 입력
btn = (Button)findViewById(R.id.btn3);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
// DB에 데이터 1건 수정
btn = (Button)findViewById(R.id.btn4);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
// DB에 데이터 1건 삭제
btn = (Button)findViewById(R.id.btn5);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
prod_id = "" + id;
Cursor c = (Cursor)getListAdapter().getItem(position);
ed_prod_code.setText(c.getString(1));
ed_prod_name.setText(c.getString(2));
}
}

[My Prod ContentProvider]
package android.edu;

import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

public class MyProdContentProvider extends ContentProvider {
private MyProdDBHelper mOpenHelper;
private static HashMap&lt;String, String&gt; sNotesProjectionMap;
private static final UriMatcher sUriMatcher; // URI가 해당 CP를 호출하는지를 판별
private static final int CASE_LIST = 1;// 다건처리(조회)
private static final int CASE_ITEM = 2;// 단건처리(입력,수정,삭제)
static {
sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
sUriMatcher.addURI(MyProdDBCons.AUTHORITY, "myprods", CASE_LIST);
sUriMatcher.addURI(MyProdDBCons.AUTHORITY, "myprods/#", CASE_ITEM);
sNotesProjectionMap = new HashMap&lt;String, String&gt;();
sNotesProjectionMap.put(MyProdDBCons.PROD_ID, MyProdDBCons.PROD_ID);
sNotesProjectionMap.put(MyProdDBCons.PROD_CODE, MyProdDBCons.PROD_CODE);
sNotesProjectionMap.put(MyProdDBCons.PROD_NAME, MyProdDBCons.PROD_NAME);
}

@Override
public int delete(Uri uri, String where, String[] whereArgs) {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int count;
switch (sUriMatcher.match(uri)) {
case CASE_LIST:
count = db.delete(MyProdDBCons.TABLE_NAME, where, whereArgs);
break;
case CASE_ITEM:
String prodid = uri.getPathSegments().get(1);
count = db.delete(MyProdDBCons.TABLE_NAME,
MyProdDBCons.PROD_ID
+ "="
+ prodid
+ (!TextUtils.isEmpty(where) ? " AND (" + where
+ ')' : ""), whereArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}

// URI를 매치해서 결과에 맞는 MIME타입을 리턴
@Override
public String getType(Uri uri) {
switch (sUriMatcher.match(uri)) {
case CASE_LIST:
return MyProdDBCons.CONTENT_TYPE;
case CASE_ITEM:
return MyProdDBCons.CONTENT_ITEM_TYPE;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
}

@Override
public Uri insert(Uri uri, ContentValues values_in) {
if (sUriMatcher.match(uri) != CASE_LIST) {
throw new IllegalArgumentException("Unknown URI " + uri);
}
ContentValues values;
if (values_in != null) {
values = new ContentValues(values_in);
} else {
values = new ContentValues();
}
if (values.containsKey(MyProdDBCons.PROD_CODE) == false) {
values.put(MyProdDBCons.PROD_CODE, "DEFAULT");
}
if (values.containsKey(MyProdDBCons.PROD_NAME) == false) {
values.put(MyProdDBCons.PROD_NAME, "");
}
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
long rowId = db.insert(MyProdDBCons.TABLE_NAME, null, values);
if (rowId &gt; 0) {
Uri myProdUri = ContentUris.withAppendedId(
MyProdDBCons.CONTENT_URI, rowId);
getContext().getContentResolver().notifyChange(myProdUri, null);
return myProdUri;
}
throw new SQLException("Failed to insert row into " + uri);
}

@Override
public boolean onCreate() {
mOpenHelper = new MyProdDBHelper(getContext(), null, null, 0);
return false;
}

@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(MyProdDBCons.TABLE_NAME);
switch (sUriMatcher.match(uri)) {
case CASE_LIST:
qb.setProjectionMap(sNotesProjectionMap);
break;
case CASE_ITEM:
qb.setProjectionMap(sNotesProjectionMap);
qb.appendWhere(MyProdDBCons.PROD_ID + "="
+ uri.getPathSegments().get(1));
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
String order_by = MyProdDBCons.PROD_NAME;
SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Cursor c = qb.query(db, projection, selection, selectionArgs, null,
null, order_by);
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}

@Override
public int update(Uri uri, ContentValues values, String where,
String[] whereArgs) {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int count;
switch (sUriMatcher.match(uri)) {
case CASE_LIST:
count = db
.update(MyProdDBCons.TABLE_NAME, values, where, whereArgs);
break;
case CASE_ITEM:
String prodid = uri.getPathSegments().get(1);
count = db.update(MyProdDBCons.TABLE_NAME, values,
MyProdDBCons.PROD_ID
+ "="
+ prodid
+ (!TextUtils.isEmpty(where) ? " AND (" + where
+ ')' : ""), whereArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}

}

[MyCPExam.java]

package android.edu;

import android.app.ListActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class MyCPExam extends ListActivity {
Button btn;
EditText ed_prod_code;
EditText ed_prod_name;
String prod_id = "0";
private static String[] MY_PROJECTION = new String[] {
MyProdDBCons.PROD_ID, MyProdDBCons.PROD_CODE,
MyProdDBCons.PROD_NAME };

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_db_exam);
ed_prod_code = (EditText) findViewById(R.id.ed_prod_code);
ed_prod_name = (EditText) findViewById(R.id.ed_prod_name);
// DB 건수 조회
btn = (Button) findViewById(R.id.btn1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Cursor c = getContentResolver().query(MyProdDBCons.CONTENT_URI,
MY_PROJECTION, null, null, null);
Toast.makeText(MyCPExam.this, "건수:" + c.getCount(), 1000)
.show();
}
});
// DB쿼리결과를ListView에보여줌
btn = (Button) findViewById(R.id.btn2);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Cursor c = getContentResolver().query(MyProdDBCons.CONTENT_URI,
MY_PROJECTION, null, null, null);
startManagingCursor(c);
String[] cols = { MyProdDBCons.PROD_CODE,
MyProdDBCons.PROD_NAME };
int[] view_ids = new int[] { android.R.id.text1,
android.R.id.text2 };

ListAdapter adapter = new SimpleCursorAdapter(MyCPExam.this,
android.R.layout.simple_list_item_2, c, cols, view_ids);

setListAdapter(adapter);
}
});
// DB에 데이터 1건 입력
btn = (Button) findViewById(R.id.btn3);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ContentValues values = new ContentValues();
values.put(MyProdDBCons.PROD_CODE, ed_prod_code.getText()
.toString());
values.put(MyProdDBCons.PROD_NAME, ed_prod_name.getText()
.toString());
getContentResolver().insert(MyProdDBCons.CONTENT_URI, values);
Toast.makeText(MyCPExam.this, "입력되었습니다", 1000).show();
}
});
// DB에 데이터 1건 수정
btn = (Button) findViewById(R.id.btn4);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ContentValues values = new ContentValues();
values.put(MyProdDBCons.PROD_CODE, ed_prod_code.getText()
.toString());
values.put(MyProdDBCons.PROD_NAME, ed_prod_name.getText()
.toString());
String whereClause = MyProdDBCons.PROD_ID + "= ? ";
String[] whereArgs = { prod_id };
getContentResolver().update(MyProdDBCons.CONTENT_URI, values,
whereClause, whereArgs);
Toast.makeText(MyCPExam.this, "업데이트되었습니다", 1000).show();
}
});
// DB에 데이터 1건 삭제
btn = (Button) findViewById(R.id.btn5);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String whereClause = MyProdDBCons.PROD_ID + "= ? ";
String[] whereArgs = { prod_id };
getContentResolver().delete(MyProdDBCons.CONTENT_URI,
whereClause, whereArgs);
Toast.makeText(MyCPExam.this, "삭제되었습니다", 1000).show();
}
});
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
prod_id = "" + id;
Cursor c = (Cursor) getListAdapter().getItem(position);
ed_prod_code.setText(c.getString(1));
ed_prod_name.setText(c.getString(2));
}
}

[Naver Open API 파싱]
package android.edu;

import java.io.StringReader;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

public class MyNaverApi extends ListActivity {
Spinner sp;
EditText ed_search;
ArrayList&lt;String&gt; items = new ArrayList&lt;String&gt;();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_naver_api);
// Spinner에 다음의 데이터가 보이도록 어댑터 설정 
sp = (Spinner)findViewById(R.id.sp);
String[] arr = {"book", "movieman", "shop"};
ArrayAdapter&lt;String&gt; adapter = 
new ArrayAdapter&lt;String&gt;(this, android.R.layout.simple_spinner_item, arr);
sp.setAdapter(adapter);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ed_search = (EditText)findViewById(R.id.ed_search);
Button btn_go = (Button)findViewById(R.id.btn_go);
btn_go.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v) {
     // 호출 URL 설정
     StringBuilder url = new StringBuilder("http://openapi.naver.com/search?");
     url.append("target=" + sp.getSelectedItem().toString());
     url.append("&query=" + ed_search.getText().toString());
     url.append("&key=각자의 네이버 키");
     // HTTP 호출 
      HttpGet req = new HttpGet(url.toString());
      HttpClient hc = new DefaultHttpClient();
      try {
       ArrayList&lt;String&gt; items = new ArrayList&lt;String&gt;();
       ResponseHandler&lt;String&gt; res = new BasicResponseHandler();
       String resStr = hc.execute(req, res);
       DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
       Document doc = builder.parse(new InputSource( new StringReader(resStr)));
       NodeList nl = doc.getElementsByTagName("item");
       for(int i=0; i&lt;nl.getLength(); i++){
           Element el = (Element)nl.item(i);
           String data = el.getElementsByTagName("title").item(0).getFirstChild().getNodeValue();
           items.add(data);
        }
        setListAdapter(new ArrayAdapter&lt;String&gt;(MyNaverApi.this, android.R.layout.simple_list_item_1, items));
    } catch (Exception e) {
        e.printStackTrace();
    }      
     }
});
}
}

// okgosu.net 블로그 새글 확인 로직
[새글 확인]
String uri = "http://okgosu.net/zbxe/deveng/rss"; // RSS 주소
HttpClient hc = new DefaultHttpClient();
HttpGet req = new HttpGet(uri);
try {
      ResponseHandler&lt;String&gt; resHandler = new BasicResponseHandler();
      String resHandlerXML = hc.execute(req, resHandler);// RSS XML 리턴
      DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      Document doc = builder.parse(new InputSource( new StringReader(resHandlerXML)));
      NodeList list = doc.getElementsByTagName("item"); 
      for (int i = 0; i &lt; list.getLength(); i++) {
          Element el = (Element) list.item(i);
          String data = el.getElementsByTagName("pubDate").item(0).getFirstChild().getNodeValue();
          Calendar checkDate = Calendar.getInstance(); 
          checkDate.set(2011, 0, 20);//2011.1.20
          Calendar itemDate = Calendar.getInstance();
          itemDate.setTime(new Date(Date.parse(data)));
          if(itemDate.after(checkDate)) {
         // 2011.1.20 이후의 새글 등록됨 
      res = true;
          }
     }
} catch (Exception e) {
   e.printStackTrace();
}

[현재 위치 정보 조회]
package android.edu;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MyLocationView extends Activity implements LocationListener {
LocationManager locationMgr = null;
Location lastLocation = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_location_view);
final Button start = (Button) findViewById(R.id.start);
final TextView status = (TextView) findViewById(R.id.status);
locationMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
start.setOnClickListener(new View.OnClickListener() { // start 버튼 클릭
public void onClick(View v) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.NO_REQUIREMENT);
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
String best = locationMgr.getBestProvider(criteria, true);
Toast.makeText(MyLocationView.this, best + "설정으로 위치 조회중....", Toast.LENGTH_SHORT).show();
locationMgr.requestLocationUpdates(best, 1000, 0, MyLocationView.this);
// 위치정보 조회 시작 (1초(1000)간격으로 0m 변화 이상)
//-- 위치가 바뀔 때 마다 onLocationChanged 호출
}
});
}
// 위치 변경시 Location 객체의 좌표로 부터 geo: 인텐트 발생
public void onLocationChanged(Location location) { 
final String geoURI = String.format("geo: %f,%f", location.getLatitude(), location.getLongitude());
Toast.makeText(MyLocationView.this, "위치 이동:" + geoURI, Toast.LENGTH_SHORT).show();
Intent map = new Intent(Intent.ACTION_VIEW, Uri.parse(geoURI));
startActivity(map);
}

public void onProviderDisabled(String arg0) { // 프로바이더를 쓸수 없게되었을때
}

public void onProviderEnabled(String provider) { // 프로바이더가 사용가능할 때
}

public void onStatusChanged(String provider, int status, Bundle extras) { // 프로바이더상태변경
}

}





profile