1. What is WAMP Server

WAMP is acronym for Windows, Apache, MySQL and PHP, Perl, Python. WAMP software is one click installer which creates an environment for developing PHP, MySQL web application. By installing this software you will be installing ApacheMySQL and PHP. Alternatively you can use XAMP Server also.

wamp server installation

2. Installing and Running WAMP Server

Download & Install WAMP server from www.wampserver.com/en/. Once you have installed wamp server, launch the program from Start -> All Programs -> WampServer -> StartWampServer.

You can test your server by opening the address http://localhost/ in your browser.
Also you can check phpmyadmin by opening http://localhost/phpmyadmin

Following is a screen cast of Downloading and Installing WAMP Server.

3. Creating and Running PHP Project

Now you have the environment ready to develop a PHP & MySQL project. Go to the location where you installed WAMP server (In my case i installed in C:\wamp\) and go to www folder and create a new folder for your project. You have to place all your project files inside this folder.

Create a folder called android_connect and create a new php file called test.php and try out simple php code. After placing following code try to openhttp://localhost/android_connect/test.php and you should see a message called “Welcome, I am connecting Android to PHP, MySQL“.

test.php

<?php
    echo "Welcome, I am connecting Android to PHP, MySQL";
?>

Following is a screen cast of Creating and Running a simple PHP project.

4. Creating MySQL Database and Tables

In this tutorial i am creating a simple database with one table. Through out this tutorial i am using same table to perform example operations. Now open phpmyadmin by opening the address http://localhost/phpmyadmin/ in your browser. You can use the PhpMyAdmin tool to create a database and a table.

I am creating a database named androidhive and a table called products.

CREATE DATABASE androidhive;
CREATE TABLE products(
pid int(11) primary key auto_increment,
name varchar(100) not null,
price decimal(10,2) not null,
description text,
created_at timestamp default now(),
updated_at timestamp
);

Following is a screen cast of Creating database and tables in phpmyadmin

5. Connecting to MySQL database using PHP

Now the actual server side coding starts. Create a PHP class to connect to MySQL database. The main purpose of this class is to open a connection to database and close the connection whenever its not needed. So create two files called db_config.php and db_connect.php

db_config.php – will have database connection variables
db_connect.php – a class file to connect to database

Following is code for two php files

db_config.php

db_config.php
<?php
 
/*
 * All database connection variables
 */
 
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "androidhive"); // database name
define('DB_SERVER', "localhost"); // db server
?>

db_connect.php

db_connect.php
<?php
 
/**
 * A class file to connect to database
 */
class DB_CONNECT {
 
    // constructor
    function __construct() {
        // connecting to database
        $this->connect();
    }
 
    // destructor
    function __destruct() {
        // closing db connection
        $this->close();
    }
 
    /**
     * Function to connect with database
     */
    function connect() {
        // import database connection variables
        require_once __DIR__ . '/db_config.php';
 
        // Connecting to mysql database
        $con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
 
        // Selecing database
        $db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
 
        // returing connection cursor
        return $con;
    }
 
    /**
     * Function to close db connection
     */
    function close() {
        // closing db connection
        mysql_close();
    }
 
}
 
?>

Usage: When ever you want to connect to MySQL database and do some operations use the db_connect.php class like this

$db = new DB_CONNECT(); // creating class object(will open database connection)

6. Basic MySQL CRUD Operations using PHP

In this tutorial i am covering basic CRUD (Create, Read, Update, Delete) operations on MySQL database using PHP.
If you are a novice about PHP and MySQL i suggest, you to learn basic PHP and SQL here.

6.a) Creating a row in MySQL (Creating a new product row)

In your PHP project create a new php file called create_product.php and place the following code. This file is mainly for creating a new product in products table.

In the following code i am reading product data via POST and storing them in products table. At the end i am echoing appropriate JSON as response.

create_product.php
<?php
 
/*
 * Following code will create a new product row
 * All product details are read from HTTP Post Request
 */
 
// array for JSON response
$response = array();
 
// check for required fields
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) {
 
    $name = $_POST['name'];
    $price = $_POST['price'];
    $description = $_POST['description'];
 
    // include db connect class
    require_once __DIR__ . '/db_connect.php';
 
    // connecting to db
    $db = new DB_CONNECT();
 
    // mysql inserting a new row
    $result = mysql_query("INSERT INTO products(name, price, description) VALUES('$name', '$price', '$description')");
 
    // check if row inserted or not
    if ($result) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "Product successfully created.";
 
        // echoing JSON response
        echo json_encode($response);
    } else {
        // failed to insert row
        $response["success"] = 0;
        $response["message"] = "Oops! An error occurred.";
 
        // echoing JSON response
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
 
    // echoing JSON response
    echo json_encode($response);
}
?>

