14
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

VolleyでのJSON処理 その2

Last updated at Posted at 2014-10-05

###発展版
・サーバのコード(PHP)
・階層かつ配列のJSONを取得

###前提
・mysqlにtestdb->members tableがある。
・members tableにはnameとageというカラムがある。

###サーバ側
DBの値を取得して返す、典型例。

json.php
<?php

	$dbh = new PDO("mysql:host=localhost;dbname=testdb","user","pass");

	$stmt = $dbh->prepare("SELECT * FROM members");
	$stmt->execute();
	
	//response用
	$response = array();

	//dbデータ格納用
	$db_data = array();

	foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $row){
		$db_data[] = array(
				'name'=>$row['name'],
				'age'=>$row['age']
			);
	}
	
	//responseの準備
	$response['status'] = "OK";
	$response['members'] = $db_data;

	//JSON出力
	header("Content-type: application/json; charset=UTF-8");
	echo json_encode($response);

###JSON
こういうのが返ります。よくあるパターン。

sample.json
{
	"status":"OK",
	"members":[
				{"name":"hoge","age":"56"},
				{"name":"foo","age":"34"}
			]
}

###android側

###追記

なお、最新環境で下記のコードを実行すると「JsonObjectRequestの参照はあいまいです」的なエラーが出ます。
以前より、引数の型が厳しくなったようです(以下は修正済)。

new JsonObjectRequest(Method.GET, url, null,

のところを、

new JsonObjectRequest(Method.GET, url, (String)null,

とすることで回避できます。

MyActivity.java
public class MyActivity extends Activity {

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

        //queue
        RequestQueue queue = Volley.newRequestQueue(this);

        //url
        String url = "http://www.bluecode.jp/test/json.php";

        //request生成
        JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET,url,(String)null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {

                        //JSONの処理
                        try{

                            //1階層目は普通に
                            String status = jsonObject.getString("status");
                            //出力
                            Log.v("tama", "status=" + status);

                            //2階層目(配列)
                            JSONArray members = jsonObject.getJSONArray("members");
                            //ループ
                            for(int i=0;i<members.length();i++){

                                //JSONObjectとして1つ1つ取得
                                JSONObject member = members.getJSONObject(i);
									//明日を取得(ListViewとかに追加)
                                String name = member.getString("name");
                                String age = member.getString("age");

                                //出力
                                Log.v("tama","name=" + name);
                                Log.v("tama","age=" + age);
                            }

                        }catch(Exception e){
                            e.printStackTrace();
                        }

                    }
                },
                new Response.ErrorListener(){
                    @Override
                    public void onErrorResponse(VolleyError error){

                    }
                }
        );

        //Queueに追加
        queue.add(jsonRequest);
    }
}
14
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?