manifast.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gusfree.touchevent"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".TouchEventActivity"
            android:label="@string/app_name" 
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
TouchEventActivity.java
package com.gusfree.touchevent;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

public class TouchEventActivity extends Activity {

	MyView myView;
	float x,y;
	int width,height;
	Bitmap bitmap;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myView = new MyView(this);
        LinearLayout layout = new LinearLayout(this);//배경
        LayoutParams params = 
        		new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);
        layout.setLayoutParams(params);
        layout.setBackgroundColor(Color.WHITE);
        layout.addView(myView);
        setContentView(layout);
        
        WindowManager manager =(WindowManager)getSystemService(WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();
        
        width=display.getWidth();//내 화면의 가로 사이즈
        height=display.getHeight();//내 화면의 세로 사이즈
        x=width/2;//초기값
        y=height/2;
        bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.snoopy);
    }
	
	class MyView extends View{

		public MyView(Context context) {
			super(context);
		}
		
		@Override
		protected void onDraw(Canvas canvas) {
			super.onDraw(canvas);
			
			canvas.drawBitmap(bitmap,x,y,null);
		}
	}
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		x=ev.getRawX();
		y=ev.getRawY();
		
		myView.postInvalidate();//다시 그려라
		return super.dispatchTouchEvent(ev);
	}
}  



'Android > 2012.04월 강좌' 카테고리의 다른 글

11일차 Weather (SAX parser)  (0) 2012.05.10
11일차 Samples for SDK 사용하기  (0) 2012.05.10
10일차 Login  (0) 2012.05.09
10일차 TabView  (0) 2012.05.09
10일차 PullParser  (1) 2012.05.09
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
	
	<!-- 예약어@android:id/tabhost -->

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <TabHost
        android:id="@android:id/tabhost"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >
            </TabWidget>

            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="match_parent"
                android:layout_height="match_parent" >

                <LinearLayout
                    android:id="@+id/tab1"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" >

                    <AnalogClock
                        android:layout_width="100dp"
                        android:layout_height="100dp" />
                </LinearLayout>

                <LinearLayout
                    android:id="@+id/tab2"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" >

                    <DigitalClock
                        android:layout_width="100dp"
                        android:layout_height="100dp" />
                </LinearLayout>

                <LinearLayout
                    android:id="@+id/tab3"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" >

                    <Chronometer
                        android:layout_width="100dp"
                        android:layout_height="100dp" />
                </LinearLayout>
            </FrameLayout>
        </LinearLayout>

    </TabHost>

</LinearLayout>
sub.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >

        <requestFocus />

    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPassword" />


    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Auto Login" />


    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

</LinearLayout>
manifast.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gusfree.tapview"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".TapViewActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="SubActivity"></activity>
    </application>

</manifest>
TabActivity.java
package com.gusfree.tapview;

import android.app.TabActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.AnalogClock;
import android.widget.TabHost;
import android.widget.TextView;

public class TapViewActivity extends TabActivity {

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //@android:id/tabhost
        //탭위젯에다가 제목등을 셋팅하고,
        //각각의 탭위젯과 LinearLayout을 연결해주기
        
        //1. TabHost를 불러오자 @android:id/tabhost
        //TabActivity 상속 받아서 가능한 메서드 
        TabHost tabHost = getTabHost();
        
        TabHost.TabSpec spec1 =tabHost.newTabSpec("태그1");
        TabHost.TabSpec spec2 =tabHost.newTabSpec("태그2");
        TabHost.TabSpec spec3 =tabHost.newTabSpec("태그3");
        TabHost.TabSpec spec4 =tabHost.newTabSpec("태그3");
        
        spec1.setIndicator("첫번째 스펙");
        spec2.setIndicator("",getResources().getDrawable(R.drawable.red));
        spec3.setIndicator(new AnalogClock(this));
        spec4.setIndicator("네번째");
        
        spec1.setContent(R.id.tab1);
        spec2.setContent(R.id.tab2);
        spec3.setContent(R.id.tab3);
        Intent intent =new Intent();
        intent.setClass(this,SubActivity.class);
        spec4.setContent(intent);
        
        tabHost.addTab(spec1);
        tabHost.addTab(spec2);
        tabHost.addTab(spec3);
        tabHost.addTab(spec4); 
        
        SharedPreferences pref=getSharedPreferences("login", MODE_PRIVATE);
        
        String id = pref.getString("id","noname");
        ((TextView)findViewById(R.id.textView1)).setText("안녕하세요! "+id+ "님");
    }
} 
SubActivity.java
package com.gusfree.tapview;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;

public class SubActivity extends Activity{
	
	EditText editText1,editText2;
	CheckBox checkbox;
	SharedPreferences preference;//공유 환경 변수
	
	@Override
	protected void onStart() {

		super.onStart();
		preference = getSharedPreferences("login", this.MODE_PRIVATE);
		
		setContentView(R.layout.sub);
		editText1=(EditText) findViewById(R.id.editText1);
		editText2=(EditText) findViewById(R.id.editText2);
		checkbox=(CheckBox) findViewById(R.id.checkBox1);
		
		findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				String id = editText1.getText().toString();
				String pw = editText2.getText().toString();
				boolean auto =checkbox.isChecked();
				
				Editor editor =preference.edit();//환경변수 에디트하기
				editor.putString("id", id);
				editor.putString("pw", pw);
				editor.putBoolean("auto",auto);
				
				editor.commit(); //save
				/*어플 지울 때까지 날아가지 않고 저장 됩니다.*/				
			}
		});
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		Log.i("onPause","onPause");
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		Log.i("onStop","onStop");
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.i("onDestroy","onDestroy");
	}
}

