메뉴 건너뛰기

조회 수 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
번호 제목 날짜 조회 수
237 안드로이드 - 익명 클래스(Anonymous Class) 사용법 file 2021.03.31 281
236 안드로이드 - 문자열 리소스를 활용한 다국어 지원 file 2021.03.31 282
235 안드로이드 - SnackBar를 사용해 팝업창 띄우기 file 2021.03.31 282
234 안드로이드 - 옵션 메뉴 (Option Menu) 구현 방법 file 2021.04.01 283
233 초기화면 페이지를 만들어보자. splash 페이지 제작 file 2020.12.14 285
232 Java에서 XML 불러와서 동적 변화 주기 file 2021.03.31 288
231 줄바꿈 문자 치환 2020.12.14 289
230 [하이브리드앱] 링크를 웹뷰가 아닌 새로운 브라우저에서 열기 2021.09.30 293
229 패키지명을 한꺼번에 변경하기 (Refactor) file 2020.12.14 295
228 앱 번들(Android App Bundle) 만들기 file 2021.09.14 305
227 android.support.v4.content.FileProvider not found file 2020.12.14 308
226 안드로이드 - 리니어 레이아웃 (Linear Layout) file 2021.03.29 319
225 안드로이드 - 토스트(Toast) 메시지 사용하기. file 2021.03.31 321
224 안드로이드 - 뷰페이저(ViewPager) 구현 file 2021.04.02 323
223 안드로이드 앱배포하기 apk 만들기 file 2020.12.14 324
222 안드로이드 - 명시적 인텐트(Explicit Intent)와 암시적 인텐트 (Implicit Intent) file 2021.04.01 324
221 안드로이드 arrayList 를 Json으로 변환 / jsonarry file 2021.03.29 326
220 Firebase - 푸시알림 보내기 file 2021.09.30 339
219 Volley 이용시에 한글 깨질때 UTF-8로 변경 2020.12.14 343
218 안드로이드 - 버튼 이벤트 처리방법 정리 (리스너 구현 및 이벤트 핸들링) file 2021.03.31 343
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 13 Next
/ 13

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

© k2s0o1d4e0s2i1g5n. All Rights Reserved