로그인 버튼을 누르면 로그인아이디, 비밀번호를 입력하는 팝업창이 뜨고, 입력 확인 하면 입력값을 Toast로 보여줌.

 

 - 로그인 버튼 선택                            - 로그인 팝업 창

 

 - 입력 후 로그인 버튼 클릭                 - 결과값 보여줌.

 

 

 

(1) activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

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

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

</LinearLayout>

 

 

(2) login.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="wrap_content"
    android:orientation="vertical"
    android:background="#00ffff">

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="6.18" >
        <TableRow
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="아이디" />
            <EditText
                android:id="@+id/edtId"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ems="10" >
                <requestFocus />
            </EditText>
        </TableRow>
          <TableRow
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="비밀번호" />
            <EditText
                android:id="@+id/edtPwd"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ems="10" >
                <requestFocus />
            </EditText>
        </TableRow>
</TableLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal">
       <Button
            android:id="@+id/btnLogin"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="로그인" />
        <Button
            android:id="@+id/btnCancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="취소" />
    </LinearLayout>

</LinearLayout>

 

 

(3) MainActivity.java

package com.example.test27_popupdlg;

import android.os.Bundle;
import android.app.Activity;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;

 

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //로그인버튼 누르면 로그인창 띄우기
        findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {           
            @Override
            public void onClick(View v) {
                //login.xml을 자바객체로 변환하기
                LinearLayout layout=
                   (LinearLayout)View.inflate(MainActivity.this,R.layout.login,null);
                //layout을 뷰로 갖는 팝업창만들기
                final PopupWindow popup=new PopupWindow(layout, 300,200,true);
                //화면 정가운데 팝업창 띄우기
                popup.showAtLocation(layout,Gravity.CENTER,0,0);
                Button btnLogin=(Button)layout.findViewById(R.id.btnLogin);
                Button btnCancel=(Button)layout.findViewById(R.id.btnCancel);
                final EditText edtId=(EditText)layout.findViewById(R.id.edtId);
                final EditText edtPwd=(EditText)layout.findViewById(R.id.edtPwd);
                //로그인버튼 눌렀을때
                btnLogin.setOnClickListener(new View.OnClickListener() {                   
                    @Override
                    public void onClick(View v) {
                        String msg=edtId.getText().toString() +"," +
                                   edtPwd.getText().toString();
                        Toast.makeText(MainActivity.this,msg,
                                Toast.LENGTH_SHORT).show();
                        //팝업창 닫기
                        popup.dismiss();
                    }
                });
                //취소버튼을 눌렀을때
                btnCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //팝업창 닫기
                        popup.dismiss();
                    }
                });
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

 

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

#24 ( File )  (0) 2013.02.03
#23 ( Preference )  (0) 2013.02.03
#22 ( Activity LifeCycle )  (0) 2013.02.03
#21 ( Intent Action : 외부 프로그램과 연결 )  (0) 2013.02.02
#20 ( 다른 Activity 로 text와 이미지 넘기기 )  (0) 2013.02.02
파일을 저장, 삭제, 읽기 예제

 

 버튼 4개. 입력 필드, 읽어온 값 보여질 부분 생성.

 

(1) activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

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

        <requestFocus />
    </EditText>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/btnSave"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="저장"
            android:layout_weight="1"
            />

        <Button
            android:id="@+id/btnLoad"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="파일읽기1" />

        <Button
            android:id="@+id/btnDelete"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="파일삭제"
            android:layout_weight="1"
            />

        <Button
            android:id="@+id/btnLoad1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="파일읽기2"
            android:layout_weight="1"
            />
    </LinearLayout>

    <EditText
        android:id="@+id/edtStr"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="top"
        android:enabled="false"
        android:autoText="false"
        android:ems="10"
        android:inputType="textMultiLine" />

</LinearLayout>

 