editText에 아이디랑 비번을 적으면 DDMS에 값이 저장이 된다.



저장된 값이 TextView에 자동으로 호출이된다.




'Android > 2012.04월 강좌' 카테고리의 다른 글

11일차 Samples for SDK 사용하기  (0) 2012.05.10
10일차 TouchEvent  (0) 2012.05.09
10일차 TabView  (0) 2012.05.09
10일차 PullParser  (1) 2012.05.09
10일차 XMLParser  (0) 2012.05.09


main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
	
	<!-- 예약어@android:id/tabhost -->
    <TabHost
        android:id="@android:id/tabhost"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >
            </TabWidget>

            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="match_parent"
                android:layout_height="match_parent" >

                <LinearLayout
                    android:id="@+id/tab1"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" >

                    <AnalogClock
                        android:layout_width="100dp"
                        android:layout_height="100dp" />
                </LinearLayout>

                <LinearLayout
                    android:id="@+id/tab2"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" >

                    <DigitalClock
                        android:layout_width="100dp"
                        android:layout_height="100dp" />
                </LinearLayout>

                <LinearLayout
                    android:id="@+id/tab3"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" >

                    <Chronometer
                        android:layout_width="100dp"
                        android:layout_height="100dp" />
                </LinearLayout>
            </FrameLayout>
        </LinearLayout>

    </TabHost>

</LinearLayout>
sub.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <RatingBar
        android:id="@+id/ratingBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ExpandableListView
        android:id="@+id/expandableListView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ExpandableListView>

</LinearLayout>
manifast.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gusfree.tapview"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".TapViewActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="SubActivity"></activity>
    </application>

</manifest>
TapViewActivity.java
package com.gusfree.tapview;

import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.AnalogClock;
import android.widget.TabHost;

public class TapViewActivity extends TabActivity {

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //@android:id/tabhost
        //탭위젯에다가 제목등을 셋팅하고,
        //각각의 탭위젯과 LinearLayout을 연결해주기
        
        //1. TabHost를 불러오자 @android:id/tabhost
        //TabActivity 상속 받아서 가능한 메서드 
        TabHost tabHost = getTabHost();
        
        TabHost.TabSpec spec1 =tabHost.newTabSpec("태그1");
        TabHost.TabSpec spec2 =tabHost.newTabSpec("태그2");
        TabHost.TabSpec spec3 =tabHost.newTabSpec("태그3");
        TabHost.TabSpec spec4 =tabHost.newTabSpec("태그3");
        
        spec1.setIndicator("첫번째 스펙");
        spec2.setIndicator("",getResources().getDrawable(R.drawable.red));
        spec3.setIndicator(new AnalogClock(this));
        spec4.setIndicator("네번째");
        
        spec1.setContent(R.id.tab1);
        spec2.setContent(R.id.tab2);
        spec3.setContent(R.id.tab3);
        Intent intent =new Intent();
        intent.setClass(this,SubActivity.class);
        spec4.setContent(intent);
        
        tabHost.addTab(spec1);
        tabHost.addTab(spec2);
        tabHost.addTab(spec3);
        tabHost.addTab(spec4);
    }
}
SubActivity.java
package com.gusfree.tapview;

import android.app.Activity;

public class SubActivity extends Activity{
	
	@Override
	protected void onStart() {

		super.onStart();
		setContentView(R.layout.sub);
	}
}



'Android > 2012.04월 강좌' 카테고리의 다른 글

10일차 TouchEvent  (0) 2012.05.09
10일차 Login  (0) 2012.05.09
10일차 PullParser  (1) 2012.05.09
10일차 XMLParser  (0) 2012.05.09
10일차 BroadcastReceiver  (0) 2012.05.09


main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>
item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <TextView
        android:tag="hi"
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" 
        android:background="#99dd99"/>

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

</LinearLayout>
test.xml
<?xml version="1.0" encoding="UTF-8"?>
<test>
	<item>
	    <name>치킨</name>
	    <price>15000</price>
	    <location>묵동</location>
	    <market>페리카나</market>
	    <image></image>
	</item>
	
	<item>
	    <name>토스트</name>
	    <price>1600</price>
	    <location>묵동</location>
	    <market>이삭토스트</market>
	    <image>http://png-2.findicons.com/files//icons/2010/free_food/128/bread1.png</image>
	</item>
	
	<item>
	    <name>피자</name>
	    <price>8000</price>
	    <location>묵동</location>
	    <market>피자스쿨</market>
	    <image>http://png-5.findicons.com/files//icons/342/food/128/pizza_slice.png</image>
	</item>
</test>
manifast.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.xmlparserexercise"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".PullParserActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
PullParserActivity.xml
package com.xmlparserexercise;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import android.app.Activity;
import android.content.res.XmlResourceParser;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;


public class PullParserActivity extends Activity{

	ListView listView;
	//Item을 담을 Collection
	ArrayList<Item> list=new ArrayList<Item>();

