Android/활용

안드로이드 - 로그인, 회원가입 관리자모드 (삭제기능) 추가 (2)

섭섭입니다 2020. 8. 21. 17:43

이전 포스팅

https://seopseop911.tistory.com/31

안드로이드 - 로그인, 회원가입 관리자모드 (회원관리기능) 추가 (1)

이전 포스팅 https://seopseop911.tistory.com/30 안드로이드 - 로그인, 회원가입 간단 구현하기 (mysql, php 이용) 이 포스팅은 동빈나, 홍드로이드님의 유튜브를 참고하였습니다. 앞서 WAMP를 이용해서 다운��

seopseop911.tistory.com

 

이번에는 관리자모드 회원관리기능에서 삭제 버튼을 추가하여 데이터를 관리할 수 있게 해보았다.

 

 

 

우선 MySQL에 연결하여 삭제 작업을 수행할 PHP문을 하나 생성해야 한다.

 

< Delete.php >

<?php
    $con = mysqli_connect("localhost", "root", "비밀번호", "user");

    $userID = $_POST["userID"];

    $statement = mysqli_prepare($con, "DELETE FROM user WHERE userID = ?");
    mysqli_stmt_bind_param($statement, "s", $userID);
    mysqli_stmt_execute($statement);

    $response = array();
    $response["success"] = true;

    echo json_encode($response);

?>

 

 

 

 

TextView 부분들을 LinearLayout으로 묶은 뒤에 button도 또 다른 생성한 LinearLayout에 추가한다.

 

< user.xml >

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="horizontal"
    android:paddingRight="10dp"
    android:paddingLeft="10dp"
    android:paddingTop="5dp"
    android:paddingBottom="5dp"
    android:background="#ffffff">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center"
        android:paddingRight="10dp"
        android:paddingLeft="10dp"
        android:paddingTop="5dp"
        android:paddingBottom="5dp"
        >

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="삭제"
            android:background="#00a7f5"
            android:textColor="#fff"
            android:textSize="18dp"
            android:id="@+id/deleteButton"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingRight="10dp"
        android:paddingLeft="10dp"
        android:paddingTop="5dp"
        android:paddingBottom="5dp"
        >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/userID"
            android:text="아이디"
            android:textSize="20dp"
            android:textColor="#00a7f5" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/userPassword"
            android:text="비밀번호"
            android:textSize="15dp"
            android:textColor="#f92a3f" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/userName"
            android:text="이름"
            android:textSize="26dp"
            android:textColor="#000" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/userAge"
            android:text="나이"
            android:textSize="18dp"
            android:textColor="#00a7f5" />

    </LinearLayout>



</LinearLayout>

 

 

 

 

- Class 추가 

 

< DeleteRequest.java >

package com.hongdroid.registerloginexample;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;

import java.util.HashMap;
import java.util.Map;

public class DeleteRequest extends StringRequest {

    final static private String URL = "http://자신의IP/Delete.php";
    private Map<String, String> parameters;

    public DeleteRequest(String userID, Response.Listener<String> listener) {
        super(Request.Method.POST, URL, listener, null);
        parameters = new HashMap<>();
        parameters.put("userID",userID);
    }

    @Override
    public Map <String, String> getParams() {
        return parameters;
    }
}

 

 

 

< userListAdapter.java >

package com.hongdroid.registerloginexample;

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;
import org.w3c.dom.Text;

import java.util.List;

public class userListAdapter extends BaseAdapter {

    private Context context;
    private List<user> userList;
    private Activity parentActivity;

    public userListAdapter(Context context, List<user> userList, Activity parentActivity) {
        this.context = context;
        this.userList = userList;
        this.parentActivity = parentActivity;
    }

    @Override
    public int getCount() {
        return userList.size();
    }

