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)
The reason for getActivity returning null is, you are using an instance of cart fragment which was initialized inside the adapter class which was not attached to any activity.
So please pass an instance of CartFragment from CartFragment to the adapter class to resolve the issue. There is a constructor in AdapterShowCart class in which the cart fragment instance is passed but it is called inside delItemCart(String email,String itemId) in fragment (I didn't understand why its done like that).
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.
Related
I am working on android app with java. and now I have to do messaging activities. I use RecyclerView to display the messages items. Also my messages Api is work with pagining, every time I send the last id and the server return the previous 10 messages.(Page size is 10). For filling the RecyclerView I use an Adapter but my problem is, that the item is added multiple times into the RecyclerView.
I will put my activity code and the adapter code
My Activity:
public class ConversationsActivity extends RootActivity implements ConversationsAdapter.ConversationOnClickHandler {
RetrofitBuilder rB = new RetrofitBuilder();
IApi service = rB.retrofit.create(IApi.class);
String authorization;
RecyclerView rv;
ConversationsAdapter adapter;
ProgressBar progressBar;
LinearLayoutManager layoutManager;
//declare it as global var for future cancel refresh
private SwipeRefreshLayout swipeLayout;
boolean wasSwiped;
// initialise loading state
boolean mIsLoading, mIsLastPage = false;
// amount of items you want to load per page
final int pageSize = 10;
int mCurrentPage =0;
int lastId;
boolean f;
int p =1;
private AlphaAnimation buttonClick = new AlphaAnimation(1F, 0.7F);
int chatId, to;
String senderType, name, to_type;
TextView no_data;
Button btnActionBar11, send;
TextView tvActionBar;
EditText message;
Context context;
ArrayList<Conversation.Data> conversationArrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_conversations);
context = this;
adapter = new ConversationsAdapter(this,context);
Intent intent = getIntent();
chatId = intent.getIntExtra("chatId",0);
Intent intent1 = getIntent();
senderType = intent1.getStringExtra("senderType");
Intent intent2 = getIntent();
name = intent2.getStringExtra("name");
Intent intent3 = getIntent();
to = intent3.getIntExtra("from",0);
Intent intent4 = getIntent();
to_type = intent4.getStringExtra("from_type");
buttonClick.setDuration(500);
authorization = checkAuthorization();
setContentView(R.layout.activity_conversations);
progressBar = (ProgressBar) findViewById(R.id.progress);
tvActionBar = (TextView) findViewById(R.id.tvActionBar);
tvActionBar.setText(name);
layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
layoutManager.setReverseLayout(true);
adapter.setHasStableIds(true);
// layoutManager.setStackFromEnd(true);
rv = (RecyclerView) findViewById(R.id.ConversationList);
no_data = (TextView) findViewById(R.id.no_data);
message = (EditText) findViewById(R.id.message);
send = (Button) findViewById(R.id.send);
rv.setLayoutManager(layoutManager);
btnActionBar11 = (Button) findViewById(R.id.btnActionBar11);
btnActionBar11.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), ChatActivity.class);
startActivity(intent);
}
});
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(message.getText().length() > 0){
sendMessage();
}
}
});
getConversation();
rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
// number of visible items
int visibleItemCount = ((LinearLayoutManager)recyclerView.getLayoutManager()).getChildCount();
// number of items in layout
int totalItemCount = ((LinearLayoutManager)recyclerView.getLayoutManager()).getItemCount();
// the position of first visible item
int firstVisibleItemPosition = ((LinearLayoutManager)recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
boolean isNotLoadingAndNotLastPage = !mIsLoading && !mIsLastPage;
// flag if number of visible items is at the last
boolean isAtLastItem = firstVisibleItemPosition + visibleItemCount >= totalItemCount;
// validate non negative values
boolean isValidFirstItem = firstVisibleItemPosition >= 0;
// validate total items are more than possible visible items
boolean totalIsMoreThanVisible = totalItemCount >= pageSize;
// flag to know whether to load more
boolean shouldLoadMore = isValidFirstItem && isAtLastItem && totalIsMoreThanVisible && isNotLoadingAndNotLastPage;
if (shouldLoadMore) loadMoreItems(false);
}
});
Intent intent11 = getIntent();
wasSwiped = intent11.getBooleanExtra("wasSwiped",false);
//where you initialize your views:
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
wasSwiped = true;
//your method to refresh content
Intent intent = new Intent(getApplicationContext(), ConversationsActivity.class)
.putExtra("chatId", chatId)
.putExtra("senderType", senderType)
.putExtra("name",name)
.putExtra("from", to)
.putExtra("from_type", to_type)
.putExtra("wasSwiped", wasSwiped);
startActivity(intent);
}
});
if(wasSwiped){
//don't forget to cancel refresh when work is done
if(swipeLayout.isRefreshing()) {
swipeLayout.setRefreshing(false);
}
}
}
#Override
public void onClickConversation(Conversation.Data conversation) {
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(getApplicationContext(), ChatActivity.class);
startActivity(intent);
}
public void sendMessage(){
Call<Message> call = service.sendMessage(authorization, to, to_type, message.getText().toString());
call.enqueue(new Callback<Message>() {
#Override
public void onResponse(Call<Message> call, Response<Message> response) {
if(response.isSuccessful()){
if(response.body()!= null)
if(response.body().getData() != null);
message.setText("");
getConversation();
//
// adapter.notifyDataSetChanged();
} else {
if(response.body()!= null)
if(response.body().getMessage() != null)
Toast.makeText(getApplicationContext(),"error: " + response.body().getMessage(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<Message> call, Throwable t) {
Toast.makeText(getApplicationContext(),"error: " + t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
public void getConversation(){
Call<Conversation> call = service.getConversation(authorization,chatId,"LANDLORD");
call.enqueue(new Callback<Conversation>() {
#Override
public void onResponse(Call<Conversation> call, Response<Conversation> response) {
if(conversationArrayList != null)
if(!conversationArrayList.isEmpty())
conversationArrayList.clear();
if(response.isSuccessful()){
if(response.body()!= null)
if(response.body().getData() != null)
if(response.body().getData().size() > 0){
if (!conversationArrayList.isEmpty())
conversationArrayList.clear(); //The list for update recycle view
adapter.notifyDataSetChanged();
for(int i =0; i < response.body().getData().size(); i++){
conversationArrayList.add(response.body().getData().get(i));
if( i == ( response.body().getData().size() -1 ))
lastId = conversationArrayList.get(conversationArrayList.size() - 1).getId();
}
progressBar.setVisibility(View.GONE);
if (conversationArrayList.isEmpty()) {
rv.setVisibility(View.GONE);
no_data.setVisibility(View.VISIBLE);
}
else {
rv.setVisibility(View.VISIBLE);
no_data.setVisibility(View.GONE);
progressBar.setVisibility(View.GONE);
configureRecyclerView(conversationArrayList);
}
} else {
progressBar.setVisibility(View.GONE);
no_data.setVisibility(View.VISIBLE);
rv.setVisibility(View.GONE);
}
} else {
Toast.makeText(getApplicationContext(),"error: " + response.body().getMessage(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<Conversation> call, Throwable t) {
Toast.makeText(getApplicationContext(),"error: " + t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
private void configureRecyclerView(ArrayList chat) {
rv = (RecyclerView) findViewById(R.id.ConversationList);
rv.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
rv.setLayoutManager(linearLayoutManager);
adapter = new ConversationsAdapter(this,context);
adapter.setConversationData(chat);
adapter.notifyDataSetChanged();
rv.setAdapter(adapter);
}
private void loadMoreItems(boolean isFirstPage) {
mIsLoading = true;
f = isFirstPage;
p = p +1;
Call<Conversation> call = service.getConversationPagenation(authorization,chatId,senderType, lastId);
call.enqueue(new Callback<Conversation>() {
#Override
public void onResponse(Call<Conversation> call, Response<Conversation> response) {
if(response.isSuccessful()){
if(response.body() != null)
if(response.body().getData()!= null) {
// conversationArrayList.clear();
for(int i =0; i < response.body().getData().size(); i++){
conversationArrayList.add(response.body().getData().get(i));
if( i == ( response.body().getData().size() -1 ))
lastId = conversationArrayList.get(conversationArrayList.size() - 1).getId();
}
progressBar.setVisibility(View.GONE);
if(conversationArrayList == null){
rv.setVisibility(View.GONE);
no_data.setVisibility(View.VISIBLE);
return;
}
else if (!f) {
if (!conversationArrayList.isEmpty())
adapter.notifyDataSetChanged();
adapter.addAll(conversationArrayList);
// conversationArrayList.clear(); //The list for update recycle view
}
else {
rv.setVisibility(View.VISIBLE);
no_data.setVisibility(View.GONE);
configureRecyclerView(conversationArrayList);
}
if(conversationArrayList.size() > 0)
lastId = conversationArrayList.get(conversationArrayList.size() - 1).getId();
mIsLoading = false;
mIsLastPage = mCurrentPage == lastId;
mCurrentPage = lastId;
}
}
}
#Override
public void onFailure(Call<Conversation> call, Throwable t) {
Log.e("SomeActivity", t.getMessage());
}
});
}
public String checkAuthorization(){
SharedPreferences settings = getSharedPreferences("log",0);
return settings.getString("Authorization", null);
}
}
My Adapter:
public class ConversationsAdapter extends
RecyclerView.Adapter<ConversationsAdapter.ConversationsAdapterViewHolder> {
private Context context;
private ArrayList<Conversation.Data> mConversation;
private ConversationsAdapter.ConversationOnClickHandler mConversationOnClickHandler;
private static SharedPreferences pref;
public ConversationsAdapter(ConversationsAdapter.ConversationOnClickHandler conversationOnClickHandler, Context _context) {
mConversationOnClickHandler = conversationOnClickHandler;
pref = _context.getSharedPreferences("log", Context.MODE_PRIVATE);
}
public void setConversationData(ArrayList<Conversation.Data> conversation) {
mConversation = conversation;
notifyDataSetChanged();
}
public void addAll(ArrayList<Conversation.Data> newList) {
int lastIndex = mConversation.size() - 1;
mConversation.addAll(newList);
notifyItemRangeInserted(lastIndex, newList.size());
}
#Override
public ConversationsAdapter.ConversationsAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View contactView = inflater.inflate(R.layout.row_msg, parent, false);
// Return a new holder instance
ConversationsAdapter.ConversationsAdapterViewHolder viewHolder = new ConversationsAdapter.ConversationsAdapterViewHolder(contactView);
return viewHolder;
}
#Override
public void onBindViewHolder(ConversationsAdapter.ConversationsAdapterViewHolder viewHolder, int position) {
Conversation.Data conversation = mConversation.get(position);
TextView tv1 = viewHolder.tv1;
TextView tv2 = viewHolder.tv2;
// SharedPreferences preferences = context.getSharedPreferences("log", Context.MODE_PRIVATE);
String agentId = pref.getString("agentId", "");
String from_type = conversation.getFromType();
int from = conversation.getFrom();
if((agentId.equals(String.valueOf(from))) && from_type.equals("AGENT")){
tv2.setVisibility(View.GONE);
tv1.setVisibility(View.VISIBLE);
tv1.setText(conversation.getBody());
}
else {
tv2.setVisibility(View.VISIBLE);
tv1.setVisibility(View.GONE);
tv2.setText(conversation.getBody());
}
}
// Returns the total count of items in the list
#Override
public int getItemCount() {
if(mConversation == null) {
return 0;
}
return mConversation.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public void setHasStableIds(boolean hasStableIds) {
super.setHasStableIds(hasStableIds);
}
public class ConversationsAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public final TextView tv1;
public final TextView tv2;
public ConversationsAdapterViewHolder(View view) {
super(view);
tv1 = (TextView) view.findViewById(R.id.tvMsgR);
tv2 = (TextView) view.findViewById(R.id.tvMsgL);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int position = getAdapterPosition();
Conversation.Data selectedNotifiction = mConversation.get(position);
mConversationOnClickHandler.onClickConversation(selectedNotifiction);
}
}
public interface ConversationOnClickHandler {
void onClickConversation(Conversation.Data conversation);
}
public long myTimeInMillis(String givenDateString ){
// String givenDateString = "Tue Apr 23 16:08:28 GMT+05:30 2013";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long timeInMilliseconds = 0;
try {
Date mDate = sdf.parse(givenDateString);
timeInMilliseconds = mDate.getTime();
// System.out.println("Date in milli :: " + timeInMilliseconds);
} catch (ParseException e) {
e.printStackTrace();
}
return timeInMilliseconds;
}
}
any help or advice?
And thankyou
in your addAll() function on ConversationsAdapter class
int lastIndex = mConversation.size() - 1;
mConversation.clear();
mConversation.addAll(newList);
notifyItemRangeInserted(lastIndex, newList.size());
this should do the trick
I am displaying a userlist and I am using serachview in my actionbar to search. When I am using the searchView in activity, it works fine but when I use it for fragment, searchview doesn't work. It does not search in the listview.
Below is my code.
UserListFragment.java
public class UsersListFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
Activity activity;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private static final String TAG = "UsersListFragment";
private OnFragmentInteractionListener mListener;
private ListView listView;
private List<UserData> users;
private CustomAdapter adapter;
SharedPreferences.Editor preferenceEditor;
Timer myTimer;
View view;
ActionBar actionBar;
private static final String PREFRENCES_NAME = "setPreferences";
private ProgressDialog progressBar;
String partnerKeyValue;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment UsersListFragment.
*/
// TODO: Rename and change types and number of parameters
public static UsersListFragment newInstance(String param1, String param2) {
UsersListFragment fragment = new UsersListFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
progressBar = new ProgressDialog(getActivity());
progressBar.setCancelable(false);
progressBar.setMessage("Loading...");
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.setProgress(0);
Log.i(TAG, "UsersListFragment onCreate");
users = new ArrayList<>();
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
SharedPreferences preferenceSettings = getActivity().getSharedPreferences(PREFRENCES_NAME,Context.MODE_PRIVATE);
preferenceEditor = preferenceSettings.edit();
preferenceEditor.putString("refresh","userlistview");
preferenceEditor.commit();
FirebaseUtil uts = new FirebaseUtil(getContext());
uts.startListeningNotification(Global.getInstance().ownerId, new CallBack() {
#Override
public void onCallback(Map<String, Object> response, String Success) {
Log.i(TAG, Success);
setHasOptionsMenu(true);
String partnerKey = (String) response.get("key");
if (partnerKey != null) {
Map<String, Object> typeCheck = (Map<String, Object>) response.get("value");
String type = (String) typeCheck.get("type");
if (type.equals("chat")) {
String key1 = Global.getInstance().ownerId;
String key2 = partnerKey;
partnerKeyValue = partnerKey;
if (key2 != null) {
String currentPartner = Global.getInstance().partnerId;
if (currentPartner.length() > 0) {
if (currentPartner.equals(partnerKey)) {
} else {
Global.getInstance().unreadMessageUsers.add(partnerKey);
}
Global.getInstance().unreadMessageUsers.add(partnerKey);
} else {
}
}
}
}
}
});
}
#Override
public void onStart() {
super.onStart();
Log.i(TAG, "UsersListFragment onStart");
}
#Override
public void onResume() {
super.onResume();
Log.i(TAG, "UsersListFragment onResume");
}
#Override
public void onPause() {
super.onPause();
Log.i(TAG, "UsersListFragment onStart");
}
#Override
public void onStop() {
super.onStop();
Log.i(TAG, "UsersListFragment onStop");
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
#Override
public void onDestroy() {
super.onDestroy();
FirebaseUtil util = new FirebaseUtil(getContext());
util.updateUserStatus(Global.getInstance().ownerId, "4");
Log.i(TAG, "UsersListFragment onDestroy");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if(actionBar!=null) {
actionBar.setDisplayUseLogoEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setLogo(R.drawable.ic_logo);
ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#006EAD"));
actionBar.setBackgroundDrawable(colorDrawable);
}
Toast.makeText(getActivity(), String.valueOf( Global.getInstance().unreadMessageUsers.size()) , Toast.LENGTH_SHORT).show();
int vd = users.size();
view = inflater.inflate(R.layout.fragment_userslist, container, false);
listView = (ListView) view.findViewById(R.id.userdisplay);
adapter = new CustomAdapter(getActivity(),R.layout.program_list, users );
listView.setAdapter(adapter);
if (users.size()==0){
usersList();
}else {
adapter.notifyDataSetChanged();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
UserData data = users.get(position);
Global.getInstance().someData = data.getId();
Global.getInstance().partnerId = data.getId();
int i = 0;
for (Iterator<String> iter = Global.getInstance().unreadMessageUsers.iterator(); iter.hasNext(); ) {
String element = iter.next();
if (element.equals(data.getId().toString())) {
iter.remove();
}
}
data.setUnreadMessageCount(0);
users.remove(position);
users.add(position, data);
Toast.makeText(getActivity().getApplicationContext(),String.valueOf(Global.getInstance().unreadMessageUsers.size()),Toast.LENGTH_LONG).show();
Fragment fragmentOne = new ChatFragment();
android.support.v4.app.FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
Bundle args = new Bundle();
args.putString(ChatFragment.DATA_RECEIVE, data.getName());
fragmentOne .setArguments(args);
ft.addToBackStack(null);
ft.replace(R.id.framecontainerMain, fragmentOne).commit();
}
});
// Inflate the layout for this fragment
return view;
}
public void usersList () {
SharedPreferences preferenceSettings = getActivity().getSharedPreferences(PREFRENCES_NAME,Context.MODE_PRIVATE);
preferenceEditor = preferenceSettings.edit();
//get the data from userlist api
final String URL = "url";
String token = preferenceSettings.getString("authToken","");
final String userId = preferenceSettings.getString("userId","");
HashMap<String, String> params = new HashMap<String, String>();
params.put("user_id",userId);
params.put("auth_token",token);
progressBar.show();
JsonObjectRequest myRequest = new JsonObjectRequest(Request.Method.POST, URL,new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, "onResponse:" +response);
String success = null;
try {
success = response.getString("success");
} catch (JSONException e) {
e.printStackTrace();
}
if(success == "true") {
JSONArray Array = null;
try {
//get the users
} else {
users.add(data);
}
}
Log.i(TAG, "arraylist");
adapter.notifyDataSetChanged();
onlineUsers();
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
TimerMethod();
}
}, 0, 5000);
progressBar.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject Obj;
} else {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.dismiss();
VolleyLog.e("Error: ", error.getMessage());
Log.i(TAG, "onErrorResponse:" +error.networkResponse);
}
});
ApplicationController.getInstance().addToRequestQueue(myRequest);
myRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
public void sortingArray(){
if (users.size()>0) {
synchronized (this) {
if (Global.getInstance().unreadMessageUsers.size() > 0) {
System.out.println("\nExample 3 - Count all with Map");
Map<String, Integer> map = new HashMap<String, Integer>();
for (String temp : Global.getInstance().unreadMessageUsers) {
Integer count = map.get(temp);
map.put(temp, (count == null) ? 1 : count + 1);
}
System.out.println("\nSorted Map");
Map<String, Integer> unreadCount = new TreeMap<String, Integer>(map);
for (String key : unreadCount.keySet()) {
int count_unread = unreadCount.get(key);
int i = 0;
for (UserData obj : users) {
UserData user = obj;
if (user.getId().equals(key)) {
user.setUnreadMessageCount(count_unread);
users.remove(i);
users.add(i, user);
break;
}
i++;
}
}
}
synchronized (this) {
if (Global.getInstance().userStatus.size() > 0) {
try {
for (Object dict : Global.getInstance().userStatus) {
Map<String, Object> val = (Map<String, Object>) dict;
String key = val.keySet().iterator().next();
val.get(key).toString().trim();
int statusValue;
if (val.get(key).toString().equals("")) {
statusValue = 4;
} else {
statusValue = Integer.valueOf(val.get(key).toString());
}
int i = 0;
for (UserData obj : users) {
UserData user = obj;
if (user.getId().equals(key)) {
user.setOnlineStatus(statusValue);
users.remove(i);
users.add(i, user);
break;
}
i++;
}
}
}catch (ConcurrentModificationException e){
e.printStackTrace();
}
}
}
Log.i(TAG, users.get(0).getName());
if (users.size() > 0) {
Collections.sort(users, new Comparator<UserData>() {
#Override
public int compare(UserData o1, UserData o2) {
if (o1.getOnlineStatus() > o2.getOnlineStatus()) {
return 1;
} else if (o1.getOnlineStatus() < o2.getOnlineStatus()) {
return -1;
} else {
return 0;
}
}
});
}
if (users.size() > 0) {
Collections.sort(users, new Comparator<UserData>() {
#Override
public int compare(UserData o1, UserData o2) {
if (o1.getUnreadMessageCount() > o2.getUnreadMessageCount()) {
return -1;
} else if (o1.getUnreadMessageCount() < o2.getUnreadMessageCount()) {
return 1;
} else {
return 0;
}
}
});
Global.getInstance().userStatus.clear();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(), "any mesage", Toast.LENGTH_LONG).show();
adapter.notifyDataSetChanged();
}
});
}
}
}
}
public void TimerMethod() {
synchronized(this) {
SharedPreferences preferenceSettings = getActivity().getSharedPreferences("setPreferences", Context.MODE_PRIVATE);
String checkView = preferenceSettings.getString("refresh", "");
if (checkView.equals("userlistview")) {
if (Global.getInstance().userStatus.size() > 0) {
sortingArray();
}
} else {
preferenceEditor = preferenceSettings.edit();
preferenceEditor.putString("refresh", "userlistview");
preferenceEditor.commit();
if (Global.getInstance().unreadMessageUsers.size() > 0){
sortingArray();
}
}
}
}
public void onlineUsers (){
String value;
for (UserData data : users) {
value = data.getId();
FirebaseUtil online = new FirebaseUtil(getContext());
online.onlineUsers(value, new CallBack() {
#Override
public void onCallback(Map<String, Object> response, String Success) {
if (response == null) {
} else {
Global.getInstance().userStatus.add(response);
}
}
});
}
}
#Override
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
inflater.inflate(R.menu.menu_userlist,menu);
MenuItem item = menu.findItem(R.id.menuSearch);
SearchView searchView = (SearchView)item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
super.onCreateOptionsMenu(menu,inflater);
}
private void logoutUser(){
Intent I = new Intent(getActivity(), LoginActivity.class);
startActivity(I);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuSearch :
return true;
case R.id.menuLogout :
logoutUser();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
String val = "'";
mListener.onFragmentInteraction(val);
}
}
public void initlizeval(Context context) {
mListener = (OnFragmentInteractionListener) context;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
myTimer.cancel();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(String val);
}
}
menu_userlist.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/menuSearch"
android:title="#string/search"
android:icon="#drawable/ic_search"
app:actionViewClass="android.widget.SearchView"
app:showAsAction="always">
</item>
<item android:id="#+id/menuLogout"
android:title="#string/logout"
android:icon="#drawable/ic_logout"
android:tint="#android:color/white"
app:showAsAction="always">
</item>
</menu>
CustomAdapter.java
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class CustomAdapter extends ArrayAdapter<UserData> {
private Activity activity;
private List<UserData> messages;
public CustomAdapter(Activity context, int resource, List<UserData> objects) {
super(context, resource, objects);
this.activity = context;
this.messages = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
packagename.CustomAdapter.ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
int layoutResource = 0; // determined by view type
UserData data = getItem(position);
int viewType = getItemViewType(position);
layoutResource = R.layout.program_list;
if (convertView != null) {
holder = (com.your.package.CustomAdapter.ViewHolder) convertView.getTag();
} else {
convertView = inflater.inflate(layoutResource, parent, false);
holder = new com.your.package.CustomAdapter.ViewHolder(convertView);
convertView.setTag(holder);
}
//set message content
holder.msg.setText(data.getName());
holder.id = data.geId();
holder.roleMsg.setText(data.getRole());
return convertView;
}
#Override
public int getViewTypeCount() {
// return the total number of view types. this value should never change
// at runtime
return 2;
}
#Override
public int getItemViewType(int position) {
// return a value between 0 and (getViewTypeCount - 1)
return position % 2;
}
private class ViewHolder {
private TextView msg;
private String id;
private TextView roleMsg;
public ViewHolder(View v) {
msg = (TextView) v.findViewById(R.id.textView1);
roleMsg = (TextView) v.findViewById(R.id.textView2);
}
}
}
HomeActivity.java
public class HomeActivity extends AppCompatActivity implements UsersListFragment.OnFragmentInteractionListener {
private UsersListFragment mItemsFragment;
private ChatFragment mFragmentOne;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
VideoFragment fragmentTwo ;
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.VISIBLE);
LinearLayout layout2 = (LinearLayout) findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.VISIBLE);
mItemsFragment = new UsersListFragment();
mItemsFragment.initlizeval(this);
android.support.v4.app.FragmentTransaction fts = getSupportFragmentManager().beginTransaction();
fts.add(R.id.framecontainer, mItemsFragment).commit();
//Instantiate some stuff here like view components
Fragment fragmentOne = new ChatFragment();
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.framecontainerTab, fragmentOne).commit();
}else{
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.GONE);
LinearLayout layout2 = (LinearLayout) findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.GONE);
layout2.removeAllViews();
mItemsFragment = new UsersListFragment();
mItemsFragment.initlizeval(this);
setFragment(mItemsFragment);
}
}
public void setFragment(Fragment frag)
{
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
}
public void attemptLogin1() {
String test = "one";
String tested = "fail";
}
#Override
public void onFragmentInteraction(String uri) {
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.GONE);
LinearLayout layout2 = (LinearLayout)findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.GONE);
findViewById(R.id.framecontainerVideo);
Toast.makeText(getApplicationContext(), "bullet", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onBackPressed() {
super.onBackPressed();
Fragment fragmentOne = new ChatFragment();
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.VISIBLE);
LinearLayout layout2 = (LinearLayout) findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.VISIBLE);
}
#Override
protected void onStart() {
super.onStart();
getDelegate().onStart();
}
}
I have written setHasOptionsMenu(true); in onCreate of UserFragment.java
The logout functionality works fine but the search isn't working.
I have tried various options given on Stackoverflow as well as from other resource, but nothing worked. :(
Any help is appreciated.
Thanks in advance.
Create Constructor in your fragment. Pass Context object inside fragment constructor.which allows your activity as global access.
Remove this line and it will work
case R.id.menuSearch:
return true;
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm currently having trouble restoring my fragment to it's previous state after clicking into a detail activity from my recyclerview adapter. The back button within the detail activity returns me to an empty fragment with no data.
Here's the detail activity class
**
* Provides UI for the Detail page with Collapsing Toolbar.
*/
public class DetailActivity extends AppCompatActivity implements View.OnClickListener {
public static final String EXTRA_POSITION = "position";
private Boolean isFabOpen = false;
private FloatingActionButton fab,fab1,fab2;
private Animation fab_open,fab_close,rotate_forward,rotate_backward;
private CollapsingToolbarLayout collapTool;
private LinearLayout linLayout;
private boolean isFavorited;
private boolean isIgnored;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
fab = (FloatingActionButton)findViewById(R.id.fab);
fab1 = (FloatingActionButton)findViewById(R.id.fab1);
fab2 = (FloatingActionButton)findViewById(R.id.fab2);
fab_open = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fab_open);
fab_close = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.fab_close);
rotate_forward = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.rotate_forward);
rotate_backward = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.rotate_backward);
fab.setOnClickListener(this);
fab1.setOnClickListener(this);
fab2.setOnClickListener(this);
//Getting the details passed from the last activity to parse proper detail display
Intent intent = getIntent();
Bundle bd = intent.getExtras();
String titleText = (String) bd.get("titleText");
String descriptionText = (String) bd.get("description");
String locations = (String) bd.get("locations");
String assetTypes = (String) bd.get("assetTypes");
String propertyStatuses = (String) bd.get("propertyStatuses");
String buyerId = (String) bd.get("buyer_id") + "";
//Buyer ID testing if proper ID is passed through
//Toast.makeText(getApplicationContext(),buyerId,Toast.LENGTH_SHORT).show();
isFavorited = (Boolean) bd.get("favorited");
isIgnored = (Boolean) bd.get("ignored");
//If item was favorited from previous page, adjust accordingly
if(isFavorited) {
fab2.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#7E57C2")));
fab1.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#133253")));
fab.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#7E57C2")));
isFavorited = true;
isIgnored = false;
}
//If item was ignored from previous page, adjust accordingly
if(isIgnored) {
fab1.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#EF5350")));
fab2.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#133253")));
fab.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#EF5350")));
isIgnored = true;
isFavorited = false;
}
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
linLayout = (LinearLayout) findViewById(R.id.linLay);
collapTool = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
linLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isFabOpen) {
fab.startAnimation(rotate_backward);
fab1.startAnimation(fab_close);
fab2.startAnimation(fab_close);
fab1.setClickable(false);
fab2.setClickable(false);
isFabOpen = false;
}
}
});
collapTool.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isFabOpen) {
fab.startAnimation(rotate_backward);
fab1.startAnimation(fab_close);
fab2.startAnimation(fab_close);
fab1.setClickable(false);
fab2.setClickable(false);
isFabOpen = false;
}
}
});
locations = locations.replace("Locations | ", "");
assetTypes = assetTypes.replace("Asset Types | ", "");
propertyStatuses = propertyStatuses.replace("Property Statuses | ", "");
// Set Collapsing Toolbar layout to the screen
CollapsingToolbarLayout collapsingToolbar =
(CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
// Set title of Detail page
// collapsingToolbar.setTitle(getString(R.string.item_title));
assert fab2 != null;
fab2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isFavorited) {
fab2.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#7E57C2")));
fab1.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#133253")));
fab.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#7E57C2")));
//Snackbar.make(v, "Favorited...",Snackbar.LENGTH_LONG).show();
isFavorited = true;
isIgnored = false;
} else {
fab.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#133253")));
fab2.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#133253")));
/*Snackbar.make(v, "Unfavorited...",
Snackbar.LENGTH_LONG).show();
*/
isFavorited = false;
}
}
});
assert fab1 != null;
fab1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isIgnored) {
fab1.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#EF5350")));
fab2.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#133253")));
fab.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#EF5350")));
isIgnored = true;
isFavorited = false;
} else {
fab1.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#133253")));
fab.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#133253")));
/*Snackbar.make(v, "Unfavorited...",
Snackbar.LENGTH_LONG).show();
*/
isIgnored = false;
}
}
});
int postion = getIntent().getIntExtra(EXTRA_POSITION, 0);
Resources resources = getResources();
String[] places = resources.getStringArray(R.array.city_array);
collapsingToolbar.setTitle(titleText);
String[] placeDetails = resources.getStringArray(R.array.city_array);
TextView placeDetail = (TextView) findViewById(R.id.place_detail);
placeDetail.setText(descriptionText);
String[] placeLocations = resources.getStringArray(R.array.city_array);
TextView placeLocation = (TextView) findViewById(R.id.place_location);
placeLocation.setText(locations);
TextView assetDetails = (TextView) findViewById(R.id.asset_details);
assetDetails.setText(assetTypes);
TextView propertyDetails = (TextView) findViewById(R.id.status_details);
propertyDetails.setText(propertyStatuses);
/*
TextView investmentDetails = (TextView) findViewById(R.id.investment_details);
investmentDetails.setText(investmentRangeMin);
*/
/*
TypedArray placePictures = resources.obtainTypedArray(R.array.city_array);
ImageView placePicutre = (ImageView) findViewById(R.id.image);
placePicutre.setImageDrawable(placePictures.getDrawable(postion % placePictures.length()));
placePictures.recycle();
*/
}
And here is my recyclerView adapter that has an onclicklistener for the item view which creates the detail activity.
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder> {
private Activity activity;
private LayoutInflater inflater;
private static List<BuyerProfile> profileItems;
private static boolean itemFavorited;
RVAdapter(List<BuyerProfile> profiles) {
this.profileItems = profiles;
}
public static class PersonViewHolder extends RecyclerView.ViewHolder {
TextView name;
TextView description;
TextView locations;
TextView id;
TextView investmentRange;
TextView investmentRangeMax;
TextView assetTypes;
TextView propertyStatuses;
TextView profileId;
ImageView headerImage;
Button favoriteButton;
Button ignoreButton;
CardView cardView;
private ImageView spacer;
private boolean favorited = false;
private boolean ignored = false;
PersonViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.titleText);
description = (TextView) itemView.findViewById(R.id.descriptionText);
investmentRange = (TextView) itemView.findViewById(R.id.investment);
//investmentRangeMax = (TextView) itemView.findViewById(R.id.investmentRangeMax);
locations = (TextView) itemView.findViewById(R.id.locations);
id = (TextView) itemView.findViewById(R.id.profileNumber);
headerImage = (ImageView) itemView.findViewById(R.id.imgBillionaire);
assetTypes = (TextView) itemView.findViewById(R.id.assetTypes);
propertyStatuses = (TextView) itemView.findViewById(R.id.propertyStatuses);
favoriteButton = (Button) itemView.findViewById(R.id.action_button);
ignoreButton = (Button) itemView.findViewById(R.id.ignore_button);
cardView = (CardView) itemView.findViewById(R.id.cv);
profileId = (TextView) itemView.findViewById(R.id.buyer_id);
spacer = (ImageView) itemView.findViewById(R.id.spacerImage);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int i = getAdapterPosition();
Context context = v.getContext();
Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra(DetailActivity.EXTRA_POSITION, getAdapterPosition());
intent.putExtra("titleText", name.getText());
intent.putExtra("description", description.getText());
intent.putExtra("locations", locations.getText());
intent.putExtra("assetTypes", assetTypes.getText());
intent.putExtra("propertyStatuses", propertyStatuses.getText());
intent.putExtra("favorited", favorited);
intent.putExtra("ignored", ignored);
HomeFragment homeReturn = new HomeFragment();
// intent.putExtra("buyer_id", profileId.getText());
//intent.putExtra("investmentRangeMin", investmentRangeMin.getText());
context.startActivity(intent);
}
});
/*
favoriteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!favorited) {
spacer.setVisibility(View.VISIBLE);
headerImage.setBackgroundColor(Color.parseColor("#7E57C2"));
favorited = true;
ignored = false;
} else {
spacer.setVisibility(View.INVISIBLE);
favorited = false;
headerImage.setBackgroundColor(Color.parseColor("#42A5F5"));
}
}
});
*/
ignoreButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!ignored) {
spacer.setVisibility(View.VISIBLE);
headerImage.setBackgroundColor(Color.parseColor("#EF5350"));
favorited = false;
ignored = true;
} else {
ignored = false;
spacer.setVisibility(View.INVISIBLE);
headerImage.setBackgroundColor(Color.parseColor("#133253"));
}
}
});
}
}
#Override
public int getItemCount() {
return profileItems.size();
}
#Override
public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item, viewGroup, false);
PersonViewHolder pvh = new PersonViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(PersonViewHolder personViewHolder, int i) {
final PersonViewHolder selectedCard = personViewHolder;
selectedCard.name.setText(profileItems.get(i).getBuyerProfTitle());
selectedCard.description.setText(profileItems.get(i).getDescription());
selectedCard.locations.setText("Locations | " + profileItems.get(i).parseLocations());
selectedCard.assetTypes.setText("Asset Types | " + profileItems.get(i).getAssetTypes());
selectedCard.propertyStatuses.setText("Property Statuses | " + profileItems.get(i).getPropertyStatuses());
selectedCard.investmentRange.setText("Investment Range | $125,000 - $250,000");
final int position = i;
personViewHolder.ignoreButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
profileItems.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, getItemCount());
}
});
selectedCard.favoriteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!selectedCard.favorited) {
profileItems.get(position).favoriteItem();
selectedCard.spacer.setVisibility(View.VISIBLE);
selectedCard.spacer.setBackgroundColor(Color.parseColor("#FFF176"));
selectedCard.headerImage.setBackgroundColor(Color.parseColor("#7E57C2"));
selectedCard.favorited = true;
selectedCard.ignored = false;
} else {
profileItems.get(position).unfavoriteItem();
selectedCard.favorited = false;
selectedCard.headerImage.setBackgroundColor(Color.parseColor("#133253"));
}
}
});
//personViewHolder.profileId.setText(profileItems.get(i).getProfileId() + "");
//personViewHolder.investmentRangeMin.setText(profileItems.get(i).getInvestmentRangeMin());
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public long getItemId(int position) {
return position;
}
}
And finally here is my main fragment which holds the recyclerview.
public class HomeFragment extends Fragment {
private CustomListAdapter listAdapter;
//private static final String profileUrl = "http://172.16.98.152:3000/apip/buyers/profiles";
private static final String matchesUrl = "http://172.16.98.152:3000/apip/sellers/profiles/1/matches";
private String matched = "http://172.16.98.152:3000/apip/sellers/profiles/";
private ProgressDialog pDialog;
private ListView listView;
private List<BuyerProfile> buyersProfiles = new ArrayList<BuyerProfile>();
private View root;
private TextView noItems;
private TextView search;
private TextView searchSecondLine;
private LinearLayoutManager llm;
private String profileUrlString;
private String KEY_RECYCLER_STATE = "recycleSave";
private Bundle viewState;
private Bundle arguments;
private RecyclerView rv;
private int mStackLevel;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.fragment_home, container, false);
noItems = (TextView) root.findViewById(R.id.empty_view);
search = (TextView) root.findViewById(R.id.search);
searchSecondLine = (TextView) root.findViewById(R.id.matchesSecondLine);
rv = (RecyclerView) root.findViewById(R.id.rv);
rv.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
rv.setItemAnimator(new DefaultItemAnimator());
final RVAdapter recyclerAdapter = new RVAdapter(buyersProfiles);
rv.setAdapter(recyclerAdapter);
rv.setHasFixedSize(true);
RequestQueue mRequestQueue;
arguments = getArguments();
if(savedInstanceState != null) {
matched = matched + savedInstanceState.getString("profileArgs") + "/matches";
} else {
if(arguments != null && arguments.containsKey("profileId")) {
matched = matched + arguments.getString("profileId") + "/matches";
search.setText("Search: " + arguments.getString("locations") + " " + arguments.getString("assetTypes"));
searchSecondLine.setVisibility(View.VISIBLE);
searchSecondLine.setText(arguments.getString("propertyStatuses"));
} else {
matched = "http://172.16.98.152:3000/apip/sellers/profiles/1/matches";
noItems.setVisibility(View.VISIBLE);
searchSecondLine.setVisibility(View.INVISIBLE);
rv.setVisibility(View.INVISIBLE);
search.setVisibility(View.INVISIBLE);
}
}
Cache cache = new DiskBasedCache(getActivity().getCacheDir(), 1024 * 1024);
Network network = new BasicNetwork(new HurlStack());
mRequestQueue = new RequestQueue(cache, network);
mRequestQueue.start();
JsonArrayRequest profileRequest = new JsonArrayRequest(matched,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
BuyerProfile parsedProfile = new BuyerProfile();
parsedProfile.setBuyerProfTitle(obj.getString("title"));
parsedProfile.setDescription(obj.getString("description"));
parsedProfile.setLocations(obj.getString("location"));
parsedProfile.setAssetTypes(obj.getString("asset_type"));
//parsedProfile.setProfileId(obj.getString("id"));
parsedProfile.setPropertyStatuses(obj.getString("property_status"));
//parsedProfile.setProfileId(obj.getInt("buyer_profile_id"));
parsedProfile.unfavoriteItem();
buyersProfiles.add(parsedProfile);
} catch (Exception e) {
e.printStackTrace();
}
}
recyclerAdapter.notifyDataSetChanged();
// notifying list adapter about data changes
// so that it renders the list view with updated data
//hidePDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(selectBuyerProfile.this,"Error",Toast.LENGTH_LONG).show();
}
});
mRequestQueue.add(profileRequest);
/*
if(buyersProfiles.isEmpty()) {
rv.setVisibility(View.GONE);
noItems.setVisibility(View.VISIBLE);
}
*/
return root;
}
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if(arguments != null && arguments.containsKey("profileId")) {
outState.putString("profileArgs", arguments.getString("profileId"));
}
}
}
I'm not sure which of these classes I need to be restoring and how I can restore the previous details and images in HomeFragment after clicking back from the detail activity. I would be able to just describe a parent activity in my manifest but the main class holding everything is a fragment and android doesn't let you choose parent fragments! Any ideas or help would be appreciated.
Try to remove initialization of List from declaration.
private List buyersProfiles = new ArrayList();
And make initialization in onCreateView method if List is null.
I am having some trouble with my app, I am trying to develop a list app that you have the option to add new "Goals" to as well as new lists so that you can categorize goals to a list like the list object title can be "Eat healthy" and then you'll have goals inside like "Eat more vegetables", etc. So in order to do this I have set up a ViewPagerHost class that grabs all the List objects from a SQLite database and initializes a factory developed "List fragment" that handles all the logic of adding a goal, editing and deleting, etc. I believe I've gotten this to work correctly because everything on the database side seems to work fine, and then the other classes are just supposed to display and manipulate that information. But everything on the display side seems to be going wrong. I have each view in the recyclerview display a star next to any goal marked as "important" or "life changing" but it displays the star wherever it wants. Also the list does not load until I've click on something.
public class ViewPagerHost extends Activity_Logger {
private static final String ARG_TITLE = "title";
private ViewPager mViewPager;
private ArrayList<Fragment> mFragmentList;
private ArrayList<GoalList> goalList;
private ArrayList<Goal> goalArrayList;
Database_Controller controller;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_pager_host);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
MobileAds.initialize(getApplicationContext(), "ad-String");
AdView adView = (AdView) findViewById(R.id.ad);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
setSupportActionBar(toolbar);
toolbar.setTitle("Ambition");
FragmentManager fragmentManager = getSupportFragmentManager();
controller = Database_Controller.get(getApplicationContext());
goalList = controller.getAllLists();
goalArrayList = controller.getAllGoals();
mViewPager = (ViewPager)findViewById(R.id.view_fragments);
if(goalList.get(0) == null){
GoalList listOne = new GoalList();
listOne.setTitle("DEFAULT");
controller.insertList(listOne);
for(int i =0; i< goalArrayList.size(); i++){
goalArrayList.get(i).setWhich_List(listOne.getTitle());
controller.updateGoal(goalArrayList.get(i));
}
}
mFragmentList = getFragmentList(goalList);
ViewPagerAdapter adapter = new ViewPagerAdapter(fragmentManager, mFragmentList);
if(adapter == null){
}else{
mViewPager.setAdapter(adapter);
}
}
public ArrayList<Fragment> getFragmentList(ArrayList<GoalList> list){
mFragmentList = new ArrayList<>();
Bundle bundle = new Bundle();
for(int i = 0; i< list.size(); i++){
List_Fragment list_fragment = new List_Fragment();
bundle.putString(ARG_TITLE, goalList.get(i).getTitle());
list_fragment.setArguments(bundle);
mFragmentList.add(list_fragment);
}
return mFragmentList;
}
}
Here is my ViewPagerHost class that creates the factory list.
public class List_Fragment extends Fragment {
private RecyclerView mRecyclerView;
private static final String ARG_TITLE = "title";
private static final String ARG_GOALNAME ="Goal";
private static final String ARG_IMPORTANT = "Important";
private Database_Controller mDatabaseController;
private static final String ARG_ID = "ID";
ArrayList<Goal> goalList;
LinearLayoutManager manager;
public RecyclerView.Adapter adapter;
public ReceiverThread UiThread;
FragmentManager fragmentManager;
String list_title;
public List_Fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_list_, container, false);
Bundle bundle = getArguments();
if(bundle != null){
list_title= bundle.getString(ARG_TITLE);
}
mDatabaseController = mDatabaseController.get(getContext());
goalList = mDatabaseController.getAllListsGoals(list_title);
mRecyclerView = (RecyclerView)view.findViewById(R.id.recyclerview);
manager = new LinearLayoutManager(getActivity());
UiThread = new ReceiverThread();
mRecyclerView.setLayoutManager(manager);
final RecyclerView_Adapter wrapperClass = new RecyclerView_Adapter(goalList,getContext(),this);
adapter = wrapperClass.adapter;
for(int counter =0; counter < goalList.size(); counter++){
System.out.println(goalList.get(counter).getWhich_List());
}
mRecyclerView.setAdapter(adapter);
fragmentManager= getFragmentManager();
//adapter goes here
final FloatingActionButton fab = (FloatingActionButton)view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment fragment = List_Fragment.this;
AddNew_PopUp popUp = AddNew_PopUp.newInstance(fragment);
popUp.setTargetFragment(fragment, 0);
popUp.show(fragmentManager, "PopUpDialog");
}
});
return view;
}
public class ReceiverThread extends Thread {
#Override
public void run() {
super.run();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
goalList.clear();
ArrayList<Goal>newGoalList = mDatabaseController.getAllGoals();
goalList.addAll(newGoalList);
adapter.notifyDataSetChanged();
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 0){
if(resultCode == Activity.RESULT_OK){
Goal newGoal = new Goal();
String GoalName = data.getStringExtra(ARG_GOALNAME);
if (GoalName.isEmpty()) {
Toast.makeText(getContext(), R.string.NoGoal, Toast.LENGTH_SHORT).show();
} else {
newGoal.setmIsImportant(data.getBooleanExtra(ARG_IMPORTANT, false));
newGoal.setmGoalName(GoalName);
newGoal.setWhich_List(ARG_TITLE);
mDatabaseController.insertGoal(newGoal);
}
}
}else{
if(requestCode == 1){
if(resultCode == Activity.RESULT_OK){
String id = data.getStringExtra(ARG_ID);
Toast.makeText(getContext(),R.string.flush, Toast.LENGTH_LONG).show();
mDatabaseController.deleteGoal(id);
}
}else{
if(requestCode == 2){
if(resultCode == Activity.RESULT_OK){
String goalName = data.getStringExtra(ARG_GOALNAME);
Boolean isImportant = data.getBooleanExtra(ARG_IMPORTANT, false);
UUID id = UUID.fromString(data.getStringExtra(ARG_ID));
Goal goal = mDatabaseController.getGoal(id.toString());
goal.setmIsImportant(isImportant);
goal.setmGoalName(goalName);
mDatabaseController.updateGoal(goal);
}
}
}
}
UiThread.run();
}
public ReceiverThread getUiThread() {
return UiThread;
}
}
This is the list fragment that is created for every list in the database. It calls methods and manipulates data based off the user's actions.
public class RecyclerView_Adapter{
private ArrayList<Goal> mGoals;
MyAdapter adapter;
Context context;
private Database_Controller mDatabaseController;
MediaPlayer mediaPlayer;
Fragment fragment;
public RecyclerView_Adapter(ArrayList<Goal> goals, Context cntxt, Fragment fragments) {
mGoals = goals;
adapter = new MyAdapter(mGoals);
context = cntxt;
mediaPlayer = new MediaPlayer();
fragment = fragments;
mDatabaseController = Database_Controller.get(context);
}
//////////////////////////////////ADAPTER\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
private class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
private List<Goal> mGoals;
public MyAdapter(List<Goal> goals) {
mGoals = goals;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.recycler_view_item_layout, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final Goal goal = mGoals.get(position);
holder.bindGoal(goal);
}
#Override
public int getItemCount() {
return mGoals.size();
}
}
////////////////////////////////////ADAPTER\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
///////////////////////////////////VIEW HOLDER\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView mTextView, importantTXT;
private CheckBox mCheckBox;
private Goal mGoal;
private ImageView imgView;
public MyViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AppCompatActivity context = (AppCompatActivity) v.getContext();
FragmentManager manager = context.getSupportFragmentManager();
Edit_PopUp dialog = Edit_PopUp.newInstance(mGoal);
dialog.setTargetFragment(fragment, 2);
dialog.show(manager, "EditDialog");
}
});
itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
//Add delete thingy
AppCompatActivity context = (AppCompatActivity) v.getContext();
FragmentManager manager = context.getSupportFragmentManager();
MoreOptions_PopUp dialog = MoreOptions_PopUp.newInstance(mGoal);
dialog.setTargetFragment(fragment, 1);
dialog.show(manager, "GoalDialog");
return true;
}
});
mTextView = (TextView) itemView.findViewById(R.id.text);
mCheckBox = (CheckBox) itemView.findViewById(R.id.checkbox);
imgView = (ImageView) itemView.findViewById(R.id.imageView);
importantTXT = (TextView) itemView.findViewById(R.id.Important_textView);
mCheckBox.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
mGoal.setFinished(mCheckBox.isChecked());
mDatabaseController.updateGoal(mGoal);
if (mCheckBox.isChecked() == true) {
boolean value = checkWinning(mGoals,context);
PlaySound(value, mGoal.ismIsImportant(), v);
}
}
});
}
public void bindGoal(Goal goal) {
mGoal = goal;
mCheckBox.setChecked(mGoal.isFinished());
mTextView.setText(mGoal.getmGoalName());
if (mGoal.ismIsImportant()) {
imgView.setImageResource(R.mipmap.ic_stars_pressed);
importantTXT.setText(R.string.isImportant);
}
}
public boolean checkWinning(ArrayList<Goal> goals, Context context) {
for (int i = 0; i < goals.size(); i++) {
if (goals.get(i).isFinished() == false) {
return false;
}
}
return true;
}
public void PlaySound(Boolean winningSound, boolean isImportant, View view) {
if(winningSound){
mediaPlayer = MediaPlayer.create(context,R.raw.victory);
Snackbar snackbar = Snackbar.make(view, R.string.completion, Snackbar.LENGTH_LONG);
snackbar.show();
mediaPlayer.start();
}else {
if (isImportant) {
mediaPlayer = MediaPlayer.create(context, R.raw.collect);
mediaPlayer.start();
Snackbar snackbar = Snackbar.make(view, R.string.congrats, Snackbar.LENGTH_SHORT);
snackbar.show();
} else {
mediaPlayer = MediaPlayer.create(context, R.raw.success);
Snackbar snackbar = Snackbar.make(view, R.string.lessCongrats, Snackbar.LENGTH_SHORT);
snackbar.show();
mediaPlayer.start();
}
}
}
}
////////////////////////////////////VIEW HOLDER\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
public MyAdapter getAdapter() {
return adapter;
}
public Fragment getFragment() {
return fragment;
}
}
Here is my adapter class that plays sounds OnClick and binds the view to the Recyclerview.
Any help would be greatly appreciated!
The problem with the stars displayed in every row will be caused because you might be setting them when needed but not hiding them when not needed.
You will have to implement something like this in the getView() method of your adapter.
ImageView starView = (ImageView) v.findViewById(R.id.starView);
starView.setVisibility(goals.get(position).isSpecial() ? View.Visible : View.Gone);
I have a shopping list app that has a bug, when the orientation of the device is changed (Portret to Landscape or the opposite) new item is added. For example, if I have one shopping item like this:
and after I change the orientation of the device it is duplicated:
and if I keep changing the orientation they keep duplicating.
How can I avoid it without the need to set the orientation to portret only?
This is my code in MainActivity:
public class MainActivity extends AppCompatActivity {
public static boolean ifLongPress = false;
private Toolbar mToolbar;
private RecyclerView mRecyclerView;
public static ArrayList<String> shoppingListItems;
private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mEditor;
private TextView mEmptyTextView;
private int arrayListSizeDefaultValue = 0;
private ShoppingListAdapter adapter;
private ActionButton actionButton;
private MaterialDialog addItemdialog = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEmptyTextView = (TextView)findViewById(R.id.list_empty);
mEmptyTextView.setVisibility(View.INVISIBLE);
mSharedPreferences = getPreferences(MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
actionButton = (ActionButton)findViewById(R.id.buttonFloat);
actionButton.setButtonColor(getResources().getColor(R.color.ColorPrimary));
actionButton.setButtonColorPressed(getResources().getColor(R.color.ColorPrimaryDark));
actionButton.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.fab_plus_icon,null));
actionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buildAlertDialog();
}
});
mToolbar = (Toolbar)findViewById(R.id.tool_bar);
setSupportActionBar(mToolbar);
mRecyclerView = (RecyclerView)findViewById(R.id.recyclerView);
if(shoppingListItems == null){
shoppingListItems = new ArrayList<>();
}
//read the array lists
readShoppingItems();
adapter = new ShoppingListAdapter(this,shoppingListItems,mSharedPreferences,mEditor);
mRecyclerView.addItemDecoration(new SimpleDividerItemDecoration(getApplicationContext()));
mRecyclerView.setAdapter(adapter);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
actionButton.setHideAnimation(ActionButton.Animations.SCALE_DOWN);
actionButton.hide();
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
actionButton.setShowAnimation(ActionButton.Animations.SCALE_UP);
actionButton.show();
}
}
});
//check weather to show the empty text view
isListEmpty();
}
private void readShoppingItems() {
int size = mSharedPreferences.getInt(Constants.ARRAY_LIST_SIZE_KEY, arrayListSizeDefaultValue);
for(int i = 0;i< size;i++){
shoppingListItems.add(mSharedPreferences.getString(Constants.ARRAY_LIST_ITEM_KEY + i,null));
}
}
private void saveShoppingItems() {
//save array list
mEditor.putInt(Constants.ARRAY_LIST_SIZE_KEY, shoppingListItems.size());
for (int i =0;i<shoppingListItems.size();i++){
mEditor.putString(Constants.ARRAY_LIST_ITEM_KEY + i,shoppingListItems.get(i));
}
mEditor.apply();
adapter.notifyDataSetChanged();
}
private void buildAlertDialog() {
final int[] choosenQuantity = {1};
final String[] str = {""};
final MaterialDialog.Builder addItemBuilder = new MaterialDialog.Builder(this);
addItemBuilder.title("Add Item");
addItemBuilder.widgetColor(getResources().getColor(R.color.ColorPrimaryDark));
addItemBuilder.inputMaxLength(30, R.color.material_blue_grey_950);
addItemBuilder.content("Quantity:" + choosenQuantity[0]);
addItemBuilder.inputType(InputType.TYPE_CLASS_TEXT);
addItemBuilder.autoDismiss(true);
addItemBuilder.input("add shopping item", "", new MaterialDialog.InputCallback() {
#Override
public void onInput(MaterialDialog dialog, CharSequence input) {
str[0] = input.toString().trim();
//add it to shoppingListItems and save to sharedPreferences
if (str[0].length() != 0) {
if (choosenQuantity[0] > 1) {
shoppingListItems.add(str[0] + " (" + choosenQuantity[0] + ")");
} else {
shoppingListItems.add(str[0]);
}
saveShoppingItems();
isListEmpty();
dialog.dismiss();
} else {
Toast.makeText(MainActivity.this, "no item description!", Toast.LENGTH_LONG).show();
}
}
});
addItemBuilder.negativeText("Cancel");
addItemBuilder.callback(new MaterialDialog.ButtonCallback() {
#Override
public void onNegative(MaterialDialog dialog) {
super.onNegative(dialog);
dialog.dismiss();
}
});
addItemBuilder.neutralText("Add Quantity");
addItemBuilder.callback(new MaterialDialog.ButtonCallback() {
#Override
public void onNeutral(final MaterialDialog dialog) {
super.onNeutral(dialog);
addItemBuilder.autoDismiss(false);
MaterialDialog.Builder quantityDialogBuilder = new MaterialDialog.Builder(MainActivity.this);
quantityDialogBuilder.title("Add Quantity");
quantityDialogBuilder.negativeText("CANCEL").callback(new MaterialDialog.ButtonCallback() {
#Override
public void onNegative(MaterialDialog dialog) {
super.onNegative(dialog);
addItemBuilder.autoDismiss(true);
}
});
quantityDialogBuilder.items(R.array.Quantaty_array);
quantityDialogBuilder.itemsCallback(new MaterialDialog.ListCallback() {
#Override
public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
choosenQuantity[0] = which + 1;
addItemdialog.setContent("Quantity:" + choosenQuantity[0]);
addItemBuilder.autoDismiss(true);
}
});
quantityDialogBuilder.cancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
addItemBuilder.autoDismiss(true);
}
});
quantityDialogBuilder.show();
}
});
addItemdialog = addItemBuilder.build();
addItemdialog.show();
}
#Override
protected void onResume() {
super.onResume();
isListEmpty();
}
private void isListEmpty() {
if (mRecyclerView.getAdapter().getItemCount() == 0) {
mEmptyTextView.setVisibility(View.VISIBLE);
}
else {
mEmptyTextView.setVisibility(View.INVISIBLE);
}
}
And this is the code in my Adapter:
public class ShoppingListAdapter extends RecyclerView.Adapter<ShoppingListAdapter.ShoppingListViewHolder> {
private ArrayList<String> mItems;
private Context mContext;
private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mEditor;
private MaterialDialog addItemdialog;
public ShoppingListAdapter(Context context, ArrayList<String> items, SharedPreferences preferences,SharedPreferences.Editor editor) {
mItems = items;
mContext = context;
mSharedPreferences = preferences;
mEditor = editor;
}
#Override
public ShoppingListViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
View view = LayoutInflater.from(mContext).inflate(R.layout.shopping_list_item,viewGroup,false);
ShoppingListViewHolder viewHolder = new ShoppingListViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ShoppingListViewHolder shoppingListViewHolder, int position) {
shoppingListViewHolder.bindShoppingList(mItems.get(position));
}
#Override
public int getItemCount() {
return mItems.size();
}
public class ShoppingListViewHolder extends RecyclerView.ViewHolder implements CompoundButton.OnCheckedChangeListener, View.OnLongClickListener{
public TextView mShoppingListItem;
public CheckBox mCheckBox;
public ShoppingListViewHolder(View itemView) {
super(itemView);
mShoppingListItem = (TextView) itemView.findViewById(R.id.shoppingListItem);
mCheckBox = (CheckBox) itemView.findViewById(R.id.shoppingListCheckBox);
mCheckBox.setOnCheckedChangeListener(this);
itemView.setOnLongClickListener(this);
}
public void bindShoppingList(String item){
mShoppingListItem.setText(item);
mCheckBox.setChecked(false);
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
mItems.remove(getAdapterPosition());
saveShoppingItems();
notifyItemRemoved(getAdapterPosition());
}
}
private void saveShoppingItems() {
//save array list
mEditor.putInt(Constants.ARRAY_LIST_SIZE_KEY, mItems.size());
for (int i =0;i<mItems.size();i++){
mEditor.putString(Constants.ARRAY_LIST_ITEM_KEY + i,mItems.get(i));
}
mEditor.apply();
}
#Override
public boolean onLongClick(View v) {
final int selectedItem = getAdapterPosition();
String itemToBeEdited = mSharedPreferences.getString(Constants.ARRAY_LIST_ITEM_KEY + selectedItem, null);
//check if the selected item has added quantity and if yes -> remove space+(number)
String formatted ="";
int itemSavedQuantity = 1;
if(itemToBeEdited.length()-4>0 && (itemToBeEdited.charAt(itemToBeEdited.length()-1)==')')){
//get the save quantity
itemSavedQuantity = Integer.parseInt(itemToBeEdited.charAt(itemToBeEdited.length()-2)+"");
//format the string by removing the space + (number)
formatted = itemToBeEdited.substring(0, itemToBeEdited.length() - 4);
}else{
formatted = itemToBeEdited;
}
final String[] str = {""};
final int[] userQuantityInput = {itemSavedQuantity};
Toast.makeText(mContext, "Long Press", Toast.LENGTH_LONG).show();
final MaterialDialog.Builder addItemBuilder = new MaterialDialog.Builder(mContext);
addItemBuilder.title("Edit Item");
addItemBuilder.widgetColor(mContext.getResources().getColor(R.color.ColorPrimaryDark));
addItemBuilder.inputMaxLength(30, R.color.material_blue_grey_950);
addItemBuilder.content("Quantity:" + userQuantityInput[0]);
addItemBuilder.inputType(InputType.TYPE_CLASS_TEXT);
addItemBuilder.autoDismiss(true);
addItemBuilder.input("Edit shopping item", "", new MaterialDialog.InputCallback() {
#Override
public void onInput(MaterialDialog dialog, CharSequence input) {
str[0] = input.toString().trim();
//add it to shoppingListItems and save to sharedPreferences
if (str[0].length() != 0) {
//save items
if (userQuantityInput[0] > 1) {
str[0] += " (" + userQuantityInput[0] + ")";
}
mEditor.putString(Constants.ARRAY_LIST_ITEM_KEY + selectedItem, str[0]);
mEditor.apply();
//clear the content
MainActivity.shoppingListItems.clear();
//read again content
readShoppingItems();
notifyDataSetChanged();
dialog.dismiss();
Toast.makeText(mContext, "Saved", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(mContext, "no item description!", Toast.LENGTH_LONG).show();
}
}
});
addItemBuilder.negativeText("Cancel");
addItemBuilder.callback(new MaterialDialog.ButtonCallback() {
#Override
public void onNegative(MaterialDialog dialog) {
super.onNegative(dialog);
dialog.dismiss();
}
});
addItemBuilder.neutralText("Edit Quantity");
addItemBuilder.callback(new MaterialDialog.ButtonCallback() {
#Override
public void onNeutral(final MaterialDialog dialog) {
super.onNeutral(dialog);
addItemBuilder.autoDismiss(false);
MaterialDialog.Builder quantityDialogBuilder = new MaterialDialog.Builder(mContext);
quantityDialogBuilder.title("Edit Quantity");
quantityDialogBuilder.negativeText("CANCEL").callback(new MaterialDialog.ButtonCallback() {
#Override
public void onNegative(MaterialDialog dialog) {
super.onNegative(dialog);
addItemBuilder.autoDismiss(true);
}
});
quantityDialogBuilder.items(R.array.Quantaty_array);
quantityDialogBuilder.itemsCallback(new MaterialDialog.ListCallback() {
#Override
public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
userQuantityInput[0] = which + 1;
addItemdialog.setContent("Quantity:" + userQuantityInput[0]);
addItemBuilder.autoDismiss(true);
}
});
quantityDialogBuilder.cancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
addItemBuilder.autoDismiss(true);
}
});
quantityDialogBuilder.show();
}
});
addItemdialog = addItemBuilder.build();
addItemdialog.getInputEditText().setText(formatted);
addItemdialog.show();
return true;
}
}
private void readShoppingItems() {
int size = mSharedPreferences.getInt(Constants.ARRAY_LIST_SIZE_KEY, 0);
for(int i = 0;i< size;i++){
MainActivity.shoppingListItems.add(mSharedPreferences.getString(Constants.ARRAY_LIST_ITEM_KEY + i, null));
}
}
Every time you change the rotation of the screen your activity is destroyed and recreated.
Caution: Your activity will be destroyed and recreated each time the
user rotates the screen. When the screen changes orientation, the
system destroys and recreates the foreground activity because the
screen configuration has changed and your activity might need to load
alternative resources (such as the layout).
Recreating an Activity
So it's important you only instantiate your objects once, and not keep recreating them each time your app is recreated. Which then adds them to your list.
You need to use onSaveInstanceState and, possibly, onRestoreInstanceState
After
if(shoppingListItems == null){
shoppingListItems = new ArrayList<>();
}
place
shoppingListItems.clear();