	@Override
	protected void onResume() {
		super.onResume();
		setContentView(R.layout.main);
		listView=(ListView) findViewById(R.id.listView1);

		//  res/xml/test.xml를 읽는 parser호출
		XmlResourceParser parser =getResources().getXml(R.xml.test);
		try{
			int eventType =parser.getEventType();
			/* START_DOCUMENT = 0
			 * END_DOCUMENT = 1
			 * START_TAG = 2
			 * END_TAG = 3
			 * TEXT = 4*/		
			String name="";
			String price="";
			String image="";
			String tag="";
			String text="";

			boolean isEnd=true;
			while(isEnd){
				switch(eventType){
				case 0:		//START_DOCUMENT = 0
					Log.e("START_DOCUMENT","START_DOCUMENT"+parser.getName());
					break;

				case 1:		//END_DOCUMENT = 1
					Log.e("END_DOCUMENT","END_DOCUMENT"+parser.getName());
					isEnd=false;
					break;

				case 2:		//START_TAG = 2
					Log.i("START_TAG","START_TAG"+parser.getName());
					break;

				case 3:		//END_TAG = 3
					Log.w("END_TAG","END_TAG"+parser.getName());
					//....떡볶이</
					if(parser.getName().equals("name")){
						name=text;
						//2000</price>	
					}else if(parser.getName().equals("price")){
						price=text;//name="떡볶이" price="2000" 완성됨
						Item item = new Item(name,price);//객체 생성
						
					}else if(parser.getName().equals("image")){
						image=text;
						Item item = new Item(name,price,image);
						list.add(item);
					}
					break;

				case 4:		//TEXT = 4
					Log.d("TEXT","TEXT"+parser.getName());
					text=parser.getText();
					break;
				}
				eventType=parser.next();//다음으로 이동
			}//while문 끝

			MyAdapter adapter= new MyAdapter();
			listView.setAdapter(adapter);

		}catch(Exception e){

		}
	}
	class MyAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			return list.size();
			//return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int position, View arg1, ViewGroup arg2) {
			/* item.xml을 불러와서 이 안에 있는 TextView에
			 * Collection안에 들은 Item객체의 값을 셋팅하고
			 * Item.xml을 retrun하기*/

			LinearLayout layout=
					(LinearLayout)View.inflate(getApplicationContext(), R.layout.item, null);
			Item oneItem = list.get(position);

			//layout에서 textView를 찾아서 findViewById
			//oneItem의 필드값으로 셋팅하기
			TextView tv1 = (TextView)layout.findViewById(R.id.textView1);
			TextView tv2 = (TextView)layout.findViewWithTag("hi");
			ImageView imgV=(ImageView)layout.findViewById(R.id.imageView1);
			
			tv1.setText(oneItem.name);
			tv2.setText(oneItem.price);
			
			if(oneItem.image!=null){
				try {
					URL url=new URL(oneItem.image);
					try {
						InputStream is=url.openStream();
						Bitmap bitmap =BitmapFactory.decodeStream(is);
						imgV.setImageBitmap(bitmap);
					} catch (IOException e) {
						e.printStackTrace();
					}
				} catch (MalformedURLException e) {
					e.printStackTrace();
				}
			}
			
			return layout;
		}
	}
	class Item{//innerClass XML의 한단위에 해당
		String name="";
		String price="";
		String image="";
		
		public Item(String n,String p){
			name=n;
			price=p;
		}
		
		//생성자 오버로딩,다양성
		public Item(String n,String p,String i){
			name=n;
			price=p;
			image=i;
		}
	}
}



'Android > 2012.04월 강좌' 카테고리의 다른 글

10일차 Login  (0) 2012.05.09
10일차 TabView  (0) 2012.05.09
10일차 XMLParser  (0) 2012.05.09
10일차 BroadcastReceiver  (0) 2012.05.09
10일차 Alarm  (0) 2012.05.09

test.xml
<?xml version="1.0" encoding="UTF-8"?>
<test>
    <!-- data: 하루의 날씨 정보를 갖는다. -->
    <data>
        <day>0</day>
        <high>26</high>
        <low>10</low>
    </data>
    <data>
        <day>1</day>
        <high>30</high>
        <low>15</low>
    </data>
    <data>
        <day>2</day>
        <high>36</high>
        <low>20</low>
    </data>
</test>
XMLParserExerciseActivity.java
package com.xmlparserexercise;

import android.app.Activity;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class XMLParserExerciseActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		Resources res =getResources();//  res/xml/test.xml
		XmlResourceParser parser =res.getXml(R.xml.test);
		TextView textView=new TextView(this);
		
		try {
			int eventType = parser.getEventType();
			StringBuilder sb=new StringBuilder();
			
			while(eventType != XmlResourceParser.END_DOCUMENT){
				//<day>만났을 때
				if(eventType==XmlResourceParser.START_TAG){
					String tagName=parser.getName();
					sb.append(tagName); //day를 붙이기
				}
				//<day>2</day>
				if(eventType==XmlResourceParser.TEXT){
					String text=parser.getText();
					Log.i("Text", "text= "+text);
					sb.append(text+"\n"); //2를 붙이기
				}
				eventType = parser.next();
			}
			textView.setText(sb.toString());
			setContentView(textView);
		} catch (Exception e) {	
		}
	}
}  



'Android > 2012.04월 강좌' 카테고리의 다른 글

10일차 TabView  (0) 2012.05.09
10일차 PullParser  (1) 2012.05.09
10일차 BroadcastReceiver  (0) 2012.05.09
10일차 Alarm  (0) 2012.05.09
9일차 ViewFlipper  (0) 2012.05.08
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="알람시작" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="알람종료" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="방송보내기" />

</LinearLayout>
manifast.xml



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gusfree.alarm"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".AlarmManagerActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name="ToastActivity"></service>
        <receiver android:name="Antena">
            <intent-filter>
                <action android:name="gusfree.tistory.com"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>
AlarmManagerActivity.java
package com.gusfree.alarm;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;

public class AlarmManagerActivity extends Activity implements OnClickListener{
	