For the above code JSON response will be like

When POST param(s) is missing

{
    "success": 0,
    "message": "Required field(s) is missing"
}

When product is successfully created

{
    "success": 1,
    "message": "Product successfully created."
}

When error occurred while inserting data

{
    "success": 0,
    "message": "Oops! An error occurred."
}

6.b) Reading a Row from MySQL (Reading product details)

Create a new php file called get_product_details.php and write the following code. This file will get single product details by taking product id (pid) as post parameter.

get_product_details.php
<?php
 
/*
 * Following code will get single product details
 * A product is identified by product id (pid)
 */
 
// array for JSON response
$response = array();
 
// include db connect class
require_once __DIR__ . '/db_connect.php';
 
// connecting to db
$db = new DB_CONNECT();
 
// check for post data
if (isset($_GET["pid"])) {
    $pid = $_GET['pid'];
 
    // get a product from products table
    $result = mysql_query("SELECT *FROM products WHERE pid = $pid");
 
    if (!empty($result)) {
        // check for empty result
        if (mysql_num_rows($result) > 0) {
 
            $result = mysql_fetch_array($result);
 
            $product = array();
            $product["pid"] = $result["pid"];
            $product["name"] = $result["name"];
            $product["price"] = $result["price"];
            $product["description"] = $result["description"];
            $product["created_at"] = $result["created_at"];
            $product["updated_at"] = $result["updated_at"];
            // success
            $response["success"] = 1;
 
            // user node
            $response["product"] = array();
 
            array_push($response["product"], $product);
 
            // echoing JSON response
            echo json_encode($response);
        } else {
            // no product found
            $response["success"] = 0;
            $response["message"] = "No product found";
 
            // echo no users JSON
            echo json_encode($response);
        }
    } else {
        // no product found
        $response["success"] = 0;
        $response["message"] = "No product found";
 
        // echo no users JSON
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
 
    // echoing JSON response
    echo json_encode($response);
}
?>

The json response for the above file will be

When successfully getting product details

{
    "success": 1,
    "product": [
        {
            "pid": "1",
            "name": "iPHone 4S",
            "price": "300.00",
            "description": "iPhone 4S white",
            "created_at": "2012-04-29 01:41:42",
            "updated_at": "0000-00-00 00:00:00"
        }
    ]
}

When no product found with matched pid

{
    "success": 0,
    "message": "No product found"
}

6.c) Reading All Rows from MySQL (Reading all products)

We need a json to list all the products on android device. So create a new php file namedget_all_products.php and write following code.

get_all_products.php
<?php
 
/*
 * Following code will list all the products
 */
 
// array for JSON response
$response = array();
 
// include db connect class
require_once __DIR__ . '/db_connect.php';
 
// connecting to db
$db = new DB_CONNECT();
 
// get all products from products table
$result = mysql_query("SELECT *FROM products") or die(mysql_error());
 
// check for empty result
if (mysql_num_rows($result) > 0) {
    // looping through all results
    // products node
    $response["products"] = array();
 
    while ($row = mysql_fetch_array($result)) {
        // temp user array
        $product = array();
        $product["pid"] = $row["pid"];
        $product["name"] = $row["name"];
        $product["price"] = $row["price"];
        $product["created_at"] = $row["created_at"];
        $product["updated_at"] = $row["updated_at"];
 
        // push single product into final response array
        array_push($response["products"], $product);
    }
    // success
    $response["success"] = 1;
 
    // echoing JSON response
    echo json_encode($response);
} else {
    // no products found
    $response["success"] = 0;
    $response["message"] = "No products found";
 
    // echo no users JSON
    echo json_encode($response);
}
?>

And the JSON response for above code

Listing all Products

{
    "products": [
        {
            "pid": "1",
            "name": "iPhone 4S",
            "price": "300.00",
            "created_at": "2012-04-29 02:04:02",
            "updated_at": "0000-00-00 00:00:00"
        },
        {
            "pid": "2",
            "name": "Macbook Pro",
            "price": "600.00",
            "created_at": "2012-04-29 02:04:51",
            "updated_at": "0000-00-00 00:00:00"
        },
        {
            "pid": "3",
            "name": "Macbook Air",
            "price": "800.00",
            "created_at": "2012-04-29 02:05:57",
            "updated_at": "0000-00-00 00:00:00"
        },
        {
            "pid": "4",
            "name": "OS X Lion",
            "price": "100.00",
            "created_at": "2012-04-29 02:07:14",
            "updated_at": "0000-00-00 00:00:00"
        }
    ],
    "success": 1
}

When products not found

{
    "success": 0,
    "message": "No products found"
}

6.d) Updating a Row in MySQL (Updating product details)

