안드로이드

 

 

 

 

 

jsonex.json

{
 	"name" : "hong gil dong",
 	"age" : 20,
 	"hobbys" : ["수영", "요리"],
 	"info" : {
 		"no" : 1,
 		"id" : "abcd",
 		"pw" : 1234
 		}
 }

 

jsonex2.json

{
	"members_info" : [
		{
			"name" : "hong gil dong",
			"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" : "hong gil soon",
        			"age" : 30,
        			"hobbys" : ["독서", "등산"],
        			"info" : {
        				"no" : 3,
        				"id" : "efgh",
        				"pw" : 5678
        			}
        		}


,
        			{
            			"name" : "hong gil dong",
            			"age" : 20,
            			"hobbys" : ["수영", "요리"],
            			"info" : {
            				"no" : 4,
            				"id" : "abcd",
            				"pw" : 1234
            			}
            		},
            		{
            			"name" : "hong gil soon",
            			"age" : 30,
            			"hobbys" : ["독서", "등산"],
            			"info" : {
            				"no" : 5,
            				"id" : "efgh",
            				"pw" : 5678
            			}
            		}


            	,
            			{
                			"name" : "hong gil dong",
                			"age" : 20,
                			"hobbys" : ["수영", "요리"],
                			"info" : {
                				"no" : 6,
                				"id" : "abcd",
                				"pw" : 1234
                			}
                		},
                		{
                			"name" : "hong gil soon",
                			"age" : 30,
                			"hobbys" : ["독서", "등산"],
                			"info" : {
                				"no" : 7,
                				"id" : "efgh",
                				"pw" : 5678
                			}
                		}






	]
}

 

