Siddharth Mishra Siddharth Mishra - 1 year ago 62
Android Question

Not Getting Activity's context in fragment

I am working on an ecom app wich includes the cart management. Now i have a fragment(CartFragment) and an adapter(ShowCartAdapter)attached to recyclerView.

I have made three network calls in a single fragment(i.e 1. add item to cart,2. show item in cart,3. delete item from cart).

The above fragment is attached to an activity(ProductDetailActivity).Adding item to cart and show item in cart is working perfect but the third one i.e remove item from cart is troubling me.I have an icon in my

cardview
to remove an item,on click of which i want to delete that item from
recyclerview
,now i am sending an unique id of item from adapter to fragment but it is giving me null pointer on
ProgressDialog(progressDialog=new ProgressDialog(getActivity());)
when i click on that icon.Might be the activity is no more attached to that fragment. Below is my code snippet for adapter,fragment and activity.Please help me !!!

CartFragment

public class CartFragment extends Fragment implements RetrofitTaskListener<AddCart> {

private ProgressDialog progressDialog;
private RecyclerView recyclerView;
private AdapterAddCart adapter;
private AdapterShowCart adapterShowCart;
private boolean loading = true;
AddCart addCartList;
int pageIndex;
private LinearLayoutManager linearLayoutManager;
private String email1,articlCode,image,quantity,cost;
private static final String STARTING_TEXT = "Four Buttons Bottom Navigation";
private Button btnCheckout;
private FragmentTransaction fragmentTransaction;
private int frag,cartSize;
private TextView cartEmptyTxt;
private Context context;
private SharedPreferences sharedPreference;
private SharedPreferences.Editor editor;
private SessionManager session;
private EditText cmntTxt;


public CartFragment() {
// Required empty public constructor
}

public static CartFragment newInstance(int text) {
Bundle args = new Bundle();
args.putInt(STARTING_TEXT, text);

CartFragment sampleFragment = new CartFragment();
sampleFragment.setArguments(args);
return sampleFragment;
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
articlCode = getArguments().getString("artCode");
image = getArguments().getString("image");
quantity = getArguments().getString("quantity");
cost = getArguments().getString("cost");
frag = getArguments().getInt("fragment");

View view = inflater.inflate(R.layout.fragment_cart, container, false);
cmntTxt = (EditText)view.findViewById(R.id.comment_txt);
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

session = new SessionManager(getActivity().getApplicationContext());

sharedPreference = getActivity().getSharedPreferences("CART",0);
editor = sharedPreference.edit();

((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Cart");

btnCheckout = (Button)view.findViewById(R.id.btnCheckout);

cartEmptyTxt = (TextView)view.findViewById(R.id.emptytxt);
cartEmptyTxt.setVisibility(View.GONE);

if (!session.isLoggedIn()) {
cartEmptyTxt.setVisibility(View.VISIBLE);
btnCheckout.setVisibility(View.GONE);
cmntTxt.setVisibility(View.GONE);

}

btnCheckout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FragmentManager fm = getFragmentManager();
fragmentTransaction = fm.beginTransaction();
AddressFragment addressFragment = new AddressFragment();
fragmentTransaction.replace(R.id.fragmentContainer,addressFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit(); }
});
pageIndex = 0;
recyclerView = (RecyclerView)view.findViewById(R.id.cart_recycler_view);
linearLayoutManager=new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(linearLayoutManager);
SQLiteHandler sqLiteHandler = new SQLiteHandler(getActivity());
List<SessionModel> sessionModelList = sqLiteHandler.getUserDetails();
Bundle arguments = getArguments();
if (arguments != null) {
for (SessionModel sm : sessionModelList){
email1 = sm.getEmail();
}

if (frag == 6){
callCartService(email1,articlCode,cost,quantity);
}else if (email1!=null){
callGetCart(email1);
}
}

return view;
}
public void callCartService(String email,String artCode,String price,String qty){
showProgreass();
pageIndex = pageIndex + 1;
String url = String.format(ServerConfigStage.ADD_CART(),email,artCode,price,qty);
RetrofitTask task = new RetrofitTask<>(CartFragment.this, CommonUtility.HTTP_REQUEST_TYPE.POST, CommonUtility.CallerFunction.ADD_CART_FUNCTION, url,getActivity());
task.execute();
}

public void callGetCart(String email){
showProgreass();
pageIndex = pageIndex + 1;
String url = String.format(ServerConfigStage.GET_CART(),email);
RetrofitTask task = new RetrofitTask<>(CartFragment.this, CommonUtility.HTTP_REQUEST_TYPE.POST, CommonUtility.CallerFunction.GET_CART, url,getActivity());
task.execute();
}

public void delItemCart(String email,String itemId){
adapterShowCart = new AdapterShowCart(getContext(),CartFragment.this);
showProgreass();
String url = String.format(ServerConfigStage.DEL_ITEM_CART(),email,itemId);
RetrofitTask task = new RetrofitTask<>(CartFragment.this, CommonUtility.HTTP_REQUEST_TYPE.POST, CommonUtility.CallerFunction.DEL_ITEM_CART, url,getActivity());
task.execute();
}
public void showProgreass(){
progressDialog=new ProgressDialog(getActivity());
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Please Wait...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
progressDialog.show();
}
public void stopProgress(){
if(progressDialog!=null && progressDialog.isShowing())
progressDialog.cancel();
}

@Override
public void onRetrofitTaskComplete(Response<AddCart> response, Context context, CommonUtility.CallerFunction _callerFunction) {
stopProgress();
if (response.isSuccess()) {
if (response.body() != null) {
addCartList =response.body();

if (_callerFunction == CommonUtility.CallerFunction.ADD_CART_FUNCTION){
if (addCartList.getStatus() == 0){
cartSize = addCartList.getDeatils().size();
editor.putInt("CART_ITEMS",cartSize);
editor.commit();
Toast.makeText(context, addCartList.getResponse(), Toast.LENGTH_SHORT).show();
if (adapter == null) {
adapter = new AdapterAddCart(context, R.layout.row_cart, addCartList);
recyclerView.setAdapter(adapter);
}
}else
if(addCartList.getStatus()>0) {
cartSize = addCartList.getDeatils().size();
editor.putInt("CART_ITEMS",cartSize);
editor.commit();
if (adapter == null) {
adapter = new AdapterAddCart(context, R.layout.row_cart, addCartList);
recyclerView.setAdapter(adapter);

}

adapter.notifyDataSetChanged();
}else {cartSize = addCartList.getDeatils().size();
editor.putInt("CART_ITEMS",cartSize);
editor.commit();
if (adapter == null) {
adapter = new AdapterAddCart(context, R.layout.row_cart, addCartList);

recyclerView.setAdapter( adapter );;

}

adapter.notifyDataSetChanged();


Toast.makeText(context, addCartList.getResponse(), Toast.LENGTH_SHORT).show();

}
}else if (_callerFunction == CommonUtility.CallerFunction.GET_CART){
if (addCartList.getStatus() == 0){
if (addCartList.getCart().size()>0){
cartSize = addCartList.getCart().size();
editor.putInt("CART_ITEMS",cartSize);
editor.commit();
}
}else
if(addCartList.getStatus()>0) {
if (addCartList.getCart().size()>0){
cartSize = addCartList.getCart().size();
editor.putInt("CART_ITEMS",cartSize);
editor.commit();}
if (adapterShowCart == null) {
adapterShowCart = new AdapterShowCart(context, R.layout.row_cart, addCartList);

recyclerView.setAdapter(adapterShowCart);
;

}
adapterShowCart.notifyDataSetChanged();
}else {
cartEmptyTxt.setVisibility(View.VISIBLE);
}

//Toast.makeText(context, addCartList.getResponse(), Toast.LENGTH_SHORT).show();
}else if (_callerFunction == CommonUtility.CallerFunction.DEL_ITEM_CART){
if (addCartList.getStatus()>0){
if (adapterShowCart == null) {
adapterShowCart = new AdapterShowCart(context, R.layout.row_cart, addCartList);
recyclerView.setAdapter(adapterShowCart);

}adapterShowCart.notifyDataSetChanged();

}
}
}

}

}

@Override
public void onRetrofitTaskFailure(Throwable t) {
stopProgress();
// Toast.makeText(getActivity(),"Fail to load Data",Toast.LENGTH_LONG).show();

if (getActivity()!= null)
{
getActivity().finish();
}
}

public void myFragmentMethod(){
// make sure to double check casts (to YourActivity) like these before invoking
((ProductDetailActivity)getActivity()).myOnResume();
}


}


