메뉴 건너뛰기

조회 수 11685 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

 

일단 php 로 연결하는 것과 똑같이 AsyncTask 를 사용해 안드로이드 코드를 만들었습니다. 그리고 웹상에 나와있는 JSP 를 이용하여 mysql 에 접속하기 예제들을 참고하여 다음과 같은 코드를 만들었습니다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
package com.example.hearingvalue;
 
import java.io.IOException;
import java.util.ArrayList;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
 
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
 
public class MainActivity extends Activity  {
 
    TextView userId,l250,l500,l1000,l2000,l4000,l8000,r250,r500,r1000,r2000,r4000,r8000;
    
    Button btnSave, btnCancle;
    
    loadJsp task;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        
        
        //텍스트 뷰 읽어오기
        btnSave = (Button)findViewById(R.id.btnSave);
        btnCancle = (Button)findViewById(R.id.btnCancel);
        l250 = (TextView)findViewById(R.id.Left1);
        l500 = (TextView)findViewById(R.id.Left2);
        l1000 = (TextView)findViewById(R.id.Left3);
        l2000 = (TextView)findViewById(R.id.Left4);
        l4000= (TextView)findViewById(R.id.Left5);
        l8000 = (TextView)findViewById(R.id.Left6);
        r250 = (TextView)findViewById(R.id.Right1);
        r500 = (TextView)findViewById(R.id.Right2);
        r1000 = (TextView)findViewById(R.id.Right3);
        r2000 = (TextView)findViewById(R.id.Right4);
        r4000= (TextView)findViewById(R.id.Right5);
        r8000 = (TextView)findViewById(R.id.Right6);
        userId = (TextView)findViewById(R.id.userId);
        
        
        
        //버튼 클릭
        
        btnSave.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // 저장을 눌렀을때
        
                
                task = new loadJsp();
                task.execute();
                        
            }
        });
        
        
        
        btnCancle.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                //취소를 선택했을때
                
            }
        });
        
        
    }
 
 
    class loadJsp extends AsyncTask<Void,String,Void>{
 
 
 
        @Override
        protected Void doInBackground(Void... param) {
            // TODO Auto-generated method stub
            
            try{
            HttpClient client = new DefaultHttpClient();
            
            
            // jsp 주소
            String postURL = "http://10.80.73.52:8080/cho/dbManager.jsp";
            
            
            
            HttpPost post = new HttpPost(postURL);
            ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
            
            //파
            params.add(new BasicNameValuePair("userId",userId.getText().toString()));
            params.add(new BasicNameValuePair("L250",l250.getText().toString()));
            params.add(new BasicNameValuePair("L500",l500.getText().toString()));
            params.add(new BasicNameValuePair("L1000",l1000.getText().toString()));
            params.add(new BasicNameValuePair("L2000",l2000.getText().toString()));
            params.add(new BasicNameValuePair("L4000",l4000.getText().toString()));
            params.add(new BasicNameValuePair("L8000",l8000.getText().toString()));
            params.add(new BasicNameValuePair("R250",r250.getText().toString()));
            params.add(new BasicNameValuePair("R500",r500.getText().toString()));
            params.add(new BasicNameValuePair("R1000",r1000.getText().toString()));
            params.add(new BasicNameValuePair("R2000",r2000.getText().toString()));
            params.add(new BasicNameValuePair("R4000",r4000.getText().toString()));
            params.add(new BasicNameValuePair("R8000",r8000.getText().toString()));
            
            UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
            post.setEntity(ent);
          
            HttpResponse responsePOST = client.execute(post);    
            HttpEntity resEntity = responsePOST.getEntity();   
            if (resEntity != null) 
            {       
                Log.i("RESPONSE", EntityUtils.toString(resEntity));  
                }
            
            }catch(IOException e){
                e.printStackTrace();
            }
            return null;
            
            
        }
        
    }
}
 