    @Override
    public Object getItem(int position) {
        return userList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int i, View convertView, final ViewGroup parent) {
        View v = View.inflate(context, R.layout.user, null);
        final TextView userID = (TextView) v.findViewById(R.id.userID);
        TextView userPassword = (TextView) v.findViewById(R.id.userPassword);
        TextView userName = (TextView) v.findViewById(R.id.userName);
        TextView userAge = (TextView) v.findViewById(R.id.userAge);

        userID.setText(userList.get(i).getUserID());
        userPassword.setText(userList.get(i).getUserPassword());
        userName.setText(userList.get(i).getUserName());
        userAge.setText(userList.get(i).getUserAge());

        v.setTag(userList.get(i).getUserID());

        Button deleteButton = (Button) v.findViewById(R.id.deleteButton);
        deleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view)
            {
                Response.Listener<String> responseListener = new Response.Listener<String>() {
                     @Override
                     public void onResponse(String response) {
                          try   {
                                JSONObject jsonResponse = new JSONObject(response);
                                boolean success = jsonResponse.getBoolean("success");
                                if(success) {
                                    userList.remove(i);
                                    notifyDataSetChanged();
                                }
                          }
                          catch (Exception e) {
                              e.printStackTrace();
                          }
                       }
                };
                DeleteRequest deleteRequest = new DeleteRequest(userID.getText().toString(), responseListener);
                RequestQueue queue = Volley.newRequestQueue(parentActivity);
                queue.add(deleteRequest);
            }
        });

        return v;
    }
}

 

 

 

< ManagementActivity.java >

package com.hongdroid.registerloginexample;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.toolbox.JsonObjectRequest;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class ManagementActivity extends AppCompatActivity {

    private ListView listView;
    private userListAdapter adapter;
    private List<user> userList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_management);
        Intent intent = getIntent();

        listView = (ListView) findViewById(R.id.listView);
        userList = new ArrayList<user>();

        adapter = new userListAdapter(getApplicationContext(), userList, this);
        listView.setAdapter(adapter);

        try {
            JSONObject jsonObject = new JSONObject(intent.getStringExtra("userList"));
            JSONArray jsonArray = jsonObject.getJSONArray(("response"));
            int count =0;
            String userID, userPassword, userName, userAge;
            while(count < jsonArray.length())
            {
                JSONObject object = jsonArray.getJSONObject(count);
                userID = object.getString("userID");
                userPassword = object.getString("userPassword");
                userName = object.getString("userName");
                userAge = object.getString("userAge");
                user user = new user(userID, userPassword, userName, userAge);
                if(!userID.equals("admin"))
                     userList.add(user);
                count++;

            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

 

 

 

< RegisterActivity.java >

Intent intent =newIntent(RegisterActivity.this, LoginActivity.class);
startActivity(intent);
(지움)

finish()(추가)

package com.hongdroid.registerloginexample;

import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

public class RegisterActivity extends AppCompatActivity {

    private EditText et_id, et_pass, et_name, et_age;
    private Button btn_register;

    @Override
    protected void onCreate(Bundle savedInstanceState) { // 액티비티 시작시 처음으로 실행되는 생명주기!
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        // 아이디 값 찾아주기
        et_id = findViewById(R.id.et_id);
        et_pass = findViewById(R.id.et_pass);
        et_name = findViewById(R.id.et_name);
        et_age = findViewById(R.id.et_age);

        // 회원가입 버튼 클릭 시 수행
        btn_register = findViewById(R.id.btn_register);
        btn_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // EditText에 현재 입력되어있는 값을 get(가져온다)해온다.
                String userID = et_id.getText().toString();
                String userPass = et_pass.getText().toString();
                String userName = et_name.getText().toString();
                int userAge = Integer.parseInt(et_age.getText().toString());

                Response.Listener<String> responseListener = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            boolean success = jsonObject.getBoolean("success");
                            if (success) { // 회원등록에 성공한 경우
                                Toast.makeText(getApplicationContext(),"회원 등록에 성공하였습니다.",Toast.LENGTH_SHORT).show();
                                finish();
                            }
                            else { // 회원등록에 실패한 경우
                                Toast.makeText(getApplicationContext(),"회원 등록에 실패하였습니다.",Toast.LENGTH_SHORT).show();
                                return;
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                };
                // 서버로 Volley를 이용해서 요청을 함.
                RegisterRequest registerRequest = new RegisterRequest(userID,userPass,userName,userAge, responseListener);
                RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
                queue.add(registerRequest);

            }
        });

    }
}

 

 

 

 

- 회원가입.

 

 

 

 

 

 

- 관리자 로그인

 

 

 

- 회원관리 데이터 삭제. (admin 관리자 데이터는 보이지 않는 모습)

 

 

 

 

 

 

 

- MySQL 데이터 확인.

삭제 전

 

 

 

삭제 후

 

 


참고 : 동빈나 유튜브: https://www.youtube.com/channel/UChflhu32f5EUHlY7_SetNWw
홍드로이드 유튜브: https://www.youtube.com/watch?v=ktjJ8xtt2Hg&t=2998s