뒤늦게 수정합니다 이미지 경로만 저장하여 하나의 디바이스에서만 불러 올 수 있습니다.
이 부분을 저도 착각하여 다음시간에 이미지 저장 후 불러오기 mysql편으로 올리겠습니다
오늘 프로필 이미지를 만들었지만,
또 하나 고전했던 것이 기존에
쓰던 데이터베이스에 이미지를 저장하고 불러오는 법을
알아내는 것이었다.
이렇게 복잡한 일이었을까?
아직 내가 초보라서 그런지, 정말 복잡한 방법들이 많았다.
나 같은 경우는 우분투 서버를 AWS EC2로 사용하고 있었기에,
구글링을 통해서 얻은 정보는
파이어 베이스를 사용해라.. 리눅스 서버를 사용해라 등등
지금 내 상황에 맞지 않는 답변들 밖에 없었다.
그래서 준비했다.
정말 간단히 이미지를 저장하고 불러오는 방법이다.
우선 phpmyadmin을 구축을 한 상태에서 진행하겠다.
나 같은 경우는 AWS서버를 구축 후 mysql을 설치하고, 동시에
php와 phpmyadmin을 putty를 통해 구축하였다.
아직 설치가 되어 있지 않는 분들은
이전에 썼던 이 글을 먼저 읽고 오길 바란다.
2021.03.03 - [Programing/Android Studio With Java] - putty에 phpMyAdmin 설치 후 안드로이드 연동하기 TIL#6
위에 두 글을 읽고 모두 시도한 후에
다시 이 글을 찾아와야 할 것이다.
혹은 닷홈이나 무료 웹호스팅 서버를 통해
phpmyadmin이 설치되어 있는 분들도
위에서 sftp설정을 하고 오셔야 이 실습을 진행할 수 있다.
이제 시작해보겠다.
우선 인터넷 권한(퍼미션) 따로 적지 않겠다.
당연히 권한을 준다.
볼리 라이브러리를 사용할 것이다.
implementation 'com.android.volley:volley:1.1.1'
사실 해결법은 그리 어렵지는 않다.
위에 글 중에 안드로이드 연동만 잘하면 되는 것이다.
우선 phpmyadmin에 데이터베이스 안에 테이블을 하나 만들어 줄 것인데,
sql문으로
다음과 같이 적어라.
CREATE TABLE `USER` ( `id` VARCHAR(20) NOT NULL, `profileimg` VARCHAR(100) NOT NULL, );
그러면 테이블 칼럼이 id와 profileimg 이 두 가지가 형성된 것을 볼 수 있다.
그리고 임의로 sql문에 값을 넣어보도록 하자.
INSERT INTO USER (id, profileimage) VALUES ('aaaa1111', 'aaa');
그러면 두 칼럼에 각각에 값이 들어가 있을 것이다.
이 상황은 만약 내가 회원가입을 하고 난 후에
내 아이디에 내가 원하는 프로필 사진을 저장한다는 가정하에
진행하겠다.
그렇다면 저 "aaaa1111'이라는 아이디를 통해서
이미지 파일을 데이터베이스에 저장할 것이다.
그렇다면 이미지 파일은 왜 aaa인가?
이유는 없다.
단지 스트링 형식으로 저장하기 위해 임의로 값을 준 것이다.
그러면 이제 sublimeText로 들어가서, php 파일을 두 개 만들 것이다.
하나는 저 이미지 파일을 가져오는 php이다.
이름은 상관없다.
comeon.php
<?php $con = mysqli_connect("서버주소", "아이디", "비번", "데이터베이스"); mysqli_query($con,'SET NAMES utf8'); $id = $_POST["id"]; $statement = mysqli_prepare($con, "SELECT * FROM USER WHERE id = ?"); mysqli_stmt_bind_param($statement, "s", $id); mysqli_stmt_execute($statement); mysqli_stmt_store_result($statement); mysqli_stmt_bind_result($statement, $id, $profileimage); $response = array(); $response["success"] = false; while(mysqli_stmt_fetch($statement)) { $response["success"] = true; $response["id"] = $id; $response["profileimage"] = $profileimage; } echo json_encode($response); ?>
위에 쿼리문에 뜻은 입력된 아이디를 통해 바인딩된 (같은 행에 있는)
데이터를 가져오는 것이다.
(id, profileimage) 이 두 가지이다.
그러고 나서 이미지를 저장하는 php이다.
save.php
<?php $con = mysqli_connect("서버 아이피 주소", "phpmyadmin아이디", "비밀번호", "데이터베이스 이름"); mysqli_query($con,'SET NAMES utf8'); $id = $_POST["id"]; $profileimg = $_POST["profileimg"]; mysqli_query($con, "UPDATE USER SET profileimg = '$profileimg' WHERE id = '$id'"); $response = array(); $response["success"] = true; echo json_encode($response); ?>
우선 이 php는 아이디 값을 통해서 이미지를 불러오는 것이다.
위에 쿼리 문은 "입력받은 아이디와 같은 행에 profileimage를 업데이트(수정)하겠다"라는 뜻이다.
자 그러면 이 php들을 저장하고 나서,
xml에 버튼 두 개를 넣어준다.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="불러오기" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.272" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.389" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="값 저장" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.702" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.389" /> </androidx.constraintlayout.widget.ConstraintLayout>
그리고 자바 코드이다.
MainActivity.java
public class MainActivity extends AppCompatActivity { String id = "aaaa1111"; //아이디 Uri uri; //uri 이미지 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button update = findViewById(R.id.button2); //값저장 Button comeon = findViewById(R.id.button); //불러오기 // 값을 저장한다. update.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { upDate(); } }); // 값을 불러온다. comeon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { comeOn(); } }); } private void comeOn() { //서버에서 이미지 가져오기 Response.Listener<String> responseListener = new Response.Listener<String>() { //여기서 여기서 Quest1에서 썼던 데이터를 다가져온다. @Override public void onResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); boolean success = jsonObject.getBoolean("success"); if(success){ String image = jsonObject.getString("profileimage"); //json데이터로 받은 image를 이미지뷰에 넣거나, //글라이드 라이브러리를 통해 사용하면 된다. } } catch (JSONException e) { e.printStackTrace(); return; } catch (Exception e) { e.printStackTrace(); } } }; ComeOn comeOn = new ComeOn(id, responseListener); RequestQueue queue = Volley.newRequestQueue(getApplicationContext()); queue.add(comeOn); } private void upDate() { //이미지 업데이트 하기 Response.Listener<String> responseListener = new Response.Listener<String>() { //여기서 여기서 Quest1에서 썼던 데이터를 다가져온다. @Override public void onResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); boolean success = jsonObject.getBoolean("success"); if(success){ Toast.makeText(MainActivity.this, "데이터베이스 이미지 바꾸기 성공", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); return; } catch (Exception e) { e.printStackTrace(); } } }; UpDate update = new UpDate(id, uri, responseListener); RequestQueue queue = Volley.newRequestQueue(getApplicationContext()); queue.add(update); } }
값을 불러올 메서드와 값을 업데이트(저장)할 메서드를
둘 다 볼리 라이브러리를 통해 구현했다.
이제 요청 각각 php를 통해 데이터베이스에 요청 코드를 전달할
코드를 작성해야 한다.
UpDate.java
public class UpDate extends StringRequest { //서버 url 설정(php파일 연동) final static private String URL="http://서버 아이피 주소/update.php"; private Map<String,String> map; public UpDate(String id, Uri profileimg, Response.Listener<String>listener){ super(Method.POST,URL,listener,null); map=new HashMap<>(); map.put("id", id); map.put("profileimg", profileimg+""); } @Override protected Map<String, String> getParams() throws AuthFailureError { return map; } }
값을 저장하는 코드이다.
id값과 profileimage값을 받는다.
여기서 Uri에 값을 스트링으로 보내야 하므로,
파라미터 끝에다가 ""을 붙여 스트링 값으로 만든 것을 볼 수 있다.
ComeOn.java
public class ComeOn extends StringRequest { //서버 url 설정(php파일 연동) final static private String URL="http://서버 아이피 주소/comeon.php"; private Map<String,String> map; public ComeOn(String id, Response.Listener<String>listener){ super(Method.POST,URL,listener,null); map=new HashMap<>(); map.put("id", id); } @Override protected Map<String, String> getParams() throws AuthFailureError { return map; } }
아이디 값을 이용해서 이미지 값을 불러오는 요청 코드를 쓴 자바이다.
이런 식으로 쓰게 되면
private void comeOn() { //서버에서 이미지 가져오기 Response.Listener<String> responseListener = new Response.Listener<String>() { //여기서 여기서 Quest1에서 썼던 데이터를 다가져온다. @Override public void onResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); boolean success = jsonObject.getBoolean("success"); if(success){ String image = jsonObject.getString("profileimage"); //json데이터로 받은 image를 이미지뷰에 넣거나, //글라이드 라이브러리를 통해 사용하면 된다. }
메인 액티비티 안에 comeOn메서드 안에
jsonObject에서 스트링 값으로 이미지를 얻어낼 수 있다.
이 값으로 이미지 뷰에 삽입하면 된다.
스트링 값이더라도 값은 Uri값이기 때문에
글라이드 라이브러리를 사용하길 바란다.
Glide.with(getApplicationContext()).load(image).into(넣을 이미지 뷰);
이런 식으로 말이다.
글라이드를 이용한 이미지 받아오기는
이 글을 참고하면 되겠다.
이렇게 이미지를 phpmyadmin을 통해 어떻게
데이터베이스에 값을 저장하고, 불러오는지 알아보았다.
https://github.com/qjsqjsaos/Tistrory14