oncreate에 있는 코드는 뷰에 있는 값들을 받아오기위해 뷰를 객체로 받은 소스입니다. 지금 보니까 에디트 텍스트로 선언되있는 뷰들을 텍스트뷰로 읽어왔네요. 그래도 정상동작을 하긴하네요..? 신기방기


아무튼 중요한 소스는 이부분 입니다. 



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
protected Void doInBackground(Void... param) {
            // TODO Auto-generated method stub
            
            try{
            HttpClient client = new DefaultHttpClient();
            
            
            // jsp 주소
            String postURL = "http://10.80.73.52:8080/cho/dbManager.jsp";
            
            
            
            HttpPost post = new HttpPost(postURL);
            ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
            
            //파
            params.add(new BasicNameValuePair("userId",userId.getText().toString()));
            params.add(new BasicNameValuePair("L250",l250.getText().toString()));
            params.add(new BasicNameValuePair("L500",l500.getText().toString()));
            params.add(new BasicNameValuePair("L1000",l1000.getText().toString()));
            params.add(new BasicNameValuePair("L2000",l2000.getText().toString()));
            params.add(new BasicNameValuePair("L4000",l4000.getText().toString()));
            params.add(new BasicNameValuePair("L8000",l8000.getText().toString()));
            params.add(new BasicNameValuePair("R250",r250.getText().toString()));
            params.add(new BasicNameValuePair("R500",r500.getText().toString()));
            params.add(new BasicNameValuePair("R1000",r1000.getText().toString()));
            params.add(new BasicNameValuePair("R2000",r2000.getText().toString()));
            params.add(new BasicNameValuePair("R4000",r4000.getText().toString()));
            params.add(new BasicNameValuePair("R8000",r8000.getText().toString()));
            
            UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
            post.setEntity(ent);
          
            HttpResponse responsePOST = client.execute(post);    
            HttpEntity resEntity = responsePOST.getEntity();   
            if (resEntity != null) 
            {       
                Log.i("RESPONSE", EntityUtils.toString(resEntity));  
                }
            
            }catch(IOException e){
                e.printStackTrace();
            }
            return null;
            
            
        }



메인스레드와 별개의 스레드에서 jsp 에 보낼 url 을 만들고 전달할 파라미터값을 입력하는 부분입니다. 대략적인 순서는 일단 HttpClient 를 만듭니다. 그 다음 jsp의 주소값을 String에 저장한다음 HttpPost 객체로 만듭니다. 전달할 파라미터 값들은 ArrayList<NameValuePair> 객체로 만들어 BasicNameValuePair 형태로 만들어 리스트에 추가합니다. BasicNameValuePair 의 첫번째 인자값은 JSP상에서 request할 때 쓰이는 이름이고, 두번째 인자값이 실제적으로 전달할 파라미터 값들입니다.


그다음 이 파라미터값들을 UTF_8 로 인코딩합니다. 이렇게 안하면 한글이 깨지는 경우가 있습니다. 이제 아까 선언한 HttpPost 객체에 인고딩한 개체를 집어넣고 맨 처음 만든 HttpClient 객체를 사용해 execute 메소드를 이용해 실행합니다. 그 아래부분은 에러를 잡아내기위해 쓴 코드로 없어도 되는 코드입니다. 


잘 만들었다면 정상적으로 jsp 를 불러와 파라미터를 전달하고 mysql 에 입력되는 모습을 볼 수 있습니다. 


근데 저는 실행해도 mysql 에 입력이 안됬습니다. 왜 지? 고민을 하다가 제가 사용하는 서버가 jsp 를 지원하지 않는다는 것을 기억했습니다. 그래서 제가 여태 PHP 를 고집했던 거구요.. 하...


그래서 결국 톰캣을 설치해 jsp 를 실행했습니다. 안쓰던 톰캣을 설치하려니 여간 복잡한게 아니더군요. 일단 톰캣을 설치하고 jsp 를 만들기 위해 이클립스와 연동했습니다. 그리고 이클립스에서 jsp 코드를 만들고 export 해서 톰캣 서버에 올린다음 실행했더니 무사히 jsp 가 실행됬습니다. php로도 충분한데 왜 jsp를 사용하지는 아직 잘 모르겠지만, jsp로 만들어진 홈페이지에서는 jsp가 편할지도 모르겠네요 ^^..


