LoginSignup
5
5

More than 5 years have passed since last update.

Android Volleyの導入

Last updated at Posted at 2015-02-25

はじめに

 AndroidStdudioへのVolleyの導入とVolleyを用いて、JSONパラメータ付きのリクエストを発行し、受け取ったJSONをパースすることについて説明する。

Android Volleyの導入

Androidプロジェクトを新規作成してVolleyが使えるようになるまでを参考にした。

JSONパラメーターを付加する

まずは送信パラメータを作る。

TopActivity.java
package me.strobo.volleytest;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;

import android.util.Log;
import java.util.Map;
import java.util.HashMap;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


public class TopActivity extends Activity {
    public static final String LOG_TAG = "volley_test";
    private RequestQueue mQueue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_top);
        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }

        mQueue = Volley.newRequestQueue(this);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.top, 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);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_top, container, false);
            return rootView;
        }
    }

    public void connectBtn_onClick(View view) {
        //String url = "http://weather.livedoor.com/forecast/webservice/json/v1?city=130010";
        String url = "https://strobospoon-staging.herokuapp.com/api/v0/user";

        HashMap<String, String> params = new HashMap<String, String>();
        params.put("sex", "1");
        params.put("height", "199");
        params.put("weight", "60");
        params.put("birthyear", "1919");
        params.put("activelevel", "1.5");
        JSONObject jsonParams = new JSONObject(params);

        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Loading");
        progressDialog.show();

        JsonObjectRequest jsonObjectReq = new JsonObjectRequest(
                Request.Method.POST, url, jsonParams,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(LOG_TAG, response.toString());
                        try {
                            Log.d(LOG_TAG, "Value: " + response.getString("value"));
                            Log.d(LOG_TAG, "Status: " + response.getString("status"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        progressDialog.hide();
                    }
                },

                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d(LOG_TAG, error.toString());
                        progressDialog.hide();
                    }
                }
        );

        mQueue.add(jsonObjectReq);
    }
}

その他の参考文献

5
5
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
5
5