我是Android和Volley的新手,需要您的帮助。我需要发布一个String,有一个json来响应它,如果它没有引发错误的请求,请从我的请求中获取一些值来启动一个新的Intent。
这是我想做的一个简单模式:按下登录按钮->星形请求->检查是否正常->使用响应值启动新的意图。
我已经看到Volley使用异步方法进行查询。这是我的代码:
boolean temp=false; login.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { boolean temp=false; if (!id.getText().toString().isEmpty() && !pw.getText().toString().isEmpty()) { temp = verifyCredentials(v.getContext()); //Doesn't work because Volley is asynchronous. if(temp==true) { Intent intentMain = new Intent(v.getContext(), MainActivity.class);//MainActivity.class); intentMain.putExtra("username", id.getText().toString()); startActivityForResult(intentMain, 0); } } else {//strighe vuote //toast Toast.makeText(v.getContext(), "Compila i campi", Toast.LENGTH_SHORT).show(); } } }); public boolean verifyCredentials(Context context) { final boolean[] tempToReturn = {false}; mTextView = (TextView) findViewById(R.id.textView2); RequestQueue queue = Volley.newRequestQueue(context); StringRequest stringRequest = new StringRequest(Request.Method.POST, apiURL, new Response.Listener<String>() { @Override public void onResponse(String response) { mTextView.setText("Response is:" + response.substring(500)); tempToReturn[0] =true; } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { String json = null; NetworkResponse response = error.networkResponse; if(response != null && response.data != null){ switch(response.statusCode){ case 400: json = new String(response.data); json = trimMessage(json, "message"); if(json != null) displayMessage(json); break; } //Additional cases } mTextView.setText("Error bad request"); } public String trimMessage(String json, String key){ String trimmedString = null; try{ JSONObject obj = new JSONObject(json); trimmedString = obj.getString(key); } catch(JSONException e){ e.printStackTrace(); return null; } return trimmedString; } //Somewhere that has access to a context public void displayMessage(String toastString){ mTextView.setText("Response is:" +toastString); } }){ @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); AuthenticationUserName = id.getText().toString(); AuthenticationPassword = pw.getText().toString(); params.put("grant_type", Authenticationgrant_type); params.put("username", AuthenticationUserName); params.put("password", AuthenticationPassword); return params; } }; queue.add(stringRequest); return tempToReturn[0]; }
我之所以使用Volley,是因为我的Gradle也是23和APi级别,因此我无法使用apache软件包。
编辑:新代码:
public void onClick(View v) { boolean temp = true; if (!id.getText().toString().isEmpty() && !pw.getText().toString().isEmpty()) { myContext = v.getContext(); VolleyResponseListener listener = new VolleyResponseListener() { @Override public void onError(VolleyError error) { String json = null; NetworkResponse response = error.networkResponse; if(response != null && response.data != null){ switch(response.statusCode){ case 400: json = new String(response.data); json = trimMessage(json, "message"); if(json != null) displayMessage(json); break; } //Additional cases } mTextView.setText("Error bad request"); } @Override public void onResponse(JSONObject response) { try { fullName = response.getString("fullName"); token= response.getString("access_token"); expirationDate=response.getString(".expires"); } catch (JSONException e) { e.printStackTrace(); } mTextView.setText("Response is:" + fullName+token+expirationDate); Intent intentMain = new Intent(myContext, MainActivity.class);//MainActivity.class); intentMain.putExtra("username", id.getText().toString()); startActivityForResult(intentMain, 0); } public String trimMessage(String json, String key){ String trimmedString = null; try{ JSONObject obj = new JSONObject(json); trimmedString = obj.getString(key); } catch(JSONException e){ e.printStackTrace(); return null; } return trimmedString; } //Somewhere that has access to a context public void displayMessage(String toastString){ //Toast.makeText(MainActivity.this, toastString, Toast.LENGTH_LONG).show(); mTextView.setText("Response is:" +toastString); } }; verifyCredentials(myContext,listener);
我已经创建了这个界面:
public interface VolleyResponseListener { void onError(VolleyError error); void onResponse(JSONObject response); }
这是我的verifycredential的新代码:
public boolean verifyCredentials(Context context,final VolleyResponseListener listener) { final boolean[] tempToReturn = {false}; mTextView = (TextView) findViewById(R.id.textView2); Map<String,String> params = new HashMap<String, String>(); AuthenticationUserName = id.getText().toString(); AuthenticationPassword = pw.getText().toString(); //key value params.put("grant_type", Authenticationgrant_type); params.put("username", AuthenticationUserName); params.put("password", AuthenticationPassword); RequestQueue queue = Volley.newRequestQueue(context); SimpleRequest jsObjRequest = new SimpleRequest(Request.Method.POST, apiURL, params,new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { listener.onResponse(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { listener.onError(error); } } }); queue.add(jsObjRequest); return tempToReturn[0]; }
我已经回答了一些看起来像您的问题的问题,例如:
Android:如何使用Volley从方法返回异步JSONObject?
您不应该等待该布尔值返回。相反,你可以试试下面的方法(当然,你可以替换JSONArray的请求JSONObject或String要求):
JSONArray
JSONObject
String
VolleyResponseListener listener = new VolleyResponseListener() { @Override public void onError(String message) { // do something... } @Override public void onResponse(Object response) { // do something... } }; makeJsonArrayRequest(context, Request.Method.POST, url, requestBody, listener);
的主体makeJsonArrayRequest可以如下:
makeJsonArrayRequest
public void makeJsonArrayRequest(Context context, int method, String url, String requestBody, final VolleyResponseListener listener) { JSONObject jsonRequest = null; try { ... if (requestBody != null) { jsonRequest = new JSONObject(requestBody); } ... } catch (JSONException e) { e.printStackTrace(); } JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(method, url, jsonRequest, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray jsonArray) { listener.onResponse(jsonArray); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { listener.onError(error.toString()); } }); // Access the RequestQueue through singleton class. MySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest); }
VolleyResponseListener 界面如下:
VolleyResponseListener
public interface VolleyResponseListener { void onError(String message); void onResponse(Object response); }
对于下面的评论:
首先是:方法的“顺序”,例如,在我的情况下,按下按钮后,我必须调用哪个方法?
假设我们在内部onCreate:您可以VolleyResponseListener listener先创建,然后verifyCredentials(..., listener);在按下按钮时调用。
onCreate
VolleyResponseListener listener
verifyCredentials(..., listener);
在哪里可以调用意图?
这将onResponse在上述内部被调用VolleyResponseListener listener(当然,在内部可以根据您的要求检查更多条件)
onResponse
第二:我必须发送一个String,但是我想要一个jsonArrayRespond,有没有一种方法可以做到这一点? 或者它仅适用于2种参数,例如字符串请求/字符串发送和json请求/ json发送?
根据Google的培训文档:
当然,对于不具有即用Volley支持的类型,您可以实现自己的自定义请求类型。看一下实现自定义请求。
希望这可以帮助!