	AlarmManager manager;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        findViewById(R.id.button1).setOnClickListener(this);
        findViewById(R.id.button2).setOnClickListener(this);
        findViewById(R.id.button3).setOnClickListener(this);
        
        manager=(AlarmManager) getSystemService(ALARM_SERVICE);
    }

	@Override
	public void onClick(View v) {
		Intent intent=new Intent();
		//intent.setClass(this, ToastActivity.class);
		//intent.putExtra("msg", "강의 시작합니다~");
		
		PendingIntent operation=
				PendingIntent.getService(this, 0, intent, 0);
		
		
		PendingIntent.getBroadcast(this, 0, intent, 0);
		
		switch(v.getId()){
		case R.id.button1:
			//알람 매니저 언제 어떤 동작을 실행해라
			long now=SystemClock.elapsedRealtime();
			//(int type,long triggerAtTime,long interval,PendingIntent operation)
			manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
					now+5000, 5000, operation);
			break;
		
		case R.id.button2:
			manager.cancel(operation);
			break;
		
		case R.id.button3://방송보내기
			Intent intent2 =new Intent();
			//주파수
			intent2.setAction("gusfree.tistory.com");
			intent2.putExtra("msg", "강의 시작~~");
			sendBroadcast(intent2);
			break;
		
		
		}
	}
}
Antena.java
package com.gusfree.alarm;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class Antena extends BroadcastReceiver {

	@Override
	public void onReceive(Context arg0, Intent intent) {
		String msg=intent.getStringExtra("msg");
		
		Toast.makeText(arg0,"방송내용 "+msg,0).show();
		
	}
}



'Android > 2012.04월 강좌' 카테고리의 다른 글

10일차 PullParser  (1) 2012.05.09
10일차 XMLParser  (0) 2012.05.09
10일차 Alarm  (0) 2012.05.09
9일차 ViewFlipper  (0) 2012.05.08
9일차 LifeCycle  (0) 2012.05.08
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="알람시작" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="알람종료" />

</LinearLayout>
manifast.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gusfree.alarm"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".AlarmManagerActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name="ToastActivity"></service>
    </application>

</manifest>
AlarmManagerActivity.java
package com.gusfree.alarm;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;

public class AlarmManagerActivity extends Activity implements OnClickListener{
	
	AlarmManager manager;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        findViewById(R.id.button1).setOnClickListener(this);
        findViewById(R.id.button2).setOnClickListener(this);
        
        manager=(AlarmManager) getSystemService(ALARM_SERVICE);
    }

	@Override
	public void onClick(View v) {
		Intent intent=new Intent();
		intent.setClass(this, ToastActivity.class);
		
		PendingIntent operation=
				PendingIntent.getService(this, 0, intent, 0);
		
		switch(v.getId()){
		case R.id.button1:
			//알람 매니저 언제 어떤 동작을 실행해라
			long now=SystemClock.elapsedRealtime();
			//(int type,long triggerAtTime,long interval,PendingIntent operation)
			manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
					now+5000, 5000, operation);
			break;
		
		case R.id.button2:
			manager.cancel(operation);
			break;
		}
	}
}
package com.gusfree.alarm;

import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;

public class ToastActivity extends Service{

	
	@Override
	public void onCreate() {
		super.onCreate();
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
		Toast.makeText(getApplicationContext(), "알람실행", 0).show();
		super.onStart(intent, startId);
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		
		return null;
	}
}




'Android > 2012.04월 강좌' 카테고리의 다른 글

10일차 XMLParser  (0) 2012.05.09
10일차 BroadcastReceiver  (0) 2012.05.09
9일차 ViewFlipper  (0) 2012.05.08
9일차 LifeCycle  (0) 2012.05.08
9일차 SQLite 연동하기(naver 메모장)  (0) 2012.05.08
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
	
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />
    
    <ViewFlipper
        android:id="@+id/viewFlipper1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        
        <ImageView 
            android:layout_width="200dp"
       		android:layout_height="200dp"
       		android:src="@drawable/red"
            />
        <ImageView 
            android:layout_width="200dp"
       		android:layout_height="200dp"
       		android:src="@drawable/yellow"
            />
        <ImageView 
            android:layout_width="200dp"
       		android:layout_height="200dp"
       		android:src="@drawable/blue"
            />
        <ImageView 
            android:layout_width="200dp"
       		android:layout_height="200dp"
       		android:src="@drawable/black"
            />
        
    </ViewFlipper>

</LinearLayout>
FlipperActivity.java
package com.gusfree.viewflipper;

import android.app.Activity;
import android.graphics.drawable.TransitionDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.ViewFlipper;

public class ViewFlipperActivity extends Activity {
	ViewFlipper flip;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		flip=(ViewFlipper)findViewById(R.id.viewFlipper1);

		TranslateAnimation ani1=new TranslateAnimation(0, 320, 100, 100);
		ani1.setDuration(1000);

		Animation utils1=AnimationUtils.makeInAnimation(this, true);
		Animation utils2=AnimationUtils.makeOutAnimation(this, true);

		flip.setInAnimation(utils1); 
		flip.setInAnimation(utils2); 


		Listener listener=new Listener();
		findViewById(R.id.button1).setOnClickListener(listener);
		findViewById(R.id.button2).setOnClickListener(listener);
	}

	class Listener implements OnClickListener{

		@Override
		public void onClick(View v) {
			if(v.getId()==R.id.button1){
				flip.startFlipping();
			}else{
				flip.stopFlipping();
			}

		}

	}
}


