본문 바로가기
안드로이드 웹앱 콘테츠 개발자 양성(국비지원)/Open API

Android Studio(기능) JSON 으로 DB데이터 불러오기

by 차누감 2019. 10. 22.
반응형

위와 같이 DB에 데이터와 이미지가 저장되어 있다. 이것을 JSON으로 불러오는 예제이다.

 

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
<?php
 
    header("Content-Type:text/html; charset=UTF-8");
 
    $conn= mysqli_connect("localhost","umul","aa142536!","umul");
 
    mysqli_query($conn"set names utf8");
 
    $sql"select * from talk";
    $result=mysqli_query($conn$sql);
 
    $rowCnt= mysqli_num_rows($result);
 
    $arrarray(); //빈 배열 생성
 
    for($i=0;$i<$rowCnt;$i++){
        $row= mysqli_fetch_array($result, MYSQLI_ASSOC);
        //각 각의 row를 $arr에 추가
        $arr[$i]= $row;
        
    }
 
    //배열을 json으로 변환하는 함수가 있음.
        $jsonData=json_encode($arr); //json배열로 만들어짐.
        echo "$jsonData";
 
    mysqli_close($conn);
 
?>
 
 

인터넷 창에 경로를 붙여 넣자.

 

위와 같이 json 내용을 확인 가능하다.

이제 DB에 있는 데이터를 json으로 변환하여 불러오자.

참고 : volleyplus:+ 라이브러리는 dev.dworks.libs:volleyplus:+로 검색해야 나온다.

 

Theme를 살짝 바꾸겠다.

기본 화면 구성을 해보자.

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
<?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=".MainActivity">
 
        android:id="@+id/recycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#DDDDDD">
 
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="load data"
        android:textAllCaps="false"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_margin="16dp"
        android:onClick="clickLoad"/>
 
</RelativeLayout>
 
 

이제 대량의 데이터를 저장할 Item Class를 만들자.

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
 
public class Item {
 
    int no;
    String name;
    String msg;
    String imgPath;
    String date;
 
    public Item() {
    }
 
    public Item(int no, String name, String msg, String imgPath, String date) {
        this.no = no;
        this.name = name;
        this.msg = msg;
        this.imgPath = imgPath;
        this.date = date;
    }
 
    public int getNo() {
        return no;
    }
 
    public void setNo(int no) {
        this.no = no;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getMsg() {
        return msg;
    }
 
    public void setMsg(String msg) {
        this.msg = msg;
    }
 
    public String getImgPath() {
        return imgPath;
    }
 
    public void setImgPath(String imgPath) {
        this.imgPath = imgPath;
    }
 
    public String getDate() {
        return date;
    }
 
    public void setDate(String date) {
        this.date = date;
    }
}
 
 
 

대량의 데이터가 어떻게 보여질지 화면을 구성하자.

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?xml version="1.0" encoding="utf-8"?>
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardCornerRadius="8dp"
    app:cardElevation="4dp"
    android:layout_margin="16dp">
 
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
 
        <TextView
            android:id="@+id/tv_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="title"
            android:textColor="#555555"
            android:textStyle="bold"
            android:textSize="24sp"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginBottom="16dp"/>
 
        <TextView
            android:id="@+id/tv_date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="2019-10-22 13:46:25"
            android:textColor="#888888"
            android:textSize="10sp"
            android:textStyle="bold"
            android:layout_alignParentRight="true"
            android:layout_alignBaseline="@+id/tv_name"
            android:layout_marginRight="16dp"/>
 
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#cccccc"
            android:layout_below="@+id/tv_name"
            android:layout_marginLeft="4dp"
            android:layout_marginRight="4dp"/>
 
        <TextView
            android:id="@+id/tv_msg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="this is message"
            android:textColor="#888888"
            android:textStyle="bold"
            android:layout_below="@+id/tv_name"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="8dp"/>
 
        <ImageView
            android:id="@+id/iv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@mipmap/ic_launcher"
            android:layout_below="@id/tv_msg"
            android:adjustViewBounds="true"
            android:maxHeight="600dp"
            android:layout_marginTop="8dp"/>
<!--        android:adjustViewBounds="true" 뷰 사이즈로 이미지를 키워줌, 그리고 이미지 비율을 유지하며 맞춤-->
<!--        android:maxHeight="600dp 는 adjustViewBounds 써야 유효하다. -->
    </RelativeLayout>
 
 
 
 

이제 어댑터를 만들자.

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
 
import android.content.Context;
 
import androidx.annotation.NonNull;
 
 
 
public class ItemAdapter extends RecyclerView.Adapter {
 
    Context context;
    ArrayList<Item> items;
 
    public ItemAdapter(Context context, ArrayList<Item> items) {
        this.context = context;
        this.items = items;
    }
 
    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater= LayoutInflater.from(context);
        View itemView=inflater.inflate(R.layout.recycler_item,parent,false);
 
        VH holder=new VH(itemView);
        return holder;
    }
 
    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        VH vh= (VH) holder;
 
        Item item= items.get(position);
 
    }
 
    @Override
    public int getItemCount() {
        return items.size();
    }
 
    class VH extends RecyclerView.ViewHolder{
 
        TextView tvName;
        TextView tvDate;
        TextView tvMsg;
        ImageView iv;
 
        public VH(@NonNull View itemView) {
            super(itemView);
 
            tvName=itemView.findViewById(R.id.tv_name);
            tvDate=itemView.findViewById(R.id.tv_date);
            tvMsg=itemView.findViewById(R.id.tv_msg);
            iv=itemView.findViewById(R.id.iv);
 
        }
    }
}
 
 
 

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
 
 
 
 
 
 
public class MainActivity extends AppCompatActivity {
 
    RecyclerView recyclerView;
 
    ArrayList<Item> items= new ArrayList<>();
 
    ItemAdapter adapter;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        recyclerView=findViewById(R.id.recycler);
        adapter= new ItemAdapter(this, items);
        recyclerView.setAdapter(adapter);
 
        //리사이클러뷰의 레이아웃 매니저 설정
        LinearLayoutManager layoutManager=new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
        recyclerView.setLayoutManager(layoutManager);
    }
 
    public void clickLoad(View view) {
 
        //Volley+ 라이브러리 사용
 
        //서버주소
        String serverUrl="http://umul.dothome.co.kr/Android/loadDBtoJson.php";
 
        //결과를 JsonArray 받을 것이므로..
        //StringRequest가 아니라..
        //JsonArrayRequest를 이용할 것임
        JsonArrayRequest jsonArrayRequest= new JsonArrayRequest(Request.Method.POST, serverUrl, nullnew Response.Listener<JSONArray>() {
            //volley 라이브러리의 GET방식은 버튼 누를때마다 새로운 갱신 데이터를 불러들이지 않음. 그래서 POST 방식 사용
            @Override
            public void onResponse(JSONArray response) {
                Toast.makeText(MainActivity.this, response.toString(), Toast.LENGTH_SHORT).show();
 
 
                //파라미터로 응답받은 결과 JsonArray를 분석
 
                items.clear();
                adapter.notifyDataSetChanged();
                    try {
 
                        for(int i=0;i<response.length();i++){
                            JSONObject jsonObject= response.getJSONObject(i);
 
                            int no= Integer.parseInt(jsonObject.getString("no")); //no가 문자열이라서 바꿔야함.
                            String name=jsonObject.getString("name");
                            String msg=jsonObject.getString("message");
                            String imgPath=jsonObject.getString("imgPath");
                            String date=jsonObject.getString("date");
 
                            //이미지 경로의 경우 서버 IP가 제외된 주소이므로(uploads/xxxx.jpg) 바로 사용 불가.
                            imgPath = "http://umul.dothome.co.kr/Android/"+imgPath;
 
                            items.add(0,new Item(no,name, msg, imgPath, date)); // 첫 번째 매개변수는 몇번째에 추가 될지, 제일 위에 오도록
                            adapter.notifyItemInserted(0);
                        }
                    } catch (JSONException e) {e.printStackTrace();}
 
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this"ERROR", Toast.LENGTH_SHORT).show();
            }
        });
 
        //실제 요청 작업을 수행해주는 요청큐 객체 생성
        RequestQueue requestQueue= Volley.newRequestQueue(this);
 
        //요청큐에 요청 객체 생성
        requestQueue.add(jsonArrayRequest);
 
 
    }
}
 
 
 

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
<?xml version="1.0" encoding="utf-8"?>
 
    <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/AppTheme"
        android:usesCleartextTraffic="true">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <uses-library android:name="org.apache.http.legacy" android:required="false"/>
    </application>
    
 
</manifest>
 
 

<최종 실행 화면>


복붙용 참고 코드 

loadJsontoDB.php 

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
<?php
 
    header("Content-Type:text/html; charset=UTF-8");
 
    $conn= mysqli_connect("localhost","umul","aa142536!","umul");
 
    mysqli_query($conn"set names utf8");
 
    $sql"select * from talk";
    $result=mysqli_query($conn$sql);
 
    $rowCnt= mysqli_num_rows($result);
 
    $arrarray(); //빈 배열 생성
 
    for($i=0;$i<$rowCnt;$i++){
        $row= mysqli_fetch_array($result, MYSQLI_ASSOC);
        //각 각의 row를 $arr에 추가
        $arr[$i]= $row;
        
    }
 
    //배열을 json으로 변환하는 함수가 있음.
        $jsonData=json_encode($arr); //json배열로 만들어짐.
        echo "$jsonData";
 
    mysqli_close($conn);
 
?>
 
 

activity_main.xml 

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
<?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=".MainActivity">
 
        android:id="@+id/recycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#DDDDDD">
 
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="load data"
        android:textAllCaps="false"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_margin="16dp"
        android:onClick="clickLoad"/>
 
</RelativeLayout>
 
 

Item.java

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
 
public class Item {
 
    int no;
    String name;
    String msg;
    String imgPath;
    String date;
 
    public Item() {
    }
 
    public Item(int no, String name, String msg, String imgPath, String date) {
        this.no = no;
        this.name = name;
        this.msg = msg;
        this.imgPath = imgPath;
        this.date = date;
    }
 
    public int getNo() {
        return no;
    }
 
    public void setNo(int no) {
        this.no = no;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getMsg() {
        return msg;
    }
 
    public void setMsg(String msg) {
        this.msg = msg;
    }
 
    public String getImgPath() {
        return imgPath;
    }
 
    public void setImgPath(String imgPath) {
        this.imgPath = imgPath;
    }
 
    public String getDate() {
        return date;
    }
 
    public void setDate(String date) {
        this.date = date;
    }
}
 
 
 

recycler_item.xml

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?xml version="1.0" encoding="utf-8"?>
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardCornerRadius="8dp"
    app:cardElevation="4dp"
    android:layout_margin="16dp">
 
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
 
        <TextView
            android:id="@+id/tv_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="title"
            android:textColor="#555555"
            android:textStyle="bold"
            android:textSize="24sp"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginBottom="16dp"/>
 
        <TextView
            android:id="@+id/tv_date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="2019-10-22 13:46:25"
            android:textColor="#888888"
            android:textSize="10sp"
            android:textStyle="bold"
            android:layout_alignParentRight="true"
            android:layout_alignBaseline="@+id/tv_name"
            android:layout_marginRight="16dp"/>
 
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#cccccc"
            android:layout_below="@+id/tv_name"
            android:layout_marginLeft="4dp"
            android:layout_marginRight="4dp"/>
 
        <TextView
            android:id="@+id/tv_msg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="this is message"
            android:textColor="#888888"
            android:textStyle="bold"
            android:layout_below="@+id/tv_name"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="8dp"/>
 
        <ImageView
            android:id="@+id/iv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@mipmap/ic_launcher"
            android:layout_below="@id/tv_msg"
            android:adjustViewBounds="true"
            android:maxHeight="600dp"
            android:layout_marginTop="8dp"/>
<!--        android:adjustViewBounds="true" 뷰 사이즈로 이미지를 키워줌, 그리고 이미지 비율을 유지하며 맞춤-->
<!--        android:maxHeight="600dp 는 adjustViewBounds 써야 유효하다. -->
    </RelativeLayout>
 
 
 
 

ItemAdapter.java

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
 
import android.content.Context;
 
import androidx.annotation.NonNull;
 
 
 
public class ItemAdapter extends RecyclerView.Adapter {
 
    Context context;
    ArrayList<Item> items;
 
    public ItemAdapter(Context context, ArrayList<Item> items) {
        this.context = context;
        this.items = items;
    }
 
    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater= LayoutInflater.from(context);
        View itemView=inflater.inflate(R.layout.recycler_item,parent,false);
 
        VH holder=new VH(itemView);
        return holder;
    }
 
    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        VH vh= (VH) holder;
 
        Item item= items.get(position);
 
    }
 
    @Override
    public int getItemCount() {
        return items.size();
    }
 
    class VH extends RecyclerView.ViewHolder{
 
        TextView tvName;
        TextView tvDate;
        TextView tvMsg;
        ImageView iv;
 
        public VH(@NonNull View itemView) {
            super(itemView);
 
            tvName=itemView.findViewById(R.id.tv_name);
            tvDate=itemView.findViewById(R.id.tv_date);
            tvMsg=itemView.findViewById(R.id.tv_msg);
            iv=itemView.findViewById(R.id.iv);
 
        }
    }
}
 
 
 

MainActivity.java

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
 
 
 
 
 
 
public class MainActivity extends AppCompatActivity {
 
    RecyclerView recyclerView;
 
    ArrayList<Item> items= new ArrayList<>();
 
    ItemAdapter adapter;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        recyclerView=findViewById(R.id.recycler);
        adapter= new ItemAdapter(this, items);
        recyclerView.setAdapter(adapter);
 
        //리사이클러뷰의 레이아웃 매니저 설정
        LinearLayoutManager layoutManager=new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
        recyclerView.setLayoutManager(layoutManager);
    }
 
    public void clickLoad(View view) {
 
        //Volley+ 라이브러리 사용
 
        //서버주소
        String serverUrl="http://umul.dothome.co.kr/Android/loadDBtoJson.php";
 
        //결과를 JsonArray 받을 것이므로..
        //StringRequest가 아니라..
        //JsonArrayRequest를 이용할 것임
        JsonArrayRequest jsonArrayRequest= new JsonArrayRequest(Request.Method.POST, serverUrl, nullnew Response.Listener<JSONArray>() {
            //volley 라이브러리의 GET방식은 버튼 누를때마다 새로운 갱신 데이터를 불러들이지 않음. 그래서 POST 방식 사용
            @Override
            public void onResponse(JSONArray response) {
                Toast.makeText(MainActivity.this, response.toString(), Toast.LENGTH_SHORT).show();
 
 
                //파라미터로 응답받은 결과 JsonArray를 분석
 
                items.clear();
                adapter.notifyDataSetChanged();
                    try {
 
                        for(int i=0;i<response.length();i++){
                            JSONObject jsonObject= response.getJSONObject(i);
 
                            int no= Integer.parseInt(jsonObject.getString("no")); //no가 문자열이라서 바꿔야함.
                            String name=jsonObject.getString("name");
                            String msg=jsonObject.getString("message");
                            String imgPath=jsonObject.getString("imgPath");
                            String date=jsonObject.getString("date");
 
                            //이미지 경로의 경우 서버 IP가 제외된 주소이므로(uploads/xxxx.jpg) 바로 사용 불가.
                            imgPath = "http://umul.dothome.co.kr/Android/"+imgPath;
 
                            items.add(0,new Item(no,name, msg, imgPath, date)); // 첫 번째 매개변수는 몇번째에 추가 될지, 제일 위에 오도록
                            adapter.notifyItemInserted(0);
                        }
                    } catch (JSONException e) {e.printStackTrace();}
 
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this"ERROR", Toast.LENGTH_SHORT).show();
            }
        });
 
        //실제 요청 작업을 수행해주는 요청큐 객체 생성
        RequestQueue requestQueue= Volley.newRequestQueue(this);
 
        //요청큐에 요청 객체 생성
        requestQueue.add(jsonArrayRequest);
 
 
    }
}
 
 
 

 

반응형

댓글