TextView 상, 하 여백 줄이기

프로그래밍/Android (Java)|2015. 11. 13. 10:06
반응형

일반적으로 아래와 같은 옵션을 줍니다.

 

.xml 사용시)

android:includeFontPadding="false"

 

.java 사용시)

setIncludeFontPadding( false );

 

하지만 위와 같이 해도 안될 경우 layout 에 아래 옵션을 사용하면 됩니다.

 

android:layout_marginTop="-3dp"
android:layout_marginBottom="-3dp"

 

반응형

댓글()

layout 에서 공백 채우기

프로그래밍/Android (Java)|2015. 11. 13. 09:55
반응형

가로 공백으로 예를 들면


<View
    android:layout_width="0dp"
    android:layout_height="match_parent"

   android:layout_weight="1" />

반응형

댓글()

Simple JSON Parsing Example in Android (리스트뷰, 그리드뷰 아님)

프로그래밍/Android (Java)|2015. 11. 11. 17:18
반응형

In this blog post, ill show you how to Retrieving JSON data and Displaying it in Android TextView.

My Other blog post on JSON Tutorial.

  1. Part I – What is JSON and how to code JSON data on Php
  2. Part II – How to retrieve a simplest JSON data in Android
  3. Part III – How to retrieve a JSON data to ListView in Android
  4. Part IV – How to retrieve a complex typed JSON data in Android
  5. Part V – How to retrieve a JSON data from a Secured Site with Basic Authentication
  6. Part VI – How to Pass a JSON data to Php as a Parameters

 

Please read Part I of this blog, there you can create JSON data in php. I’m using Example 1 from that blog in this tutorial for making this blog to be simple. Hope you have created JSON data in php, so lets get started with retrieving in Android.

Step 1: Create a new project File -> Android Project. While creating a new project give activity name as MainActivity and copy paste this code.

1 import org.json.JSONException;
2 import org.json.JSONObject;
3  
4 import android.app.Activity;
5 import android.app.ProgressDialog;
6 import android.os.AsyncTask;
7 import android.os.Bundle;
8 import android.widget.TextView;
9  
10 public class MainActivity extends Activity {
11 /** Called when the activity is first created. */
12  
14 String name, version;
15 TextView tv1;
16  
17 @Override
18 public void onCreate(Bundle savedInstanceState) {
19 super.onCreate(savedInstanceState);
20 setContentView(R.layout.activity_main);
21  
22 new JSONParse().execute();
23 }
24  
25 private class JSONParse extends AsyncTask<String, String, JSONObject> {
26 private ProgressDialog pDialog;
27 @Override
28 protected void onPreExecute() {
29 super.onPreExecute();
30 tv1 = (TextView) findViewById(R.id.textView1);
31  
32 pDialog = new ProgressDialog(MainActivity.this);
33 pDialog.setMessage("Loading Data ...");
34 pDialog.setIndeterminate(false);
35 pDialog.setCancelable(true);
36 pDialog.show();
37 tv1.setText("Getting Values Pls wait..");
38 }
39  
40 @Override
41 protected JSONObject doInBackground(String... args) {
42 JsonParser jParser = new JsonParser();
43 // Getting JSON from URL
44 JSONObject json = jParser.getJSONFromUrl(url);
45 return json;
46 }
47  
48 @Override
49 protected void onPostExecute(JSONObject json) {
50 try {
51 pDialog.dismiss();
52 name = json.getString("name");
53 version = json.getString("version");
54 tv1.setText(name + " - " + version);
55 } catch (JSONException e) {
56 e.printStackTrace();
57 }
58 }
59 }
60 }

Step 2: Create a new class, JsonParser.java and copy paste this code.