Create a php file named update_product.php to update product details. Each product is identified by pid.

update_product.php
<?php
 
/*
 * Following code will update a product information
 * A product is identified by product id (pid)
 */
 
// array for JSON response
$response = array();
 
// check for required fields
if (isset($_POST['pid']) && isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) {
 
    $pid = $_POST['pid'];
    $name = $_POST['name'];
    $price = $_POST['price'];
    $description = $_POST['description'];
 
    // include db connect class
    require_once __DIR__ . '/db_connect.php';
 
    // connecting to db
    $db = new DB_CONNECT();
 
    // mysql update row with matched pid
    $result = mysql_query("UPDATE products SET name = '$name', price = '$price', description = '$description' WHERE pid = $pid");
 
    // check if row inserted or not
    if ($result) {
        // successfully updated
        $response["success"] = 1;
        $response["message"] = "Product successfully updated.";
 
        // echoing JSON response
        echo json_encode($response);
    } else {
 
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
 
    // echoing JSON response
    echo json_encode($response);
}
?>

The json reponse of above code, when product is updated successfully

{
    "success": 1,
    "message": "Product successfully updated."
}

6.e) Deleting a Row in MySQL (Deleting a product)

The last operation is deletion on database. Create a new php file called delete_product.php and paste the following code. The main functionality of this file is to delete a product from database.

delete_product.php
<?php
 
/*
 * Following code will delete a product from table
 * A product is identified by product id (pid)
 */
 
// array for JSON response
$response = array();
 
// check for required fields
if (isset($_POST['pid'])) {
    $pid = $_POST['pid'];
 
    // include db connect class
    require_once __DIR__ . '/db_connect.php';
 
    // connecting to db
    $db = new DB_CONNECT();
 
    // mysql update row with matched pid
    $result = mysql_query("DELETE FROM products WHERE pid = $pid");
 
    // check if row deleted or not
    if (mysql_affected_rows() > 0) {
        // successfully updated
        $response["success"] = 1;
        $response["message"] = "Product successfully deleted";
 
        // echoing JSON response
        echo json_encode($response);
    } else {
        // no product found
        $response["success"] = 0;
        $response["message"] = "No product found";
 
        // echo no users JSON
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
 
    // echoing JSON response
    echo json_encode($response);
}
?>

When product successfully deleted

{
    "success": 1,
    "message": "Product successfully deleted"
}

When product not found

{
    "success": 0,
    "message": "No product found"
}

Until now, we built a simple api for our products table. We are now done with the server side coding (PHP) and its time to take a break and start our actual android application coding.



웹뷰를 통해 모바일 페이지를 보여주는 어플을 만들었는데, 

모바일 크롬이나 모바일 브라우저로 카카오톡 공유를 누르면 잘 되는데, 웹뷰를 통해서 버튼을 누르면 

아래와같은 오류 나면서 되지 않을때 해결방법


private class JsWebViewClient extends WebViewClient{ @Override public boolean shouldOverrideUUrlLoading(WebView view, String url){ if(url.startsWith("kakolink:")){ Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent);      } else{ view.loadUrl(url); } return true; } } // http://www.kakao.com/link/ko/api?tab=android // 카카오톡 API 확인해보면 kakaolink:로 시작하기때문에 // 코드를 넣어주면 됨

이런 방법으로도 가능

private class JsWebViewClient extends WebViewClient{ @Override public boolean shouldOverrideUrlLoading(WebView view, String url){ if(("kakaolink").equals(url.substring(0,9))){ loadkakao(url); } else{ view.loadUrl(url); } return true; } } //for Enabling kakaotalk link public void loadkakao(String url){ Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); intent.addCategory(Intent.CATEGORY_BROWSABLE); intent.putExtra(Browser.EXTRA_APPLICATION_ID,getPackageName()); startActivity(intent); }


결과



기본적으로 ImageView사용하여 xml작성하였을경우


<ImageView android:id="@+id/imageView1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/img_jasontody" />

타이틀 말고 이미지 꽉 채우기

<ImageView android:id="@+id/imageView1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/img_jasontody"         android:scaleType="fitXY" />

타이틀까지 채우기

super.onCreate(savedInstanceState);

requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main_imagexml);


http://www.androidhive.info/2012/02/android-gridview-layout-tutorial/

http://collegewires.com/android/2012/06/android-grid-view-example/

그리드뷰 xml