class MainActivity
package com.example.choi.mystudy26_3;

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.EditText;
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.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    final static String TAG="MainActivity";

    Button button1, button2;
    EditText editText;
    Member member;
    List<Member> memberList;

    ListView list1;

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

        button1=(Button)findViewById(R.id.button1);
        button2=(Button)findViewById(R.id.button2);
        editText=(EditText)findViewById(R.id.editText);
        list1=(ListView)findViewById(R.id.list1);


        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                parse();
                editText.setText(
                        member.getNo() +
                        " - 이름 :" + member.getName()
                     + " 나이 :" +member.getAge()
                    +", 취미 :[ " +member.getHobby1() + ","+ member.getHobby2() +" ]"
                    + " , 기타 정보 :" +member.getId() + " , "+member.getPw() +""

                );
            }
        });


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

                memberList=new ArrayList<Member>();
                parser2();
                MemberAdapter memberAdapter=new MemberAdapter(MainActivity.this, memberList);

                list1.setAdapter(memberAdapter);

            }
        });

    }


    public void parse(){

        InputStream is =getResources().openRawResource(R.raw.jsonex);
        InputStreamReader isr =new InputStreamReader(is);
        BufferedReader reader=new BufferedReader(isr);

        StringBuffer sb =new StringBuffer();
        String line=null;
        try {

            while ( (line=reader.readLine())!=null){
                sb.append(line);
            }
            Log.i(TAG, "sb : " +sb.toString());

            member=new Member();

            JSONObject jsonObject =new JSONObject(sb.toString());
            member.setName(jsonObject.getString("name"));
            member.setAge(jsonObject.getInt("age"));

            JSONArray jsonArray =jsonObject.getJSONArray("hobbys");
            for(int i =0; i<jsonArray.length(); i++){
                member.setHobby1(jsonArray.getString(0));
                member.setHobby2(jsonArray.getString(1));
            }

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

        }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();
            }

        }
    }

    private void parser2(){

        Log.i(TAG, "parser()2");

        InputStream is =getResources().openRawResource(R.raw.jsonex2);
        InputStreamReader isr =new InputStreamReader(is);
        BufferedReader reader=new BufferedReader(isr);

        StringBuffer sb=new StringBuffer();
        String line=null;

        try {

            while ( (line=reader.readLine())!=null){
                sb.append(line);
            }
            Log.i(TAG, "sb : " + sb.toString());


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

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

                member=new Member();

                JSONObject jsonObject1 =(JSONObject)jsonArray.get(i);
                member.setName(jsonObject1.getString("name"));
                member.setAge(jsonObject1.getInt("age"));

                JSONArray jsonArray2= jsonObject1.getJSONArray("hobbys");
                for(int j=0; j<jsonArray2.length(); j++){
                    member.setHobby1(jsonArray2.getString(0));
                    member.setHobby2(jsonArray2.getString(1));
                }

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

                memberList.add(member);
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                if(reader!=null) reader.close();
                if(isr!=null) isr.close();
                if(is!=null) is.close();
            }catch (Exception ex2){
                ex2.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.mystudy26_3.MainActivity">

    <EditText
        android:layout_width="wrap_content"
        android:inputType="textMultiLine"
        android:ems="10"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:id="@+id/editText"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_height="100dp" />


    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/editText"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_above="@+id/layout1"

        android:id="@+id/list1" />


    <LinearLayout
        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"
        android:id="@+id/layout1"
        >

        <Button
            android:text="JSON 파싱"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/button1"
            android:background="@android:color/holo_orange_dark"
            android:textColor="@android:color/background_light"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_weight="1" />

        <Button
            android:text="JSON 파싱 -List "
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/button2"
            android:layout_weight="1"
            android:textColor="@android:color/background_light"
            android:background="@android:color/holo_green_dark" />



    </LinearLayout>



</RelativeLayout>

 

class Member
package com.example.choi.mystudy26_3;

import java.io.Serializable;

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

public class Member implements Serializable{

    private String name;
    private int age;
    private String hobby1;
    private String hobby2;
    private int no;
    private String id;
    private int pw;

    public Member(){

    }


    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 String getHobby1() {
        return hobby1;
    }

    public void setHobby1(String hobby1) {
        this.hobby1 = hobby1;
    }

    public String getHobby2() {
        return hobby2;
    }

    public void setHobby2(String hobby2) {
        this.hobby2 = hobby2;
    }

    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 +
                ", hobby1='" + hobby1 + '\'' +
                ", hobby2='" + hobby2 + '\'' +
                ", no=" + no +
                ", id='" + id + '\'' +
                ", pw=" + pw +
                '}';
    }
}

 

class MemberAdapter
package com.example.choi.mystudy26_3;

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.List;

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

public class MemberAdapter extends BaseAdapter{

    Context context;
    List<Member> memberList;
    LayoutInflater layoutInflater;

    public MemberAdapter(Context context, List<Member> memberList) {
        this.context=context;
        this.memberList=memberList;
        layoutInflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @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(int position, View convertView, ViewGroup parent) {

        if(convertView==null){
            //inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
            // false 면   View를  생성 전개하고 마지막 파라메터가 false이므로 root에 붙이지 않는다.
            convertView=layoutInflater.inflate(R.layout.custom, parent, false);
        }

        TextView name =(TextView)convertView.findViewById(R.id.name);
        TextView age =(TextView)convertView.findViewById(R.id.age);
        TextView no=(TextView)convertView.findViewById(R.id.no);
        TextView id=(TextView)convertView.findViewById(R.id.id);
        TextView hobby1=(TextView)convertView.findViewById(R.id.hobby1);
        TextView hobby2=(TextView)convertView.findViewById(R.id.hobby2);
        TextView pw=(TextView)convertView.findViewById(R.id.pw);

        name.setText(memberList.get(position).getName());
        age.setText(String.valueOf(memberList.get(position).getAge()));
        no.setText(String.valueOf(memberList.get(position).getNo()));
        id.setText(String.valueOf(memberList.get(position).getId()));
        hobby1.setText(memberList.get(position).getHobby1());
        hobby2.setText(memberList.get(position).getHobby2());
        pw.setText(String.valueOf(memberList.get(position).getPw()));


        if ((position%2)==1) {
            convertView.setBackgroundColor(0x5000ff00);
        }else{
            convertView.setBackgroundColor(0x2000ff00);
        }

        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);

    */


}

 

 

R.layout.custom
<?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:layout_marginTop="5dp"
    android:layout_marginBottom="5dp">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="16dp"
        android:layout_weight="1"
        >

        <TextView
            android:text="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/no"
            android:layout_weight="1"
            android:textColor="@color/colorAccent"
            android:textStyle="normal|bold"
            android:textAlignment="center" />

        <TextView
            android:text="홍길동"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/name"
            android:layout_weight="3"
            android:textStyle="normal|bold"
            android:textAlignment="center" />

        <TextView
            android:text="나이"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/textView3"
            android:layout_weight="1"
            android:textStyle="normal|bold"
            android:textAlignment="center"
            android:textColor="@color/colorAccent"
            />

        <TextView
            android:text="30"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/age"
            android:layout_weight="1"
            android:textStyle="normal|bold"
            android:textAlignment="center" />
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="16dp"
        android:layout_weight="1"
        >

        <TextView
            android:text="취미"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/textView5"
            android:layout_weight="1"
            android:textStyle="normal|bold"
            android:textAlignment="center"
            android:textColor="@color/colorAccent"
             />

        <TextView
            android:text="취미1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/hobby1"
            android:layout_weight="1"

            android:textStyle="normal|bold"
            android:textAlignment="center" />

        <TextView
            android:text="취미2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/hobby2"
            android:layout_weight="1"
            android:textStyle="normal|bold"
            android:textAlignment="center" />


    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="20dp"
        android:layout_weight="1"
        android:layout_marginBottom="2dp">

        <TextView
            android:text="아이디"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textView8"
            android:layout_weight="1"
            android:textStyle="normal|bold"
            android:textAlignment="center"
            android:textColor="@color/colorAccent"

            android:layout_marginBottom="2dp" />

        <TextView
            android:text="avadd"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/id"
            android:layout_weight="1"
            android:textAlignment="center"
            android:textStyle="normal|bold" />

        <TextView
            android:text="패스워드"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textView10"
            android:layout_weight="1"
            android:textStyle="normal|bold"
            android:textAlignment="center"
            android:textColor="@color/colorAccent" />

        <TextView
            android:text="1111"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/pw"
            android:layout_weight="1"
            android:textStyle="normal|bold"
            android:textAlignment="center" />

    </LinearLayout>


</LinearLayout>

 

 

 

 

 

about author

PHRASE

Level 60  머나먼나라

자기가 아는 것이 적음을 인식하기 위해서 많은 것을 배워야 한다. -몽테뉴

댓글 ( 4)

댓글 남기기

작성