1 import java.io.BufferedReader;
2 import java.io.IOException;
3 import java.io.InputStream;
4 import java.io.InputStreamReader;
5 import java.io.UnsupportedEncodingException;
6  
7 import org.apache.http.HttpEntity;
8 import org.apache.http.HttpResponse;
9 import org.apache.http.client.ClientProtocolException;
10 import org.apache.http.client.methods.HttpPost;
11 import org.apache.http.impl.client.DefaultHttpClient;
12 import org.json.JSONException;
13 import org.json.JSONObject;
14  
15 import android.util.Log;
16  
17 public class JsonParser {
18 static InputStream is = null;
19 static JSONObject jObj = null;
20 static String json = "";
21  
22 // constructor
23 public JsonParser() {
24 }
25  
26 public JSONObject getJSONFromUrl(String url) {
27 // Making HTTP request
28 try {
29 // defaultHttpClient
30 DefaultHttpClient httpClient = new DefaultHttpClient();
31 HttpPost httpPost = new HttpPost(url);
32 HttpResponse httpResponse = httpClient.execute(httpPost);
33 HttpEntity httpEntity = httpResponse.getEntity();
34 is = httpEntity.getContent();
35 } catch (UnsupportedEncodingException e) {
36 e.printStackTrace();
37 } catch (ClientProtocolException e) {
38 e.printStackTrace();
39 } catch (IOException e) {
40 e.printStackTrace();
41 }
42 try {
43 BufferedReader reader = new BufferedReader(new InputStreamReader(
44 is, "iso-8859-1"), 8);
45 StringBuilder sb = new StringBuilder();
46 String line = null;
47 while ((line = reader.readLine()) != null) {
48 sb.append(line + "n");
49 }
50 is.close();
51 json = sb.toString();
52 } catch (Exception e) {
53 Log.e("Buffer Error", "Error converting result " + e.toString());
54 }
55 // try parse the string to a JSON object
56 try {
57 jObj = new JSONObject(json);
58 } catch (JSONException e) {
59 Log.e("JSON Parser", "Error parsing data " + e.toString());
60 }
61 // return JSON String
62 return jObj;
63 }
64 }

Step 3: Open your activity_main.xml and copy paste this code:

1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:layout_width="match_parent"
4 android:layout_height="match_parent"
5 android:paddingBottom="@dimen/activity_vertical_margin"
6 android:paddingLeft="@dimen/activity_horizontal_margin"
7 android:paddingRight="@dimen/activity_horizontal_margin"
8 android:paddingTop="@dimen/activity_vertical_margin" >
9  
10 <TextView
11 android:id="@+id/textView1"
12 android:layout_width="wrap_content"
13 android:layout_height="wrap_content"
14 android:layout_centerHorizontal="true"
15 android:layout_centerVertical="true"
16 android:text="Medium Text"
17 android:textAppearance="?android:attr/textAppearanceMedium" />
18  
19 </RelativeLayout>

Step 4: Open your AndroidManifest.xml and add Internet Permission.

1 <?xml version="1.0" encoding="utf-8"?>
2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3 package="com.geeks.gallery.json_demoexample"
4 android:versionCode="1"
5 android:versionName="1.0" >
6  
7 <uses-sdk
8 android:minSdkVersion="16"
9 android:targetSdkVersion="19" />
10 <uses-permission android:name="android.permission.INTERNET"/>
11 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
12  
13 <application
14 android:allowBackup="true"
15 android:icon="@drawable/ic_launcher"
16 android:label="@string/app_name"
17 android:theme="@style/AppTheme" >
18 <activity
19 android:name=".MainActivity"
20 android:label="@string/app_name" >
21 <intent-filter>
22 <action android:name="android.intent.action.MAIN" />
23  
24 <category android:name="android.intent.category.LAUNCHER" />
25 </intent-filter>
26 </activity>
27 </application>
28  
29 </manifest>

ScreenShot:

Screenshot_2015-01-11-13-54-24

Download Source Code from here.

 

 

[출처] http://www.geeks.gallery/simple-json-parsing-example-in-android-part-ii/

 

반응형

댓글()

외부 이미지 (url) 출력하기

프로그래밍/Android (Java)|2015. 11. 6. 16:29
반응형

import java.io.InputStream;

import java.net.MalformedURLException;

import java.net.URL;

import android.app.Activity;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.os.Bundle;

import android.os.Handler;

import android.widget.ImageView;


public class MainActivity extends Activity {


    Handler handler = new Handler();


