我正在尝试实现一项功能,即,如果网络连接打开,则应用程序将进入api。我在父级活动中添加了网络连接代码,并从其片段中调用了一个方法,但出现空对象引用错误。我正在添加代码。请检查。
父活动代码以从片段调用函数:
private void showSnack(boolean isConnected) {
String message;
int color;
if (isConnected) {
**FinalizePreOrderFragment finalizePreOrderFragment = new FinalizePreOrderFragment(this);
finalizePreOrderFragment.finalizePreOrderApi();**
}
用于调用Api的片段代码
public void finalizePreOrderApi() {
// pBar.setVisibility(View.VISIBLE);
String tag_json_obj = "json_obj_req";
String url = Constants.Pre_Order;
HashMap<String, String> params = new HashMap<String, String>();
final SessionManager sessionManager = new SessionManager(getActivity());
HashMap<String, String> loggedDetails = sessionManager.getLoggedUserDetails();
params.put("api_token", loggedDetails.get("api_token"));
params.put("user_id", loggedDetails.get("id"));
params.put("shops_order_list", lis);
Log.e("TAG", "preOrderApi: " + params);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, new JSONObject(params),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.e("pre_order_response", response.toString());
try {
if (response.has("error")) {
Toast.makeText(getActivity(), response.getString("error"), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), response.getString("success"), Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
Activity activity = getActivity();
if (activity != null && isAdded()) {
Toast.makeText(activity, R.string.some_error_occured, Toast.LENGTH_LONG).show();
}
}
// pBar.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: " + error.getMessage());
Activity activity = getActivity();
if (activity != null && isAdded()) {
Toast.makeText(activity, R.string.some_error_occured, Toast.LENGTH_LONG).show();
pBar.setVisibility(View.GONE);
}
}
});
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
我在以下几点使用了 SharedPreference :
final SessionManager sessionManager = new SessionManager(getActivity());
HashMap<String, String> loggedDetails = sessionManager.getLoggedUserDetails();
我将自己的首选项保存在会话管理器类中。并在以下几点出现错误:
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
答案 0 :(得分:1)
您可以在getLoggedUserDetails()
方法中添加它。
SharedPreferences prefs = getSharedPreferences(YOUR_PREFRENCE_KEY, MODE_PRIVATE);
//Lets say you have stored user_id in object retrieve it
int mUserId = prefs.getInt("user_id", 0);//default is 0
if (mUserId >0)
//Return your Object
else
//User is not logged in or stored in Prefrences