메뉴 건너뛰기

조회 수 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 카카오톡 분석하기 (1) - sqlite 파해치기 file 2016.05.26 10063
236 카카오톡 대화내용 가져오기(sqlite3, chat_logs) file 2016.05.26 15116
235 초기화면 페이지를 만들어보자. splash 페이지 제작 file 2020.12.14 285
234 체크 박스(CheckBox)의 이미지 바꾸기 2015.07.16 6398
233 줄바꿈 문자 치환 2020.12.14 289
232 전화 인텐트와 나의 전화 번호가져오기 2014.08.28 6312
231 인텐트를 이용한 Activity간 데이터 전달 (사용자 정의 클래스) file 2015.07.16 7061
230 이미지의 Orientation를 체크해서 이미지 회전하기 2015.07.16 7658
229 이미지 버튼(ImageButton) 만들기 2015.07.16 7114
228 이미지 버튼 설정 2015.07.16 6378
227 위젯 업데이트 주기 빠르게 하기 2018.10.02 2142
226 월별 캘린더에 일정 입력 및 조회 기능 리스트로 추가하기 file 2015.07.16 18552
225 옵션 메뉴 동적으로 생성하기 2015.07.16 6926
224 어댑터 뷰(Adapter View) & 어댑터(Adapter) (1) file 2016.06.08 7852
223 앱 번들(Android App Bundle) 만들기 file 2021.09.14 305
222 암시적 인텐트를 사용한 인터넷열기, 전화걸기, 문자보내기 [Intent (인텐트)] file 2016.06.07 7736
221 알아놓으면 좋은 내용정리 2016.06.07 7458
220 안드로이트 비콘 스캐닝시 고려 사항 2015.07.26 6658
219 안드로이드용 채팅프로그램 클라이언트(java), 서버(c#) 소스 file 2016.05.19 11722
218 안드로이드와 mysql 연동시키기. php 와 json 사용 file 2015.07.16 24487
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 13 Next
/ 13

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

© k2s0o1d4e0s2i1g5n. All Rights Reserved