【发布时间】:2016-06-08 06:38:52
【问题描述】:
如何创建一个单独的类,在其中定义所有关于 volley 在另一个活动中,我们直接传递 URL、CONTEXT 和 Get Response...
【问题讨论】:
如何创建一个单独的类,在其中定义所有关于 volley 在另一个活动中,我们直接传递 URL、CONTEXT 和 Get Response...
【问题讨论】:
首先在Activity中创建回调接口获取结果
public interface IResult {
public void notifySuccess(String requestType,JSONObject response);
public void notifyError(String requestType,VolleyError error);
}
使用 volley 函数创建一个单独的类,通过接口响应结果到活动
public class VolleyService {
IResult mResultCallback = null;
Context mContext;
VolleyService(IResult resultCallback, Context context){
mResultCallback = resultCallback;
mContext = context;
}
public void postDataVolley(final String requestType, String url,JSONObject sendObj){
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObj = new JsonObjectRequest(url,sendObj, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if(mResultCallback != null)
mResultCallback.notifySuccess(requestType,response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null)
mResultCallback.notifyError(requestType,error);
}
});
queue.add(jsonObj);
}catch(Exception e){
}
}
public void getDataVolley(final String requestType, String url){
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObj = new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if(mResultCallback != null)
mResultCallback.notifySuccess(requestType, response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null)
mResultCallback.notifyError(requestType, error);
}
});
queue.add(jsonObj);
}catch(Exception e){
}
}
}
然后将回调接口初始化为主Activity
mResultCallback = new IResult() {
@Override
public void notifySuccess(String requestType,JSONObject response) {
Log.d(TAG, "Volley requester " + requestType);
Log.d(TAG, "Volley JSON post" + response);
}
@Override
public void notifyError(String requestType,VolleyError error) {
Log.d(TAG, "Volley requester " + requestType);
Log.d(TAG, "Volley JSON post" + "That didn't work!");
}
};
现在创建 VolleyService 类的对象并传递给它上下文和回调接口
mVolleyService = new VolleyService(mResultCallback,this);
现在调用 Volley 方法进行发布或获取数据,同时传递 requestType,用于在将结果返回到主活动时识别服务请求者
mVolleyService.getDataVolley("GETCALL","http://192.168.1.150/datatest/get/data");
JSONObject sendObj = null;
try {
sendObj = new JSONObject("{'Test':'Test'}");
} catch (JSONException e) {
e.printStackTrace();
}
mVolleyService.postDataVolley("POSTCALL", "http://192.168.1.150/datatest/post/data", sendObj);
最终的 MainActivity
public class MainActivity extends AppCompatActivity {
private String TAG = "MainActivity";
IResult mResultCallback = null;
VolleyService mVolleyService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initVolleyCallback();
mVolleyService = new VolleyService(mResultCallback,this);
mVolleyService.getDataVolley("GETCALL","http://192.168.1.150/datatest/get/data");
JSONObject sendObj = null;
try {
sendObj = new JSONObject("{'Test':'Test'}");
} catch (JSONException e) {
e.printStackTrace();
}
mVolleyService.postDataVolley("POSTCALL", "http://192.168.1.150/datatest/post/data", sendObj);
}
void initVolleyCallback(){
mResultCallback = new IResult() {
@Override
public void notifySuccess(String requestType,JSONObject response) {
Log.d(TAG, "Volley requester " + requestType);
Log.d(TAG, "Volley JSON post" + response);
}
@Override
public void notifyError(String requestType,VolleyError error) {
Log.d(TAG, "Volley requester " + requestType);
Log.d(TAG, "Volley JSON post" + "That didn't work!");
}
};
}
}
在以下链接中找到整个项目
【讨论】:
JsonParserVolley.java
(我们将获得响应的单独类)
public class JsonParserVolley {
final String contentType = "application/json; charset=utf-8";
String JsonURL = "Your URL";
Context context;
RequestQueue requestQueue;
String jsonresponse;
private Map<String, String> header;
public JsonParserVolley(Context context) {
this.context = context;
requestQueue = Volley.newRequestQueue(context);
header = new HashMap<>();
}
public void addHeader(String key, String value) {
header.put(key, value);
}
public void executeRequest(int method, final VolleyCallback callback) {
StringRequest stringRequest = new StringRequest(method, JsonURL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
jsonresponse = response;
Log.e("RES", " res::" + jsonresponse);
callback.getResponse(jsonresponse);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return header;
}
}
;
requestQueue.add(stringRequest);
}
public interface VolleyCallback
{
public void getResponse(String response);
}
}
MainActivity.java (onCreate方法中编写的代码片段)
final JsonParserVolley jsonParserVolley = new JsonParserVolley(this);
jsonParserVolley.addHeader("Authorization", "Your value");
jsonParserVolley.executeRequest(Request.Method.GET, new JsonParserVolley.VolleyCallback() {
@Override
public void getResponse(String response) {
jObject=response;
Log.d("VOLLEY","RES"+jObject);
parser();
}
}
);
parser()是获取的json响应用于绑定activity组件的方法。
【讨论】:
您实际上错过了上述 VolleyService 类中的一个参数。你需要包括,它是,... JsonObjectRequest jsonObj = new JsonObjectRequest(Request.Method.GET, url,null,new Response.Listener() { /..../ } null 是应该包含的参数,否则它会给出错误
【讨论】:
在活动或片段中创建监听器(因为它们是接口,它们不能被实例化,但它们可以被实例化为实现接口的匿名类)。并将此实例作为参数传递给请求。(StringRequest、JsonObjectRequest 或 ImageRequest)。
public class MainActivity extends Activity {
private static final String URI = "";
// This is like BroadcastReceiver instantiation
private Listener<JSONObject> listenerResponse = new Listener<JSONObject>() {
@Override
public void onResponse(JSONObject arg0) {
// Do what you want with response
}
};
private ErrorListener listenerError = new ErrorListener() {
@Override
public void onErrorResponse(VolleyError arg0) {
// Do what you want with error
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
接下来,创建一个有 request 的类,并将这个监听器传递给这个类的 request 方法,仅此而已。我不解释这部分这与在任何教程中创建请求对象相同。但是您可以根据需要自定义此类。您可以创建单例RequestQueue 来检查优先级,或者将body http body 参数设置为此方法作为参数。
public class NetworkHandler {
public static void requestJSON(Context context, String url, Listener<JSONObject> listenerResponse, ErrorListener listenerError) {
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, url, null, listenerResponse, listenerError);
Volley.newRequestQueue(context).add(jsonRequest);
}
}
【讨论】:
public class VolleyService {
IResult mResultCallback = null;
Context mContext;
VolleyService(IResult resultCallback, Context context)
{
mResultCallback = resultCallback;
mContext = context;
}
//--Post-Api---
public void postDataVolley(String url,final Map<String,String> param){
try {
StringRequest sr = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if(mResultCallback != null)
mResultCallback.notifySuccessPost(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null)
mResultCallback.notifyError(error);
}
}) {
@Override
protected Map<String, String> getParams() {
return param;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
AppController.getInstance(mContext).addToRequestQueue(sr);
}catch(Exception e){
}
}
//==Patch-Api==
public void patchDataVolley(String url,final HashMap<String,Object> param)
{
JsonObjectRequest request = new JsonObjectRequest(Request.Method.PATCH, url, new JSONObject(param),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if(mResultCallback != null)
mResultCallback.notifySuccessPatch(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null)
mResultCallback.notifyError(error);
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
return headers;
}
};
AppController.getInstance(mContext).addToRequestQueue(request);
}
}
public interface IResult {
void notifySuccessPost(String response);
void notifySuccessPatch(JSONObject jsonObject);
void notifyError(VolleyError error);
}
【讨论】: