일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- rxjava disposable
- 안드로이드 레트로핏 crud
- 안드로이드 라이선스 종류
- 객체
- jvm이란
- android retrofit login
- 클래스
- ANR이란
- 멤버변수
- rxjava hot observable
- 안드로이드 유닛 테스트 예시
- 안드로이드 라이선스
- android ar 개발
- 안드로이드 레트로핏 사용법
- Rxjava Observable
- 안드로이드 유닛테스트란
- 플러터 설치 2022
- 2022 플러터 안드로이드 스튜디오
- 스택 큐 차이
- 스택 자바 코드
- ar vr 차이
- 안드로이드 유닛 테스트
- rxjava cold observable
- jvm 작동 원리
- 안드로이드 os 구조
- 서비스 vs 쓰레드
- 서비스 쓰레드 차이
- 2022 플러터 설치
- 자바 다형성
- 큐 자바 코드
- Today
- Total
나만을 위한 블로그
[Android] 갤러리에서 사진을 선택해 프로필 이미지로 지정하고 Volley로 서버에 업로드하는 법 본문
참고한 사이트 : https://www.youtube.com/watch?v=zkiGwNiSKLI
6편까지 길게 있어서 코드를 기록하려고 쓴다. AWS에서 작업하며 php, MySQL을 사용한다.
먼저 DB 설정이다. DB 이름은 users고 테이블 이름은 users_table이다.
다음은 php 파일이다. 대략적인 파일명은 주석식으로 써뒀다.
// volley_connect.php
<?php
$conn = mysqli_connect("11.111.111.11", "root", "비밀번호", "users");
// login.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$email = $_POST['email'];
$password = $_POST['password'];
require_once 'volley_connect.php';
$sql = "SELECT * FROM users_table WHERE email = '$email'";
$response = mysqli_query($conn, $sql);
$result = array();
$result['login'] = array();
if (mysqli_num_rows($response) === 1)
{
$row = mysqli_fetch_assoc($response);
if (password_verify($password, $row['password']))
{
$index['name'] = $row['name'];
$index['email'] = $row['email'];
$index['id'] = $row['id'];
array_push($result['login'], $index);
$result['success'] = "1";
$result['message'] = "success";
echo json_encode($result);
mysqli_close($conn);
}
else
{
$result['success'] = "0";
$result['message'] = "error";
echo json_encode($result);
mysqli_close($conn);
}
}
}
// edit_detail.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$name = $_POST['name'];
$email = $_POST['email'];
$id = $_POST['id'];
require_once 'volley_connect.php';
$sql = "UPDATE users_table SET name = '$name', email = '$email' WHERE id = '$id'";
if (mysqli_query($conn, $sql))
{
$result['success'] = "1";
$result['message'] = "사용자 정보 수정 완료";
echo json_encode($result);
mysqli_close($conn);
}
}
else
{
$result['success'] = "0";
$result['message'] = "사용자 정보 수정 실패";
echo json_encode($result);
mysqli_close($conn);
}
// read_detail.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$id = $_POST['id'];
require_once 'volley_connect.php';
$sql = "SELECT * FROM users_table WHERE id = '$id'";
$response = mysqli_query($conn, $sql);
$result = array();
$result['read'] = array();
if (mysqli_num_rows($response) === 1)
{
if ($row = mysqli_fetch_assoc($response))
{
$h['name'] = $row['name'];
$h['email'] = $row['email'];
array_push($result['read'], $h);
$result['success'] = "1";
echo json_encode($result);
}
}
}
else
{
$result['success'] = "0";
$result['message'] = "error";
echo json_encode($result);
mysqli_close($conn);
}
// register.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$password = password_hash($password, PASSWORD_DEFAULT);
require_once 'volley_connect.php';
$sql = "INSERT INTO users_table(name, email, password) VALUES ('$name', '$email', '$password')";
if (mysqli_query($conn, $sql))
{
$result["success"] = "1";
$result["message"] = "success";
echo json_encode($result);
mysqli_close($conn);
}
else
{
$result["success"] = "0";
$result["message"] = "error";
echo json_encode($result);
mysqli_close($conn);
}
}
// upload.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$id = $_POST['id'];
$photo = $_POST['photo'];
$path = "uploads/$id.jpeg";
$finalPath = "http://11.111.111.11/" . $path;
require_once 'volley_connect.php';
$sql = "UPDATE users_table SET photo = '$finalPath' WHERE id = '$id'";
if (mysqli_query($conn, $sql))
{
if (file_put_contents($path, base64_decode($photo)))
{
$result['success'] = "1";
$result['message'] = "success";
echo json_encode($result);
mysqli_close($conn);
}
}
}
다음은 안드로이드 코드다. 먼저 매니페스트에 인터넷 권한을 줘야 한다.
<uses-permission android:name="android.permission.INTERNET" />
그리고 application 태그 안에 두 속성을 넣어야 한다.
android:networkSecurityConfig="@xml/network_security_config"
android:usesCleartextTraffic="true"
android:networkSecurityConfig 속성을 건드리려면 res 폴더 안에 xml 폴더를 만들고 network_security_config이란 이름의 xml 파일을 하나 만들어야 한다. 이 파일의 내용은 아래와 같이 한다.
<?xml version="1.0" encoding="utf-8"?>
<network-security-config xmlns:tools="http://schemas.android.com/tools">
<base-config cleartextTrafficPermitted="true"
tools:ignore="InsecureBaseConfiguration" />
</network-security-config>
아래는 매니페스트의 최종 형태다. 이런 형태로 만들어지면 된다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.volley">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppThemeRegist"
android:networkSecurityConfig="@xml/network_security_config"
android:usesCleartextTraffic="true">
<activity android:name=".HomeActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".LoginActivity"/>
<activity android:name=".MainActivity"/>
</application>
</manifest>
그리고 메뉴가 사용되기 때문에, 마찬가지로 res 폴더 안에 menu 폴더를 만들고 menu_action.xml 파일을 하나 만들어준다.
icon 속성에 edit, save가 있는데 대충 수정이랑 저장에 맞는 이미지를 넣어주면 된다.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/menu_edit"
android:title="Edit"
android:icon="@drawable/edit"
app:showAsAction="always"/>
<item android:id="@+id/menu_save"
android:title="save"
android:icon="@drawable/save"
app:showAsAction="always"/>
</menu>
다음은 앱 수준 gradle 파일에 추가하는 의존성이다. 딱 3개만 입력한다.
3번째 것은 이미지뷰를 원 모양으로 나오게 하는 의존성이다.
implementation 'com.android.volley:volley:1.1.1'
implementation 'com.google.android.material:material:1.1.0'
implementation 'de.hdodenhof:circleimageview:2.2.0'
다음은 액티비티 클래스 파일을 제외한 클래스 파일이다. SessionManager.java 파일을 만들고 아래 내용을 복붙한다.
쉐어드 프리퍼런스를 활용해 로그인 세션을 유지할 수 있도록 하는 클래스다.
영상 만든 분은 PRIVATE_MODE = 0이라는 변수를 만드셨는데 그냥 쉐어드 이름 뒤에 0 넣으면 되는 걸 왜 굳이 변수로 만들어 쓰는지 지금도 이해가 안 간다. 개취인걸로 이해하려고 한다.
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import java.util.HashMap;
public class SessionManager {
SharedPreferences sharedPreferences;
public SharedPreferences.Editor editor;
public Context context;
int PRIVATE_MODE = 0;
private static final String PREF_NAME = "LOGIN";
private static final String LOGIN = "IS_LOGIN";
public static final String NAME = "NAME";
public static final String EMAIL = "EMAIL";
public static final String ID = "ID";
public SessionManager(Context context)
{
this.context = context;
sharedPreferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = sharedPreferences.edit();
}
public void createSession(String name, String email, String id)
{
editor.putBoolean(LOGIN, true);
editor.putString(NAME, name);
editor.putString(EMAIL, email);
editor.putString(ID, id);
editor.apply();
}
public boolean isLoggin()
{
return sharedPreferences.getBoolean(LOGIN, false);
}
public void checkLogin()
{
if (!this.isLoggin())
{
Intent i = new Intent(context, LoginActivity.class);
context.startActivity(i);
((HomeActivity) context).finish();
}
}
public HashMap<String, String> getUserDetail()
{
HashMap<String, String> user = new HashMap<>();
user.put(NAME, sharedPreferences.getString(NAME, null));
user.put(EMAIL, sharedPreferences.getString(EMAIL, null));
user.put(ID, sharedPreferences.getString(ID, null));
return user;
}
public void logout()
{
editor.clear();
editor.commit();
Intent i = new Intent(context, LoginActivity.class);
context.startActivity(i);
((HomeActivity) context).finish();
}
}
다음은 액티비티 xml 파일이다. activity_main, activity_home, activity_login 순서다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingStart="30dp"
android:paddingTop="80dp"
android:paddingEnd="30dp"
android:theme="@style/AppTheme"
tools:context=".MainActivity">
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="name"/>
<EditText
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="email"/>
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="password"/>
<EditText
android:id="@+id/c_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="confirm password"/>
<ProgressBar
android:id="@+id/loading"
android:layout_marginTop="30dp"
android:visibility="gone"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/btn_regist"
android:backgroundTint="@color/colorPrimary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="register"
android:layout_marginTop="30dp"/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".HomeActivity">
<de.hdodenhof.circleimageview.CircleImageView
android:id="@+id/profile_image"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_gravity="center"
android:src="@mipmap/ic_launcher"
android:layout_marginTop="50dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/Widget.AppCompat.ActionButton.CloseMode"
android:layout_gravity="center"
android:layout_marginTop="30dp"
android:text="edit photo"
android:id="@+id/btn_photo"/>
<LinearLayout
android:layout_marginStart="30dp"
android:layout_marginEnd="30dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/layout_text"
android:weightSum="2"
android:orientation="horizontal">
<ImageView
android:layout_width="70dp"
android:layout_height="50dp"
android:src="@drawable/name"
android:layout_weight="1"/>
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginStart="10dp"
android:inputType="textPersonName"
android:hint="name"/>
</LinearLayout>
<LinearLayout
android:layout_marginStart="30dp"
android:layout_marginEnd="30dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="2"
android:orientation="horizontal">
<ImageView
android:layout_width="70dp"
android:layout_height="50dp"
android:src="@drawable/email"
android:layout_weight="1"/>
<EditText
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginStart="10dp"
android:inputType="textPersonName"
android:hint="email"/>
</LinearLayout>
<Button
android:id="@+id/btn_logout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="logout"
android:layout_marginTop="400dp"
android:layout_marginStart="30dp"
android:layout_marginEnd="30dp"/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".LoginActivity"
android:paddingStart="30dp"
android:paddingEnd="30dp"
android:paddingTop="80dp">
<ImageView
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_marginBottom="30dp"
android:id="@+id/logo"
android:src="@mipmap/ic_launcher"/>
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/layout_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/logo">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/email"
android:hint="email"
android:inputType="textEmailAddress"/>
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/layout_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/layout_email">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/password"
android:hint="password"
android:inputType="textPassword"/>
</com.google.android.material.textfield.TextInputLayout>
<ProgressBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="35dp"
android:id="@+id/loading"
android:layout_below="@id/layout_password"
android:visibility="gone"/>
<Button
android:id="@+id/btn_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/layout_password"
android:layout_marginTop="30dp"
android:text="login"/>
<TextView
android:id="@+id/link_regist"
android:layout_marginBottom="20dp"
android:gravity="center"
android:text="register"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
다음은 액티비티 자바 클래스 파일이다. 마찬가지로 MainActivity, HomeActivity, LoginActivity 순이다.
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private EditText name, email, password, c_password;
private Button btn_regist;
private ProgressBar loading;
private static String URL_REGIST = "http://11.111.111.11/register.php";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loading = findViewById(R.id.loading);
name = findViewById(R.id.name);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
c_password = findViewById(R.id.c_password);
btn_regist = findViewById(R.id.btn_regist);
btn_regist.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
regist();
}
});
}
private void regist()
{
loading.setVisibility(View.VISIBLE);
btn_regist.setVisibility(View.GONE);
final String name = this.name.getText().toString().trim();
final String email = this.name.getText().toString().trim();
final String password = this.name.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGIST, new Response.Listener<String>() {
@Override
public void onResponse(String response)
{
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if (success.equals("1"))
{
Toast.makeText(MainActivity.this, "회원가입 성공", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "회원가입 도중 에러 발생 : " + e.toString(), Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_regist.setVisibility(View.VISIBLE);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(MainActivity.this, "회원가입 도중 에러 발생 : " + error.toString(), Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_regist.setVisibility(View.VISIBLE);
}
})
{
@Override
protected Map<String, String> getParams() throws AuthFailureError
{
Map<String, String> params = new HashMap<>();
params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import de.hdodenhof.circleimageview.CircleImageView;
public class HomeActivity extends AppCompatActivity {
private static final String TAG = HomeActivity.class.getSimpleName();
private TextView name, email;
private Button btn_logout, btn_photo;
SessionManager sessionManager;
String getId;
private static final String URL_HEAD = "http://11.111.111.11/read_detail.php";
private static final String URL_EDIT = "http://11.111.111.11/edit_detail.php";
private static final String URL_UPLOAD = "http://11.111.111.11/upload.php";
private Menu action;
private Bitmap bitmap;
CircleImageView profile_image;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
sessionManager = new SessionManager(this);
name = findViewById(R.id.name);
email = findViewById(R.id.email);
btn_logout = findViewById(R.id.btn_logout);
btn_photo = findViewById(R.id.btn_photo);
profile_image = findViewById(R.id.profile_image);
sessionManager.checkLogin();
HashMap<String, String> user = sessionManager.getUserDetail();
getId = user.get(sessionManager.ID);
// String mName = user.get(sessionManager.NAME);
// String mEmail = user.get(sessionManager.EMAIL);
// name.setText(mName);
// email.setText(mEmail);
// Intent intent = getIntent();
// String extraName = intent.getStringExtra("name");
// String extraEmail = intent.getStringExtra("email");
//
// name.setText(extraName);
// email.setText(extraEmail);
btn_logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
// finish();
sessionManager.logout();
}
});
btn_photo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
chooseFile();
}
});
}
private void getUserDetail()
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_HEAD, new Response.Listener<String>() {
@Override
public void onResponse(String response)
{
progressDialog.dismiss();
Log.e(TAG, response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
JSONArray jsonArray = jsonObject.getJSONArray("read");
if (success.equals("1"))
{
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
String strName = object.getString("name").trim();
String strEmail = object.getString("email").trim();
name.setText(strName);
email.setText(strEmail);
}
}
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
Toast.makeText(HomeActivity.this, "Error Reading Detail : " + e.toString(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error)
{
progressDialog.dismiss();
Toast.makeText(HomeActivity.this, "Error Reading Detail : " + error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
@Override
protected Map<String, String> getParams() throws AuthFailureError
{
Map<String, String> params = new HashMap<>();
params.put("id", getId);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
@Override
protected void onResume()
{
super.onResume();
getUserDetail();
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_action, menu);
action = menu;
action.findItem(R.id.menu_save).setVisible(false);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item)
{
switch (item.getItemId())
{
case R.id.menu_edit :
name.setFocusableInTouchMode(true);
email.setFocusableInTouchMode(true);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(name, InputMethodManager.SHOW_IMPLICIT);
action.findItem(R.id.menu_edit).setVisible(false);
action.findItem(R.id.menu_save).setVisible(true);
return true;
case R.id.menu_save :
saveEditDetail();
action.findItem(R.id.menu_edit).setVisible(true);
action.findItem(R.id.menu_save).setVisible(false);
name.setFocusableInTouchMode(false);
email.setFocusableInTouchMode(false);
name.setFocusable(false);
email.setFocusable(false);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// save
private void saveEditDetail()
{
final String name = this.name.getText().toString().trim();
final String email = this.email.getText().toString().trim();
final String id = getId;
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Saving...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_EDIT, new Response.Listener<String>() {
@Override
public void onResponse(String response)
{
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if (success.equals("1"))
{
Toast.makeText(HomeActivity.this, "Success!", Toast.LENGTH_SHORT).show();
sessionManager.createSession(name, email, id);
}
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
Toast.makeText(HomeActivity.this, "Error : " + e.toString(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error)
{
progressDialog.dismiss();
Toast.makeText(HomeActivity.this, "Error : " + error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
@Override
protected Map<String, String> getParams() throws AuthFailureError
{
Map<String, String> params = new HashMap<>();
params.put("name", name);
params.put("email", email);
params.put("id", id);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void chooseFile()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null)
{
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
profile_image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
uploadPicture(getId, getStringImage(bitmap));
}
}
private void uploadPicture(final String id, final String photo)
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Uploading...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_UPLOAD, new Response.Listener<String>() {
@Override
public void onResponse(String response)
{
Log.e(TAG, response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if (success.equals("1"))
{
progressDialog.dismiss();
Toast.makeText(HomeActivity.this, "Success!", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
Toast.makeText(HomeActivity.this, "Try Again! error : " + e.toString(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error)
{
progressDialog.dismiss();
Toast.makeText(HomeActivity.this, "Error : " + error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
@Override
protected Map<String, String> getParams() throws AuthFailureError
{
Map<String, String> params = new HashMap<>();
params.put("id", id);
params.put("photo", photo);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public String getStringImage(Bitmap bitmap)
{
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] imageByteArray = byteArrayOutputStream.toByteArray();
String encodedImage = Base64.encodeToString(imageByteArray, Base64.DEFAULT);
return encodedImage;
}
}
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class LoginActivity extends AppCompatActivity {
private EditText email, password;
private Button btn_login;
private TextView link_regist;
private ProgressBar loading;
private static final String URL_LOGIN = "http://11.111.111.11/login.php";
SessionManager sessionManager;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
sessionManager = new SessionManager(this);
loading = findViewById(R.id.loading);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
btn_login = findViewById(R.id.btn_login);
link_regist = findViewById(R.id.link_regist);
btn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
String mEmail = email.getText().toString().trim();
String mPass = password.getText().toString().trim();
if (!mEmail.isEmpty() || !mPass.isEmpty())
{
login(mEmail, mPass);
}
else
{
email.setError("이메일을 입력해 주세요");
password.setError("비밀번호를 입력해 주세요");
}
}
});
link_regist.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
startActivity(new Intent(LoginActivity.this, MainActivity.class));
}
});
}
private void login(final String email, final String password)
{
loading.setVisibility(View.VISIBLE);
btn_login.setVisibility(View.GONE);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN, new Response.Listener<String>() {
@Override
public void onResponse(String response)
{
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
JSONArray jsonArray = jsonObject.getJSONArray("login");
if (success.equals("1"))
{
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
String name = object.getString("name").trim();
String email = object.getString("email").trim();
String id = object.getString("id").trim();
sessionManager.createSession(name, email, id);
// Toast.makeText(LoginActivity.this, "로그인 성공, 이름 : " + name + ", 이메일 : " + email, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
intent.putExtra("name", name);
intent.putExtra("email", email);
startActivity(intent);
loading.setVisibility(View.GONE);
}
}
} catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
btn_login.setVisibility(View.VISIBLE);
Toast.makeText(LoginActivity.this, "에러 : " + e.toString(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error)
{
loading.setVisibility(View.GONE);
btn_login.setVisibility(View.VISIBLE);
Toast.makeText(LoginActivity.this, "에러 : " + error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
@Override
protected Map<String, String> getParams() throws AuthFailureError
{
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
모두 복붙 완료했다면 빌드해서 테스트해보면 된다.
'Android' 카테고리의 다른 글
[Android] 레트로핏으로 네이버 검색 API 사용하는 법 (0) | 2021.08.04 |
---|---|
[Android] Duplicate class android.support.v4.app.INotificationSideChannel 에러 해결 (0) | 2021.08.04 |
[Android] JSONArray 안의 JSONArray 파싱하는 방법 (0) | 2021.06.26 |
[Android] startActivityForResult()를 대체할 registerForActivityResult()로 이미지 가져오는 법 (0) | 2021.06.20 |
[Android] 로그에 사용할 태그 만드는 법 (0) | 2021.06.09 |