안드로이드

 

Android Device Monitor 에서   File explorer 를 보기 위해서는 

 

android Virture Device 의 android 가 7.0 이상에서는 안보인다. 

 

따라서 

 

 

API 버전을 23 이하로 낮춰 줘야 File explorer 볼수 있고 data  >  data  > database 를 db에 접근 할 수 있다.

 

 

   

 

 

MainActivity
package com.example.choi.ex03_db;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MainActivity extends AppCompatActivity {

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

    //버튼을 눌렀을때 호출 되는 메서드
    public void onClick(View v){
        Intent intent =null;
        switch (v.getId()){
            case R.id.button1:
               intent =new Intent(this, ProductAcitivity.class);
               break;
        }
        startActivity(intent);
    }



}

 

 

main.xml

 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.choi.ex03_db.MainActivity">

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

        <Button
            android:text="상품목록"
            android:onClick="onClick"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/button1" />
    </LinearLayout>

</RelativeLayout>

 

 

ProductDTO
package com.example.choi.ex03_db.dto;

/**
 * Created by choi on 2017-02-11.
 */

public class ProductDTO {

    private String product_name;
    private int price;
    private int amount;

    public ProductDTO(String product_name, int price, int amount) {
        this.product_name = product_name;
        this.price = price;
        this.amount = amount;
    }

    public String getProduct_name() {
        return product_name;
    }

    public void setProduct_name(String product_name) {
        this.product_name = product_name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public int getAmount() {
        return amount;
    }

    public void setAmount(int amount) {
        this.amount = amount;
    }

    @Override
    public String toString() {
        return "ProductDTO{" +
                "product_name='" + product_name + '\'' +
                ", price=" + price +
                ", amount=" + amount +
                '}';
    }


}

 

ProductDAO
package com.example.choi.ex03_db.dao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.example.choi.ex03_db.dto.ProductDTO;

/**
 * Created by choi on 2017-02-11.
 */

// Context :  문맥, 흐름, 현재 실행중인 화면
public class ProductDAO {

    Context context;
    SQLiteDatabase db;

    //Context context =activity
    public ProductDAO(Context context){
        this.context=context;
    }

//  Context.MODE_PRIVATE : 단독 사용 모드
    public SQLiteDatabase dbConn(){
        //데이터베이스를 오픈하거나 생성
        db=context.openOrCreateDatabase("product.db", Context.MODE_PRIVATE, null);

        //테이블이 존재하지 않으면  create
        // 자동증가컬럼은 자료형을 integer 로 하고 primary key 로 설정
        Log.v("메시지",  "dbConn() start");
        try{

            String sql ="create table if not exists product (" +
                    " id integer primary key autoincrement , " +
                    " product_name varchar(50) not null , " +
                    " price int  not null ," +
                    " amount int not null )";
            db.execSQL(sql);  // select 이외의 쿼리

        }catch (Exception e){
            e.printStackTrace();
            Log.v("메시지",  "dbConn() execSQL : " + e.getMessage());
        }

        return db;
    }

    public void insert(ProductDTO dto){
        SQLiteDatabase db=null;
        try{

            db =dbConn();
            Log.v("메시지",  "insert() start");
            String sql =String.format(" insert into product " +
                    " ( product_name , price, amount ) values " +
                    " ('%s' , %d, %d ) ", dto.getProduct_name(), dto.getPrice(), dto.getAmount() );
            db.execSQL(sql); // select  이외의 쿼리 실행
        }catch (Exception e){
            Log.v("메시지",  "error :" + e.getMessage());
            e.printStackTrace();
        }finally {
            if(db!=null) db.close(); //db 닫기
        }
    }



}

 

ProductAcitivity
package com.example.choi.ex03_db;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

public class ProductAcitivity extends AppCompatActivity {

    //1.변수 선언
    Button btnAdd;
    ListView list;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.product_acitivity);

        //2.객체 생성
        btnAdd=(Button)findViewById(R.id.btnAdd);
        list=(ListView)findViewById(R.id.list);
        //3.이벤트 처리
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(ProductAcitivity.this, ProductAddActivity.class);
                startActivity(intent);

            }
        });


    }


}

 

product_acitivity

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/product_acitivity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.choi.ex03_db.ProductAcitivity">

    <Button
        android:text="추가"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:id="@+id/btnAdd" />

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/btnAdd"
        android:id="@+id/list" />
</RelativeLayout>

 

 

ProductAddActivity

 

package com.example.choi.ex03_db;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.choi.ex03_db.dao.ProductDAO;
import com.example.choi.ex03_db.dto.ProductDTO;

public class ProductAddActivity extends AppCompatActivity {

    //1.변수 선언
    EditText editProductName ,editPrice, editAmount;
    Button btnSave;
    //SQLiteDatabase db; // sqlite 객체
    ProductDAO dao;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.product_add);

        //2. 객체 생성
        editProductName=(EditText)findViewById(R.id.editProductName);
        editPrice=(EditText)findViewById(R.id.editPrice);
        editAmount=(EditText)findViewById(R.id.editAmount);

        btnSave=(Button)findViewById(R.id.btnSave);

        dao=new ProductDAO(this);

        //3.버튼 클릭 이벤트
        //이벤트소스.이벤트리스너(이벤트핸들러)
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String product_name=editProductName.getText().toString();

                int price =Integer.parseInt(editPrice.getText().toString());

                int amount =Integer.parseInt(editAmount.getText().toString());

                ProductDTO dto
                            =new ProductDTO(product_name, price, amount);

                dao.insert(dto);

                Toast.makeText(ProductAddActivity.this, "저장 되었습니다.",
                        Toast.LENGTH_SHORT).show();
                finish(); //현재 화면을 종료함
            }
        });
    }





}

 

product_add
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/product_add"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.choi.ex03_db.ProductAddActivity">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:id="@+id/editProductName"
        android:hint="상품이름을 입력하세요" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="10"
        android:layout_marginTop="77dp"
        android:id="@+id/editAmount"
        android:hint="수량을 입력하세요"
        android:layout_below="@+id/editPrice"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="10"
        android:id="@+id/editPrice"
        android:hint="가격을 입력하세요"
        android:layout_below="@+id/editProductName"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="37dp" />

    <Button
        android:text="저장"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editAmount"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="35dp"
        android:id="@+id/btnSave" />


</RelativeLayout>

 

 

 

 

 

 

about author

PHRASE

Level 60  머나먼나라

군자는 의(義)를 가장 귀하게 여긴다. 바른 의리를 근본으로 하여 그 의(義)를 행함에 있어서 존비친소(尊卑親疎)를 생각해서 예(禮)로써 대하고 겸손한 태도로써 말하고 항상 거짓 없는 신으로써 완수하는 것이 참된 군자의 도리다. -논어

댓글 ( 5)

댓글 남기기

작성