posted by Kyleslab 2013. 3. 26. 18:48

출처 : http://osh2357.blog.me/130098179373


안드로이드에서 사용하는 SQLite 는 모바일에서 가볍게 사용하기에 너무 좋다.

 하지만 다수의 Insert 문을 반복할때의 수행속도는 입이 쩍벌어지게 느렸는데......

 원인을 파해쳐보니 SQLite 에서는 Transaction을 사용하고 안하고의 차이가 다량 Insert 시 엄청난 시간 차이를 보여주고 있었다.

 다음 사이트의 Insert Test 를 보면 이해가 되리라 -> http://www.sqlite.org/speed.html

 

1000 건의 record 를 Insert 했을시에

SQLite 는 13.061 초

MySQL 은 0.114 초가 걸린다

 

반면에 25000 건의 record 를 Transaction 을 이용하여 Insert 했을시에

SQLite 는 0.914 초

MySQL 은 2.184 초가 걸렸다..

 

record 의 수는 25배가 늘었지만 Transaction 처리를 함으로

MySQL 의 속도 향상 대비 SQLite 의 경우 오히려 처리 속도 차이는 어마어마 하다

 

건수로만 비교했을때 25배 늘어난 데이터 처리속도는, Transaction 비 처리시

SQLite 는 326.525초 (헉), MySQL 은 2.85초가 예상된다

 

326.525초 -> 0.914 초 어마어마하지 않은가..

 

물론 이 SQLite 를 Android 에서 구동하느냐 iPhone 에서 구동하느냐 PC 에서 구동하느냐에 따른 차이도 많이 있을것이다..

하지만 확실한건 반복된 Insert 구문 사용시에는 Transaction 을 반드시 걸어야 할것으로 보인다~

- Android 에서 테스트시 Select 구문이 포함된 반복문이어서 정확한 속도비교는 불가능했으나 소모시간 약  1/10 수준으로 빨라졌다

 

 

자. 그럼 이제 Android 에서 Insert 시 Transaction 사용 구문 예제를 알아보자.

늘상 사용하는 방식대로라면 아래와 같이 사용하게 될것이다.

 

db.insert(TABLE_NAME, null, VALUE);

 

이것을 이제는 다음과 같이 사용하면 된다. (물론 반복문에서 사용할때 큰 효과를 발휘한다)

 

db.beginTransaction();

db.insert(TABLE_NAME, null, VALUE);

db.setTransactionSuccessful();

db.endTransaction();

 

그런데 이렇게 쓰고나면 뭔가 좀 허전해보인다.. SQL Exception 이 발생할 경우를 대비해야 하는데, 아래와 같이 수정한다.

 

try{

db.beginTransaction();

db.insert(TABLE_NAME, null, VALUE);

db.setTransactionSuccessful();

} catch (SQLException e){

} finally {

db.endTransaction();

}

 

보통의 경우라면 insert 구문 부근에는 조건문이나 반복문이 있으리라~

posted by Kyleslab 2013. 3. 13. 16:01


Error generating final archive: Debug certificate expired on ...

이클립스에서 안드로이드 애플리케이션 빌드 중에 이런 오류 메시지가 나오는 경우가 있다.

Debug certificate가 만료되어서 발생하는 문제인데, Debug certificate는 만들어진 후 365일이 지나면 만료된다. 그러므로 만료된 Debug certificate를 새로 갱신해주면 된다. 방법은 간단하다. debug.keystore 파일을 삭제한 후, 프로젝트를 클린하면 이 debug.keystore파일 생성해준다고 모든 사이트들이 알려주나 나의 경우는 절대 다시 생성되지 않았다.

콘솔창으로 debug.keystore가 저장되있던 경로로 이동한후 아래의 명령어로 생성해준 후에야 문제가 해결되었다.

keytool -genkey -v -keystore debug.keystore -alias androiddebugkey -storepass android -keypass android -keyalg RSA -validity 14000

debug.keystore 파일의 위치는 'Window > Preferences > Android > Build'에서 'Default debug keystore' 항목을 참조하면 된다.


'Mobile > Android' 카테고리의 다른 글

안드로이드 SQLite 속도 향상!  (0) 2013.03.26
xml에서 include로 포함한 뷰들의 inflate여부  (0) 2012.11.13
JNIEnv* 와 jclass  (0) 2012.11.13
JNI를 Xcode이용하기  (2) 2012.11.13
Fragment(2)  (0) 2012.11.12
posted by Kyleslab 2012. 11. 13. 18:34

