我有这个Volley GET请求类:
public class VolleyGetHeaders {
private static final String TAG = "VolleyGet";
private static VolleyGetHeaders instance = null;
//for Volley API
public RequestQueue requestQueue;
private VolleyGetHeaders(Context context)
{
requestQueue = Volley.newRequestQueue(context.getApplicationContext());
return;
}
public static synchronized VolleyGetHeaders getInstance(Context context)
{
if (null == instance)
instance = new VolleyGetHeaders(context);
return instance;
}
public static synchronized VolleyGetHeaders getInstance()
{
if (null == instance)
{
throw new IllegalStateException(VolleyGetHeaders.class.getSimpleName() +
" is not initialized, call getInstance(...) first");
}
return instance;
}
public void VolleyGETHeaders(String domain, String api, final CustomListener<String> listener){
StringRequest sr = new StringRequest(Request.Method.GET, domain +api,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e("HttpClient", "success! response: " + response);
if(null != response)
listener.getResult(response);
return;
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (null != error.networkResponse)
{
Log.d(TAG + ": ", "Error Response code: " + error.networkResponse.statusCode);
//listener.getResult(false);
}
}
})
{
@Override
public Map<String,String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers= new HashMap<>();
headers.put("Authorization",finalToken);
return headers;
}
};
requestQueue.add(sr);
}
}
在我的片段中,我想将我的字符串finalToken发送到类中以设置为标题:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
SharedPreferences sp=this.getActivity().getSharedPreferences("domainname", Context.MODE_PRIVATE);
String domain = sp.getString("domainname", "");
SharedPreferences sp1=this.getActivity().getSharedPreferences("FINALTOKEN", Context.MODE_PRIVATE);
String finalToken = sp1.getString("FINALTOKEN","");
VolleyGetHeaders.getInstance(getActivity());
VolleyGetHeaders.getInstance().VolleyGETHeaders(domain, api, new CustomListener<String>(){
@Override
public void getResult(String result){
if (!result.isEmpty())
{
Log.e("customer info", result);
System.out.println("customer info----------->" + result);
}
}
});
return inflater.inflate(R.layout.my_account, container, false);
我的问题是如何将finalToken传递给我的非活动类,因为你可以看到我已经做了最终的共享偏好但我不知道如何在我的非活动类中检索它。
答案 0 :(得分:0)
1)声明一个变量(finalToken)非活动类:VolleyGetHeaders
public class VolleyGetHeaders {
private static final String TAG = "VolleyGet";
private static VolleyGetHeaders instance = null;
public RequestQueue requestQueue;
String finalToken;
private VolleyGetHeaders(Context context,String finalToken)
{
this.context=context;
this.finalToken=finalToken;
requestQueue = Volley.newRequestQueue(context.getApplicationContext());
return;
}
2)在您的片段中,当您调用getInstance
时,也会发送最终令牌例如。
VolleyGetHeaders.getInstance(getActivity(),finalToken);