맥에서 실행 시켜본 이클립스~~~ 저 이미지가 바뀌면선 오른쪽으로 움직인다~~



'Android > 2012.04월 강좌' 카테고리의 다른 글

10일차 BroadcastReceiver  (0) 2012.05.09
10일차 Alarm  (0) 2012.05.09
9일차 LifeCycle  (0) 2012.05.08
9일차 SQLite 연동하기(naver 메모장)  (0) 2012.05.08
9일차 복습  (0) 2012.05.08



main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left"
        android:text="Main" />

</LinearLayout>
sub.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:text="Sub" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:orientation="horizontal">
    </LinearLayout>

</LinearLayout>
manifast.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gusfree.lifecycle"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".LifeCycleActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="SubActivity"></activity>
    </application>

</manifest>

LifeCycleActivity.java

package com.gusfree.lifecycle;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

public class LifeCycleActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.i ("onCreate","onCreateMAIN");
		setContentView(R.layout.main);
		findViewById(R.id.button1).setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0){
				startActivity(new Intent(
						getApplicationContext(),SubActivity.class));					
			}        			
		});       
	}

	@Override
	protected void onStart() {
		Log.i ("onStart","onStartMAIN");
		super.onStart();
	}

	@Override
	protected void onResume() {
		Log.i ("onResume","onResumeMAIN");
		super.onResume();
	}

	@Override
	protected void onPause() {
		Log.i ("onPause","onPauseMAIN");
		super.onPause();
	}

	@Override
	protected void onStop() {
		Log.i ("onStop","onStopMAIN");
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		Log.i ("onDestroy","onDestroyMAIN");
		super.onDestroy();
	}

	@Override
	protected void onRestart() {
		Log.i ("onRestart","onRestartMAIN");
		super.onRestart();
	}
}

SubActivity.java

package com.gusfree.lifecycle;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

public class SubActivity extends Activity{

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.sub);
		findViewById(R.id.button1).setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				finish(); 			
			}
		});  
	}


	@Override
	protected void onStart() {
		Log.w ("onStart","onStartSUB");
		super.onStart();
	}

	@Override  
	protected void onResume() {
		Log.w ("onResume","onResumeSUB");
		super.onResume();
	}

	@Override
	protected void onPause() {
		Log.w ("onPause","onPauseSUB");
		super.onPause();
	}

	@Override
	protected void onStop() {
		Log.w ("onStop","onStopSUB");
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		Log.w ("onDestroy","onDestroySUB");
		super.onDestroy();
	}

	@Override
	protected void onRestart() {
		Log.w ("onRestart","onRestartSUB");
		super.onRestart();
	}
}


LogCat을 보세요~~


'Android > 2012.04월 강좌' 카테고리의 다른 글

10일차 Alarm  (0) 2012.05.09
9일차 ViewFlipper  (0) 2012.05.08
9일차 SQLite 연동하기(naver 메모장)  (0) 2012.05.08
9일차 복습  (0) 2012.05.08
8일차 Google Map 2  (0) 2012.05.07

- DataBase 

  1. 연다 2. 넣는다 3. 닫는다 


  1. 문연다. 2. 나간다. 3. 문 닫는다.


  파일 입출력

  1. 인풋스트림을 얻는다. 2. 읽는다. 3. 닫는다.


- 자바 JDBC - 1. 드라이버을 로딩한다. 

              2. 연결한다. (Connection)

              3. 데이터를 주고 받는다.

- 안드로이드 SQLite - SQLiteOpenHelper class 


SQLite는 Oracle이나 MS-SQL 처럼 무겁지 않으며, 아주 가볍고 빠르고, 간결한 db 엔진이다.

 

DDMS -> File Explorer -> data -> data -> 응용 패키지 이름 -> databases -> 이 곳에 위치

예) data/data/com.android.email/databases/EmailProvider.db

 

1. ADB Shell 띄우고, SQLite3 실행 및 데이터베이스 연결하기

   sqlite> 이 곳에서 테이블 생성, 데이타 수정, 삽입, 삭제 등이 가능하다.

[ADB Shell 띄우기]

C:\Documents and Settings\XNOTE> adb -s emulator-5554 shell
(에뮬레이터를 띄운 상태라면)adb shell
sqlite3 /data/data/com.android.email/databases/EmailProvider.db
sqlite3 /data/data/com.android.email/databases/EmailProvider.db
SQLite version 3.5.9
Enter ".help" for instructions
sqlite> .help
.help
.bail ON|OFF           Stop after hitting an error.  Default OFF
.databases             List names and files of attached databases
.dump ?TABLE? ...      Dump the database in an SQL text format
.echo ON|OFF           Turn command echo on or off
 .................... (생략)

 

[SQLite 명령 프롬프트 나가기]

sqlite> .quit

sqlite> .exit

 

[사용가능한 DB 확인]

sqlite> .databases
.databases
seq  name             file
---  ---------------  ----------------------------------------------------------
0    main             /data/data/com.android.email/databases/EmailProvider.db

 

 

[사용가능한 테이블 확인]

sqlite> .tables
.tables
Account           HostAuth          Message           Message_Updates
Attachment        Mailbox           Message_Deletes   android_metadata

 

[DB 스키마와 자료 Export]

sqlite>  .output /data/local/tmp/dump.sql 
.output /data/local/tmp/dump.sql

Tip! local/temp 폴더는 읽고, 쓰기가 가능한 디렉토리이다.

 

[SQL 스크립트 덤프하기]

테이블 이름을 지정하면 해당 테이블의 스크립트만 생성. 지정하지 않으면 전체 db sql 스크립트 생성