참고로 jsp코드도 올리도록 하겠습니다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<%@ page contentType="text/html; charset=euc-kr" errorPage="DBError.jsp" %>
<%@ page import="java.sql.*"%>
<%
    String userId = request.getParameter("userId");
    
    String l250 = request.getParameter("L250");
    String l500 = request.getParameter("L500");
    String l1000 = request.getParameter("L1000");
    String l2000 = request.getParameter("L2000");
    String l4000 = request.getParameter("L4000");
    String l8000 = request.getParameter("L8000");
    
    String r250 = request.getParameter("R250");
    String r500 = request.getParameter("R500");
    String r1000 = request.getParameter("R1000");
    String r2000 = request.getParameter("R2000");
    String r4000 = request.getParameter("R4000");
    String r8000 = request.getParameter("R8000");
        
    Connection conn = null;
    Statement stmt = null;
    
    try{
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql://디비주소/hearingDB", "root", "0000");
        if (conn == null)
            throw new Exception("데이터베이스에 연결할 수 없습니다.");
        stmt = conn.createStatement();
        String command = String.format("insert into hearingDB " + 
                                       "(userId, L_250, L_500, L_1000, L_2000, L_4000, L_8000, R_250, 
                                       R_500, R_1000, R_2000, R_4000, R_8000) values 
                                      ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', 
                                     '%s', '%s', '%s');", userId, l250, l500, l1000, l2000, l4000, l8000, 
                                      r250, r500, r1000, r2000, r4000, r8000);
        int rowNum = stmt.executeUpdate(command);
        if (rowNum < 1)
            throw new Exception("데이터를 DB에 입력할 수 없습니다.");
    }
    finally{
        try{
            stmt.close();
        }
        catch(Exception ignored){
        }
        try{
            conn.close();
        }
        catch(Exception ignored){
        }
    }
    response.sendRedirect("DBInputResult.jsp");
%>    

 


List of Articles
번호 제목 날짜 조회 수
177 ScrollView의 활용 2015.07.16 6530
176 특정 폴더에서 오래된 파일 삭제하기 2015.07.16 6767
175 네트워크를 통해 받은 이미지를 파일로 저장하고, 크기 조절해서 불러오기 2015.07.16 6146
174 화면 해상도에 관계없는 레이아웃(Layout) 만들기 file 2015.07.16 8641
173 화면 회전에 따른 애니메이션 효과 구현하기 2015.07.16 8055
172 이미지의 Orientation를 체크해서 이미지 회전하기 2015.07.16 7658
171 이미지 버튼(ImageButton) 만들기 2015.07.16 7114
170 체크 박스(CheckBox)의 이미지 바꾸기 2015.07.16 6398
169 사용자 정의 팝업창 띄우기 2015.07.16 6337
168 EditText의 글자 수 제한 걸기 2015.07.16 13881
167 옵션 메뉴 동적으로 생성하기 2015.07.16 6926
166 네트워크 상태 변화 감지하기(BroadcastReceiver 사용) 2015.07.16 9935
165 푸쉬 알림 기능. GCM (Google Cloud Messaging) 사용하기 (1) file 2015.07.16 6726
164 푸쉬 알림 기능. GCM (Google Cloud Messaging) 사용하기 (2) file 2015.07.16 7292
163 푸쉬 알림 기능. GCM (Google Cloud Messaging) 사용하기 (3) file 2015.07.16 6267
162 탭 뷰에 탭 추가하기, 아이콘 넣기 file 2015.07.16 9360
161 스토리보드 짜는 방법 file 2015.07.16 15419
160 [안드로이드] Activity에 대해서 file 2015.07.16 6767
159 [안드로이드] 레이아웃의 기본1 file 2015.07.16 6962
158 [안드로이드] 레이아웃의 기본2 file 2015.07.16 7071
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 13 Next
/ 13

하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved