Android (ListView/GridView) get Result from Web Server and Paging Pagination
Android (ListView/GridView) get Result from Web Server and Paging Pagination บทความการเขียน Androidเพื่ออ่านข้อมูลจาก Web Server ที่อยู่ในรูปแบบของ JSON และเมื่อได้ JSON ที่ส่งมาทั้งหมดในครั้งเดียวมาจาก Web Server ก็จะนำข้อมูลเหล่านั้นมาจัดการแบ่งหน้าข้อมูล โดยแปลงข้อมูลที่ได้ให้อยู่ในรูปแบบ ArrayList และแสดงข้อมูลใน ArrayList ตามIndex ทีก่ำหนดในหน้านั้น ๆ ซึ่งวิธีนี้จะติดต่อกับ Web Server เพียงครั้งเดียว แต่จะใช้การเขียน function เพื่อจัดการกับข้อมูลที่ได้ ให้แสดงผลบน ListView หรือ GridView เป็นหน้า ๆ ตามต้องการ
จากภาพประกอบ แสดงการอ่านข้อมูล Web Server และการแปลงค่า JSON แสดงข้อมูลแบ่งหลาย ๆ หน้าบน ListView และ GridView
AndroidManifest.xml
1.
<
uses-permission
android:name
=
"android.permission.INTERNET"
/>
ในการเขียน Android เพื่อติดต่อกับ Internet จะต้องกำหนด Permission ในส่วนนี้ด้วยทุกครั้ง
บทความที่เกี่ยวข้อง
Web Server (PHP and MySQL)
MySQL Database
`ImageID` int(2) NOT NULL auto_increment,
`ItemID` varchar(50) NOT NULL,
`ImagePath` varchar(50) NOT NULL,
PRIMARY KEY (`ImageID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=31 ;
--
-- Dumping data for table `images`
--
INSERT INTO `images` VALUES (1, 'Item 01', 'http://www.thaicreate.com/android/images/img01.gif');
INSERT INTO `images` VALUES (2, 'Item 02', 'http://www.thaicreate.com/android/images/img02.gif');
INSERT INTO `images` VALUES (3, 'Item 03', 'http://www.thaicreate.com/android/images/img03.gif');
INSERT INTO `images` VALUES (4, 'Item 04', 'http://www.thaicreate.com/android/images/img04.gif');
INSERT INTO `images` VALUES (5, 'Item 05', 'http://www.thaicreate.com/android/images/img05.gif');
INSERT INTO `images` VALUES (6, 'Item 06', 'http://www.thaicreate.com/android/images/img06.gif');
INSERT INTO `images` VALUES (7, 'Item 07', 'http://www.thaicreate.com/android/images/img07.gif');
INSERT INTO `images` VALUES (8, 'Item 08', 'http://www.thaicreate.com/android/images/img08.gif');
INSERT INTO `images` VALUES (9, 'Item 09', 'http://www.thaicreate.com/android/images/img09.gif');
INSERT INTO `images` VALUES (10, 'Item 10', 'http://www.thaicreate.com/android/images/img10.gif');
INSERT INTO `images` VALUES (11, 'Item 11', 'http://www.thaicreate.com/android/images/img11.gif');
INSERT INTO `images` VALUES (12, 'Item 12', 'http://www.thaicreate.com/android/images/img12.gif');
INSERT INTO `images` VALUES (13, 'Item 13', 'http://www.thaicreate.com/android/images/img13.gif');
INSERT INTO `images` VALUES (14, 'Item 14', 'http://www.thaicreate.com/android/images/img14.gif');
INSERT INTO `images` VALUES (15, 'Item 15', 'http://www.thaicreate.com/android/images/img15.gif');
INSERT INTO `images` VALUES (16, 'Item 16', 'http://www.thaicreate.com/android/images/img16.gif');
INSERT INTO `images` VALUES (17, 'Item 17', 'http://www.thaicreate.com/android/images/img17.gif');
INSERT INTO `images` VALUES (18, 'Item 18', 'http://www.thaicreate.com/android/images/img18.gif');
INSERT INTO `images` VALUES (19, 'Item 19', 'http://www.thaicreate.com/android/images/img19.gif');
INSERT INTO `images` VALUES (20, 'Item 20', 'http://www.thaicreate.com/android/images/img20.gif');
INSERT INTO `images` VALUES (21, 'Item 21', 'http://www.thaicreate.com/android/images/img21.gif');
INSERT INTO `images` VALUES (22, 'Item 22', 'http://www.thaicreate.com/android/images/img22.gif');
INSERT INTO `images` VALUES (23, 'Item 23', 'http://www.thaicreate.com/android/images/img23.gif');
INSERT INTO `images` VALUES (24, 'Item 24', 'http://www.thaicreate.com/android/images/img24.gif');
INSERT INTO `images` VALUES (25, 'Item 25', 'http://www.thaicreate.com/android/images/img25.gif');
INSERT INTO `images` VALUES (26, 'Item 26', 'http://www.thaicreate.com/android/images/img26.gif');
INSERT INTO `images` VALUES (27, 'Item 27', 'http://www.thaicreate.com/android/images/img27.gif');
INSERT INTO `images` VALUES (28, 'Item 28', 'http://www.thaicreate.com/android/images/img28.gif');
INSERT INTO `images` VALUES (29, 'Item 29', 'http://www.thaicreate.com/android/images/img29.gif');
INSERT INTO `images` VALUES (30, 'Item 30', 'http://www.thaicreate.com/android/images/img30.gif');
getAllData.php
01.
<?php
02.
$objConnect
= mysql_connect(
"localhost"
,
"root"
,
"root"
);
03.
$objDB
= mysql_select_db(
"mydatabase"
);
04.
05.
$strSQL
=
"SELECT * FROM images WHERE 1 "
;
06.
$objQuery
= mysql_query(
$strSQL
);
07.
$intNumField
= mysql_num_fields(
$objQuery
);
08.
$resultArray
=
array
();
09.
while
(
$obResult
= mysql_fetch_array(
$objQuery
))
10.
{
11.
$arrCol
=
array
();
12.
for
(
$i
=0;
$i
<
$intNumField
;
$i
++)
13.
{
14.
$arrCol
[mysql_field_name(
$objQuery
,
$i
)] =
$obResult
[
$i
];
15.
}
16.
array_push
(
$resultArray
,
$arrCol
);
17.
}
18.
19.
mysql_close(
$objConnect
);
20.
21.
echo
json_encode(
$resultArray
);
22.
?>
จาก Code ของ PHP จะทำการ return ค่า JSON ไปยัง Client ได้ค่าดังนี้
JSON Result
,{"ImageID":"2","ItemID":"Item 02","ImagePath":"http://www.thaicreate.com/android/images/img02.gif"}
,{"ImageID":"3","ItemID":"Item 03","ImagePath":"http://www.thaicreate.com/android/images/img03.gif"}
,{"ImageID":"4","ItemID":"Item 04","ImagePath":"http://www.thaicreate.com/android/images/img04.gif"}
,{"ImageID":"5","ItemID":"Item 05","ImagePath":"http://www.thaicreate.com/android/images/img05.gif"}
,{"ImageID":"6","ItemID":"Item 06","ImagePath":"http://www.thaicreate.com/android/images/img06.gif"}
,{"ImageID":"7","ItemID":"Item 07","ImagePath":"http://www.thaicreate.com/android/images/img07.gif"}
,{"ImageID":"8","ItemID":"Item 08","ImagePath":"http://www.thaicreate.com/android/images/img08.gif"}
,{"ImageID":"9","ItemID":"Item 09","ImagePath":"http://www.thaicreate.com/android/images/img09.gif"}
,{"ImageID":"10","ItemID":"Item 10","ImagePath":"http://www.thaicreate.com/android/images/img10.gif"}
,{"ImageID":"11","ItemID":"Item 11","ImagePath":"http://www.thaicreate.com/android/images/img11.gif"}
,{"ImageID":"12","ItemID":"Item 12","ImagePath":"http://www.thaicreate.com/android/images/img12.gif"}
,{"ImageID":"13","ItemID":"Item 13","ImagePath":"http://www.thaicreate.com/android/images/img13.gif"}
,{"ImageID":"14","ItemID":"Item 14","ImagePath":"http://www.thaicreate.com/android/images/img14.gif"}
,{"ImageID":"15","ItemID":"Item 15","ImagePath":"http://www.thaicreate.com/android/images/img15.gif"}
,{"ImageID":"16","ItemID":"Item 16","ImagePath":"http://www.thaicreate.com/android/images/img16.gif"}
,{"ImageID":"17","ItemID":"Item 17","ImagePath":"http://www.thaicreate.com/android/images/img17.gif"}
,{"ImageID":"18","ItemID":"Item 18","ImagePath":"http://www.thaicreate.com/android/images/img18.gif"}
,{"ImageID":"19","ItemID":"Item 19","ImagePath":"http://www.thaicreate.com/android/images/img19.gif"}
,{"ImageID":"20","ItemID":"Item 20","ImagePath":"http://www.thaicreate.com/android/images/img20.gif"}
,{"ImageID":"21","ItemID":"Item 21","ImagePath":"http://www.thaicreate.com/android/images/img21.gif"}
,{"ImageID":"22","ItemID":"Item 22","ImagePath":"http://www.thaicreate.com/android/images/img22.gif"}
,{"ImageID":"23","ItemID":"Item 23","ImagePath":"http://www.thaicreate.com/android/images/img23.gif"}
,{"ImageID":"24","ItemID":"Item 24","ImagePath":"http://www.thaicreate.com/android/images/img24.gif"}
,{"ImageID":"25","ItemID":"Item 25","ImagePath":"http://www.thaicreate.com/android/images/img25.gif"}
,{"ImageID":"26","ItemID":"Item 26","ImagePath":"http://www.thaicreate.com/android/images/img26.gif"}
,{"ImageID":"27","ItemID":"Item 27","ImagePath":"http://www.thaicreate.com/android/images/img27.gif"}
,{"ImageID":"28","ItemID":"Item 28","ImagePath":"http://www.thaicreate.com/android/images/img28.gif"}
,{"ImageID":"29","ItemID":"Item 29","ImagePath":"http://www.thaicreate.com/android/images/img29.gif"}
,{"ImageID":"30","ItemID":"Item 30","ImagePath":"http://www.thaicreate.com/android/images/img30.gif"}]
JSON Code ที่ถูกส่งไปยัง Android
จาก Code ของ JSON จะเห็นว่า JSON จะถุกส่งมาครั้งเดียว โดยถ้าข้อมูลมาหลายร้อยรายการ ก็จะถูกส่งกลับมายัง Web Serverทั้งหมด ทำให้ลดอัตรา Transfer การติดต่อกับ Web Server
แต่ถ้าต้อมูลมีหลายหมื่นหรือแสน Record การใช้วิธีนี้จะเป็นปัญหาอย่างยิ่ง เพราะการที่จะส่งข้อมูลขนาดนั้นมายัง Android Clientย่อมเป็นเรื่องที่ยาก เพราะฉะนั้น ถ้าข้อมูลมามากหลายหมื่นหรือแสนรายการควรจะให้เป็นหน้าที่ของ PHP กับ MySQL ที่จะจัดการกับข้อมูล และทำการอ่านข้อมูลมาแสดงผลเฉพาะในหน้านั้น ๆ ที่ต้องการ สามารถอ่านได้ที่บทความนี้
Android Split Page Data (Next,Previous) result from PHP and MySQL
Android Project
Example 1 การแสดงผลและแบ่งหน้าข้อมูลจาก Web Server บน ListView Widgets
โครงสร้างของไฟล์ประกอบด้วย 3 ไฟล์คือ MainActivity.java, activity_main.xml และ activity_column.xml
activity_main.xml
01.
<
TableLayout
xmlns:android
=
"http://schemas.android.com/apk/res/android"
02.
android:id
=
"@+id/tableLayout1"
03.
android:layout_width
=
"fill_parent"
04.
android:layout_height
=
"fill_parent"
>
05.
06.
<
TableRow
07.
android:id
=
"@+id/tableRow1"
08.
android:layout_width
=
"wrap_content"
09.
android:layout_height
=
"wrap_content"
>
10.
11.
<
TextView
12.
android:id
=
"@+id/textView1"
13.
android:layout_width
=
"wrap_content"
14.
android:layout_height
=
"wrap_content"
15.
android:gravity
=
"center"
16.
android:text
=
"ListView Pagination : "
17.
android:layout_span
=
"1"
/>
18.
19.
<
Button
20.
android:id
=
"@+id/btnPre"
21.
android:layout_width
=
"wrap_content"
22.
android:layout_height
=
"wrap_content"
23.
android:text
=
"<< Prev"
/>
24.
25.
26.
<
Button
27.
android:id
=
"@+id/btnNext"
28.
android:layout_width
=
"wrap_content"
29.
android:layout_height
=
"wrap_content"
30.
android:text="Next >>" />
31.
32.
</
TableRow
>
33.
34.
<
View
35.
android:layout_height
=
"1dip"
36.
android:background
=
"#CCCCCC"
/>
37.
38.
<
LinearLayout
39.
android:orientation
=
"horizontal"
40.
android:layout_width
=
"fill_parent"
41.
android:layout_height
=
"wrap_content"
42.
android:layout_weight
=
"0.1"
>
43.
44.
<
ListView
45.
android:id
=
"@+id/listView1"
46.
android:layout_width
=
"match_parent"
47.
android:layout_height
=
"wrap_content"
>
48.
</
ListView
>
49.
50.
</
LinearLayout
>
51.
52.
<
View
53.
android:layout_height
=
"1dip"
54.
android:background
=
"#CCCCCC"
/>
55.
56.
<
LinearLayout
57.
android:id
=
"@+id/LinearLayout1"
58.
android:layout_width
=
"wrap_content"
59.
android:layout_height
=
"wrap_content"
60.
android:padding
=
"5dip"
>
61.
62.
<
TextView
63.
android:id
=
"@+id/textView2"
64.
android:layout_width
=
"wrap_content"
65.
android:layout_height
=
"wrap_content"
66.
android:text
=
"By.. ThaiCreate.Com"
/>
67.
68.
</
LinearLayout
>
69.
70.
</
TableLayout
>
activity_column.xml
01.
<
TableLayout
xmlns:android
=
"http://schemas.android.com/apk/res/android"
02.
android:id
=
"@+id/tableLayout1"
03.
android:layout_width
=
"fill_parent"
04.
android:layout_height
=
"fill_parent"
>
05.
06.
<
TableRow
07.
android:layout_width
=
"wrap_content"
08.
android:layout_height
=
"wrap_content"
>
09.
10.
<
ImageView
11.
android:id
=
"@+id/ColImagePath"
12.
android:layout_width
=
"wrap_content"
13.
android:layout_height
=
"wrap_content"
14.
/>
15.
16.
<
TextView
17.
android:id
=
"@+id/ColImageID"
18.
android:text
=
"Column 1"
/>
19.
20.
<
TextView
21.
android:id
=
"@+id/ColItemID"
22.
android:text
=
"Column 2"
/>
23.
24.
</
TableRow
>
25.
26.
27.
</
TableLayout
>
MainActivity.java
001.
package
com.myapp;
002.
003.
import
java.io.BufferedInputStream;
004.
import
java.io.BufferedOutputStream;
005.
import
java.io.BufferedReader;
006.
import
java.io.ByteArrayOutputStream;
007.
import
java.io.Closeable;
008.
import
java.io.IOException;
009.
import
java.io.InputStream;
010.
import
java.io.InputStreamReader;
011.
import
java.io.OutputStream;
012.
import
java.net.URL;
013.
import
java.util.ArrayList;
014.
import
java.util.HashMap;
015.
016.
import
org.apache.http.HttpEntity;
017.
import
org.apache.http.HttpResponse;
018.
import
org.apache.http.StatusLine;
019.
import
org.apache.http.client.ClientProtocolException;
020.
import
org.apache.http.client.HttpClient;
021.
import
org.apache.http.client.methods.HttpGet;
022.
import
org.apache.http.impl.client.DefaultHttpClient;
023.
import
org.json.JSONArray;
024.
import
org.json.JSONException;
025.
import
org.json.JSONObject;
026.
027.
import
android.app.Activity;
028.
import
android.content.Context;
029.
import
android.graphics.Bitmap;
030.
import
android.graphics.BitmapFactory;
031.
import
android.os.AsyncTask;
032.
import
android.os.Bundle;
033.
import
android.util.Log;
034.
import
android.view.LayoutInflater;
035.
import
android.view.View;
036.
import
android.view.ViewGroup;
037.
import
android.view.Window;
038.
import
android.widget.BaseAdapter;
039.
import
android.widget.Button;
040.
import
android.widget.ImageView;
041.
import
android.widget.ListView;
042.
import
android.widget.TextView;
043.
044.
045.
public
class
MainActivity
extends
Activity {
046.
047.
private
ListView lstView;
048.
private
ImageAdapter imageAdapter;
049.
050.
public
int
currentPage =
1
;
051.
public
int
TotalPage =
0
;
052.
053.
public
Button btnNext;
054.
public
Button btnPre;
055.
056.
ArrayList<HashMap<String, Object>> MyArrList =
new
ArrayList<HashMap<String, Object>>();
057.
058.
@Override
059.
public
void
onCreate(Bundle savedInstanceState) {
060.
super
.onCreate(savedInstanceState);
061.
// ProgressBar
062.
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
063.
064.
setContentView(R.layout.activity_main);
065.
066.
// ListView and imageAdapter
067.
lstView = (ListView) findViewById(R.id.listView1);
068.
lstView.setClipToPadding(
false
);
069.
imageAdapter =
new
ImageAdapter(getApplicationContext());
070.
lstView.setAdapter(imageAdapter);
071.
072.
073.
// Next
074.
btnNext = (Button) findViewById(R.id.btnNext);
075.
// Perform action on click
076.
btnNext.setOnClickListener(
new
View.OnClickListener() {
077.
public
void
onClick(View v) {
078.
currentPage = currentPage +
1
;
079.
ShowData();
080.
}
081.
});
082.
083.
// Previous
084.
btnPre = (Button) findViewById(R.id.btnPre);
085.
// Perform action on click
086.
btnPre.setOnClickListener(
new
View.OnClickListener() {
087.
public
void
onClick(View v) {
088.
currentPage = currentPage -
1
;
089.
ShowData();
090.
}
091.
});
092.
093.
// Show first load
094.
ShowData();
095.
096.
}
097.
098.
public
void
ShowData()
099.
{
100.
btnNext.setEnabled(
false
);
101.
btnPre.setEnabled(
false
);
102.
103.
setProgressBarIndeterminateVisibility(
true
);
104.
new
LoadContentFromServer().execute();
105.
}
106.
107.
108.
class
LoadContentFromServer
extends
AsyncTask<Object, Integer, Object> {
109.
110.
@Override
111.
protected
Object doInBackground(Object... params) {
112.
113.
String url =
"http://www.thaicreate.com/android/getAllData.php"
;
114.
115.
JSONArray data;
116.
try
{
117.
data =
new
JSONArray(getJSONUrl(url));
118.
119.
MyArrList =
new
ArrayList<HashMap<String, Object>>();
120.
HashMap<String, Object> map;
121.
122.
/*
123.
* TotalRows = Show for total rows
124.
* TotalPage = Show for total page
125.
*/
126.
127.
int
displayPerPage =
7
;
// Per Page
128.
int
TotalRows = data.length();
129.
int
indexRowStart = ((displayPerPage*currentPage)-displayPerPage);
130.
131.
if
(TotalRows<=displayPerPage)
132.
{
133.
TotalPage =
1
;
134.
}
135.
else
if
((TotalRows % displayPerPage)==
0
)
136.
{
137.
TotalPage =(TotalRows/displayPerPage) ;
138.
}
139.
else
140.
{
141.
TotalPage =(TotalRows/displayPerPage)+
1
;
142.
TotalPage = (
int
)TotalPage;
143.
}
144.
int
indexRowEnd = displayPerPage * currentPage;
145.
if
(indexRowEnd > TotalRows)
146.
{
147.
indexRowEnd = TotalRows;
148.
}
149.
150.
for
(
int
i = indexRowStart; i < indexRowEnd; i++){
151.
JSONObject c = data.getJSONObject(i);
152.
map =
new
HashMap<String, Object>();
153.
map.put(
"ImageID"
, (String)c.getString(
"ImageID"
));
154.
map.put(
"ItemID"
, (String)c.getString(
"ItemID"
));
155.
156.
// Thumbnail Get ImageBitmap To Object
157.
map.put(
"ImagePath"
, (String)c.getString(
"ImagePath"
));
158.
Bitmap newBitmap = loadBitmap(c.getString(
"ImagePath"
));
159.
map.put(
"ImagePathBitmap"
, newBitmap);
160.
161.
MyArrList.add(map);
162.
163.
publishProgress(i);
164.
165.
}
166.
167.
168.
}
catch
(JSONException e) {
169.
// TODO Auto-generated catch block
170.
e.printStackTrace();
171.
}
172.
173.
return
null
;
174.
}
175.
176.
@Override
177.
public
void
onProgressUpdate(Integer... progress) {
178.
imageAdapter.notifyDataSetChanged();
179.
}
180.
181.
@Override
182.
protected
void
onPostExecute(Object result) {
183.
184.
// Disabled Button Next
185.
if
(currentPage >= TotalPage)
186.
{
187.
btnNext.setEnabled(
false
);
188.
}
189.
else
190.
{
191.
btnNext.setEnabled(
true
);
192.
}
193.
194.
// Disabled Button Previos
195.
if
(currentPage <=
1
)
196.
{
197.
btnPre.setEnabled(
false
);
198.
}
199.
else
200.
{
201.
btnPre.setEnabled(
true
);
202.
}
203.
204.
setProgressBarIndeterminateVisibility(
false
);
// When Finish
205.
}
206.
}
207.
208.
209.
class
ImageAdapter
extends
BaseAdapter {
210.
211.
private
Context mContext;
212.
213.
public
ImageAdapter(Context context) {
214.
mContext = context;
215.
}
216.
217.
public
int
getCount() {
218.
return
MyArrList.size();
219.
}
220.
221.
public
Object getItem(
int
position) {
222.
return
MyArrList.get(position);
223.
}
224.
225.
public
long
getItemId(
int
position) {
226.
return
position;
227.
}
228.
229.
public
View getView(
int
position, View convertView, ViewGroup parent) {
230.
// TODO Auto-generated method stub
231.
232.
LayoutInflater inflater = (LayoutInflater) mContext
233.
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
234.
235.
236.
if
(convertView ==
null
) {
237.
convertView = inflater.inflate(R.layout.activity_column,
null
);
238.
}
239.
240.
// ColImagePath
241.
ImageView imageView = (ImageView) convertView.findViewById(R.id.ColImagePath);
242.
imageView.getLayoutParams().height =
60
;
243.
imageView.getLayoutParams().width =
60
;
244.
imageView.setPadding(
5
,
5
,
5
,
5
);
245.
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
246.
try
247.
{
248.
imageView.setImageBitmap((Bitmap)MyArrList.get(position).get(
"ImagePathBitmap"
));
249.
}
catch
(Exception e) {
250.
// When Error
251.
imageView.setImageResource(android.R.drawable.ic_menu_report_image);
252.
}
253.
254.
// ColImageID
255.
TextView txtImgID = (TextView) convertView.findViewById(R.id.ColImageID);
256.
txtImgID.setPadding(
10
,
0
,
0
,
0
);
257.
txtImgID.setText(
"ID : "
+ MyArrList.get(position).get(
"ImageID"
).toString());
258.
259.
// ColItemID
260.
TextView txtItemID = (TextView) convertView.findViewById(R.id.ColItemID);
261.
txtItemID.setPadding(
50
,
0
,
0
,
0
);
262.
txtItemID.setText(
"Item : "
+ MyArrList.get(position).get(
"ItemID"
).toString());
263.
264.
return
convertView;
265.
266.
}
267.
268.
}
269.
270.
/*** Get JSON Code from URL ***/
271.
public
String getJSONUrl(String url) {
272.
StringBuilder str =
new
StringBuilder();
273.
HttpClient client =
new
DefaultHttpClient();
274.
HttpGet httpGet =
new
HttpGet(url);
275.
try
{
276.
HttpResponse response = client.execute(httpGet);
277.
StatusLine statusLine = response.getStatusLine();
278.
int
statusCode = statusLine.getStatusCode();
279.
if
(statusCode ==
200
) {
// Download OK
280.
HttpEntity entity = response.getEntity();
281.
InputStream content = entity.getContent();
282.
BufferedReader reader =
new
BufferedReader(
new
InputStreamReader(content));
283.
String line;
284.
while
((line = reader.readLine()) !=
null
) {
285.
str.append(line);
286.
}
287.
}
else
{
288.
Log.e(
"Log"
,
"Failed to download file.."
);
289.
}
290.
}
catch
(ClientProtocolException e) {
291.
e.printStackTrace();
292.
}
catch
(IOException e) {
293.
e.printStackTrace();
294.
}
295.
return
str.toString();
296.
}
297.
298.
/***** Get Image Resource from URL (Start) *****/
299.
private
static
final
String TAG =
"Image"
;
300.
private
static
final
int
IO_BUFFER_SIZE =
4
*
1024
;
301.
public
static
Bitmap loadBitmap(String url) {
302.
Bitmap bitmap =
null
;
303.
InputStream in =
null
;
304.
BufferedOutputStream out =
null
;
305.
306.
try
{
307.
in =
new
BufferedInputStream(
new
URL(url).openStream(), IO_BUFFER_SIZE);
308.
309.
final
ByteArrayOutputStream dataStream =
new
ByteArrayOutputStream();
310.
out =
new
BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
311.
copy(in, out);
312.
out.flush();
313.
314.
final
byte
[] data = dataStream.toByteArray();
315.
BitmapFactory.Options options =
new
BitmapFactory.Options();
316.
//options.inSampleSize = 1;
317.
318.
bitmap = BitmapFactory.decodeByteArray(data,
0
, data.length,options);
319.
}
catch
(IOException e) {
320.
Log.e(TAG,
"Could not load Bitmap from: "
+ url);
321.
}
finally
{
322.
closeStream(in);
323.
closeStream(out);
324.
}
325.
326.
return
bitmap;
327.
}
328.
329.
private
static
void
closeStream(Closeable stream) {
330.
if
(stream !=
null
) {
331.
try
{
332.
stream.close();
333.
}
catch
(IOException e) {
334.
android.util.Log.e(TAG,
"Could not close stream"
, e);
335.
}
336.
}
337.
}
338.
339.
private
static
void
copy(InputStream in, OutputStream out)
throws
IOException {
340.
byte
[] b =
new
byte
[IO_BUFFER_SIZE];
341.
int
read;
342.
while
((read = in.read(b)) != -
1
) {
343.
out.write(b,
0
, read);
344.
}
345.
}
346.
/***** Get Image Resource from URL (End) *****/
347.
348.
}
Screenshot
กำลังโหลดและแสดงข้อมูลจาก Web Server และจัดการกับข้อมูลโดยการแบ่งการแสดงผลออกเป็นหลายหน้า
ทดสอบคลิกไปที่ Next >> เพื่อไปยังหน้าถัดไป
ในการเปลี่ยนแปลงหน้าทุกครั้งจะมีการใช้ ProgressBar ควบคุมการทำงาน เพื่อป้องกันโปรแกรมค้าง
สามารถคลิก << Prev หรือ Next >> เพื่อดูรายการข้อมูลในหน้าต่าง ๆ
Example 2 การแสดงผลและแบ่งหน้าข้อมูลจาก Web Server บน GridView Widgets
โครงสร้างของไฟล์ประกอบด้วย 3 ไฟล์คือ MainActivity.java, activity_main.xml และ activity_column.xml
activity_main.xml
01.
<
TableLayout
xmlns:android
=
"http://schemas.android.com/apk/res/android"
02.
android:id
=
"@+id/tableLayout1"
03.
android:layout_width
=
"fill_parent"
04.
android:layout_height
=
"fill_parent"
>
05.
06.
<
TableRow
07.
android:id
=
"@+id/tableRow1"
08.
android:layout_width
=
"wrap_content"
09.
android:layout_height
=
"wrap_content"
>
10.
11.
<
TextView
12.
android:id
=
"@+id/textView1"
13.
android:layout_width
=
"wrap_content"
14.
android:layout_height
=
"wrap_content"
15.
android:gravity
=
"center"
16.
android:text
=
"GridView Pagination : "
17.
android:layout_span
=
"1"
/>
18.
19.
<
Button
20.
android:id
=
"@+id/btnPre"
21.
android:layout_width
=
"wrap_content"
22.
android:layout_height
=
"wrap_content"
23.
android:text
=
"<< Prev"
/>
24.
25.
26.
<
Button
27.
android:id
=
"@+id/btnNext"
28.
android:layout_width
=
"wrap_content"
29.
android:layout_height
=
"wrap_content"
30.
android:text="Next >>" />
31.
32.
</
TableRow
>
33.
34.
<
View
35.
android:layout_height
=
"1dip"
36.
android:background
=
"#CCCCCC"
/>
37.
38.
<
LinearLayout
39.
android:orientation
=
"horizontal"
40.
android:layout_width
=
"fill_parent"
41.
android:layout_height
=
"wrap_content"
42.
android:layout_weight
=
"0.1"
>
43.
44.
<
GridView
45.
android:id
=
"@+id/gridView1"
46.
android:layout_width
=
"match_parent"
47.
android:layout_height
=
"wrap_content"
48.
android:numColumns
=
"3"
>
49.
</
GridView
>
50.
51.
</
LinearLayout
>
52.
53.
<
View
54.
android:layout_height
=
"1dip"
55.
android:background
=
"#CCCCCC"
/>
56.
57.
<
LinearLayout
58.
android:id
=
"@+id/LinearLayout1"
59.
android:layout_width
=
"wrap_content"
60.
android:layout_height
=
"wrap_content"
61.
android:padding
=
"5dip"
>
62.
63.
<
TextView
64.
android:id
=
"@+id/textView2"
65.
android:layout_width
=
"wrap_content"
66.
android:layout_height
=
"wrap_content"
67.
android:text
=
"By.. ThaiCreate.Com"
/>
68.
69.
</
LinearLayout
>
70.
71.
</
TableLayout
>
activity_column.xml
01.
<?
xml
version
=
"1.0"
encoding
=
"utf-8"
?>
02.
<
LinearLayout
xmlns:android
=
"http://schemas.android.com/apk/res/android"
03.
android:orientation
=
"horizontal"
04.
android:layout_width
=
"fill_parent"
05.
android:layout_height
=
"fill_parent"
>
06.
<
ImageView
07.
android:id
=
"@+id/ColPhoto"
08.
android:layout_width
=
"50dp"
09.
android:layout_height
=
"50dp"
10.
/>
11.
<
LinearLayout
12.
android:orientation
=
"vertical"
13.
android:layout_width
=
"fill_parent"
14.
android:layout_height
=
"fill_parent"
>
15.
<
LinearLayout
16.
android:orientation
=
"horizontal"
17.
android:layout_width
=
"wrap_content"
18.
android:layout_height
=
"wrap_content"
>
19.
20.
<
TextView
android:id
=
"@+id/ColImageID"
21.
android:layout_width
=
"wrap_content"
22.
android:layout_height
=
"wrap_content"
23.
android:text
=
"ImageID"
24.
/>
25.
</
LinearLayout
>
26.
<
LinearLayout
27.
android:orientation
=
"horizontal"
28.
android:layout_width
=
"wrap_content"
29.
android:layout_height
=
"wrap_content"
>
30.
31.
<
TextView
android:id
=
"@+id/ColItemID"
32.
android:layout_width
=
"wrap_content"
33.
android:layout_height
=
"wrap_content"
34.
android:text
=
"ItemID"
35.
/>
36.
37.
</
LinearLayout
>
38.
</
LinearLayout
>
39.
</
LinearLayout
>
MainActivity.java
001.
package
com.myapp;
002.
003.
import
java.io.BufferedInputStream;
004.
import
java.io.BufferedOutputStream;
005.
import
java.io.BufferedReader;
006.
import
java.io.ByteArrayOutputStream;
007.
import
java.io.Closeable;
008.
import
java.io.IOException;
009.
import
java.io.InputStream;
010.
import
java.io.InputStreamReader;
011.
import
java.io.OutputStream;
012.
import
java.net.URL;
013.
import
java.util.ArrayList;
014.
import
java.util.HashMap;
015.
016.
import
org.apache.http.HttpEntity;
017.
import
org.apache.http.HttpResponse;
018.
import
org.apache.http.StatusLine;
019.
import
org.apache.http.client.ClientProtocolException;
020.
import
org.apache.http.client.HttpClient;
021.
import
org.apache.http.client.methods.HttpGet;
022.
import
org.apache.http.impl.client.DefaultHttpClient;
023.
import
org.json.JSONArray;
024.
import
org.json.JSONException;
025.
import
org.json.JSONObject;
026.
027.
import
android.app.Activity;
028.
import
android.content.Context;
029.
import
android.graphics.Bitmap;
030.
import
android.graphics.BitmapFactory;
031.
import
android.os.AsyncTask;
032.
import
android.os.Bundle;
033.
import
android.util.Log;
034.
import
android.view.LayoutInflater;
035.
import
android.view.View;
036.
import
android.view.ViewGroup;
037.
import
android.view.Window;
038.
import
android.widget.BaseAdapter;
039.
import
android.widget.Button;
040.
import
android.widget.GridView;
041.
import
android.widget.ImageView;
042.
import
android.widget.TextView;
043.
044.
045.
public
class
MainActivity
extends
Activity {
046.
047.
private
GridView gridV;
048.
private
ImageAdapter imageAdapter;
049.
050.
public
int
currentPage =
1
;
051.
public
int
TotalPage =
0
;
052.
053.
public
Button btnNext;
054.
public
Button btnPre;
055.
056.
ArrayList<HashMap<String, Object>> MyArrList =
new
ArrayList<HashMap<String, Object>>();
057.
058.
@Override
059.
public
void
onCreate(Bundle savedInstanceState) {
060.
super
.onCreate(savedInstanceState);
061.
// ProgressBar
062.
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
063.
064.
setContentView(R.layout.activity_main);
065.
066.
// GridView and imageAdapter
067.
gridV = (GridView) findViewById(R.id.gridView1);
068.
gridV.setClipToPadding(
false
);
069.
imageAdapter =
new
ImageAdapter(getApplicationContext());
070.
gridV.setAdapter(imageAdapter);
071.
072.
073.
// Next
074.
btnNext = (Button) findViewById(R.id.btnNext);
075.
// Perform action on click
076.
btnNext.setOnClickListener(
new
View.OnClickListener() {
077.
public
void
onClick(View v) {
078.
currentPage = currentPage +
1
;
079.
ShowData();
080.
}
081.
});
082.
083.
// Previous
084.
btnPre = (Button) findViewById(R.id.btnPre);
085.
// Perform action on click
086.
btnPre.setOnClickListener(
new
View.OnClickListener() {
087.
public
void
onClick(View v) {
088.
currentPage = currentPage -
1
;
089.
ShowData();
090.
}
091.
});
092.
093.
// Show first load
094.
ShowData();
095.
096.
}
097.
098.
public
void
ShowData()
099.
{
100.
btnNext.setEnabled(
false
);
101.
btnPre.setEnabled(
false
);
102.
103.
setProgressBarIndeterminateVisibility(
true
);
104.
new
LoadContentFromServer().execute();
105.
}
106.
107.
108.
class
LoadContentFromServer
extends
AsyncTask<Object, Integer, Object> {
109.
110.
@Override
111.
protected
Object doInBackground(Object... params) {
112.
113.
String url =
"http://www.thaicreate.com/android/getAllData.php"
;
114.
115.
JSONArray data;
116.
try
{
117.
data =
new
JSONArray(getJSONUrl(url));
118.
119.
MyArrList =
new
ArrayList<HashMap<String, Object>>();
120.
HashMap<String, Object> map;
121.
122.
/*
123.
* TotalRows = Show for total rows
124.
* TotalPage = Show for total page
125.
*/
126.
127.
int
displayPerPage =
9
;
// Per Page
128.
int
TotalRows = data.length();
129.
int
indexRowStart = ((displayPerPage*currentPage)-displayPerPage);
130.
131.
if
(TotalRows<=displayPerPage)
132.
{
133.
TotalPage =
1
;
134.
}
135.
else
if
((TotalRows % displayPerPage)==
0
)
136.
{
137.
TotalPage =(TotalRows/displayPerPage) ;
138.
}
139.
else
140.
{
141.
TotalPage =(TotalRows/displayPerPage)+
1
;
142.
TotalPage = (
int
)TotalPage;
143.
}
144.
int
indexRowEnd = displayPerPage * currentPage;
145.
if
(indexRowEnd > TotalRows)
146.
{
147.
indexRowEnd = TotalRows;
148.
}
149.
150.
for
(
int
i = indexRowStart; i < indexRowEnd; i++){
151.
JSONObject c = data.getJSONObject(i);
152.
map =
new
HashMap<String, Object>();
153.
map.put(
"ImageID"
, (String)c.getString(
"ImageID"
));
154.
map.put(
"ItemID"
, (String)c.getString(
"ItemID"
));
155.
156.
// Thumbnail Get ImageBitmap To Object
157.
map.put(
"ImagePath"
, (String)c.getString(
"ImagePath"
));
158.
Bitmap newBitmap = loadBitmap(c.getString(
"ImagePath"
));
159.
map.put(
"ImagePathBitmap"
, newBitmap);
160.
161.
MyArrList.add(map);
162.
163.
publishProgress(i);
164.
165.
}
166.
167.
168.
}
catch
(JSONException e) {
169.
// TODO Auto-generated catch block
170.
e.printStackTrace();
171.
}
172.
173.
return
null
;
174.
}
175.
176.
@Override
177.
public
void
onProgressUpdate(Integer... progress) {
178.
imageAdapter.notifyDataSetChanged();
179.
}
180.
181.
@Override
182.
protected
void
onPostExecute(Object result) {
183.
184.
// Disabled Button Next
185.
if
(currentPage >= TotalPage)
186.
{
187.
btnNext.setEnabled(
false
);
188.
}
189.
else
190.
{
191.
btnNext.setEnabled(
true
);
192.
}
193.
194.
// Disabled Button Previos
195.
if
(currentPage <=
1
)
196.
{
197.
btnPre.setEnabled(
false
);
198.
}
199.
else
200.
{
201.
btnPre.setEnabled(
true
);
202.
}
203.
204.
setProgressBarIndeterminateVisibility(
false
);
// When Finish
205.
}
206.
}
207.
208.
209.
class
ImageAdapter
extends
BaseAdapter {
210.
211.
private
Context mContext;
212.
213.
public
ImageAdapter(Context context) {
214.
mContext = context;
215.
}
216.
217.
public
int
getCount() {
218.
return
MyArrList.size();
219.
}
220.
221.
public
Object getItem(
int
position) {
222.
return
MyArrList.get(position);
223.
}
224.
225.
public
long
getItemId(
int
position) {
226.
return
position;
227.
}
228.
229.
public
View getView(
int
position, View convertView, ViewGroup parent) {
230.
// TODO Auto-generated method stub
231.
232.
LayoutInflater inflater = (LayoutInflater) mContext
233.
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
234.
235.
236.
if
(convertView ==
null
) {
237.
convertView = inflater.inflate(R.layout.activity_column,
null
);
238.
}
239.
240.
// ColPhoto
241.
ImageView imageView = (ImageView) convertView.findViewById(R.id.ColPhoto);
242.
imageView.getLayoutParams().height =
60
;
243.
imageView.getLayoutParams().width =
60
;
244.
imageView.setPadding(
5
,
5
,
5
,
5
);
245.
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
246.
try
247.
{
248.
imageView.setImageBitmap((Bitmap)MyArrList.get(position).get(
"ImagePathBitmap"
));
249.
}
catch
(Exception e) {
250.
// When Error
251.
imageView.setImageResource(android.R.drawable.ic_menu_report_image);
252.
}
253.
254.
// ColImageID
255.
TextView txtImageID = (TextView) convertView.findViewById(R.id.ColImageID);
256.
txtImageID.setPadding(
5
,
0
,
0
,
0
);
257.
txtImageID.setText(
"ID : "
+ MyArrList.get(position).get(
"ImageID"
).toString());
258.
259.
// ColItemID
260.
TextView txtItemID = (TextView) convertView.findViewById(R.id.ColItemID);
261.
txtItemID.setPadding(
5
,
0
,
0
,
0
);
262.
txtItemID.setText(
"Item : "
+ MyArrList.get(position).get(
"ItemID"
).toString());
263.
264.
return
convertView;
265.
266.
}
267.
268.
}
269.
270.
/*** Get JSON Code from URL ***/
271.
public
String getJSONUrl(String url) {
272.
StringBuilder str =
new
StringBuilder();
273.
HttpClient client =
new
DefaultHttpClient();
274.
HttpGet httpGet =
new
HttpGet(url);
275.
try
{
276.
HttpResponse response = client.execute(httpGet);
277.
StatusLine statusLine = response.getStatusLine();
278.
int
statusCode = statusLine.getStatusCode();
279.
if
(statusCode ==
200
) {
// Download OK
280.
HttpEntity entity = response.getEntity();
281.
InputStream content = entity.getContent();
282.
BufferedReader reader =
new
BufferedReader(
new
InputStreamReader(content));
283.
String line;
284.
while
((line = reader.readLine()) !=
null
) {
285.
str.append(line);
286.
}
287.
}
else
{
288.
Log.e(
"Log"
,
"Failed to download file.."
);
289.
}
290.
}
catch
(ClientProtocolException e) {
291.
e.printStackTrace();
292.
}
catch
(IOException e) {
293.
e.printStackTrace();
294.
}
295.
return
str.toString();
296.
}
297.
298.
/***** Get Image Resource from URL (Start) *****/
299.
private
static
final
String TAG =
"Image"
;
300.
private
static
final
int
IO_BUFFER_SIZE =
4
*
1024
;
301.
public
static
Bitmap loadBitmap(String url) {
302.
Bitmap bitmap =
null
;
303.
InputStream in =
null
;
304.
BufferedOutputStream out =
null
;
305.
306.
try
{
307.
in =
new
BufferedInputStream(
new
URL(url).openStream(), IO_BUFFER_SIZE);
308.
309.
final
ByteArrayOutputStream dataStream =
new
ByteArrayOutputStream();
310.
out =
new
BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
311.
copy(in, out);
312.
out.flush();
313.
314.
final
byte
[] data = dataStream.toByteArray();
315.
BitmapFactory.Options options =
new
BitmapFactory.Options();
316.
//options.inSampleSize = 1;
317.
318.
bitmap = BitmapFactory.decodeByteArray(data,
0
, data.length,options);
319.
}
catch
(IOException e) {
320.
Log.e(TAG,
"Could not load Bitmap from: "
+ url);
321.
}
finally
{
322.
closeStream(in);
323.
closeStream(out);
324.
}
325.
326.
return
bitmap;
327.
}
328.
329.
private
static
void
closeStream(Closeable stream) {
330.
if
(stream !=
null
) {
331.
try
{
332.
stream.close();
333.
}
catch
(IOException e) {
334.
android.util.Log.e(TAG,
"Could not close stream"
, e);
335.
}
336.
}
337.
}
338.
339.
private
static
void
copy(InputStream in, OutputStream out)
throws
IOException {
340.
byte
[] b =
new
byte
[IO_BUFFER_SIZE];
341.
int
read;
342.
while
((read = in.read(b)) != -
1
) {
343.
out.write(b,
0
, read);
344.
}
345.
}
346.
/***** Get Image Resource from URL (End) *****/
347.
348.
}
Screenshot
กำลังแสดงผลข้อมูลจาก Web Server บน GridView และมีการแบ่งหน้าการแสดงผลข้อมูล
ทดสอบคลิกที่ Next >> เพื่อไปหน้าถัดไป
กำลังโหลดหน้าข้อมูลหในหน้าอื่น ๆ
สามารถคลิกเพื่อไปดูข้อมูลในหน้าต่าง ๆ ได้
เพิ่มเติม
วิธีนี้จะเป็นการติดต่อกับ Web Server เพียงครั้งเดียว ซึ่งจะเหมาะกับข้อมูลไม่มาก อาจจะอยู่ในหลัก สิบหรือร้อยรายการ แต่ถ้าข้อมูลมีมากกว่า พัน หมื่น หรือ แสนรายการ แนะนำให้ใช้วิธีนี้
Android Split Page Data (Next,Previous) result from PHP and MySQL
[출처] http://www.thaicreate.com/mobile/android-listview-gridview-get-result-from-web-server-and-paging-pagination.html
'프로그래밍 > Android (Java)' 카테고리의 다른 글
그리드뷰(gridview) 이미지에 이벤트 넣기 (0) | 2015.11.04 |
---|---|
액티비티 간 String 전송 (데이터 전송) (0) | 2015.11.03 |
버튼 이벤트 처리 (두가지 방법) (0) | 2015.11.03 |
안드로이드 버튼 숨기기 (0) | 2015.11.03 |
이미지 랜덤하게 출력하기 (ImageView) (0) | 2015.10.15 |