sqlite> .output /data/local/tmp/dump.sql
.output /data/local/tmp/dump.sql
sqlite> .dump Account
.dump Account
sqlite> .output stdout
.output stdout

- 아래 그림과 같이 local/tmp/dump.sql 파일에 SQL 스크립트가 생성

 




main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:text="메모 추가하기" />

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>
sub.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:text="뒤로가기" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:orientation="horizontal">

        <Button
            android:id="@+id/button3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="수정/입력" />

        <Button
            android:id="@+id/button2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
           android:layout_weight="1"
            android:text="취소" />

        <Button
            android:id="@+id/button4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="지우기" />
    </LinearLayout>

</LinearLayout>
manifast.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gusfree.sqlite"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".SQLiteActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- 등록하지 않으면 Activity not found error -->
        <activity android:name=".SubActivity"></activity>
    </application>

</manifest>
item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

</LinearLayout>
SQLiteActivity.java
package com.gusfree.sqlite;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class SQLiteActivity extends Activity {
	ListView listView;
	Helper helper;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		listView=(ListView)findViewById(R.id.listView1);
		helper=new Helper(getApplicationContext(),"memojang.db", null, 1); 
		helper.open();

		findViewById(R.id.button1).setOnClickListener(
				new OnClickListener(){

					@Override
					public void onClick(View arg0) {
						Intent intent=new Intent();
						intent.setClass(getApplicationContext(),SubActivity.class);
						startActivity(intent); //이동					
					}
				});        
	}

	@Override //다른 액티비티를 갖다오면 실행된다 
	protected void onResume() {

		super.onResume();
		//cursor안에 정보가 담겨있다.
		Cursor cursor=helper.selectAll();

		//커서안의 정보를 한줄씩 빼서 item.xml에 셋팅하고
		//결국 listView전부 보여지도록
		if(cursor!=null){
			String[] from={"_id","memo","time"};
			int[] to={R.id.textView1,R.id.textView2,R.id.textView3};
			SimpleCursorAdapter adapter= 
					new SimpleCursorAdapter(this, R.layout.item, cursor, from, to);

			listView.setAdapter(adapter);
			listView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int postion,
						long arg3) {
					Cursor cursor=helper.select(postion+1);
					Intent intent = new Intent();
					intent.setClass(SQLiteActivity.this, SubActivity.class);
					
					if(cursor.moveToNext()){
						String id =cursor.getString(0);
						String memo =cursor.getString(1);
						String time =cursor.getString(2);
						
						intent.putExtra("id", id);
						intent.putExtra("memo", memo);
						intent.putExtra("time", time);
						Log.w("커서 읽기","memo= "+memo);
					}
					
					cursor.close();
					startActivity(intent);
				}
			});
		}else Toast.makeText(this, "데이터가 없습니다.", 0).show();
	}
}  


SubActivity.java
package com.gusfree.sqlite;

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

public class SubActivity extends Activity implements android.view.View.OnClickListener{

	EditText editText;
	Helper helper;
	Intent theIntent;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sub);
		
		editText =(EditText) findViewById(R.id.editText1);
		findViewById(R.id.button1).setOnClickListener(this);
		findViewById(R.id.button2).setOnClickListener(this);
		findViewById(R.id.button3).setOnClickListener(this);
		findViewById(R.id.button4).setOnClickListener(this);
		helper =
			new Helper(getApplicationContext(), "memojang.db", null, 1);
		helper.open();
		
		theIntent= getIntent();
		String memo =theIntent.getStringExtra("memo");
		if(memo!=null){
			editText.setText(memo);
		}
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.button1 ://뒤로가기
			finish();//activity를 종료시켜라
			break;
			
		case R.id.button2 ://입력&수정
			String id =theIntent.getStringExtra("id");
			Log.e("id","id= "+id);
			if(id==null){//새글쓰기
				String memo=editText.getText().toString().trim();
				helper.insert(memo);
			}else{
				//글수정 - 업데이트
				String memo =editText.getText().toString().trim();
				helper.update(id,memo);
			}
			break;
			
		case R.id.button3 ://취소
			finish();
			break;
			
		case R.id.button4 ://지우기
			id=theIntent.getStringExtra("id");
			helper.delete(id);
			break;
		}
	}
}