AdapterShowCart

public class AdapterShowCart extends RecyclerView.Adapter<AdapterShowCart.ViewHolder>{
private AddCart addCartList;
private RemoveItemCommunication removeItemCommunication;
private CartFragment cartFragment = new CartFragment();


Context context;
private int layoutResourceId,cart;
private SharedPreferences sharedPreferences;

public AdapterShowCart(Context context, int layoutResourceId, AddCart addCarts) {
this.context = context;
this.layoutResourceId = layoutResourceId;
this.addCartList = addCarts;
}

public AdapterShowCart(Context context, CartFragment cartFragment) {
this.context = context;
this.cartFragment=cartFragment;
}

public void setOnClickListener(RemoveItemCommunication removeItemCommunication1){
removeItemCommunication = removeItemCommunication1;
}

@Override
public AdapterShowCart.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_cart, viewGroup, false);
return new ViewHolder(view);
}

@Override
public void onBindViewHolder(AdapterShowCart.ViewHolder viewHolder, int i) {


viewHolder.tv_android.setText("Price :"+" "+addCartList.getCart().get(i).getPrice());
viewHolder.tv_art_number.setText("Article No. :"+" "+addCartList.getCart().get(i).getItemCode());
viewHolder.tvQty.setText("Quantity :"+""+addCartList.getCart().get(i).getCartQuantity());


//viewHolder.img_android.setImageResource(products.get(i).getAndroid_image_url());
Picasso.with(context).load(addCartList.getCart().get(i).getURL()).resize(240, 120).into(viewHolder.img_android);
}