layout xml을 만들때 다른 xml layout을 include라는 명령어로 포함시킬수 있습니다. 반복적으로 사용되는 layout인경우 자주이렇게 합니다. 



여기서 생긴궁금증 include가 포함된 xml레이아웃을 setContentView등으로 inflate를 시킨다면 include된 xml레이아웃 안의 뷰들도 inflate되어 바로 사용할 수 있을까?


정답은 가능합니다. 




    

가령 이런경우 레퍼런스 사이트에서는 layout_textview xml안에있는 뷰들을 소스코드에서 사용하려면 위의 예제처럼 id를 주어 먼저 불러오고 사용하게 되있습니다. 가령 이런식입니다. 


// layout_textview를 받아온다. layout_textview를 받아온 View textView 객체는 하위 자식들을 그대로 포함하고 있다.
        // 이렇게 받아온 View textView는 layout_textview의 root뷰이다.
        View textView = (View)findViewById(R.id.main_layout_textview);
         
        // 받아온 textview를 통해 해당 View가 가진 하위 자식들을 받아온다.(reference한다.)
        TextView tv01 = (TextView)textView.findViewById(R.id.layout_textview_01);
        TextView tv02 = (TextView)textView.findViewById(R.id.layout_textview_02);

하지만 상식적으로 생각해볼때 include의 명령어는 java의 inline명령어처럼 그부분에 xml코드를 대입해준것 불과합니다. 그러므로 include부분에 id를 줄필요도 다르게 생각할 필요도 없습니다. 그냥 원래 포함된 레이아웃인양 사용하면됩니다. 왜냐하면 setContentView에서 해당 xml전체를 inflate시켰기때문입니다. 다시말해 위와 같은 작업이 필요없습니다. 그냥 아래처럼 id만주면 사용할 수 있습니다.


        TextView tv01 = (TextView)findViewById(R.id.layout_textview_01);
        TextView tv02 = (TextView)findViewById(R.id.layout_textview_02);


'Mobile > Android' 카테고리의 다른 글

안드로이드 SQLite 속도 향상!  (0) 2013.03.26
Error generating final archive: Debug certificate expired on ... 문제해결법  (0) 2013.03.13
JNIEnv* 와 jclass  (0) 2012.11.13
JNI를 Xcode이용하기  (2) 2012.11.13
Fragment(2)  (0) 2012.11.12
posted by Kyleslab 2012. 11. 13. 15:24

JNIEnv*

JNI 인터페이스 포인터는 자바 메쏘드와 매핑되는 각 네이티브 함수(i.e., c/c++ 함수)를 위한 매개 변수로 전달된다. 이 포인터(매개변수)는 JNI환경에 있는 함수들과 상호작용하도록 해 준다. JNI 인터페이스 포인터는 저장될 수 있으나 오로지 현재의 쓰레드(동작 중인 쓰레드)에서 유효한 상태(사용 가능한 상태)로 유지된다. 다른 쓰레드들(정지 혹은 휴면 상태로 된 쓰레드들)은 먼저 반드시 AttachCurrentThread() 메소드를 호출하여 VM에 자신을 연결하고 JNI 인터페이스 포인터를 획득해야 한다. 일단 연결이 되고 나면 네이티브 쓰레드는 네이티브 메쏘드에서 동작하는 정상적인 자바쓰레드처럼 동작한다. 이 네이티브 쓰레드는 자신이 연결 해제하기 위해 DetachCurrentThread()를 호출하기 전까지는 VM에 연결된 상태로 유지된다.

현재의 쓰레드에 연결하고 JNI 인터페이스 포인터를 획득하기 위해서는:

 

JNIEnv *env;
(*g_vm)->AttachCurrentThread (g_vm, (void **) &env, NULL);

To detach from the current thread:

(*g_vm)->DetachCurrentThread (g_vm);
최종 결론:
JNIEnv *env는 자바와 네이티브 메소드를 연결하는 인터페이스 포인터
출처 : http://blog.naver.com/PostView.nhn?blogId=ethyo&logNo=80137761570

jclass

jclass 객체는 자바 클래스에 대한 정보를 나타냄. Class 오브젝트와 비슷