Helper.java
package com.gusfree.sqlite;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class Helper extends SQLiteOpenHelper{

	SQLiteDatabase myDb;
	String table="memojang";
	
	public Helper(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
		
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		String sql=
		"CREATE TABLE memojang (_id INTEGER PRIMARY KEY AUTOINCREMENT,memo TEXT, time TEXT); ";
		db.execSQL(sql);		
	}
	
	public void open(){
		// 읽고 쓸 수 있는 db 얻기
		myDb= this.getWritableDatabase(); 
		//this.getReadableDatabase(); //읽을 수만 있는
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		
	}

	public void insert(String memo) { //db에 insert시키기
		
		SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
		String time = sdf.format(new Date());
		
		String sql="INSERT INTO memojang (memo, time) values (?, ?);";
		
		// ? ,? 에 해당하는 값을 넣는다
		Object[] bindArgs={memo, time } ;  
		myDb.execSQL(sql, bindArgs);
		
		Log.i("insert","insertOK"); 
		
		
		/*Calendar cal=Calendar.getInstance();
		int month=cal.get(Calendar.DAY_OF_MONTH);
		int hour=cal.get(Calendar.HOUR_OF_DAY);
		int minute=cal.get(Calendar.MINUTE);*/
		
		/* 비추천 */
		/*String sql="INSERT INTO memojang "
			       +"(memo, time) values ("
			       +memo + ", "+ time
			       +") ;";
		myDb.execSQL(sql);*/
	}
	
	public Cursor selectAll(){
		
		//1. 테이블이름 2. 원하는 컬럼명 3. 원하는 조건 
		// 4. 조건에 해당하는 값 5. groupBy 6. Having 7. 정렬
		/*myDb.query(	"memojang", new String[]{"memo","time"},
		"_id<?", new String[]{10},null,null,null); */
		Cursor cursor=
		myDb.query(	"memojang", null,null,null,null,null,null);
		return cursor;
	}
	
	public Cursor select(int no){
		Cursor cursor =
		myDb.query("memojang", null, "_id=?", 
				new String[]{String.valueOf(no)},//int->String
				null,null,null);
		return cursor;
	}

	public void update(String id, String newMemo) {
		
		ContentValues values=new ContentValues();
		// "memo"컬럼의 내용을 newMemo값으로 바꾸겠다 
		values.put("memo", newMemo);

		String[] whereArgs={id};		
 		int update=myDb.update("memojang", values,"_id=?", whereArgs);

 		Log.i("수정","수정된 row수는 ? "+ update);		
	}

	public void delete(String id) {
		//myDb.delete(table, "_id=?", new String[]{id});
		
		//String sql="DELETE FROM memojang where _id=?"+id;
		//myDb.execSQL(sql);	
		
		String sql="DELETE FROM memojang where _id=?";
		myDb.execSQL(sql,new String[]{id});
	}
}




실행하면 memojang.db가 생성된다.







'Android > 2012.04월 강좌' 카테고리의 다른 글

9일차 ViewFlipper  (0) 2012.05.08
9일차 LifeCycle  (0) 2012.05.08
9일차 복습  (0) 2012.05.08
8일차 Google Map 2  (0) 2012.05.07
8일차 GoogleMap  (0) 2012.05.07
- 구글맵 

  googleAPI 로 프로젝트 생성
  .android/debug.keystore 안의 MD5 : 

  layout.xml 
    <android......MapView>
    Permission : internet, gooleMap 
    MapActivity를 상속해서 만들어야 함. 

  LocationManager를 호출해서 나의 마지막으로
  알려진 위치를 얻을 수 있다. 위도/경도  
  23.345623457 / 38.3421234 
  234686542 / 392345123
      


- Activity , Service(음악재생) 
  Intent intent=new Intent();
  intent.setClass(this, 서비스클래스.class);

  startService(인텐트); // -> onStart() 호출
  stopService(인텐트);  // -> onDestroy() 호출
  서비스클래스 extends Service  {
     onStart(){

     }

     onDestroy(){

     }
  }


- 입출력(대상 : File) 
  입력 : 
  inputStream 얻어서 File.openStrea()/// 
  this.openStream();
   while ( (int k =is.read() )!= -1) {
         배열.append(k)
   }
   배열 -> String 형변환해서 화면에 출력 
  출력 : 화면에 출력, 파일에 저장
  setText().. print()... 

  FileOutputStream fos...
   fos.write(배열);  
   fos.flush();     
   fos.close();   

  - 파일을 읽어오기
   File file=new File("c:\\abc.txt");  
   FileInputStream fis=new FileInputStream(file);
   while(    fis.read() ) {

   }


'Android > 2012.04월 강좌' 카테고리의 다른 글

9일차 LifeCycle  (0) 2012.05.08
9일차 SQLite 연동하기(naver 메모장)  (0) 2012.05.08
8일차 Google Map 2  (0) 2012.05.07
8일차 GoogleMap  (0) 2012.05.07
8일차 Google Key 인증  (0) 2012.05.07
package com.googlemap;

import android.os.Bundle;
import android.view.MotionEvent;

import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

public class GoogleMapActivity extends MapActivity {

	MapView map;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		map=(MapView) findViewById(R.id.map);

		//지도 사이즈 조절하기
		map.setBuiltInZoomControls(true);

		MapController controller =map.getController();

		//최초의 확대 배율
		controller.setZoom(5);//1~21
	}
	boolean satel=true;
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if(event.getAction()==MotionEvent.ACTION_DOWN &&event.getRawY()<100){
			map.setSatellite(satel);//위성지도 <->일반지도
			satel=!satel;
		}
		return super.onTouchEvent(event);
	}
	@Override
	protected boolean isRouteDisplayed() {

		return false;
	}
}




'Android > 2012.04월 강좌' 카테고리의 다른 글

9일차 SQLite 연동하기(naver 메모장)  (0) 2012.05.08
9일차 복습  (0) 2012.05.08
8일차 GoogleMap  (0) 2012.05.07
8일차 Google Key 인증  (0) 2012.05.07
8일차 Service 2(음악 파일 재생)  (0) 2012.05.07










avd를 구글 api용으로 다시 만들어준다.




main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <com.google.android.maps.MapView
        android:id="@+id/map"
        android:clickable="true"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:apiKey="여기에다가 구글키를 복사해둠" />
			
</LinearLayout>


manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.googlemap"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".GoogleMapActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <uses-library android:name="com.google.android.maps"/>
    </application>

</manifest>


GoogleMapActivity.java
package com.googlemap;

import android.os.Bundle;

import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;

public class GoogleMapActivity extends MapActivity {
	
	MapView map;
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        map=(MapView) findViewById(R.id.map);
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
}



'Android > 2012.04월 강좌' 카테고리의 다른 글

