안드로이드


 

 

 

 

 

 

AndroidManifest.xml


    <uses-permission android:name="android.permission.INTERNET"/>

 

http://braverokmc.dothome.co.kr/include/json_members.json

json_members.json

{
members_info: [
{
name: "이순신",
age: 20,
hobbys: [
"낚시",
"요리"
],
info: {
no: 1,
id: "abcd",
pw: 1234
}
},
{
name: "hong gil soon",
age: 30,
hobbys: [
"독서",
"등산"
],
info: {
no: 2,
id: "efgh",
pw: 5678
}
},
{
name: "hong gil dong",
age: 20,
hobbys: [
"수영",
"요리"
],
info: {
no: 1,
id: "abcd",
pw: 1234
}
},
{
name: "강감창",
age: 30,
hobbys: [
"독서",
"등산"
],
info: {
no: 3,
id: "efgh",
pw: 5678
}
},
{
name: "이산",
age: 20,
hobbys: [
"살인",
"요리"
],
info: {
no: 4,
id: "abcd",
pw: 1234
}
},
{
name: "김하늘",
age: 30,
hobbys: [
"낚시",
"게임"
],
info: {
no: 5,
id: "efgh",
pw: 5678
}
},
{
name: "김민종",
age: 27,
hobbys: [
"수영",
"요리"
],
info: {
no: 6,
id: "abcd",
pw: 1234
}
},
{
name: "최준호",
age: 35,
hobbys: [
"독서",
"등산"
],
info: {
no: 7,
id: "aafgh",
pw: 5678
}
}
]
}

 

class MainActivity
package com.example.choi.mystudy29_2;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

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 {

    final static String TAG="MainActivity";
    String urlAddr="http://braverokmc.dothome.co.kr/include/json_members.json";
    Button threadButton, asyncTaskButton;
    ListView listView;
    ArrayList<Member> members;
    MemberAdapter adapter;

    ProgressDialog dialog;
    static String METHOD;

    MyThread thread;

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

        threadButton=(Button)findViewById(R.id.threadButton);
        asyncTaskButton=(Button)findViewById(R.id.asyncTaskButton);
        listView=(ListView)findViewById(R.id.listView1);


        threadButton.setOnClickListener(listener);
        asyncTaskButton.setOnClickListener(listener);
    }


    View.OnClickListener listener =new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            switch (v.getId()){

                case R.id.threadButton:

                    members=null;
                    METHOD="thread";
                    if(thread!=null)thread.interrupt();



                    thread=new MyThread(MainActivity.this);
                    thread.setDaemon(true);
                    thread.start();

                    break;


                //2. AsyncTask 사용
                case R.id.asyncTaskButton:
                    try {

                        members=null;
                        METHOD="async";
                        if(thread!=null)thread.interrupt();


                        NetWorkAsyncTask netWorkAsyncTask =new NetWorkAsyncTask(MainActivity.this, urlAddr, listView);
//반환된 arrayList 를 가져오는 온다.
// 그러나 async를 사용 할 경우 progressDialog 가 작동하지 않는다.
                        members =(ArrayList<Member>)netWorkAsyncTask.execute().get();
                        adapter= new MemberAdapter(MainActivity.this, members);
                        listView.setAdapter(adapter);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;

            }

        }
    };


    public void dialog(){
        dialog=new ProgressDialog(MainActivity.this);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setTitle("ProgressDialog");
        dialog.setMessage("JSON downLoad...");
        dialog.show();
    }


    class MyThread extends Thread{

        StringBuffer stringBuffer;
        Context context;

        public MyThread(Context context){
            this.context=context;
        }

        @Override
        public void run() {
            try {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //다이얼로그 호출
                        dialog();
                    }
                });

                contact();

                //데이터 완료후 다이얼로그 닫기
                if(dialog!=null){
                    dialog.dismiss();
                }


                adapter= new MemberAdapter(context, members);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        listView.setAdapter(adapter);
                    }
                });


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


        public void contact(){

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

                URL url =new URL(urlAddr);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(10000);

                if(connection.getResponseCode()==HttpURLConnection.HTTP_OK){
                    is=connection.getInputStream();
                    isr=new InputStreamReader(is);
                    reader=new BufferedReader(isr);



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

                        //0.01초 지연
                        try {
                            Thread.sleep(10);
                        }catch (Exception e){

                        }

                    }
                    Log.i(TAG, " stringBuffer : " +stringBuffer.toString());
                    parser(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 e2){
                    e2.printStackTrace();
                }
            }

        }



        public void parser(String str){

            members=new ArrayList<>();

            try {

                JSONObject jsonObject=new JSONObject(str);
                JSONArray jsonArray=new JSONArray(jsonObject.getString("members_info"));
                // arrayList 클리어
                members.clear();

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


                    Member member=new Member();

                    JSONObject jsonObject1=(JSONObject)jsonArray.get(i);

                    member.setName(jsonObject1.getString("name"));
                    member.setAge(jsonObject1.getInt("age"));

                    ArrayList<String> hobbys=new ArrayList<>();
                    JSONArray jsonArray2=jsonObject1.getJSONArray("hobbys");
                    for (int j=0; j<jsonArray2.length(); j++){
                        String hobby=jsonArray2.getString(j);
                        hobbys.add(hobby);
                    }
                    member.setHobbys(hobbys);

                    JSONObject jsonObject2=jsonObject1.getJSONObject("info");
                    member.setNo(jsonObject2.getInt("no"));
                    member.setId(jsonObject2.getString("id"));
                    member.setPw(jsonObject2.getInt("pw"));

                    members.add(member);
                }

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

        }


    }










}










 

 

