메뉴 건너뛰기

조회 수 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 Volley 로 웹요청하고 응답받기1 - Get방식 file 2020.12.14 348
176 Volley 로 웹요청하고 응답받기2 - Post방식 , 로그인-회원가입 (php,mysql 연동) file 2020.12.14 1425
175 Fragment를 통한 하단탭 예제1 file 2020.12.14 242
174 Fragment에서 Toast 사용하기 2020.12.14 371
173 Volley 이용시에 한글 깨질때 UTF-8로 변경 2020.12.14 339
172 줄바꿈 문자 치환 2020.12.14 289
171 구글맵 snippet을 두줄이상으로 구현하기 file 2020.12.14 478
170 Volley 로 웹요청하고 응답받기3 - Get방식 , json 읽기 (php,mysql) file 2020.12.14 373
169 android.support.v4.content.FileProvider not found file 2020.12.14 305
168 WebView에서 카메라 및 이미지 업로드 (선택적용가능) file 2020.12.14 2666
167 WebView 작업할때 Net::ERR_UNKNOWN_URL_SCHEME 에러 발생할때 (전화걸기,문자보내기 안된다) 2020.12.14 1056
166 WebView를 사용할때 HttpClient를 이용한 Session 유지 2018.12.27 4378
165 하이브리드 앱에서의 세션관리(로그인 상태 유지) 2018.12.27 4983
164 MediaPlayer 클래스 사용법 file 2018.10.02 1803
163 위젯 업데이트 주기 빠르게 하기 2018.10.02 2142
162 Android Studio에서 SQLCipher 라이브러리 추가 방법 file 2018.10.02 1769
161 안드로이드 WebView 에서 tel: 이 되지않는 경우. 2018.10.02 1624
160 안드로이드스택(Android Stack) 확인 file 2016.06.10 7778
159 AndroidManifest에 선언한 메타데이터(meta-data) 가져오기 2016.06.10 9304
158 버튼(Button) 패딩 제거 2016.06.10 7649
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 13 Next
/ 13

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

© k2s0o1d4e0s2i1g5n. All Rights Reserved