        @Override

        protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);


        setContentView(R.layout.activity_main);

        Thread t = new Thread(new Runnable() {


        @Override

        public void run() {

            try {

                final ImageView imgSunny = (ImageView) findViewById(R.id.getImage);

                URL url = new URL("http://img.naver.net/static/www/u/2013/0731/nmms_224940510.gif");

                InputStream is = url.openStream();

                final Bitmap bm = BitmapFactory.decodeStream(is);

                handler.post(new Runnable() {

                    @Override

                    public void run() {

                        imgSunny.setImageBitmap(bm);

                    }

                });

                is.close();

            } catch (Exception e) {

                e.printStackTrace();

            }

            }

        });

        t.start();


[출처http://cieneyes.tistory.com/435


반응형

댓글()

안드로이드의 android:layout_weight 속성

프로그래밍/Android (Java)|2015. 11. 6. 09:01
반응형

LinearLayout의 속성 중에 android:layout_weight 이라는 속성이 있는데요.

이 것을 이용하면 LinearLayout의 항목들 배치에 아주 도움이 됩니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<LinearLayout
     android:orientation="horizontal"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:background="#ffffffff"
     android:gravity="center|right"
     android:padding="1dp">
 
     <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/update_time"
      style="@style/text_item.preference"
      android:layout_weight="1"
      android:gravity="right" />
 
     <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/edit"/>
</LinearLayout>

layout_weight 란 한마디로 UI영역에서 차지하는 중요도라고 할 수 있습니다. 이 중요도 비중을 높이면 그만큼 많은 영역을 UI영역에서 차지할 수 있죠. 설정을하지 않으면 디폴트로 0으로 설정됩니다.

위의 코드에서 TextView의 layout_weight가 1이고 Button은 설정을 하지 않았습니다. 그러면 Button이 높이가 wrap_content로 설정되어 있으니까 먼저 필요한 영역을 차지한 후 나머지 영역은 모두 TextView로 채워집니다. 만약 TextView와 Button에 layout_weight를 모두 1로 두면 어떻게 될까요? 중요도가 1:1로 설정이 되니까 화면을 절반씩 나우어 가지게 됩니다. 사용하실때 3:4든 5:5든 정수값이기만하면 비율을 맞추어 줍니다. 
LinearLayout을 사용하면서 화면에 꽉차는 UI를 개발할 때는 필수품이라고 할 수 있겠죠~

그런데 만약 TextView의 layout_height를 wrap_content가 아닌 fill_parent로 하면 어떻게 될까요? 음 다른 분들은 다들 알고 계신지 모르겠는데 layout_weight를 줄때는 layout_height가 wrap_content를 쓰던지 아니면 0dp를 줘야 합니다.
전 이걸 모르고 fill_parent로 지정을 했더니 속성값이 반대로 움직이더군요.ㅋ
TextView와 Button부분의 layout_height를 fill_parent로 해두고 layout_weight를 조절 했더니 양쪽이 반대로 움직이더군요. 1:9로 두고 실행시키면 9:1이 되는...
꼭 반대로 동작하지는 않을지도 모르지만 어쨋든 정상적인 동작은 기대할 수가 없으니깐 절대 꼭 wrap_content나 0dp로 하시고 사용하세요. 전 이거 잡는데 하루 걸렸습니다. 레이아웃을 너무 복잡하게 만든후에 문제를 발견해서ㅋㅋ

그리고 한가지 더, wrap_content를 지정하고 화면 비율을 나눈 경우에는 레이아웃 안쪽에 많은 항목이 있어서 크기가 커질 경우에 비율을 무시하고 내용물의 크기 많큼 레이아웃이 커집니다. 안쪽에 많은 항목이 있으면 나눈 비율보다 커질 수 도 있는거죠. 그리고 0dp를 사용한 경우에는 정확히 설정한 비율까지만 보여지게 됩니다. 나머지 항목은 가려지게 되겠죠~



[출처] 달료~ | 쏜다 (http://gunwi.tistory.com/entry/%EC%95%88%EB%93%9C%EB%A1%9C%EC%9D%B4%EB%93%9C%EC%9D%98-androidlayoutweight-%EC%86%8D%EC%84%B1)

 

반응형

댓글()

그리드뷰(gridview) 이미지에 이벤트 넣기

프로그래밍/Android (Java)|2015. 11. 4. 10:42
반응형

그리드뷰 중에 이미지를 표현하는 곳이 있습니다.

 

ImageView sysdocu_image = (ImageView) convertView.findViewById(R.id.ColPhoto);

이런식으로.. 이 하단에 아래 코드를 입력하면 됩니다.

 

sysdocu_image.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
    Intent intent = new Intent(ListActivity.this, VideoViewActivity.class);    // intent 변경 예(2줄). 다른 이벤트를 넣어도 됩니다.
    startActivity(intent);
    }
});

 

