2015年1月25日日曜日

Android StudioでZXingのライブラリを使う

Android StudioでZXingのライブラリを使う設定です。
非常に簡単で、アプリのbuild.gradleに追加するだけです。

1
2
3
4
5
6
7
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.2'
+    compile 'com.google.zxing:core:3.1.0'
+    compile 'com.google.zxing:android-integration:3.1.0'
 
}

2015年1月17日土曜日

Volleyのリクエストにパラメータとヘッダーの値を追加する方法

Volleyのリクエストにパラメータとヘッダーの値を追加する方法です。
StringRequestクラスの親クラスであるRequestクラスに、次のようなメソッドがあります。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
 * Returns a list of extra HTTP headers to go along with this request. Can
 * throw {@link AuthFailureError} as authentication may be required to
 * provide these values.
 * @throws AuthFailureError In the event of auth failure
 */
public Map<String, String> getHeaders() throws AuthFailureError {
    return Collections.emptyMap();
}
 
 /**
 * Returns a Map of parameters to be used for a POST or PUT request.  Can throw
 * {@link AuthFailureError} as authentication may be required to provide these values.
 *
 * <p>Note that you can directly override {@link #getBody()} for custom data.</p>
 *
 * @throws AuthFailureError in the event of auth failure
 */
protected Map<String, String> getParams() throws AuthFailureError {
    return null;
}

StringRequestを生成する際、getHeaders()とgetParams()をオーバーライドすれば、POSTパラメータとヘッダーの値を追加することができます。
次のソースはオーバーライドによって値を渡すサンプルです。


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
30
31
32
33
34
35
36
37
38
/**
 * Request(StringRequest) with params
 *
 * @param url      request url
 * @param listener listener for Response or Error
 * @param params   value of setting Http Params
 * @param headers  value of setting Http headers
 */
public void get(String url, final ResponseListener listener, final Map<String, String> params
        , final Map<String, String> headers) {
 
    StringRequest request = new StringRequest(url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    listener.onResponse(s);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    listener.onErrorResponse(volleyError);
                }
            }
    ) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            return params;
        }
 
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            return headers;
        }
    };
 
    mRequestQueue.add(request);
}