<GridView android:id="@+id/gridview_id" // 아이디 값 
   android:layout_width="750px" //너비
   android:layout_height="340px"//높이 
   android:verticalSpacing="5px" //item의 상하 간격
   android:horizontalSpacing="5px"//아이템의 좌우 간격
   android:numColumns="auto_fit" //Grid 한 Row에 나열될 Column의 개수를 지정(1~n개). "auto_fit"으로 설정하면 사용 가능한 공간에 따라 자동으로 column의 개수 정해짐. 
   android:columnWidth="100px"  //  Column의 너비를 pixel로 지정. 
   android:stretchMode="none" //android:numColumns이 "auto_fit"으로 설정되었을때만 적용. auto_fit을 하고 남은 좌우 공간을 어떻게 분배할지를 결정함. columnWidth로 설정되면 남은 공간이 column들에게 골고루 할당되며, spacingWidth로 설정되면 column간 여백이 남은 공간을 골고루 나눠 할당 받음.
   android:gravity="center" //레이아웃에서의 그리드뷰 위치 
   android:visibility="gone"//화면에 보이기 설정 
  />

일정시간이 지나고나서 액티비티를 자동으로 넘겨주게 하자
아래 예제코드 (ImageTab.java -> Temp2.java로 '3000' 후에 이동)
 Handler mHandler = new Handler();
        mHandler.postDelayed(new Runnable() {
         // Do Something
         public void run()
         {
                Intent intent = new Intent(ImageTab.this, Temp2.class);
                startActivity(intent);
                finish();         
         }
        }, 3000);


'공부 > Android' 카테고리의 다른 글

안드로이드 타이틀 없이 화면 채우기(화면 꽉 채우기)  (0) 2012.10.28
Gridview 썸네일 이미지 클릭시 확대하기  (0) 2012.08.23
그리드뷰 GridView Xml  (0) 2012.08.23
타이머  (0) 2012.07.25
Inflater 설명  (0) 2012.07.25


myTimer.zip


출처 : http://blog.naver.com/PostView.nhn?blogId=kookh1&logNo=120163211357


LayoutInflater
 - inflate의 사전적 의미 : 부풀리다. 팽창하다.
 - 안드로이드에서 inflate의 의미 : 전개


기능 
 1. XML 문서에 정의된 레이아웃과 Child 뷰의 속성을 읽어 실제 뷰 객체를 생성해내는 동작.
 2. 레이아웃의 정보대로 객체를 생성하고 속성 변경 메소드를 순서대로 호출하는 것.
 3. 동적으로 View를 교체할 수 있으며 복합적인 View를 여러 곳에서 공통으로 사용하고자할때 유용하다.


안드로이드에서 어떤 View가 화면에서 보일려면 반드시 객체화(인스턴스화)되어 있어야 된다.
안드로이드에서 뷰 객체를 생성하는 과정은 크게 2가지가 있다.

직접 코드 상에서 아래와 같이 생성하는 방법이 있고

1
Button b = new Button(this);      // this는 context

그리고 XML 파일을 통해 객체를 생성하는 방법이 있다. 
Inflate는 XML을 통해서 객체화 시키는 것을 의미한다.

보통 액티비티의 onCreate() 함수에서도 자주 쓰이는 setContentView() 메소드는 내부적으로
XML을 통해 뷰 객체를 생성하는 Inflate 과정이 포함되어 있다. 내부는 아래와 같이 동일하다.
1
2
3
4
setContentView(View.inflate(this, R.layout.main, null));
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = (View)inflater(R.layout.main, null);
serContentView(v);

결국 setContentView(R.layout.main)와 같이 리소스 아이디를 지정하지 않고, 직접 LayoutInflater를
이용해서 레이아웃 객체를 생성한 후 setContentView()를 통해서 그 생성된 레이아웃 객체를
올려도 동일한 결과가 나오게 된다.


Inflate에는 여러 종류의 메소드가 있다.
위에서 설명한 LayoutInflater, menu의 XML을 읽어들여 메뉴 객체를 구성하는 MenuInflater,
또 View 클래스의 정적 메소드로 inflate도 있다.

아래는 main layout 대신 커스터마이징된 dialog layout을 생성하는 코드이다.
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
public class AlertCustom extends Activity {
    ...
    @Override
    protected Dialog onCreateDialog(int id) {
        switch(id) {
        case CUSTOM_DIALOG :
            AlertDialog.Builder builder;
            AlertDialog alertDialog;
     
            LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
     
            View layout = inflater.inflate(R.layout.custom_dialog,
                    (ViewGroup) findViewById(R.id.layout_root));
     
            TextView text = (TextView) layout.findViewById(R.id.text);
            text.setText("Hello, this is a custom dialog!");
            ImageView image = (ImageView) layout.findViewById(R.id.image);
            image.setImageResource(R.drawable.icon);
     
            builder = new AlertDialog.Builder(this);
            builder.setView(layout);
            alertDialog = builder.create();
     
            return alertDialog;
        }
         
        return null;
    }
}

 

 출처 : http://warmz.tistory.com/579

+ Recent posts