(2) MainActivity.java

 [파일처리]
 - 안드로이드에서 자바의 모든 입출력기능을 다 사용할수는 없으며, 보안상의 이유로 임의위치의 파일을 아무나 읽고 쓸수는 없다. 응용프로그램은 허가받은 위치에만 파일을 생성할 수 있고, 자신이 만든 파일만 액세스 할 수 있다.
 ( 단, 콘텐트프로바이더를 이용하면 다른 프로그램도 접근 가능 )
 
- 파일의 생성모드
 MODE_PRIVATE : 혼자만 사용하는 배타적모드의 파일 생성(기본모드)
 MODE_APPEND : 덮어씌우지 않고 추가모드로 연다.
 MODE_WORLD_READABLE : 다른 응용프로그램이 파일을 읽을 수 있도록 허용한다.
 MODE_WORLD_WRITABLE : 다른 응용프로그램이 파일을 기록할 수 있도록 허용한다.

 

package com.example.test25_file;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
    EditText edtData;
    EditText edtStr;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //editText 참조값 얻어오기.
        edtData = (EditText)findViewById(R.id.edtData);
        edtStr  = (EditText)findViewById(R.id.edtStr);
        //버튼에 이벤트 등록하기
        findViewById(R.id.btnSave).setOnClickListener(this);
        findViewById(R.id.btnLoad).setOnClickListener(this);
        findViewById(R.id.btnDelete).setOnClickListener(this);
        findViewById(R.id.btnLoad1).setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch(v.getId()){
        case R.id.btnSave: save();break;
        case R.id.btnLoad: load();break;
        case R.id.btnDelete: remove();break;
        case R.id.btnLoad1: load1();break;
        }
    }
    //파일삭제하기
    public void remove(){
        String msg="";
        if(deleteFile("test.txt")){
            msg="파일삭제에 성공했습니다.";
        }else{
            msg="파일삭제에 실패했습니다.";
        }
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }
    // raw 특정폴더의 파일읽어오기.
    public void load1(){
        //raw폴더안의 파일을 읽어오기 위한 스트림 객체
        InputStream is = getResources().openRawResource(R.raw.arirang);
        try{
            //리소스자원의 크기만큼 배열 만들기
            byte []b = new byte[is.available()];
            //파일에서 읽어와 b에 저장
            is.read(b);
            // 바이트배열을 string객체로 변환하여 만들기
            String str=new String(b,"euc-kr");
            //에디트텍스트에 문자열 넣기
            edtStr.setText(str);
            //파일닫기
            is.close();
        }catch(IOException ie){
            Log.i("logMsg", ie.getMessage());
        }
    }
    //파일에서 읽어오기
    public void load(){
        FileInputStream fis = null;
        try{
            //파일을 읽기위한 스트림 객체 얻어오기.
            fis=openFileInput("test.txt");
            //읽어온 문자열을 저장할 문자열 객체
            StringBuffer sb=new StringBuffer();
            //문자열을 읽어와 저장할 배열
            byte []b=new byte[255];
            int n=0;
            while((n=fis.read(b))!=-1){//파일에서 읽어와 b배열에 저장.
                sb.append(new String(b,0,n));//읽어온 문자열을 sb에 연결
            }
            //파일에서 읽어온 문자열을 에디트텍스트에 보이기
            edtStr.setText(sb.toString());
            fis.close();
        }catch(FileNotFoundException ie){
            edtStr.setText("해당파일이 존재하지 않아요.!");
        }catch(IOException ie){
            Log.i("logMsg",ie.getMessage());
        }
    }
    public void save(){
        FileOutputStream fos=null;
        try{
            fos=openFileOutput("test.txt", Context.MODE_WORLD_READABLE);
            String text=edtData.getText().toString();
            //파일에 1바이트처리스트림으로 출력하기.
            fos.write(text.getBytes());
            //파일닫기
            fos.close();
            Log.i("logMsg","파일저장성공!");
        }catch(IOException ie){
            Log.i("logMsg",ie.getMessage());
        }
    }
}

 