posted by Kyleslab 2012. 11. 13. 12:03

JNI를 공부하는데 Mac에서는 C혹은 C++코딩을 하기위해서는 Xcode를 이용해야한다. 그러나 Xcode를 이용해본적이 없는 나로서는 어려웠다.


http://crystalcube.co.kr/119


이 블로그의 글에서 친절히 설명이 나와있었다 그러나 한가지점 User Header Search Paths에 jni.h 헤더파일이 있는 경로를 추가해줘도 계속 jni.h file not found. 에러가 뜨면서 동작하지 않았다.


이 문제는 User Header Search Paths가 아니라 Header Search Paths에 추가해줌으로써 간단히 해결되었다.




'Mobile > Android' 카테고리의 다른 글

xml에서 include로 포함한 뷰들의 inflate여부  (0) 2012.11.13
JNIEnv* 와 jclass  (0) 2012.11.13
Fragment(2)  (0) 2012.11.12
fragment에서 attach, detach method!  (0) 2012.11.12
Fragment 에서 방향 전환시 null 체크  (0) 2012.11.09
posted by Kyleslab 2012. 11. 12. 14:13

당연히 Activity와는 다른 생명주기를 갖기때문에 fragment를 사용하는 개념은 액티비티와는 완전히 다르다. 모든 것은 FragmentManager를 통해 독립적으로 관리된다. 액티비티는 UI중심 즉 각각의 layout파일 중심으로 작동하면 된다고 생각하면되나 fragment는 fragmentManager중심이라고 생각하는 것이 맞다.

한 가지 예를 들어보자면 fragment는 혼자서 보일수는 없다 반드시 액티비티에 포함되어야한다. 하지만 그렇다고 해도 액티비티가 다시 생성되어서 모든 정보가 초기화되어도 fragmentManager에 기록된 정보는 그대로 살아 있다. 액티비티가 onCreate부터 다시 불리더라도 이전에 만들어서 fragmentManager에 add해둔 fragment는 아직 살아있다는 것이다. 

fragment를 포함하고 있는 Activity가 onCreate부터 다시불려초기화 되어도 add된 fragment들이 살아 있는 이유는 생명주기 자체가 따로 관리 되기 때문이다.



- Fragment LifeCycle(출처 android:Reference)

onAttach()(Activity Layout에 추가된 순간 호출! )부터 onResume()되면 화면에 display 되게 되고 onDetach되어 FragmentManager에서 사라질때까지 display되게 된다.


Fragment 생명주기에 대한 자세한 설명

http://blog.saltfactory.net/190

http://nkstudy.tistory.com/1


언제든 잘못된 설명은 말씀해주세요^^


'Mobile > Android' 카테고리의 다른 글

JNIEnv* 와 jclass  (0) 2012.11.13
JNI를 Xcode이용하기  (2) 2012.11.13
fragment에서 attach, detach method!  (0) 2012.11.12
Fragment 에서 방향 전환시 null 체크  (0) 2012.11.09
Fragment를 이용한 TabActivity  (0) 2012.11.09
posted by Kyleslab 2012. 11. 12. 11:24

fragmentManager에 추가된 fragment를 어떻게 떼어내어 다시 fragment로 만들수 있을까? 혹은 이미 있는 fragment를 어떻게 다시 붙일수 있을까? 이때 attach와 detach메소드가 있다.

먼저 reference를 보자 

public abstract FragmentTransaction attach (Fragment fragment)

Re-attach a fragment after it had previously been deatched from the UI with detach(Fragment). This causes its view hierarchy to be re-created, attached to the UI, and displayed.

Parameters
fragmentThe fragment to be attached.
Returns
  • Returns the same FragmentTransaction instance.

public abstract FragmentTransaction detach (Fragment fragment)

Detach the given fragment from the UI. This is the same state as when it is put on the back stack: the fragment is removed from the UI, however its state is still being actively managed by the fragment manager. When going into this state its view hierarchy is destroyed.

Parameters
fragmentThe fragment to be detached.
Returns
  • Returns the same FragmentTransaction instance.