@Override
public int getItemCount() {

// cart = sharedPreferences.getInt("CART_ITEMS",0);


return addCartList.getCart().size();

}



class ViewHolder extends RecyclerView.ViewHolder{
private TextView tv_android,tv_art_number,tvQty;
private ImageView img_android,remove;
private int pos;
private CardView cardView;
public ViewHolder(View view) {
super(view);

tv_android = (TextView)view.findViewById(R.id.tvTitle);
tv_art_number=(TextView)view.findViewById(R.id.tvNumber);
cardView = (CardView)view.findViewById(R.id.card_view);
img_android = (ImageView) view.findViewById(R.id.mealImage);
tvQty=(TextView)view.findViewById(R.id.tvQty);
remove=(ImageView)view.findViewById(R.id.removeItem);
remove.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int pos = getAdapterPosition();
cartFragment.delItemCart(addCartList.getEmail(),addCartList.getCart().get(pos).getId());
}
});

cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
pos = getAdapterPosition();



}
});
}
}

}


ProductDetailActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_detail);

this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Product Details");
supportInvalidateOptionsMenu();
toolbar.setTitleTextColor(Color.WHITE);

session = new SessionManager(getApplicationContext());


itemCode = getIntent().getExtras().getString("ItemCode");
itemName = getIntent().getExtras().getString("ItemName");

stockAvailibility = (ImageView) findViewById(R.id.stock_image);
code = (TextView) findViewById(R.id.item_code);
price = (TextView) findViewById(R.id.price_txt);
name = (TextView) findViewById(R.id.product_name);
productImage = (ImageView) findViewById(R.id.image_big);
stock = (TextView) findViewById(R.id.stock);
stock_status = (TextView) findViewById(R.id.stock_text);
quantity_txt = (EditText) findViewById(R.id.unit_number);
qtyText = (TextView) findViewById(R.id.selectQty);


addCart = (Button) findViewById(R.id.btn_add_cart);



callProductDetail(itemCode);


addCart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String selectedQty = quantity_txt.getText().toString();

if (session.isLoggedIn()) {

if (!selectedQty.isEmpty() && Integer.parseInt(selectedQty) > Integer.parseInt(qty)) {
AlertDialog.Builder builder = new AlertDialog.Builder(ProductDetailActivity.this);
builder.setMessage("You can not add more than" + " " + qty + " " + "units")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
}
});
AlertDialog alert = builder.create();
alert.show();
} else if (selectedQty.isEmpty() || Integer.parseInt(selectedQty) == 0) {
AlertDialog.Builder builder = new AlertDialog.Builder(ProductDetailActivity.this);
builder.setMessage("Please Add Quantity")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
}
});
AlertDialog alert = builder.create();
alert.show();

} else if (!selectedQty.isEmpty() && Integer.parseInt(selectedQty) != 0 && Integer.parseInt(selectedQty) <= Integer.parseInt(qty)) {
addCart.setVisibility(View.GONE);
hideKeyboard(ProductDetailActivity.this);
fm = getSupportFragmentManager();

fragmentTransaction = fm.beginTransaction();
CartFragment cartFragment = new CartFragment();
fragmentTransaction.replace(R.id.fragmentContainer,cartFragment);
Bundle bundle = new Bundle();
bundle.putString("artCode", artCode);
bundle.putString("image",image_url);
bundle.putString("quantity",selectedQty);
bundle.putString("cost",cost);
bundle.putInt("fragment",6);
cartFragment.setArguments(bundle);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commitAllowingStateLoss();
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(ProductDetailActivity.this);
builder.setMessage("Please Login To Continue")
.setCancelable(false)
.setNegativeButton("NOT NOW", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {

}
})
.setPositiveButton("LOGIN", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(ProductDetailActivity.this, LoginActivity.class);
intent.putExtra("fragment", 7);
startActivity(intent);
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
});



}