(3) 확인은 이클립스 DDMS모드에서 File Explorer에서 해당 data / data / 해당프로젝트이름 폴더 밑에 보면 확인이 가능하다.

 

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

#25 ( popup dialog )  (0) 2013.02.03
#23 ( Preference )  (0) 2013.02.03
#22 ( Activity LifeCycle )  (0) 2013.02.03
#21 ( Intent Action : 외부 프로그램과 연결 )  (0) 2013.02.02
#20 ( 다른 Activity 로 text와 이미지 넘기기 )  (0) 2013.02.02
화면 종료직전에 화면에 있는 필드값2개를 파일로 저장한다.

화면에 저장된 값 불러오기 ( key-value )

 

 [[ 프레퍼런스(Preference) ]]
 - 응용프로그램의 실정정보를 영구적으로 저장하는 장치(용량이 작다)
 - 사용자의 옵션선택사항이나 프로그램 자체의 구성정보를 저장할때 주로 사용한다. (세팅파일 또는 ini파일과 유사한 기능 )

 

(1) activity_main.xml

; Edit두개

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="학생이름입력" />

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

    </LinearLayout>
 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="학생번호입력" />

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

    </LinearLayout>
</LinearLayout>

 

 

(2) MainActivity.java

package com.example.test24_preference;

import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.Menu;
import android.widget.EditText;

 

public class MainActivity extends Activity {
    EditText edtName;
    EditText edtNum;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        edtName=(EditText)findViewById(R.id.edtName);
        edtNum=(EditText)findViewById(R.id.edtNum);
       

        //프레프런스객체 얻어오기
        SharedPreferences spf=getSharedPreferences("info",0);


        //프레프런스에 저장된 값 얻어오기
        //spf.getString("저장된키값",키가없을때 보여줄 정보)
        String sname=spf.getString("sname","입력정보 없음");
        String snum=spf.getString("snum","입력정보 없음");

 

        //저장된 값들을 에디트텍스트에 넣기
        edtName.setText(sname);
        edtNum.setText(snum);


    }

    //프로그램이 종료되기 직전 설정정보를 저장
    @Override
    protected void onPause() {
        super.onPause();

 

        //프레프런스객체 얻어오기
        //getSharedPreferences("파일명",모드):모드가 0이면 읽기쓰기 가능
        SharedPreferences spf=getSharedPreferences("info",0);

 

        //프레프런스에 정보를 기록하기 위한 에디트객체 얻어오기
        SharedPreferences.Editor editor=spf.edit();

 

        //에디트텍스트에 입력된 값 얻어오기

        String sname=edtName.getText().toString();
        String snum=edtNum.getText().toString();

 

        //프레프런스에 넣기
        editor.putString("sname",sname);
        editor.putString("snum",snum);

 

        //프레프런스에 저장하기
        editor.commit();
    }


}

 

 

- 이름과 번호를 입력한다. 에뮬레이터 우측의 버튼으로 화면 이동.

 

 

- info파일로 이름과 번호가 저장되었는지 확인.

 이클립스에서 에뮬레이터를 탐색기로 볼수 있다.

 DDMS 선택

 

- File Explorer 탭선택

- data / data / 밑에 해당 테스트 중인 프로젝트 선택

 

- info.xml

 

- 앞에 화살표 버튼으로 xml파일을 export한다.

- 열어보면

 

 

 

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

#25 ( popup dialog )  (0) 2013.02.03
#24 ( File )  (0) 2013.02.03
#22 ( Activity LifeCycle )  (0) 2013.02.03
#21 ( Intent Action : 외부 프로그램과 연결 )  (0) 2013.02.02
#20 ( 다른 Activity 로 text와 이미지 넘기기 )  (0) 2013.02.02

Activity의 동작이벤트를 알아본다.