보면 attach보다 detach를 먼저 사용하도록 되어있다. detach는 UI로부터 fragment를 떼어내는 것이고 attach는 그것을 다시 UI에 붙인다는 의미이다. 이것을 제대로 사용하는 예제는 tab fragment소스에 찾아볼수 있다.


        @Override
        public void onTabChanged(String tabId) {
            TabInfo newTab = mTabs.get(tabId);	// 넣어놨던 tabinfo찾아온다.
            if (mLastTab != newTab) {//라스트탭이 뉴탭과 같지 않다면
                FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
                if (mLastTab != null) {	//라스트탭이 널이 아니면
                    if (mLastTab.fragment != null) {	//라스트탭의 프래그먼트가 널이 아니면
                        ft.detach(mLastTab.fragment);	//떼어낸다
                    }
                }
                if (newTab != null) {	// 뉴탭이 널이 아니면
                    if (newTab.fragment == null) {	//프래그먼트가 널이면
                        newTab.fragment = Fragment.instantiate(mActivity,
                                newTab.clss.getName(), newTab.args);//새로 만들어준다
                        ft.add(mContainerId, newTab.fragment, newTab.tag);	//추가해준다
                    } else {
                        ft.attach(newTab.fragment);	//널이 아니면 그대로 붙여준다.
                    }
                }

                mLastTab = newTab;	//새로운탭이 라스트탭이 된다.
                ft.commit();
                mActivity.getSupportFragmentManager().executePendingTransactions();
            }
        }


위에 소스처럼 detach로 잘떼어놨다가 다시 attach로 붙여준다.

이것만 봐도 위에서 설명한 것처럼 Activity와는 사용하는 방법, 개념이 완전히 다르고 조금 더 유동적을 사용할 수 있다는 것을 알수 있다. 

그런데 여기서 한가지 생기는 의문은 fragmentTransaction에는 add, remove와 같은 메소드도 있다. 이것을 왜 사용하지 않았을까? 내가 보기에는 자원 재활용과 fragment정보 유지라는 생각이 들었다. add와 remove를 반복적으로 사용하려면 fragment를 계속 동적으로 생성하고 지우고를 반복해야한다. 그리고 위의 예제처럼 TabInfo라는 자료형을 만들어 fragment를 유지한다면 그안의 정보도 유지될것으로 보인다.

그런데 이 detach메소드가 작동하지 않은경우가 있다. 바로 정적으로 fragment가 선언된 경우이다.

xml 파일로 아래와 같이 class가 지정되어 fragment가 선언된경우에는 detach, remove모두 작동하지 않는다.

    


###. Fragment생명주기에 onAttach, onDetach라는 콜백메소드가 있어 attach(), detach()메소드 실행시 이 콜백메소드들을 호출하지 않을까 했지만 호출하지는 않았다.


언제든 틀린 설명은 말씀해주세요^^





'Mobile > Android' 카테고리의 다른 글

JNI를 Xcode이용하기  (2) 2012.11.13
Fragment(2)  (0) 2012.11.12
Fragment 에서 방향 전환시 null 체크  (0) 2012.11.09
Fragment를 이용한 TabActivity  (0) 2012.11.09
Fragment(1)  (0) 2012.11.09
posted by Kyleslab 2012. 11. 9. 18:55
@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);

		Log.e("온크리에이트", "입니다.");

		if(getSupportFragmentManager().findFragmentByTag("listfra") == null){
			FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
			ListViewFragment lvf = new ListViewFragment();
			ft.add(R.id.menu, lvf, "listfra");
			ft.addToBackStack(null);
			ft.commit();
			
		}

	}


fragment 코드들을 보다보면 이렇게 onCreate안에 fragment 를 추가해주는 코드들을 볼수 있는데 저렇게 처음부터 null인지 체크를 한다. 이것은 이 액티비티가 처음 실행되었을 때가 아닌 다음번에 실행했을 때를 대비한 코드다. fragment가 이미 생성되어있다면 같은 fragment를 manager에 커밋할필요가 없기때문에 없는 경우에만 프래그먼트를 만들게 한다. 그렇지 않으면 중복해서 만들어서 표시하게된다.

'Mobile > Android' 카테고리의 다른 글

Fragment(2)  (0) 2012.11.12
fragment에서 attach, detach method!  (0) 2012.11.12
Fragment를 이용한 TabActivity  (0) 2012.11.09
Fragment(1)  (0) 2012.11.09
생명주기 메소드를 Override할때 super의 위치  (0) 2012.11.08
posted by Kyleslab 2012. 11. 9. 17:57