그리고 .java 파일 상단에 아래 항목을 잊지말고 추가해줍니다.

 

import android.view.View.OnClickListener;

 

 

* 참고

setOnclickListener 에서 상위 클래스의 변수를 가져오려고 할때 변수에 final 설정을 해주면 됩니다.



반응형

댓글()

액티비티 간 String 전송 (데이터 전송)

프로그래밍/Android (Java)|2015. 11. 3. 15:20
반응형
액티비티간에 자료를 전송해 주고 싶은 경우가 있다.

나같은 경우는 String형의 값을 전달해 주고 싶었다. 

이럴경우 쓰는 방법.


자료를 전송하고자 하는 액티비티에서 다음과 같이 해당 액티비티를 불러온다.

Intent intentAA = new Intent(this, Connect.class);    //Connect.java가 있어야한다. (액티비티)
intentAA.putExtra("key", "원하는 문자열 값");             //key는 해당 문자열을 알기 위한 값 받는 액티비티는 이 key를 통해서 문자열을 검색.
startActivity(intentAA);

--------------------------------------------------------------------------------------------

Connect 액티비티에서 문자열 값을 받는 방법.

String STR = getIntent().getStringExtra("key");                   //인텐트의 key값을 통해 해당 String을 받는다.
Toast.makeText(this, STR, Toast.LENGTH_LONG).show();   //토스트 기능으로 확인해보자.



[출처] http://egloos.zum.com/hiiq/v/1877208



안될경우 아래와 같이 액티비티명을 기재할것. 그리고 Toast 작성 위치도 중요

Toast.makeText(SubActivity.this, STR, Toast.LENGTH_LONG).show();


반응형

댓글()

Android (ListView/GridView) get Result from Web Server and Paging Pagination

프로그래밍/Android (Java)|2015. 11. 3. 08:41
반응형

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 เป็นหน้า ๆ ตามต้องการ

Android (ListView/GridView) get Result from Web Server and Paging Pagination



จากภาพประกอบ แสดงการอ่านข้อมูล 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

