본문 바로가기
프로그래밍/안드로이드

안드로이드 ViewPager, SQLite 예제 소스

by -현's- 2015. 4. 25.
반응형


●ViewPager와 SQLite를 이용한 예제


- MainActivity.java

package com.example.example1;


import java.util.ArrayList;


import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.os.Bundle;

import android.support.v4.view.ViewPager;

import android.support.v4.view.ViewPager.OnPageChangeListener;

import android.support.v7.app.ActionBarActivity;


public class MainActivity extends ActionBarActivity implements OnPageChangeListener{

SQLiteDatabase db;

ViewPager viewPager;

MyViewPagerAdapter adapter;

ResultFragment resultFragment;

ArrayList memLst = new ArrayList();

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

viewPager = (ViewPager)findViewById(R.id.viewPager);

adapter = new MyViewPagerAdapter(getSupportFragmentManager());

viewPager.setAdapter(adapter);

viewPager.setOnPageChangeListener(this);

adapter.getItem(1);

MyOpenHelper helper = new MyOpenHelper(getApplicationContext());

db = helper.getWritableDatabase();

resultFragment = (ResultFragment)adapter.getItem(1);

}

//페이지 전환 메서드를 정의(프레그먼트들이 사용한다)

public void setPage(int position){

viewPager.setCurrentItem(position);

}


public void onPageScrollStateChanged(int arg0) {

System.out.println("onPageScrollStateChanged arg0:"+arg0);


}


public void onPageScrolled(int arg0, float arg1, int arg2) {


System.out.println("onPageScrolled");

}

//회원가입 정보 확인

public MemberVo getDetail(){

MemberVo memberVo=null;

StringBuffer sqlQry = new StringBuffer();

sqlQry.append("select idx, id, pw, name from member ");

sqlQry.append("where idx = (select max(idx) from member); ");

Cursor rs = db.rawQuery(sqlQry.toString(), null);

System.out.println("getdetail");

if(rs.moveToNext()){

memberVo = new MemberVo();

memberVo.setIdx(rs.getInt(0));

memberVo.setId(rs.getString(1));

memberVo.setPw(rs.getString(2));

memberVo.setName(rs.getString(3));

System.out.println("aaa:"+rs.getInt(0)+rs.getInt(1)+rs.getInt(2)+rs.getInt(3));

}

return memberVo;

}

//두번째 페이지에 데이터를 주입

public void dataSend(){

MemberVo memberVo = getDetail();

if(adapter.getItem(1)==null){

System.out.println("null입니다");

}

String txt = "id:"+memberVo.getId()+" 비번:"+memberVo.getPw()+" 이름:"+memberVo.getName();


resultFragment.textView.setText(txt);

}

//페이지 스크롤의 확정, 즉 선택한 페이지가 확정될때 호출되는 메시지

public void onPageSelected(int arg0) {

System.out.println("onPageSelected arg0:"+arg0);

switch(arg0){

case 0:

break;

case 1:

dataSend();

break;

}

}

}

 



- 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="${relativePackage}.${activityClass}" >

  <com.example.example1.MyViewPager  

     android:id="@+id/viewPager"

   android:layout_width="match_parent"

   android:layout_height="match_parent">

  </com.example.example1.MyViewPager>

</RelativeLayout>




- MyViewPager.java

package com.example.example1;


import android.content.Context;

import android.support.v4.view.ViewPager;

import android.util.AttributeSet;

import android.view.MotionEvent;


public class MyViewPager extends ViewPager{


public MyViewPager(Context context, AttributeSet attrs) {

super(context, attrs);

}


//뷰페이저의 스와이핑(swipe) 막기

public boolean onTouchEvent(MotionEvent arg0) {

return false;

}

public boolean onInterceptTouchEvent(MotionEvent arg0) {

return false;

}

}




- MyViewPagerAdapter

package com.example.example1;


import android.support.v4.app.Fragment;

import android.support.v4.app.FragmentManager;

import android.support.v4.app.FragmentStatePagerAdapter;