MainActivity.java

package com.example.hellotabfragment;

import java.util.HashMap;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.TabHost;

import com.example.hellotabfragment.fragment.Fragment1;
import com.example.hellotabfragment.fragment.Fragment2;
import com.example.hellotabfragment.fragment.Fragment3;

/**
 * This demonstrates how you can implement switching between the tabs of a
 * TabHost through fragments.  It uses a trick (see the code below) to allow
 * the tabs to switch between fragments instead of simple views.
 */
public class MainActivity extends FragmentActivity {
    TabHost mTabHost;
    TabManager mTabManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        mTabHost = (TabHost)findViewById(android.R.id.tabhost);//Container for a tabbed window view.
        mTabHost.setup();

        mTabManager = new TabManager(this, mTabHost, R.id.realtabcontent);// tab host와 탭을 눌렀을때 바뀌어야하는 부분의 id
        mTabManager.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"), Fragment1.class, null);	//새로운 탭을 만든다.
        //tabspec -> A tab has a tab indicator, content, and a tag that is used to keep track of it
        mTabManager.addTab(mTabHost.newTabSpec("contacts").setIndicator("Contacts"), Fragment2.class, null);
        mTabManager.addTab(mTabHost.newTabSpec("custom").setIndicator("Custom"), Fragment3.class, null);


        if (savedInstanceState != null) {
            mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));	// 방향 전환 전에 선택된 탭이 있다면 가져와서 설정
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("tab", mTabHost.getCurrentTabTag());	// 방향 전환될때 넣어준다.
        Log.e("tab", mTabHost.getCurrentTabTag());
    }

    /**
     * This is a helper class that implements a generic mechanism for
     * associating fragments with the tabs in a tab host.  It relies on a
     * trick.  Normally a tab host has a simple API for supplying a View or
     * Intent that each tab will show.  This is not sufficient for switching
     * between fragments.  So instead we make the content part of the tab host
     * 0dp high (it is not shown) and the TabManager supplies its own dummy
     * view to show as the tab content.  It listens to changes in tabs, and takes
     * care of switch to the correct fragment shown in a separate content area
     * whenever the selected tab changes.
     */
    public static class TabManager implements TabHost.OnTabChangeListener {
        private final FragmentActivity mActivity;	//context
        private final TabHost mTabHost;
        private final int mContainerId;	
        private final HashMap mTabs = new HashMap();	// tag기준으로 tab에대한 정보가 들어있다.
        TabInfo mLastTab;

        static final class TabInfo {
            private final String tag;
            private final Class clss;
            private final Bundle args;
            private Fragment fragment;

            TabInfo(String _tag, Class _class, Bundle _args) {
                tag = _tag;
                clss = _class;
                args = _args;
            }
        }

        static class DummyTabFactory implements TabHost.TabContentFactory{ // Makes the content of a tab when it is selected. 
        	// 굳이 필요 없어 보이는 듯
            private final Context mContext;

            public DummyTabFactory(Context context) {
                mContext = context;
            }

            @Override
            public View createTabContent(String tag) {
                View v = new View(mContext);
                v.setMinimumWidth(0);
                v.setMinimumHeight(0);
                return v;
            }
        }

        public TabManager(FragmentActivity activity, TabHost tabHost, int containerId) {
            mActivity = activity;
            mTabHost = tabHost;
            mContainerId = containerId;
            mTabHost.setOnTabChangedListener(this);
        }

        public void addTab(TabHost.TabSpec tabSpec, Class clss, Bundle args) {	// tab추가하기
            tabSpec.setContent(new DummyTabFactory(mActivity));
            String tag = tabSpec.getTag();

            TabInfo info = new TabInfo(tag, clss, args);	// 그닥 필요없어 보이긴함

            // Check to see if we already have a fragment for this tab, probably
            // from a previously saved state.  If so, deactivate it, because our
            // initial state is that a tab isn't shown.
            info.fragment = mActivity.getSupportFragmentManager().findFragmentByTag(tag);	//tag로 프래그먼트 찾아서 넣어준다.
            if (info.fragment != null && !info.fragment.isDetached()) {	//frament가 null이아니고 떨어져있지 않으면 떼준다.
            	
                FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
                ft.detach(info.fragment);
                ft.commit();
            }

            mTabs.put(tag, info);	//자료형에 넣어준다. 이것도 불필요함
            mTabHost.addTab(tabSpec);	// 탭호스트에 실제로 탭을 넣어준다.
        }

        @Override
        public void onTabChanged(String tabId) {
            TabInfo newTab = mTabs.get(tabId);	// 넣어놨던 tabinfo찾아온다.
            if (mLastTab != newTab) {//라스트탭이 뉴탭과 같지 않다면
                FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
                if (mLastTab != null) {	//라스트탭이 널이 아니면
                    if (mLastTab.fragment != null) {	//라스트탭의 프래그먼트가 널이 아니면
                        ft.detach(mLastTab.fragment);	//떼어낸다
                    }
                }
                if (newTab != null) {	// 뉴탭이 널이 아니면
                    if (newTab.fragment == null) {	//프래그먼트가 널이면
                        newTab.fragment = Fragment.instantiate(mActivity,
                                newTab.clss.getName(), newTab.args);//새로 만들어준다
                        ft.add(mContainerId, newTab.fragment, newTab.tag);	//추가해준다
                    } else {
                        ft.attach(newTab.fragment);	//널이 아니면 그대로 붙여준다.
                    }
                }

                mLastTab = newTab;	//새로운탭이 라스트탭이 된다.
                ft.commit();
                mActivity.getSupportFragmentManager().executePendingTransactions();
            }
        }
    }
}
activity_main.xml


    

        

        

        
    





