안드로이드

 

R.layout.activity_management

<?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="match_parent"
    android:orientation="vertical"
    android:background="#d1d1d1">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/search"
        android:hint="검색"
        />


    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listView"
        android:layout_marginTop="10dp"
        android:layout_marginRight="15dp"
        android:layout_marginLeft="15dp"
        android:dividerHeight="10dp"
        android:divider="#d1d1d1">


    </ListView>






</LinearLayout>

 

 

 

 

class UserListAdapter

package kr.co.dothome.braverokmc.managerment;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
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 java.util.ArrayList;

/**
 * Created by choi on 2017-05-08.
 */

public class UserListAdapter extends BaseAdapter {

    private Context mContext;
    private ArrayList<MemberDTO> memberList;
    private LayoutInflater inflater;

    private Activity activity;
    private ArrayList<MemberDTO> saveList;


    public UserListAdapter(Context mContext, ArrayList<MemberDTO> memberList, Activity parentAtivity,
                           ArrayList<MemberDTO> saveList
                           ) {
        this.mContext = mContext;
        this.memberList = memberList;
        inflater=(LayoutInflater)mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
        activity=parentAtivity;
        this.saveList=saveList;
    }

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

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

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


    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {

        if(convertView==null){
            convertView=inflater.inflate(R.layout.user, parent, false);
        }

         TextView userID =(TextView)convertView.findViewById(R.id.userID);
         TextView userName =(TextView)convertView.findViewById(R.id.userName);
         TextView userPassword=(TextView)convertView.findViewById(R.id.userPassword);
         TextView userAge =(TextView)convertView.findViewById(R.id.userAge);

        userID.setText("아이디 : " +memberList.get(position).getUserID());
        userName.setText("이름 : " +memberList.get(position).getUserName());
        userPassword.setText("패스워드 : "+ memberList.get(position).getUserPassword());
        userAge.setText("나이 : " + memberList.get(position).getUserAge());



        Button button =(Button)convertView.findViewById(R.id.deleteButton);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

               // Toast.makeText(activity, "e" +position, Toast.LENGTH_SHORT).show();


                Response.Listener<String> responseListener =new Response.Listener<String>(){

                    @Override
                    public void onResponse(String response) {

                        try{
                            JSONObject jsonResposne =new JSONObject(response);
                            boolean success=jsonResposne.getBoolean("success");
                            if(success){

                                //검색 처리를 위한 saveList 제거
                                //현재 memberList i 값과 검색 처리를 위한 i 값이 다르다.
                                //즉 memberList 는 검색 결과 데이터 만 담겨 있고
                                //saverList 는 전체 데이터가 담겨 있기 때문이다.
                                for(int i=0; i<saveList.size(); i++){
                                    if(saveList.get(i).getUserID().equals(
                                            memberList.get(position).getUserID().toString())){
                                        saveList.remove(i);
                                        break;
                                    }
                                }

                                //ArrayList 에서 해당부분 제거
                                memberList.remove(position);

                                //어댑터에 알려줌
                                notifyDataSetChanged();
                            }

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

                    }
                };

               // Toast.makeText(activity, userID.getText().toString(), Toast.LENGTH_SHORT).show();

                DeleteRequest deleteRequest =new DeleteRequest(memberList.get(position).getUserID().toString(), responseListener);
                RequestQueue queue= Volley.newRequestQueue(activity);
                queue.add(deleteRequest);


            }
        });


/*
        if((position%2)==1){
          //  convertView.setBackgroundColor(0xffff8800);

        }else {
            convertView.setBackgroundColor(0xff748790);
        }
*/

        return convertView;
    }




}




 

class ManagementActivity

package kr.co.dothome.braverokmc.managerment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

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

import java.util.ArrayList;

public class ManagementActivity extends AppCompatActivity {

    //TextView userListTextView;
    private ListView listView;

    private ArrayList<MemberDTO> members;
    private ArrayList<MemberDTO> saveList;
    private UserListAdapter adapter;

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


      //  userListTextView=(TextView)findViewById(userListTextView);
        listView=(ListView)findViewById(R.id.listView);


        Intent intent=getIntent();

        if(intent!=null) {

     /*        Bundle membersBundle = intent.getBundleExtra("members");
             membsers=(ArrayList<MemberDTO>) membersBundle.get("members");
*/
            //검색처리에서 members 를 클리어 할 때 saveList 도 클리어 되는 현상 때문에
            //데이터를 다르게 처리 하였다.
            //=>오류 Bundle 에서 오류 가 있어서 변경


            members=new ArrayList<>();
            saveList = new ArrayList<>();

            String membersData =intent.getStringExtra("members");
            String saveListData =intent.getStringExtra("saveList");
            members=parsing(membersData);
            saveList=parsing(saveListData);


            adapter =new UserListAdapter(ManagementActivity.this, members, this, saveList);
            listView.setAdapter(adapter);


/*
            StringBuilder builder = new StringBuilder();
            for (MemberDTO dto : membsers) {

                builder.append("아이디 : "  + dto.getUserID()+"\n");
                builder.append( "이름 : " + dto.getUserName() +"\n");
                builder.append("패스워드 : " + dto.getUserPassword() +"\n");
                builder.append("나이 : " +dto.getUserAge() + "\n");
                builder.append("--------------------------------------\n\n\n");

            }
*/


        }


        EditText search =(EditText)findViewById(R.id.search);
        search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