R.layout.activity_main
<?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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.choi.mystudy29_2.MainActivity">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/line1"
        android:id="@+id/listView1" />

    <LinearLayout
        android:id="@+id/line1"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true">

        <Button
            android:text="쓰레드 방법"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/threadButton"
            android:layout_weight="1"
            android:textAllCaps="false"
            android:background="@android:color/holo_blue_dark"
            android:textColor="@android:color/background_light" />

        <Button
            android:text="AsyncTask방법"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/asyncTaskButton"
            android:layout_weight="1"
            android:textAllCaps="false"
            android:background="@android:color/holo_red_dark"
            android:textColor="@android:color/background_light" />
    </LinearLayout>
</RelativeLayout>

 

R.layout.custom_layout
<?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"
    >

    <TextView
        android:id="@+id/tv_name"
        android:text="tv_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tv_age"
        android:text="tv_age"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tv_hobbys"
        android:text="tv_hobbys"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tv_no"
        android:text="tv_no"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tv_id"
        android:text="tv_id"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />


</LinearLayout>

 

class Member 
package com.example.choi.mystudy29_2;

import java.util.ArrayList;

/**
 * Created by choi on 2017-03-17.
 */

public class Member {

    private String name;
    private int age;
    private ArrayList<String> hobbys;
    private int no;
    private String id;
    private int pw;

    public Member(){

    }

    public Member(String name, int age, ArrayList<String> hobbys, int no, String id, int pw) {
        this.name = name;
        this.age = age;
        this.hobbys = hobbys;
        this.no = no;
        this.id = id;
        this.pw = pw;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public ArrayList<String> getHobbys() {
        return hobbys;
    }

    public void setHobbys(ArrayList<String> hobbys) {
        this.hobbys = hobbys;
    }

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public int getPw() {
        return pw;
    }

    public void setPw(int pw) {
        this.pw = pw;
    }

    @Override
    public String toString() {
        return "Member{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", hobbys=" + hobbys +
                ", no=" + no +
                ", id='" + id + '\'' +
                ", pw=" + pw +
                '}';
    }
}

 

 class NetWorkAsyncTask
package com.example.choi.mystudy29_2;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ListView;

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;

/**
 * Created by choi on 2017-03-18.
 */

public class NetWorkAsyncTask extends AsyncTask<Integer, String, Object>{

    final static String TAG ="NetWorkAsyncTask";
    Context context;
    String mAddr;
    ProgressDialog progressDialog;
    ArrayList<Member> members;

    ListView listView;

    public NetWorkAsyncTask(Context context, String urlAddress, ListView listView ) {
        this.context=context;
        this.mAddr=urlAddress;
        members=new ArrayList<>();

        this.listView=listView;
    }


    @Override
    protected void onPreExecute() {
        Log.i(TAG, "onPreExecute()");
       progressDialog=new ProgressDialog(context);
       progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
       progressDialog.setTitle("Async Dialog");
       progressDialog.setMessage("JSON Down...");
       progressDialog.show();
    }



    @Override
    protected Object doInBackground(Integer... params) {
        Log.i(TAG, "doInBackground()");
        StringBuffer sb =new StringBuffer();
        InputStream is =null;
        InputStreamReader isr =null;
        BufferedReader bufferedReader=null;

        try {

            URL url =new URL(mAddr);
            HttpURLConnection connection=(HttpURLConnection)url.openConnection();
            //접속시간 10초간의 여유을 준다
            connection.setConnectTimeout(10000);

            //접속 코드 200 번 이면
            if(connection.getResponseCode()==HttpURLConnection.HTTP_OK){
                is=connection.getInputStream();
                isr=new InputStreamReader(is);
                bufferedReader=new BufferedReader(isr);

                String strLine;
                while ((strLine=bufferedReader.readLine())!=null){
                    sb.append(strLine +"\n");

                    //0.01초 지연
                    try {
                        Thread.sleep(10);
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                }
                Log.i(TAG,  "sb : " + sb.toString());
                parser(sb.toString());
            }

            //onProgressUpdate() 호출
            publishProgress(sb.toString());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if(bufferedReader!=null)bufferedReader.close();
                if(isr!=null)isr.close();
                if(is!=null)is.close();
            }catch (Exception e2){
                e2.printStackTrace();
            }
        }

        return members;
    }



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

    }

    @Override
    protected void onPostExecute(Object o) {

        Log.i(TAG, "onPostExecute()");
        progressDialog.dismiss();

    }