9일차 복습  (0) 2012.05.08
8일차 Google Map 2  (0) 2012.05.07
8일차 Google Key 인증  (0) 2012.05.07
8일차 Service 2(음악 파일 재생)  (0) 2012.05.07
8일차 Service (음악 파일 재생)  (0) 2012.05.07

Adroid SDK Manager 로 가서 Google APIs를 install한다~





구글맵 인증키를 발급받는다.

실험용이기 때문에 디버그용 핑거프린터를 만들어야 한다.


절차는 아래와 같다.


1.debug.keystore파일이 있는 디렉토리로 이동하여 파일이 있는지 체크한다. 

-> 커멘드 창에서 .android 폴더에 들어갑니다. 

 (운영체제마다 폴더명이 틀림) 


Windows Vista: C:\Users\<user>\.android\debug.keystore 


 Windows XP: C:\Documents and Settings\MYHOME\.android\





2. 아래 명령을 실행 한다.

 keytool -list -alias androiddebugkey -keystore debug.keystore -storepass android -keypass android






keytool -list -alias androiddebugkey -v -keystore debug.keystore -storepass android -keypass android



ps. -v 옵션을 안주면 default value로 SHA1로 설정될 수 있습니다. 


3. 모자이크처리된  인증서 지문을 일단 복사한다 


지문이 마우스로 드래그가 되지 않으면 속성을 지정하자. 






 

 


만약 keytool 명령을 알 수 없다는 에러가 나오면 

keytool.exe 파일의 PATH가 연결이 되지 않은 것이다. 


 



위의 폴더경로를 복사해서 

내컴퓨터의 속성에서 PATH를 연결해 준다. 

 





*지문 복사까지 완료하였으면, 구글맵 인증키를 발급받기 위해 웹브라우저로 아래 사이트로 접속한다. 


http://code.google.com/intl/ko/android/maps-api-signup.html

약관 동의 후 복사한 인증서 지문 붙여넣고 -> API Key Generation -> 구글 계정으로 로그인 하면 절차는 끝난다.




Map을 띄울 Activity를 하나 만든다.

구글 Map Api를 이용하여 구현하려면 무조건 MapActivity를 상속받아야 한다.




참고:http://www.sogangori.com/www/studyAndroid15_01.action

'Android > 2012.04월 강좌' 카테고리의 다른 글

8일차 Google Map 2  (0) 2012.05.07
8일차 GoogleMap  (0) 2012.05.07
8일차 Service 2(음악 파일 재생)  (0) 2012.05.07
8일차 Service (음악 파일 재생)  (0) 2012.05.07
8일차 숙제  (0) 2012.05.07
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <ImageButton
        android:id="@+id/imageButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/sel" 
        android:layout_gravity="center"/>
    
    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="stop" />

</LinearLayout>
sel.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <!-- 눌러졌을때 보여질 이미지 선택 -->
    <item android:state_pressed="true"
          android:drawable="@drawable/red"/>
	
    <!-- 기본 상태에서 보여질 이미지 -->
	<item android:drawable="@drawable/yellow"/>
	    
</selector>
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gusfree.service"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".ServiceActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name="MusicService"></service>
    </application>

</manifest>





ServiceActivity.java
package com.gusfree.service;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

public class ServiceActivity extends Activity {
    ImageButton imageButton;
    Button button;
    MediaPlayer mp;
    Intent intent; 
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        imageButton=(ImageButton) findViewById(R.id.imageButton1);
        button = (Button)findViewById(R.id.button1);
       
        ClickListener listener = new ClickListener();
        imageButton.setOnClickListener(listener);
        button .setOnClickListener(listener) ;                
        
        intent =new Intent();
        intent.setClass(this, MusicService.class);
        intent.putExtra("vol", 100);
        
        //mp = MediaPlayer.create(this, R.raw.riverside);
        
        
    }
    //inner class
    class ClickListener implements android.view.View.OnClickListener{
  
		@Override
		public void onClick(View v) {
			
			if(v==imageButton){//음악 시작
				imageButton.setEnabled(false);//못누르게

				//onStart메서드를 호출한다.
				startService(intent);
				
				//mp.start();
			}else if(v==button) {//음악 종료
				imageButton.setEnabled(true);
				
				//onDestory 메서드를 호출한다.
				stopService(intent);
				
				//mp.pause();
			}
		}
    }
}
MusicService.java
package com.gusfree.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;

public class MusicService extends Service{

	MediaPlayer mp;
	
	//시작될때 호출
	@Override
	public void onCreate() {		
		super.onCreate();
		//에러 체크
		mp=MediaPlayer.create(getApplicationContext(), R.raw.riverside);
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
		int vol =intent.getIntExtra("vol",50);
		mp.setVolume(vol, vol);
		mp.start();
		super.onStart(intent, startId);
	}
	
	// 종료될때 호출
	@Override
	public void onDestroy() {		
		super.onDestroy();
		mp.stop();
		mp.release();//메모리에서 mp3제거
		
	}
	
	@Override
	public IBinder onBind(Intent arg0) {
		// Activity 와 Service를 묶는 기능..
		return null;
	}
}

음악을 실행 시키고 서비스창에 갑







'Android > 2012.04월 강좌' 카테고리의 다른 글

8일차 GoogleMap  (0) 2012.05.07
8일차 Google Key 인증  (0) 2012.05.07
8일차 Service (음악 파일 재생)  (0) 2012.05.07
8일차 숙제  (0) 2012.05.07
8일차 FileIO 3 - 저장된 파일 가져오기  (0) 2012.05.07

+ Recent posts