               searchUser(s.toString());

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });



    }


    public void searchUser(String search){
        //검색에 글자를 입력하면 members 리스트는 제거
        members.clear();

      Toast.makeText(ManagementActivity.this, "memberSize : " + members.size() + " ,  saverList Size :" +
                saveList.size()+" ", Toast.LENGTH_SHORT).show();

        //saver List 에서 검색 목록을 찾은 후 이것을
        //members 에 데이터를 담는다.
        for(int i=0; i<saveList.size(); i++){

            if(saveList.get(i).getUserID().contains(search)){
                members.add(saveList.get(i));
                Log.i("TT", String.valueOf(i));
                //Toast.makeText(ManagementActivity.this, String.valueOf(i), Toast.LENGTH_SHORT).show();
            }
        }

        // 데이터가 갱신 되었음을 어댑터에 알린다.
        adapter.notifyDataSetChanged();

    }



    public  ArrayList<MemberDTO> parsing(String data) {

        ArrayList<MemberDTO> arrayList=new ArrayList<>();
         try {
            JSONObject jsonObject = new JSONObject(data);
            JSONArray jsonArray = new JSONArray(jsonObject.getString("response"));


            for (int i = 0; i < jsonArray.length(); i++) {

                MemberDTO member = new MemberDTO();

                JSONObject jsonObject1 = (JSONObject) jsonArray.get(i);
                member.setUserID(jsonObject1.getString("userID"));
                member.setUserName(jsonObject1.getString("userName"));
                member.setUserPassword(jsonObject1.getString("userPassword"));
                member.setUserAge(jsonObject1.getInt("userAge"));

                if (!member.getUserID().equals("admin")) {
                    arrayList.add(member);
                }
            }

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

        return arrayList;
    }


}







 

class MainActivity

package kr.co.dothome.braverokmc.managerment;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

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

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;


//로그인 성공시
public class MainActivity extends AppCompatActivity {


    TextView idText, pswordText, welcome;
    Button manageMentButton;
    String userID, userPassword,message;
    ArrayList<MemberDTO> members ;
    StringBuffer stringBuffer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        idText =(TextView)findViewById(R.id.idText);
        pswordText =(TextView)findViewById(R.id.pswordText);
        welcome=(TextView)findViewById(R.id.welcome);

        manageMentButton=(Button)findViewById(R.id.manageMentButton);


        manageMentButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new BackgroundTask().execute();
            }
        });


        Intent intent=getIntent();
        if(intent!=null){
            userID=intent.getStringExtra("userID");
            userPassword=intent.getStringExtra("userPassword");
            message ="환영 합니다. " + userID + "님!";

            idText.setText(userID);
            pswordText.setText(userPassword);
            welcome.setText(message);
        }


        if(!userID.equals("admin")){
            manageMentButton.setVisibility(View.GONE);
        }


    }


    //실제 회원 목록 가져오기,, AsyncTask 이용 또는 스레드 사용

    class BackgroundTask extends AsyncTask<Void, Void,  String>{

        String target;

        @Override
        protected void onPreExecute() {
            target="http://braverokmc2.dothome.co.kr/List.php";
        }


        @Override
        protected String doInBackground(Void... params) {

            InputStream is=null;
            InputStreamReader isr =null;
            BufferedReader reader=null;
            stringBuffer =new StringBuffer();


            try{

                URL url =new URL(target);
                HttpURLConnection httpURLConnection =(HttpURLConnection)url.openConnection();

                httpURLConnection.setConnectTimeout(10000);
                if(httpURLConnection.getResponseCode()==HttpURLConnection.HTTP_OK){

                    is=httpURLConnection.getInputStream();
                    reader=new BufferedReader(new InputStreamReader(is));

                    while(true){
                        String stringLine =reader.readLine();
                        if(stringLine==null)break;
                        stringBuffer.append(stringLine+"\n");
                    }

                }

                parsing(stringBuffer.toString());
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                try {
                    if(reader!=null) reader.close();
                    if(isr!=null) isr.close();
                    if(is!=null)is.close();

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

            }
            return null;
        }


        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }


        @Override
        protected void onPostExecute(String s) {

            Intent intent =new Intent(MainActivity.this, ManagementActivity.class);
/*

            Bundle bundle =new Bundle();
            bundle.putSerializable("members", members);
            intent.putExtra("members",  bundle);
*/

            //
            intent.putExtra("members", stringBuffer.toString());
            intent.putExtra("saveList", stringBuffer.toString());
            startActivity(intent);

        }

    }


    public void parsing(String data){

        members=new ArrayList<>();
        try{
            JSONObject jsonObject =new JSONObject(data);
            JSONArray jsonArray=new JSONArray(jsonObject.getString("response"));

            //arrayList 클리어
            members.clear();

            for(int i=0; i<jsonArray.length(); i++){

                MemberDTO member=new MemberDTO();

                JSONObject jsonObject1=(JSONObject)jsonArray.get(i);
                member.setUserID(jsonObject1.getString("userID"));
                member.setUserName(jsonObject1.getString("userName"));
                member.setUserPassword(jsonObject1.getString("userPassword"));
                member.setUserAge(jsonObject1.getInt("userAge"));

                if(!member.getUserID().equals("admin")) {
                    members.add(member);
                }
            }

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

    }





}

 

 

 

 

 

 

 

 

 

 

about author

PHRASE

Level 60  머나먼나라

양생법(養生法)은 몸에 손해가 되는 일을 하지 않는 것이 장수하는 방법이니라. -동의보감

댓글 ( 1)

댓글 남기기

작성