CREATE TABLE `images` (
`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":"1","ItemID":"Item 01","ImagePath":"http://www.thaicreate.com/android/images/img01.gif"}
,{"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 

Android (ListView/GridView) get Result from Web Server and Paging Pagination

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="&lt;&lt; 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>



Android (ListView/GridView) get Result from Web Server and Paging Pagination

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. 
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(5555);
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(10000);
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(50000);
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

Android (ListView/GridView) get Result from Web Server and Paging Pagination

กำลังโหลดและแสดงข้อมูลจาก Web Server และจัดการกับข้อมูลโดยการแบ่งการแสดงผลออกเป็นหลายหน้า

Android (ListView/GridView) get Result from Web Server and Paging Pagination

ทดสอบคลิกไปที่ Next >> เพื่อไปยังหน้าถัดไป

Android (ListView/GridView) get Result from Web Server and Paging Pagination

ในการเปลี่ยนแปลงหน้าทุกครั้งจะมีการใช้ ProgressBar ควบคุมการทำงาน เพื่อป้องกันโปรแกรมค้าง

Android (ListView/GridView) get Result from Web Server and Paging Pagination

สามารถคลิก << Prev หรือ Next >> เพื่อดูรายการข้อมูลในหน้าต่าง ๆ 





Example 2 การแสดงผลและแบ่งหน้าข้อมูลจาก Web Server บน GridView Widgets

โครงสร้างของไฟล์ประกอบด้วย 3 ไฟล์คือ MainActivity.java, activity_main.xml และ activity_column.xml 

Android (ListView/GridView) get Result from Web Server and Paging Pagination

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="&lt;&lt; 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>



Android (ListView/GridView) get Result from Web Server and Paging Pagination

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. 
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(5555);
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(5000);
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(5000);
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

Android (ListView/GridView) get Result from Web Server and Paging Pagination

กำลังแสดงผลข้อมูลจาก Web Server บน GridView และมีการแบ่งหน้าการแสดงผลข้อมูล

Android (ListView/GridView) get Result from Web Server and Paging Pagination

ทดสอบคลิกที่ Next >> เพื่อไปหน้าถัดไป

Android (ListView/GridView) get Result from Web Server and Paging Pagination

กำลังโหลดหน้าข้อมูลหในหน้าอื่น ๆ 

Android (ListView/GridView) get Result from Web Server and Paging Pagination

สามารถคลิกเพื่อไปดูข้อมูลในหน้าต่าง ๆ ได้


เพิ่มเติม
วิธีนี้จะเป็นการติดต่อกับ 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)|2015. 11. 3. 08:39
반응형

[ 첫번째 방법 ]


        Button btn_submit = (Button) v.findViewById(R.id.btn_submit);


        btn_submit.setOnClickListener(new Button.OnClickListener() {

            @Override

            public void onClick(View view) {

                // 내용 넣는곳

            }

        });




[ 두번째 방법 ]


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

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

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


        View.OnClickListener listener = new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                switch (v.getId()) {

                    case R.id.btn_sysdocu:

                        // 내용 넣는 곳

                        break;


                    case R.id.btn_mp3:

                        // 내용 넣는 곳

                        break;


                    case R.id.btn_mp4:

                        // 내용 넣는 곳

                        break;

                }

            }

        };


        btn_sysdocu.setOnClickListener(listener);

        btn_mp3.setOnClickListener(listener);

        btn_mp4.setOnClickListener(listener);

반응형

댓글()

안드로이드 버튼 숨기기

프로그래밍/Android (Java)|2015. 11. 3. 07:44
반응형

방법1

test.java 파일에서 수정

 

만약에 버튼아뒤가 bt1 = (Button) findbyViewId(R.id.bt01); << 이런식이라면

bt1.setVisibility(View.VISIBLE); // 화면에보임
bt1.settVisibility(View.INVISIBLE); // 화면에 안보임



방법2
test.xml 파일에서 수정

 

android:visibility="visible" << 버튼을 보이고 싶을때
android:visibility="invisible" << 버튼을 안보이고 싶을때(공간 차지함)

android:visibility="gone" << 버튼을 안보이고 싶을때(공간 차지하지않음)



[출처] http://blog.naver.com/PostView.nhn?blogId=junimohano&logNo=80126747520

반응형

댓글()

이미지 랜덤하게 출력하기 (ImageView)

프로그래밍/Android (Java)|2015. 10. 15. 13:50
반응형

activity_main.xml

 

<ImageView 
    android:id="@+id/SYSDOCU"
    android:layout_width="350dp"
    android:layout_height="160dp" />

 

 

MainActivity.java

 

package com.tistory.sysdocu;
import android.os.Bundle;
import android.app.Activity;
import android.widget.ImageView;
import android.graphics.drawable.Drawable;


public class MainActivity extends Activity {


        int[] images = new int[] {R.drawable.beautifulindonesia1, R.drawable.beautifulindonesia2, R.drawable.beautifulindonesia3, R.drawable.beautifulindonesia4, R.drawable.beautifulindonesia5};


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


        ImageView mImageView = (ImageView)findViewById(R.id.SYSDOCU);
        int imageId = (int)(Math.random() * images.length);
        mImageView.setBackgroundResource(images[imageId]);


        }


}

 

 

 

 

반응형

댓글()