- 생성될때

- 화면에 보일때

- 프로그램 종료할때 등 ..

 

기본 layout으로 에뮬레이터로 실행해 본다. 중간에 logCat 찍히도록 설정하여 확인한다.

 

- logCat에 필터를 추가한다.

 

- Filter Name과 Log Tag를 추가한다.

 - 추가 

(1) activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

</RelativeLayout>

 

(2) MainActivity.java

; 에뮬레이터로 run 해보면 하단 logCat에 보일 것이다.

package com.example.test23_activitylifecycle;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;

public class MainActivity extends Activity {

    // 액티비티가 생성될때 호출-초기화작업(최초로 한번만 호출)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.i("logMsg", "onCreate메소드 호출!");
    }

 

    //onCreate직후 onResume직전에 수행
    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        Log.i("logMsg","onStart메소드 호출!");
    }


    //화면에 보일때 마다 호출(***)
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        Log.i("logMsg","onResume메소드 호출!");
    }


   

//프로그램이 종료되기 직전에 호출(***)
    //프로그램이 종료되기 직전에 해야 할일을 구현(현재상태정보 저장등..)
    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        Log.i("logMsg","onPause메소드 호출");
    }


   

    //화면에서 사라지기 직전에 호출(onDestroy()직전)
    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        Log.i("logMsg","onStop메소드 호출");
    }


   

    //프로그램이 종료될때 호출
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        Log.i("logMsg","onDestroy메소드 호출");
    }

}

외부프로그램과 연결

- 브라우저 : 네이버

- 전화걸기 화면 이동

- 구글 검색화면 이동

- 전화번호부로 이동

 

 

아래 화면으로 이동.

 

 

 

(1) activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="네이버로이동" />

    <Button
        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="전화번호부" />

    <Button
        android:id="@+id/btn3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="전화걸기" />

    <Button
        android:id="@+id/btn4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="검색하기" />

</LinearLayout>

 

 

 

(2) MainActivity.java

인텐트
 - 명시적인텐트 : 호출할 대상 컴포넌트가 분명히 명시되어 있는 인텐트(클래스)
 - 암시적 인텐트: 호출대상이 분명히 정해지지 않은 인텐트(안드로이드가 분석해서 해당 작업을 수행할 액티비티를 호출한다.)

 

package com.example.test22_intentaction;

import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;

 

public class MainActivity extends Activity implements OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        findViewById(R.id.btn1).setOnClickListener(this);
        findViewById(R.id.btn2).setOnClickListener(this);
        findViewById(R.id.btn3).setOnClickListener(this);
        findViewById(R.id.btn4).setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    public void onClick(View v) {

        switch(v.getId()){

        case R.id.btn1:
            Intent intent=new Intent();
            //액션지정하기
            intent.setAction(Intent.ACTION_VIEW);
            //보여줄 정보지정(무엇을 보여줄건지를 url로 설정)
            intent.setData(Uri.parse("http://www.naver.com"));
            startActivity(intent);
            break;

       

       // 전화걸기
        case R.id.btn2:           
            Intent intent1=new Intent();
            //액션지정
            intent1.setAction(Intent.ACTION_VIEW);
            //보여줄 정보 지정
            intent1.setData(ContactsContract.Contacts.CONTENT_URI);
            startActivity(intent1);
            break;

 

      case R.id.btn3:
            Intent intent2 = new Intent();
            intent2.setAction(Intent.ACTION_DIAL);
            intent2.setData(Uri.parse("tel:010-111-1234"));
            startActivity(intent2);
            break;

 

       case R.id.btn4:
            Intent intent3 = new Intent();
            //호출액션
            intent3.setAction(Intent.ACTION_WEB_SEARCH);
            //검색단어 넣기
            intent3.putExtra(SearchManager.QUERY,"김연아");
            startActivity(intent3);
            break;
        }

    }
}

+ Recent posts