VolleyでのJSON処理
volleyはcloneしてビルドする。Android Studioの場合は、libsにコピーした後、GrandleのSyncをする。
volleyはQueueを作成し、そこにrequestを追加するのが基本。
追記
なお、最新環境で下記のコードを実行すると「JsonObjectRequestの参照はあいまいです」的なエラーが出ます。
以前より、引数の型が厳しくなったようです(以下は修正済)。
new JsonObjectRequest(Method.GET, url, null,
のところを、
new JsonObjectRequest(Method.GET, url, (String)null,
とすることで回避できます。
MainActivity.java
package com.example.json01;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
public class MainActivity extends Activity {
//ネットリクエストをQueue
private RequestQueue mQueue;
//ボタンを宣言
private Button btn;
//テキストを宣言
private TextView tv;
//アプリ起動時に呼ばれる
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//リクト用のQueueを初期化
mQueue = Volley.newRequestQueue(this);
//テキストを初期化
tv = (TextView)findViewById(R.id.textView1);
//ボタンを初期化
btn = (Button) findViewById(R.id.button1);
//クリックリスナーをセット
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//押されたボタンのIDを取得して場合分け
switch(v.getId()){
case R.id.button1:
//tv.setText("Hello");
//接続先
String url = "http://www.bluecode.jp/test/stock/price.php";
//キューにリクエストを追加
mQueue.add(new JsonObjectRequest(Method.GET, url, (String)null,
new Listener<JSONObject>(){
@Override
public void onResponse(JSONObject response){
try{
//Log.v("tama",response.getString("price"));
//取得した値を表示
tv.setText(response.getString("price"));
}catch(JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error){
//エラー処理
}
}));
//
break;
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}