    @Override
    protected void onCancelled() {
        Log.i(TAG, "onCancelled()");
        progressDialog.dismiss();

    }


    public void parser(String str){
        Log.i(TAG, "parser()");
        Log.i(TAG, "str : "+str);

        try {

            JSONObject jsonObject =new JSONObject(str);
            JSONArray jsonArray=new JSONArray(jsonObject.getString("members_info"));

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

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

                JSONObject jsonObject1=(JSONObject)jsonArray.get(i);
                String name =jsonObject1.getString("name");
                int age =jsonObject1.getInt("age");

                ArrayList<String> hobbys =new ArrayList<>();
                JSONArray jsonArray2=jsonObject1.getJSONArray("hobbys");
                for(int j=0; j<jsonArray2.length(); j++){
                    String hobby=jsonArray2.getString(j);
                    hobbys.add(hobby);
                }

                JSONObject jsonObject2=jsonObject1.getJSONObject("info");
                int no=jsonObject2.getInt("no");
                String id =jsonObject2.getString("id");
                int pw=jsonObject2.getInt("pw");
                Member member = new Member(name,  age, hobbys, no,  id,  pw) ;
                members.add(member);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


}







 

 

class MemberAdapter
package com.example.choi.mystudy29_2;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by choi on 2017-03-18.
 */

public class MemberAdapter extends BaseAdapter {

    private Context mContext;
    private ArrayList<Member> data;
    private LayoutInflater inflater;


    public MemberAdapter(Context context, ArrayList<Member> members) {
        this.mContext=context;
        this.data=members;
        this.inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

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

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

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

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

        if(convertView==null){
            convertView=inflater.inflate(R.layout.custom_layout, parent, false);
        }
        TextView tv_name =(TextView)convertView.findViewById(R.id.tv_name);
        TextView tv_age =(TextView)convertView.findViewById(R.id.tv_age);
        TextView tv_hobbys=(TextView)convertView.findViewById(R.id.tv_hobbys);
        TextView tv_no =(TextView)convertView.findViewById(R.id.tv_no);
        TextView tv_id=(TextView)convertView.findViewById(R.id.tv_id);

        tv_name.setText("이름  : "+ data.get(position).getName());
        tv_age.setText("나이 : " + String.valueOf(data.get(position).getAge()));
        tv_hobbys.setText("취미 : "+ data.get(position).getHobbys().toString());
        tv_no.setText("번호 : " + String.valueOf(data.get(position).getNo()));
        tv_id.setText("아이디 : " + data.get(position).getId());

        if((position%2)==1){

            if(MainActivity.METHOD.equals("thread")){
                convertView.setBackgroundColor(0xffff8800);
            }else if (MainActivity.METHOD.equals("async")){
                convertView.setBackgroundColor(0x50efefef);
            }


        }else {

            if(MainActivity.METHOD.equals("thread")){
                convertView.setBackgroundColor(0xffffbb33);
            }else if (MainActivity.METHOD.equals("async")){
                convertView.setBackgroundColor(0x20b9b9b9);
            }
        }

        return convertView;
    }

/*
    LayoutInflater 클래스의 inflate메소드는 xml로 정의된 Layout을 View로 전개할 때 사용하며 정의된
    layout xml의 resouce의 id를 함수 파라메터로 전달하면 전개된 View를 리턴한다.

    전개할 View를 root에 붙일지에 따라 호출하는 파라메터가 달라지는데 root에 붙이지 않고
     전개된 View만 얻고 싶을 때는 아래 두 가지 코드를 이용 할 수 있다.

    View view = inflater.inflate(R.layout.layout_xxxx, null);

    View view = inflater.inflate(R.layout.layout_xxxx, root, false);

    첫번째 코드는 동작은 하지만 View를 전개할 때 참고할 parameter 정보가 없어 경고가 발생된다.

    Avoid passing null as the view root
            (needed to resolve layout parameters on the inflated layout's root element)
                    두번 째 샘플은 두번째 파라메터로 전달된 root의 레이아웃의 파라메터 정보를
                     참고해서 View를 전개하고 마지막 파라메터가 false이므로 root에 붙이지 않는다.
                      물론 경고도 발생하지 않는다.

                    전개된 View를 root에 attach하기
                    전개와 동시에 root에 붙이고 싶다면 아래 샘플 중에서 하나를 선택해서 사용한다.

                    View view = inflater.inflate(R.layout.layout_xxxx, root);

    View view = inflater.inflate(R.layout.layout_xxxx, root, true);
    Android 소스를 보면 inflate(int, ViewGoup)은 inflate(int, ViewGroup, boolean) 함수를 호출하므로 결과는 동일하다.
    View inflate(int resource, ViewGroup root) {
        return inflate(resource, root, root != null);

    */



}










 

 

 

android

 

about author

PHRASE

Level 60  머나먼나라

행복한 결혼생활을 위해 친절하고 부드러운 말투와 둘만의 은어나 표현을 개발하라.

댓글 ( 4)

댓글 남기기

작성