public void myOnResume(){
this.onResume();
addCart.setVisibility(View.VISIBLE);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

switch (item.getItemId()) {

case android.R.id.home:
// todo: goto back activity from here

finish();
return true;


default:
return super.onOptionsItemSelected(item);
}
}

public void showProgreass() {
progressDialog = new ProgressDialog(ProductDetailActivity.this);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Please Wait...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
progressDialog.show();
}

public void stopProgress() {
if (progressDialog != null && progressDialog.isShowing())
progressDialog.cancel();
}

public void callProductDetail(String productId) {
showProgreass();

String url = String.format(ServerConfigStage.GET_PRODUCT_DETAIL(), productId);
RetrofitTask task = new RetrofitTask<List<ProductDetail>>(ProductDetailActivity.this, CommonUtility.HTTP_REQUEST_TYPE.GET, CommonUtility.CallerFunction.GET_PRODUCT_DETAIL, url, ProductDetailActivity.this);
task.execute();


}

@Override
public void onRetrofitTaskComplete(Response<List<ProductDetail>> response, Context context, CommonUtility.CallerFunction _callerFunction) {
stopProgress();
if (response.isSuccess()) {
if (response.body() != null) {
if (response.body().get(0).getStatus() > 0) {

String json = gson.toJson(response);
System.out.println(json);

artCode = response.body().get(0).getItemcode();
cost = response.body().get(0).getPrice();
String desc = response.body().get(0).getDescription();
image_url = response.body().get(0).getURL();
Double d = response.body().get(0).getStock();
Double aDouble = new Double(d);
int i = aDouble.intValue();
qty = String.valueOf(i);

if (qty.equals("0")) {
stock_status.setText("Not In Stock");
stockAvailibility.setImageResource(R.mipmap.stockunavailable);
quantity_txt.setVisibility(View.GONE);
qtyText.setVisibility(View.GONE);
addCart.setVisibility(View.GONE);


} else {
stockAvailibility.setImageResource(R.mipmap.stock_image);
}
code.setText(artCode);
price.setText("Euro" + "" + cost);
productDescription = (ExpandableTextView) findViewById(R.id.expand_text_view);
productDescription.setText(desc);
name.setText(itemName);
stock.setText("Units :" + " " + qty);
Picasso.with(context).load(image_url).resize(240, 120).into(productImage);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(response.body().get(0).getResponse())
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
}
});
AlertDialog alert = builder.create();
alert.show();

//Toast.makeText(context, response.body().get(0).getResponse(), Toast.LENGTH_SHORT).show();

}
}

}
}

@Override
public void onRetrofitTaskFailure(Throwable t) {
stopProgress();
//Toast.makeText(ProductDetailActivity.this,"Fail to load Data",Toast.LENGTH_LONG).show();

finish();
}

public static void hideKeyboard(Context ctx) {
InputMethodManager inputManager = (InputMethodManager) ctx
.getSystemService(Context.INPUT_METHOD_SERVICE);

// check if no view has focus:
View v = ((Activity) ctx).getCurrentFocus();
if (v == null)
return;

inputManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
}


}


StackTrace

Process: com.jbm.jbmcustomer, PID: 9188
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:222)
at android.app.AlertDialog.<init>(AlertDialog.java:200)
at android.app.AlertDialog.<init>(AlertDialog.java:196)
at android.app.AlertDialog.<init>(AlertDialog.java:141)
at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
at com.jbm.jbmcustomer.fragment.CartFragment.showProgreass(CartFragment.java:179)
at com.jbm.jbmcustomer.fragment.CartFragment.delItemCart(CartFragment.java:172)
at com.jbm.jbmcustomer.adapter.AdapterShowCart$1.onClick(AdapterShowCart.java:80)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Answer Source

In AdapterShowCart line 80 you are triggering an action, which tries to get a value from resources using a reference to a Context which doesn't exist anymore.

Presumably, ProductDetailActivity.this causes the issues.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download