'Mobile > Android' 카테고리의 다른 글

fragment에서 attach, detach method!  (0) 2012.11.12
Fragment 에서 방향 전환시 null 체크  (0) 2012.11.09
Fragment(1)  (0) 2012.11.09
생명주기 메소드를 Override할때 super의 위치  (0) 2012.11.08
IntentService  (0) 2012.11.06
posted by Kyleslab 2012. 11. 9. 15:42

개인적인 생각으로 Fragment는 객체화시킬수 있는 서브 액티비티라는 생각이다. 

액티비티자체는 객체화 시킬수 없어 사용에 불편함이 있다. 

그러나 프래그먼트는 객체화가 가능하여 유연성있게 사용할 수 있다. 그리고 단독으로는 사용할 수 없다. 액티비티안에 사용할 수 있다.

액티비티 끼리는 인텐트를 주고받지만 프래그먼트는 argument로 값을 주고 받는다.

그런데 프래그먼트를 생성할때마다 Bundle을 만들어 아규먼트를 전달 받고 전달하는 것은 낭비라는 생각이 들어 메소드를 만든다.

static TextFragment newInstance(String _msg){
		TextFragment tf = new TextFragment();
		Bundle bundle = new Bundle();
		bundle.putString("msg", _msg);
		tf.setArguments(bundle);

		return tf;
	}

	public String getMsg(){
		if(getArguments().getString("msg")!=null){
			return getArguments().getString("msg");
		}
		return "msg";
	}


이런 식으로 메소드를 만들고 실제로 Fragment 객체를 생성할때는 new가 아닌

TextFragment tf = TextFragment.newInstance(((TextView)v).getText().toString());

이런 식으로 메소드를 호출하여 사용한다.

new로 생성하는 것외에 Fragment 에서 자체적으로 지원해주는 메소드도 있다. new로 생성하는 것과 차이는 없지만

인스턴스화가 실패했을 경우 에러 처리를 해준다.

public static Fragment instantiate (Context context, String fname, Bundle args)

Added in API level 11

Create a new instance of a Fragment with the given class name. This is the same as calling its empty constructor.

Parameters
contextThe calling context being used to instantiate the fragment. This is currently just used to get its ClassLoader.
fnameThe class name of the fragment to instantiate.
argsBundle of arguments to supply to the fragment, which it can retrieve with getArguments(). May be null.
Returns
  • Returns a new fragment instance.
Throws
InstantiationExceptionIf there is a failure in instantiating the given fragment class. This is a runtime exception; it is not normally expected to happen.



'Mobile > Android' 카테고리의 다른 글

Fragment 에서 방향 전환시 null 체크  (0) 2012.11.09
Fragment를 이용한 TabActivity  (0) 2012.11.09
생명주기 메소드를 Override할때 super의 위치  (0) 2012.11.08
IntentService  (0) 2012.11.06
weight값설정시 최적화  (0) 2012.11.06