public class MyViewPagerAdapter extends FragmentStatePagerAdapter{

Fragment[] fragments =  new Fragment[2];

public MyViewPagerAdapter(FragmentManager fm) {

super(fm);

fragments[0] = new JoinFragment();

fragments[1] = new ResultFragment();

}


public Fragment getItem(int arg0) {

return fragments[arg0];

}


public int getCount() {

return fragments.length;

}


}




- JoinFragment.java

package com.example.example1;


import android.database.sqlite.SQLiteDatabase;

import android.os.Bundle;

import android.support.v4.app.Fragment;

import android.util.Log;

import android.view.LayoutInflater;

import android.view.View;

import android.view.View.OnClickListener;

import android.view.ViewGroup;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;


public class JoinFragment extends Fragment implements OnClickListener{


EditText edit_id;

EditText edit_pw;

EditText edit_name;

public View onCreateView(LayoutInflater inflater, ViewGroup container,

Bundle savedInstanceState) {

//버튼들과 리스너와의 연결

View view = inflater.inflate(R.layout.join_fragment, container, false);


Button btn_join = (Button)view.findViewById(R.id.btn_join);


edit_id = (EditText)view.findViewById(R.id.edit_id);

edit_pw = (EditText)view.findViewById(R.id.edit_pw);

edit_name = (EditText)view.findViewById(R.id.edit_name);

btn_join.setOnClickListener(this);

return view;

}

//DB에 한건 입력하는 메서드

public void insert(String id, String pw, String name){

StringBuffer sqlQry = new StringBuffer();

sqlQry.append("insert into member (id, pw,name) ");

sqlQry.append(" values('"+id+"','"+pw+"', '"+name+"');");

MainActivity mainActivity = (MainActivity)getActivity();

SQLiteDatabase db = mainActivity.db;

db.execSQL(sqlQry.toString());

//수행 성공하면 화면전환하기

System.out.println("insert 성공");

//결과페이지로 전환

mainActivity.setPage(1);

}

public void valueCheck(){

//무결성 데이터를 넣기 위해 데이터 검사후 insert()호출

String msg=null;

if(edit_id.getText().toString().trim().equals("")||edit_id.getText().toString().trim().length()==0){

msg="아이디를 입력하세요";

Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();

return;

}

if(edit_pw.getText().toString().trim().equals("")||edit_pw.getText().toString().trim().length()==0){

msg="패스워드를 입력하세요";

Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();

return;

}

if(edit_name.getText().toString().trim().equals("")||edit_name.getText().toString().trim().length()==0){

msg="이름을 입력하세요";

Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();

return;

}

Toast.makeText(getActivity(), "가입하기", Toast.LENGTH_SHORT).show();

insert(edit_id.getText().toString(), edit_pw.getText().toString(), edit_name.getText().toString());

}

public void onClick(View v) {

switch(v.getId()){

case R.id.btn_join:

valueCheck();

break;

default:

break;

}

}

} 



- join_fragment.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent" >

    <TextView 

        android:id="@+id/txt_title"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="회원가입"

        android:textSize="25dp"

        android:gravity="center_horizontal"

        android:layout_marginTop="30dp"/>

    

    

    <LinearLayout 

        android:id="@+id/layout_id"

        android:orientation="horizontal"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_below="@id/txt_title">

        

   <TextView 

       android:id="@+id/txt_id"

       android:layout_width="100dp"

       android:layout_height="wrap_content"

       android:text="ID"

       android:textSize="20dp"

       android:layout_marginLeft="30dp"

       android:layout_marginTop="50dp"/>

   <EditText 

       android:id="@+id/edit_id"

       android:layout_width="150dp"

       android:inputType="textVisiblePassword"

       android:layout_height="wrap_content"

       android:layout_marginTop="50dp"/>

    </LinearLayout>

    

    <LinearLayout 

        android:id="@+id/layout_pw"

        android:orientation="horizontal"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_below="@id/layout_id">

        

    <TextView 

       android:id="@+id/txt_pw"

       android:layout_width="100dp"

       android:layout_height="wrap_content"

       android:text="PW"

       android:textSize="20dp"

       android:layout_marginLeft="30dp"

       android:layout_marginTop="20dp"/>

    <EditText 

       android:id="@+id/edit_pw"

       android:password="true"

       android:layout_width="150dp"

       android:inputType="textVisiblePassword"

       android:layout_height="wrap_content"

       android:layout_marginTop="20dp"/>

     

    </LinearLayout>

    

    <LinearLayout 

        android:id="@+id/layout_name"

        android:orientation="horizontal"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_below="@id/layout_pw">

          <TextView 

       android:id="@+id/txt_name"

       android:layout_width="100dp"

       android:layout_height="wrap_content"

       android:text="이름"

       android:textSize="20dp"

       android:layout_marginLeft="30dp"

       android:layout_marginTop="20dp"/>

    <EditText 

       android:id="@+id/edit_name"

       android:layout_width="150dp"

       android:inputType="text"

       android:layout_height="wrap_content"

       android:layout_marginTop="20dp"/>

        

    </LinearLayout>

    

   <LinearLayout 

        android:id="@+id/layout_btn"

        android:orientation="horizontal"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_below="@id/layout_name"

        android:layout_marginTop="30dp"

        android:gravity="center_horizontal">

    <Button 

        android:id="@+id/btn_join"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="가입하기"

        android:layout_marginRight="20dp"/>

     </LinearLayout>     

</RelativeLayout>

 



- ResultFragment.xml

package com.example.example1;


import android.os.Bundle;

import android.support.v4.app.Fragment;

import android.view.LayoutInflater;

import android.view.View;

import android.view.View.OnClickListener;

import android.view.ViewGroup;

import android.widget.Button;

import android.widget.TextView;


public class ResultFragment extends Fragment implements OnClickListener{

TextView textView;

MainActivity mainActivity;

public View onCreateView(LayoutInflater inflater, ViewGroup container,

Bundle savedInstanceState) {


mainActivity = (MainActivity)getActivity();

View view = inflater.inflate(R.layout.result_fragment, container, false);

textView = (TextView)view.findViewById(R.id.textView);

Button btn_prv = (Button)view.findViewById(R.id.btn_prv);


btn_prv.setOnClickListener(this);

return view;

}


@Override

public void onClick(View v) {

switch(v.getId()){

case R.id.btn_prv:

mainActivity.setPage(0);

break;

}

}

}

 



- result_fragment.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"

    android:background="#2F9D27"

    android:gravity="center" >

    

    <TextView 

        android:id="@+id/textView"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="회원정보"

        android:textSize="20dp"/>

    

    <Button 

        android:id="@+id/btn_prv"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="돌아가기"/>

</LinearLayout>

 



- MemberVo.java

package com.example.example1;


public class MemberVo {

private int idx;

private String id="";

private String pw="";

private String name="";

public int getIdx() {

return idx;

}

public void setIdx(int idx) {

this.idx = idx;

}

public String getId() {

return id;

}

public void setId(String id) {

this.id = id;

}

public String getPw() {

return pw;

}

public void setPw(String pw) {

this.pw = pw;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

 


- MyOpenHelper.java

package com.example.example1;


import android.content.Context;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

import android.widget.Toast;


public class MyOpenHelper extends SQLiteOpenHelper{

Context context;

public MyOpenHelper(Context context) {

super(context, "dbname2.sqlite", null, 1);

this.context = context;

}

public void onCreate(SQLiteDatabase db) {

//표준sql

//String형은 immutable 수정불가능한 객체다.

//따라서 String형을 계속 누적해나가면 변경되는 것이 아니라

//새롭게 생성된다. 문제점 해결을 우해 수정가능한 문자열 처리 개체를 사용한다.

StringBuffer sqlQry = new StringBuffer();

sqlQry.append("create table member(");

sqlQry.append("idx integer primary key autoincrement,");

sqlQry.append("id varchar(20),");

sqlQry.append("pw varchar(20),");

sqlQry.append("name varchar(20)");

sqlQry.append(");");

db.execSQL(sqlQry.toString());

System.out.println("데이터베이스 생성 성공");

Toast.makeText(context, "데이터베이스 생성 성공", Toast.LENGTH_LONG);

}

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

}

}

 

























반응형

댓글