How to add clicked button position to session - java

I have implemented a small shopping cart project, there is a list of products with a button. When i click a "ADD" button it will change the button name "ADD" to "REMOVE" and color also changing Green to Red. Here my problem is if i revisit the products form clicked button should be "REMOVE" and red color. So how to add clicked button position to session.
My code:
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
#Override
public View getView(final int position, View convertView, ViewGroup arg2) {
final ViewHolderGrid holderForGrid;
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.consumer_catalog_list_item, null);
holderForGrid = new ViewHolderGrid(convertView);
convertView.setTag(holderForGrid);
} else {
holderForGrid = (ViewHolderGrid) convertView.getTag();
}
final BusinessCatalogVariables Catalog = catalogList.get(position);
holderForGrid.AddtoCart.setClickable(false);
holderForGrid.AddtoCart.setTag(position);
if (catalogList.get(position).isAdded()) {
holderForGrid.AddtoCart.setText("Remove");
holderForGrid.AddtoCart.setBackgroundResource(R.drawable.btnred);
} else {
holderForGrid.AddtoCart.setText("Add to Cart");
holderForGrid.AddtoCart.setBackgroundResource(R.drawable.buttonsignup);
}
if (Pref_Storage.checkDetail(context, Items)) {
holderForGrid.AddtoCart.setText("Remove");
holderForGrid.AddtoCart.setBackgroundResource(R.drawable.btnred);
Toast.makeText(context, Items, Toast.LENGTH_SHORT).show();
} else {
holderForGrid.AddtoCart.setText("Add to Cart");
holderForGrid.AddtoCart.setBackgroundResource(R.drawable.buttonsignup);
}
holderForGrid.AddtoCart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Position = (Integer) v.getTag();
Log.d("ADD BUTTON POSITION:", "position=" + position);
if (holderForGrid.AddtoCart.getText().equals("Add to Cart")) {
catalogList.get(position).setAdded(true);
holderForGrid.AddtoCart.setText("Remove");
holderForGrid.AddtoCart.setBackgroundResource(R.drawable.btnred);
Items = String.valueOf(Position);
Pref_Storage.setDetail(context, Items, "added");
//
} else if (holderForGrid.AddtoCart.getText().equals("Remove")) {
catalogList.get(position).setAdded(false);
holderForGrid.AddtoCart.setBackgroundResource(R.drawable.buttonsignup);
holderForGrid.AddtoCart.setText("Add to Cart");
Items = String.valueOf(Position);
Pref_Storage.deleteKey(context,Items);
}
}
});
return convertView;
}

You have to use setTag(),getTag() method,
Class Pref_Storage.java [For storing products id]
public class Pref_Storage {
private static SharedPreferences sharedPreferences = null;
public static void openPref(Context context) {
sharedPreferences = context.getSharedPreferences(context.getResources().getString(R.string.app_name),
Context.MODE_PRIVATE);
}
public static void deleteKey(Context context, String key) {
HashMap<String, String> result = new HashMap<String, String>();
Pref_Storage.openPref(context);
for (Entry<String, ?> entry : Pref_Storage.sharedPreferences.getAll()
.entrySet()) {
result.put(entry.getKey(), (String) entry.getValue());
}
boolean b = result.containsKey(key);
if (b) {
Pref_Storage.openPref(context);
Editor prefsPrivateEditor = Pref_Storage.sharedPreferences.edit();
prefsPrivateEditor.remove(key);
prefsPrivateEditor.commit();
prefsPrivateEditor = null;
Pref_Storage.sharedPreferences = null;
}
}
public static void setDetail(Context context, String key, String value) {
Pref_Storage.openPref(context);
Editor prefsPrivateEditor = Pref_Storage.sharedPreferences.edit();
prefsPrivateEditor.putString(key, value);
prefsPrivateEditor.commit();
prefsPrivateEditor = null;
Pref_Storage.sharedPreferences = null;
}
public static Boolean checkDetail(Context context, String key) {
HashMap<String, String> result = new HashMap<String, String>();
Pref_Storage.openPref(context);
for (Entry<String, ?> entry : Pref_Storage.sharedPreferences.getAll()
.entrySet()) {
result.put(entry.getKey(), (String) entry.getValue());
}
boolean b = result.containsKey(key);
return b;
}
}
And in Adapter Class you have to check:
if(Pref_Storage.checkDetail(context, pid)){
holderForGrid.AddtoCart.setText("Remove");
}
else{
holderForGrid.AddtoCart.setText("Add to Cart");
}
holderForGrid.AddtoCart.setTag(position);
holderForGrid.AddtoCart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int pos = (int) v.getTag();
Button btn=(Button)v;
if (btn.getText().equals("Add to Cart")) {
catalogList.get(position).setAdded(true);
btn.setText("Remove");
btn.setBackgroundResource(R.drawable.btnred);
Pref_Storage.setDetail(context, pid, "added");
} else if (btn.getText().equals("Remove")) {
catalogList.get(position).setAdded(false);
btn.setBackgroundResource(R.drawable.buttonsignup);
btn.setText("Add to Cart");
Pref_Storage.deleteKey(context,pid);
}
}
});

Try this.
if (catalogList.get(position).isAdded()) {
holderForGrid.AddtoCart.setText("Remove");
holderForGrid.AddtoCart.setBackgroundResource(R.drawable.btnred);
} else {
holderForGrid.AddtoCart.setText("Add to Cart");
holderForGrid.AddtoCart.setBackgroundResource(R.drawable.buttonsignup);
}

Related

Recycerview changing the wrong items

here is my recyclerview adapter classs
public class WebsiteAdapter extends RecyclerView.Adapter<WebsiteAdapter.WebsiteHolder> {
private List<Website> websites = new ArrayList<>();
private WebsiteViewModel websiteViewModel;
WebsiteAdapter(WebsiteViewModel viewModel){
this.websiteViewModel = viewModel;
}
#NonNull
#Override
public WebsiteHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.website_item, parent, false);
return new WebsiteHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull final WebsiteHolder holder, final int position) {
final Website currentWebsite = websites.get(position);
final Boolean bookmarkStatus = currentWebsite.getFavourite();
final List<WebPage> webPages = websiteViewModel.getRepository().getAllWebPagesForWebsite(currentWebsite.getWebsite_id());
holder.textViewTitle.setText(currentWebsite.getWebsiteName());
if(currentWebsite.getDescription() != null){
holder.textViewDescription.setText(currentWebsite.getDescription());
holder.textViewDescription.setVisibility(View.VISIBLE);
}
if(webPages!=null && !webPages.isEmpty()) {
holder.secondaryAdapter.setWebPages(webPages);
holder.expandCollapse.setVisibility(View.VISIBLE);
}
if(bookmarkStatus){
holder.isBookmarked = true;
holder.bookmarkButton.setBackgroundResource(R.drawable.ic_bookmark_24px);
} else {
holder.isBookmarked = false;
holder.bookmarkButton.setBackgroundResource(R.drawable.ic_bookmark_border_24px);
}
holder.cardViewWebsite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String websiteUrl = currentWebsite.getWebsite_url();
System.out.println("Description = " + currentWebsite.getDescription() + ", boomarked : " + currentWebsite.getFavourite());
List<WebPage> webPages = websiteViewModel.getRepository().getAllWebPagesForWebsite(currentWebsite.getWebsite_id());
for(WebPage webPage : webPages){
System.out.println("Web pages: ");
System.out.println(webPage.toString() + ", ");
}
launchWebsite(v.getContext(), websiteUrl);
}
});
holder.bookmarkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Website bookmarked before click : " + bookmarkStatus + ", Description is : " + currentWebsite.getDescription());
currentWebsite.setFavourite(!bookmarkStatus);
System.out.println("Website bookmark clicked, status has been set to : " + currentWebsite.getFavourite());
websiteViewModel.getRepository().websiteDao.updateWebsite(currentWebsite);
notifyItemChanged(position);
}
});
}
private void launchWebsite(Context context, String URL) {
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
builder.setStartAnimations(context, R.anim.push_off_screen_left, R.anim.push_onto_screen_from_right);
builder.setExitAnimations(context, R.anim.push_onto_screen_from_left, R.anim.push_off_screen_right);
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(context,Uri.parse(URL));
}
#Override
public int getItemCount() {
return websites.size();
}
public void setWebsites(List<Website> websites) {
this.websites = websites;
notifyDataSetChanged();
}
class WebsiteHolder extends RecyclerView.ViewHolder {
private TextView textViewTitle;
private TextView textViewDescription;
private CardView cardViewWebsite;
private boolean isBookmarked; // ALSO FAVOURITED
private boolean isExpanded = false;
private Button expandCollapse;
private Button bookmarkButton;
private SecondaryAdapter secondaryAdapter;
private RecyclerView childRecyclerView;
public WebsiteHolder(View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.text_view_title);
textViewDescription = itemView.findViewById(R.id.text_view_description);
cardViewWebsite = itemView.findViewById(R.id.cardViewWebsite);
bookmarkButton = itemView.findViewById(R.id.bookmarkButton);
childRecyclerView = itemView.findViewById(R.id.childRecyclerview);
expandCollapse = itemView.findViewById(R.id.expandCollapse);
expandCollapse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isExpanded) {
collapseView();
} else {
expandView();
}
}
});
childRecyclerView.setLayoutManager(new LinearLayoutManager(itemView.getContext(), LinearLayoutManager.HORIZONTAL, false));
LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(itemView.getContext(), R.anim.layout_animation_slide_in);
childRecyclerView.setLayoutAnimation(animation);
childRecyclerView.setHasFixedSize(true);
secondaryAdapter = new SecondaryAdapter();
childRecyclerView.setAdapter(secondaryAdapter);
}
private void collapseView() {
isExpanded = false;
childRecyclerView.setVisibility(View.GONE);
}
private void expandView() {
isExpanded = true;
childRecyclerView.setVisibility(View.VISIBLE);
}
}
}
The issue I am having is, when I press the bookmark button on item A: the expand button on a different item will appear when it should not. B: The secondaryRecyclerView gets set to some other website. How do I go about debugging this? Is there anything that jumps out as a culpit? I feel like I am setting somethings in the wrong place. Thanks very much
wrong item changes in recyclerview
Thanks to this post, I one, added in a bindView method, and 2: added ELSE statements to negate the if statements. Problems solved :) For now :)

duplicate actions in android application when going to home screen

Intro:
My client require some components across the application like navigationDrawer, toolbar. So I have a MainActivity having two toolbar(top/bottom) and two navigation drawer(left/right). All other screens consist of fragments that I change in MainActivity. I have a little problem that is some of the action are being duplicated.
Cases:
In some fragments when user perform an action i.e.
1: User press "Add To Cart" button and press home button that is in toolbar Bottom, the code of "Add To Cart" button run twice (once clicking button, once going to home screen) so my item is being added to cart twice.
2: In another fragment I have "apply coupon" checkbox when user check that checkbox an AlertDialog appear and when user go to home screen the AlertDialog again appear in the home screen.
I'm simply recreating the main activity on home button press with recreate();
I check the code but can't understand why those actions duplicate. If someone faced the same or a bit similar problem please guide me how to tackle that. Any help would be appreciated.
If I need to show code tell me which part?
Edit:
inside onCreateView of fragment Cart Detail
useCoupon.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
createAndShowCustomAlertDialog();
}
}
});
Sequence of this code is Main Activity(Main Fragment)=>Product Frag=>Cart Detail Frag.
Edit 2: MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
this.utils = new Utils(this);
utils.changeLanguage("en");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
this.context = this;
setupToolbar(this);
utils.switchFragment(new MainFrag());
setOnClickListener();
initRightMenuData();
initLeftMenuData();
listAdapter = new ExpandableListAdapter(headerListLeft, hashMapLeft,
false, loggedInIconList);
listViewExpLeft.setAdapter(listAdapter);
if (isLoggedIn()) {
listAdapterRight = new ExpandableListAdapterRight(headerListRight, hashMapRight,
loggedInIconList);
} else {
listAdapterRight = new ExpandableListAdapterRight(headerListRight, hashMapRight,
NotLoggedInIconList);
}
listViewExpRight.setAdapter(listAdapterRight);
enableSingleSelection();
setExpandableListViewClickListener();
setExpandableListViewChildClickListener();
}
private void setOnClickListener() {
myAccountTV.setOnClickListener(this);
checkoutTV.setOnClickListener(this);
discountTV.setOnClickListener(this);
homeTV.setOnClickListener(this);
searchIcon.setOnClickListener(this);
cartLayout.setOnClickListener(this);
}
private void setExpandableListViewClickListener() {
listViewExpRight.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition,
long id) {
utils.printLog("GroupClicked", " Id = " + id);
int childCount = parent.getExpandableListAdapter().getChildrenCount(groupPosition);
if (!isLoggedIn()) {
if (childCount < 1) {
if (groupPosition == 0) {
utils.switchFragment(new FragLogin());
} else if (groupPosition == 1) {
utils.switchFragment(new FragRegister());
} else if (groupPosition == 2) {
utils.switchFragment(new FragContactUs());
} else {
recreate();
}
drawer.closeDrawer(GravityCompat.END);
}
} else {
if (childCount < 1) {
changeFragment(103 + groupPosition);
drawer.closeDrawer(GravityCompat.END);
}
}
return false;
}
});
listViewExpLeft.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
int childCount = parent.getExpandableListAdapter().getChildrenCount(groupPosition);
if (childCount < 1) {
MenuCategory textChild = (MenuCategory) parent.getExpandableListAdapter()
.getGroup(groupPosition);
moveToProductFragment(textChild.getMenuCategoryId());
utils.printLog("InsideChildClick", "" + textChild.getMenuCategoryId());
}
return false;
}
});
}
private void setExpandableListViewChildClickListener() {
listViewExpLeft.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
int childPosition, long id) {
MenuSubCategory subCategory = (MenuSubCategory) parent.getExpandableListAdapter()
.getChild(groupPosition, childPosition);
moveToProductFragment(subCategory.getMenuSubCategoryId());
utils.printLog("InsideChildClick", "" + subCategory.getMenuSubCategoryId());
return true;
}
});
listViewExpRight.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
String str = parent.getExpandableListAdapter().getGroup(groupPosition).toString();
UserSubMenu userSubMenu = (UserSubMenu) parent.getExpandableListAdapter()
.getChild(groupPosition, childPosition);
if (str.contains("Information") || str.contains("معلومات")) {
Bundle bundle = new Bundle();
bundle.putString("id", userSubMenu.getUserSubMenuCode());
utils.switchFragment(new FragShowText(), bundle);
} else if (str.contains("اللغة") || str.contains("Language")) {
recreate();
} else if (str.contains("دقة") || str.contains("Currency")) {
makeDefaultCurrencyCall(userSubMenu.getUserSubMenuCode());
}
utils.printLog("InsideChildClick", "" + userSubMenu.getUserSubMenuCode());
drawer.closeDrawer(GravityCompat.END);
return false;
}
});
}
private void setupToolbar(Context context) {
ViewCompat.setLayoutDirection(appbarBottom, ViewCompat.LAYOUT_DIRECTION_RTL);
ViewCompat.setLayoutDirection(appbarTop, ViewCompat.LAYOUT_DIRECTION_RTL);
String imgPath = Preferences
.getSharedPreferenceString(appContext, LOGO_KEY, DEFAULT_STRING_VAL);
utils.printLog("Product Image = " + imgPath);
if (!imgPath.isEmpty()) {
Picasso.with(getApplicationContext()).load(imgPath)
.into(logoIcon);
}
logoIcon.setOnClickListener(this);
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
actionbarToggle();
drawer.addDrawerListener(mDrawerToggle);
drawerIconLeft.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
drawer.openDrawer(GravityCompat.START);
drawerIconLeft.setScaleX(1);
drawerIconLeft.setImageResource(R.drawable.ic_arrow_back_black);
}
}
});
drawerIconRight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawer(GravityCompat.END);
} else {
drawer.openDrawer(GravityCompat.END);
}
}
});
}
private void initViews() {
drawerIconLeft = findViewById(R.id.drawer_icon_left);
drawerIconRight = findViewById(R.id.drawer_icon_right);
logoIcon = findViewById(R.id.logo_icon);
searchIcon = findViewById(R.id.search_icon);
cartLayout = findViewById(R.id.cart_layout);
counterTV = findViewById(R.id.actionbar_notification_tv);
drawer = findViewById(R.id.drawer_layout);
listViewExpLeft = findViewById(R.id.expandable_lv_left);
listViewExpRight = findViewById(R.id.expandable_lv_right);
appbarBottom = findViewById(R.id.appbar_bottom);
appbarTop = findViewById(R.id.appbar_top);
myAccountTV = findViewById(R.id.my_account_tv);
discountTV = findViewById(R.id.disc_tv);
checkoutTV = findViewById(R.id.checkout_tv);
homeTV = findViewById(R.id.home_tv);
searchView = findViewById(R.id.search_view);
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawer(GravityCompat.END);
} else {
super.onBackPressed();
}
}
private void initRightMenuData() {
headerListRight = new ArrayList<>();
hashMapRight = new HashMap<>();
String[] notLoggedInMenu = {findStringByName("login_text"),
findStringByName("action_register_text"),
findStringByName("contact_us_text")};
String[] loggedInMenu = {findStringByName("account"), findStringByName("edit_account_text"),
findStringByName("action_change_pass_text"),
findStringByName("order_history_text"),
findStringByName("logout"), findStringByName("contact_us_text")};
List<UserSubMenu> userSubMenusList = new ArrayList<>();
if (isLoggedIn()) {
for (int i = 0; i < loggedInMenu.length; i++) {
headerListRight.add(loggedInMenu[i]);
hashMapRight.put(headerListRight.get(i), userSubMenusList);
}
} else {
for (int i = 0; i < notLoggedInMenu.length; i++) {
headerListRight.add(notLoggedInMenu[i]);
hashMapRight.put(headerListRight.get(i), userSubMenusList);
}
}
String responseStr = "";
if (getIntent().hasExtra(KEY_EXTRA)) {
responseStr = getIntent().getStringExtra(KEY_EXTRA);
utils.printLog("ResponseInInitData", responseStr);
try {
JSONObject responseObject = new JSONObject(responseStr);
boolean success = responseObject.optBoolean("success");
if (success) {
try {
JSONObject homeObject = responseObject.getJSONObject("home");
JSONArray slideshow = homeObject.optJSONArray("slideshow");
AppConstants.setSlideshowExtra(slideshow.toString());
JSONArray menuRight = homeObject.optJSONArray("usermenu");
for (int z = 0; z < menuRight.length(); z++) {
List<UserSubMenu> userSubMenuList = new ArrayList<>();
JSONObject object = menuRight.getJSONObject(z);
headerListRight.add(object.optString("name"));
JSONArray childArray = object.optJSONArray("children");
for (int y = 0; y < childArray.length(); y++) {
JSONObject obj = childArray.optJSONObject(y);
userSubMenuList.add(new UserSubMenu(obj.optString("code"),
obj.optString("title"), obj.optString("symbol_left"),
obj.optString("symbol_right")));
}
hashMapRight.put(headerListRight.get(headerListRight.size() - 1), userSubMenuList);
utils.printLog("AfterHashMap", "" + hashMapRight.size());
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
utils.showErrorDialog("Error Getting Data From Server");
utils.printLog("SuccessFalse", "Within getCategories");
}
} catch (JSONException e) {
e.printStackTrace();
utils.printLog("JSONObjEx_MainAct", responseStr);
}
} else {
utils.printLog("ResponseExMainActivity", responseStr);
throw new IllegalArgumentException("Activity cannot find extras " + KEY_EXTRA);
}
}
private void initLeftMenuData() {
headerListLeft = new ArrayList<>();
hashMapLeft = new HashMap<>();
String responseStr = "";
if (getIntent().hasExtra(KEY_EXTRA)) {
responseStr = getIntent().getStringExtra(KEY_EXTRA);
utils.printLog("ResponseInMainActivity", responseStr);
try {
JSONObject responseObject = new JSONObject(responseStr);
utils.printLog("JSON_Response", "" + responseObject);
boolean success = responseObject.optBoolean("success");
if (success) {
try {
JSONObject homeObject = responseObject.getJSONObject("home");
JSONArray menuCategories = homeObject.optJSONArray("categoryMenu");
utils.printLog("Categories", menuCategories.toString());
for (int i = 0; i < menuCategories.length(); i++) {
JSONObject menuCategoryObj = menuCategories.getJSONObject(i);
JSONArray menuSubCategoryArray = menuCategoryObj.optJSONArray(
"children");
List<MenuSubCategory> childMenuList = new ArrayList<>();
for (int j = 0; j < menuSubCategoryArray.length(); j++) {
JSONObject menuSubCategoryObj = menuSubCategoryArray.getJSONObject(j);
MenuSubCategory menuSubCategory = new MenuSubCategory(
menuSubCategoryObj.optString("child_id"),
menuSubCategoryObj.optString("name"));
childMenuList.add(menuSubCategory);
}
MenuCategory menuCategory = new MenuCategory(menuCategoryObj.optString(
"category_id"), menuCategoryObj.optString("name"),
menuCategoryObj.optString("icon"), childMenuList);
headerListLeft.add(menuCategory);
hashMapLeft.put(headerListLeft.get(i), menuCategory.getMenuSubCategory());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
utils.printLog("ResponseExMainActivity", responseStr);
throw new IllegalArgumentException("Activity cannot find extras " + KEY_EXTRA);
}
}
private void actionbarToggle() {
mDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawer,
R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
drawerIconLeft.setImageResource(R.drawable.ic_list_black);
drawerIconLeft.setScaleX(-1);
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
}
#Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.logo_icon) {
recreate();
} else if (id == R.id.my_account_tv) {
utils.switchFragment(new Dashboard());
} else if (id == R.id.disc_tv) {
utils.printLog("From = Main Act");
Bundle bundle = new Bundle();
bundle.putString("from", "mainActivity");
utils.switchFragment(new FragProduct(), bundle);
} else if (id == R.id.checkout_tv) {
if (isLoggedIn()) {
utils.switchFragment(new FragCheckout());
} else {
AlertDialog alertDialog = utils.showAlertDialogReturnDialog("Continue As",
"Select the appropriate option");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE,
"As Guest", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
utils.switchFragment(new FragCheckout());
}
});
alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
"Login", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
utils.switchFragment(new FragLogin());
}
});
alertDialog.setButton(DialogInterface.BUTTON_NEUTRAL,
"Register", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
utils.switchFragment(new FragRegister());
}
});
alertDialog.show();
}
} else if (id == R.id.home_tv) {
recreate();
} else if (id == R.id.search_icon) {
startActivityForResult(new Intent(context, SearchActivity.class), SEARCH_REQUEST_CODE);
} else if (id == R.id.cart_layout) {
Bundle bundle = new Bundle();
bundle.putString("midFix", "cartProducts");
utils.switchFragment(new FragCartDetail(), bundle);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SEARCH_REQUEST_CODE || requestCode == CURRENCY_REQUEST_CODE
|| requestCode == LANGUAGE_REQUEST_CODE) {
if (data != null) {
String responseStr = data.getStringExtra("result");
utils.printLog("ResponseIs = " + responseStr);
if (responseStr != null) {
if (resultCode == Activity.RESULT_OK) {
JSONObject response;
if (!isJSONString(responseStr)) {
try {
response = new JSONObject(responseStr);
if (requestCode == CURRENCY_REQUEST_CODE) {
JSONObject object = response.optJSONObject("currency");
Preferences.setSharedPreferenceString(appContext
, CURRENCY_SYMBOL_KEY
, object.optString("symbol_left")
+ object.optString("symbol_right")
);
recreate();
} else if (requestCode == LANGUAGE_REQUEST_CODE) {
JSONObject object = response.optJSONObject("language");
Preferences.setSharedPreferenceString(appContext
, LANGUAGE_KEY
, object.optString("code")
);
recreate();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
if (requestCode == SEARCH_REQUEST_CODE) {
if (responseStr.isEmpty())
return;
Bundle bundle = new Bundle();
bundle.putString("id", responseStr);
bundle.putString("from", "fromSearch");
utils.switchFragment(new FragProduct(), bundle);
} else {
utils.showAlertDialog("Alert", responseStr);
}
}
} else if (resultCode == FORCED_CANCEL) {
utils.printLog("WithinSearchResult", "If Success False" + responseStr);
} else if (resultCode == Activity.RESULT_CANCELED) {
utils.printLog("WithinSearchResult", "Result Cancel" + responseStr);
}
}
}
}
}
}
MainFragment
public class MainFrag extends MyBaseFragment {
public MainFrag() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_main, container, false);
initUtils();
initViews(view);
utils.setupSlider(mPager, indicator, pb, true, true);
RecyclerView.LayoutManager mLayoutManager =
new LinearLayoutManager(getActivity()
, LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(mLayoutManager);
List<String> keysList = prepareData();
if (keysList.size() > 0 && !keysList.isEmpty()) {
mRecyclerView.setAdapter(new MainFragmentAdapter(keysList));
}
return view;
}
private void initViews(View view) {
mRecyclerView = view.findViewById(R.id.parent_recycler_view);
mPager = view.findViewById(R.id.pager);
indicator = view.findViewById(R.id.indicator);
pb = view.findViewById(R.id.loading);
}
private List<String> prepareData() {
String responseStr = getHomeExtra();
List<String> keysStr = new ArrayList<>();
try {
JSONObject responseObject = new JSONObject(responseStr);
utils.printLog("JSON_Response", "" + responseObject);
boolean success = responseObject.optBoolean("success");
if (success) {
JSONObject homeObject = responseObject.optJSONObject("home");
JSONObject modules = homeObject.optJSONObject("modules");
Iterator<?> keys = modules.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
keysStr.add(key);
utils.printLog("KeyStr", key);
}
utils.printLog("ModuleSize", modules.toString());
} else {
utils.printLog("SuccessFalse", "Within getCategories");
}
} catch (JSONException e) {
e.printStackTrace();
utils.printLog("JSONEx_MainFragTest", responseStr);
}
return keysStr;
}
}
I removed global variables and some method because of length.
You should not use recreate() method here, as it forces the activity to reload everything. Just use intent to call your Home activity, that should solve this issue.
From the hint of #Akash Khatri I use to switch to mainFragment and its fine now. Actually #Akash is right recreate(); everything at present But as I was setting main fragment in OnCreate of MainActivity. So, It was hard to notice that Android first recreate everything and in no time It call the main Fragment.
I do not using Intent to start the same activity again Because Switching fragment is more convenient. And also I pass Some extras to it that I will loose With new Intent.

In android : how to make strings inside Listview enable copying

public class mychatorderdetails extends ActionBarActivity {
private MyApplication app;
private String order_id;
private String orderdate;
private String cust_name;
private String cust_address;
private String cust_pincode;
private String cust_mobile;
private String action;
private String UPI;
private Button bt;
private OrderDetailsAdapter oa;
private ListView lv;
private ArrayList<HashMap<String, String>> messageList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mychatorderdetails);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
messageList = new ArrayList<HashMap<String, String>>();
app=((MyApplication) getApplicationContext());
Bundle extras = getIntent().getExtras();
if(extras != null) {
order_id = extras.getString("order_id");
orderdate = extras.getString("orderdate");
cust_name = extras.getString("cust_name");
cust_address = extras.getString("cust_address");
cust_pincode = extras.getString("cust_pincode");
cust_mobile=extras.getString("cust_mobile");
UPI=extras.getString("UPI");
action=extras.getString("action"); //setaccepted, setdelivered
}
bt = (Button) findViewById(R.id.btnAction);
switch (action)
{
case "setdelivered":{
bt.setText("Delivered");
break;
}
case "setaccepted":{
bt.setText("Accept");
break;
}
default:
}
try {
String dpart = orderdate.substring(0, 10);
String tpart = orderdate.substring(11, 19);
orderdate = dpart.substring(8,10);
orderdate+="/"+dpart.substring(5,7);
orderdate+="/"+dpart.substring(0,4);
orderdate+=" "+tpart;
}
catch (Exception e)
{
Log.d(getString(R.string.app_name), e.getMessage());
}
HashMap<String, String> row = new HashMap<String, String>();
row.put("type", "text");
row.put("details", "Order ID:"+order_id);
messageList.add(row);
HashMap<String, String> rowd = new HashMap<String, String>();
rowd.put("type", "text");
rowd.put("details", "Order Date:"+orderdate);
messageList.add(rowd);
HashMap<String, String> row1 = new HashMap<String, String>();
row1.put("type", "text");
row1.put("details",cust_name);
messageList.add(row1);
HashMap<String, String> row2 = new HashMap<String, String>();
row2.put("type", "text");
row2.put("details",cust_address);
messageList.add(row2);
HashMap<String, String> row3 = new HashMap<String, String>();
row3.put("type", "text");
row3.put("details","Pin:"+cust_pincode);
messageList.add(row3);
HashMap<String, String> row4 = new HashMap<String, String>();
row4.put("type", "text");
row4.put("details","Mob:"+cust_mobile);
messageList.add(row4);
HashMap<String, String> row5 = new HashMap<String, String>();
row5.put("type", "text");
row5.put("details","UPI:"+UPI);
messageList.add(row5);
oa=new OrderDetailsAdapter(mychatorderdetails.this,messageList);
lv = (ListView) findViewById(R.id.lstOrderDetails);
lv.setAdapter(oa);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
HashMap<String, String> temp = new HashMap<String, String>();
temp = messageList.get(position);
if(temp.get("type")=="image")
{
//Uri uri = Uri.parse(temp.get("details"));
showImage(temp.get("details"));
}
} catch (Exception e) {
Log.d(getString(R.string.app_name), e.getMessage());
}
}
});
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONArray det = app.getMyChatOrderDetails(order_id);
for (int i = 0; i < det.length(); i++) {
JSONObject cat = det.getJSONObject(i);
HashMap<String, String> row = new HashMap<String, String>();
if(!TextUtils.isEmpty(cat.getString("msg_image").toString()))
{
row.put("type", "image");
row.put("details",cat.getString("msg_image").toString());
}
else
{
row.put("type", "text");
String mfv=cat.getString("msg_for_vendor").toString();
if(mfv.equals("1"))
{
row.put("details","Customer: "+cat.getString("msg_text").toString());
}
else{
row.put("details","Me: "+cat.getString("msg_text").toString());
}
}
messageList.add(row);
}
oa.notifyDataSetChanged();
} catch (JSONException e) {
Log.d(getString(R.string.app_name), e.getMessage());
} catch (Exception e) { //connection timeout
Log.d(getString(R.string.app_name), e.getMessage());
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
public void showImage(String imageUri) {
Dialog builder = new Dialog(this);
builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
builder.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
//nothing;
}
});
try {
ImageView imageView = new ImageView(this);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(imageUri).getContent());
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(450, 400);
imageView.setLayoutParams(layoutParams);
imageView.setVisibility(View.VISIBLE);
builder.addContentView(imageView, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
builder.show();
}
}
catch (Exception e)
{
Log.d(getString(R.string.app_name), e.getMessage());
}
}
public void doAction(View v)
{
switch (action)
{
case "setdelivered":{
if(app.setOrderDelivered(order_id)) {
Toast.makeText(this,"Order marked as delivered...",Toast.LENGTH_LONG).show();
bt.setVisibility(View.INVISIBLE);
}
break;
}
case "setaccepted":{
if(app.acceptChatOrder(order_id)){
Toast.makeText(this,"Order accepted...",Toast.LENGTH_LONG).show();
bt.setVisibility(View.INVISIBLE);
}
break;
}
default:
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_mychatorderdetails, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
Intent intent;
//noinspection SimplifiableIfStatement
if (id == R.id.action_logout) {
app = ((MyApplication) getApplicationContext());
app.logOut();
intent = new Intent(mychatorderdetails.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
mychatorderdetails.this.startActivity(intent);
}
mychatorderdetails.this.finish();
return super.onOptionsItemSelected(item);
}
}
Following is the code to display my List ITEMS. I wanted my 5th row item i.e UPI to be enabled copying when long pressed on it. How do I do this? Please edit my code for the same to happen.
Change in layout file: add the below property to your TextView:
android:textIsSelectable="true"
OR
In your Java class write this line to set it programatically:
myTextView.setTextIsSelectable(true);
Copy text:
tv.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("", tv.getText());
clipboard.setPrimaryClip(clip);
Toast.makeText(context, "Copied to clipboard", Toast.LENGTH_SHORT).show();
return true;
}
});
Make sure you have imported android.content.ClipboardManager and NOT android.text.ClipboardManager.
In your row_layout for your ListView, just add the property android:textIsSelectable to the TextView on which you want copying to be allowed.

java.lang.OutOfMemoryError with ArrayList.addAll()

I have a list of threads which I have paginated to use an endless scroll the issue I'm having (well my users) is an OutOfMemoryError: Failed to allocate a [x] byte allocation with [y] free bytes and [z] until OOM. the x, y and z attribute is different per user but the cause of the bug is always in the same place and it's when I refresh the posts. I'm completely out of my depth here as I have no idea how to optimise my code or make it so this doesn't happen. As it's the biggest crash on my app at the moment. I've posted my PostFragment below please see the refreshPosts(ArrayList<Posts> newObjects) method as this is where the crash is happening.
public class PostFragment extends Fragment implements View.OnClickListener {
private View mRootView;
private GridLayoutManager mLayoutManager;
private ThreadItem mThreads;
private PostItem mPost;
private PostAdapter mAdapter;
private PostResponse mData;
private EmoticonResponse mEmoticon;
private PostFeedDataFactory mDataFactory;
private EmoticonFeedDataFactory mEmoticonDataFactory;
private static PostFragment mCurrentFragment;
private int REQUEST_CODE;
//Flip
private boolean isFlipped = false;
private Animation flipAnimation;
#BindView(R.id.postsRecyclerView)
RecyclerView mRecyclerView;
#BindView(R.id.toolbarForPosts)
Toolbar mToolbar;
#BindView(R.id.threadText)
TextView mThreadText;
#BindView(R.id.flipText)
TextView mFlipTextView;
#BindView(R.id.shareText)
TextView mShareTextView;
#BindView(R.id.replyText)
TextView mReplyTextView;
#BindView(R.id.scrimColorView)
View mBackgroundView;
#BindView(R.id.fabMenu)
FloatingActionButton mFabMenu;
#BindView(R.id.flipFab)
FloatingActionButton mFlipFab;
#BindView(R.id.shareFab)
FloatingActionButton mShareFab;
#BindView(R.id.replyFab)
FloatingActionButton mReplyFab;
//Collapsing Toolbar
#BindView(R.id.postParentAppBarLayout)
AppBarLayout postAppBarLayout;
#BindView(R.id.postCollapseToolbar)
CollapsingToolbarLayout postCollapseToolbarLayout;
#BindView(R.id.mainImageContainer)
ViewGroup mainContainer;
//Back to top
#BindView(R.id.backToTopButton)
Button mBackToTop;
public static boolean isFromReply;
//FAB
private boolean mIsFabOpen = false;
private Animation fab_open, fab_close, rotate_forward, rotate_backward;
//Pagination
private int mCurrentPage = 1;
private ArrayList<Posts> postList = new ArrayList<>();
private boolean mIsLoading = false;
private boolean mIsLastPage = false;
public static PostFragment newInstance(#NonNull ThreadItem threadItem) {
Bundle args = new Bundle();
args.putParcelable("ThreadItem", Parcels.wrap(threadItem));
mCurrentFragment = new PostFragment();
mCurrentFragment.setArguments(args);
isFromReply = false;
return mCurrentFragment;
}
public static PostFragment newPostInstance(#NonNull PostItem postItem) {
Bundle args = new Bundle();
args.putParcelable("PostItemFromCompose", Parcels.wrap(postItem));
mCurrentFragment = new PostFragment();
mCurrentFragment.setArguments(args);
isFromReply = true;
return mCurrentFragment;
}
public PostFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.fragment_post, container, false);
if (savedInstanceState == null) {
ButterKnife.bind(this, mRootView);
initUI();
}
return mRootView;
}
private void initUI() {
//UI Setup
mLayoutManager = new GridLayoutManager(getActivity(), 1);
mRecyclerView.setLayoutManager(mLayoutManager);
mDataFactory = new PostFeedDataFactory(getActivity());
mEmoticonDataFactory = new EmoticonFeedDataFactory(getActivity());
TextView textThreadTopic = (TextView) mRootView.findViewById(R.id.threadTopic);
TextView textNumPosts = (TextView) mRootView.findViewById(R.id.numPosts);
//FAB onClick Set-Up
mFabMenu.setOnClickListener(this);
mShareFab.setOnClickListener(this);
mReplyFab.setOnClickListener(this);
mFlipFab.setOnClickListener(this);
//FAB Animation Set up
fab_open = AnimationUtils.loadAnimation(getActivity().getApplicationContext(),
R.anim.fab_open);
fab_close = AnimationUtils.loadAnimation(getActivity().getApplicationContext(),
R.anim.fab_close);
rotate_forward = AnimationUtils.loadAnimation(getActivity().getApplicationContext(),
R.anim.rotate_forward);
rotate_backward = AnimationUtils.loadAnimation(getActivity().getApplicationContext(),
R.anim.rotate_backward);
//Toolbar
((AppCompatActivity) getActivity()).setSupportActionBar(mToolbar);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);
mToolbar.setNavigationIcon(R.drawable.ic_back_white);
mToolbar.invalidate();
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().finish();
}
});
//Load Parcel
Intent intent = getActivity().getIntent();
mThreads = Parcels.unwrap(getArguments().getParcelable("ThreadItem"));
mPost = Parcels.unwrap(getArguments().getParcelable("PostItemFromCompose"));
if (mThreads != null) {
if (mThreads.getName() != null) {
mThreadText.setText(mThreads.getName());
}
if (mThreads.getTopic_name() != null) {
textThreadTopic.setText(mThreads.getTopic_name());
}
if (mThreads.getNum_posts() != null) {
int numPosts = Integer.parseInt(mThreads.getNum_posts());
if (numPosts > 1000) {
textNumPosts.setText("1K");
} else {
textNumPosts.setText(mThreads.getNum_posts());
}
}
}
postAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = false;
int scrollRange = -1;
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
postCollapseToolbarLayout.setTitle("Threads");
mainContainer.setVisibility(View.INVISIBLE);
isShow = true;
} else if (isShow) {
postCollapseToolbarLayout.setTitle("");
isShow = false;
mainContainer.setVisibility(View.VISIBLE);
}
}
});
flipAnimation =
AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.flip);
loadData(true, 1);
}
private void loadData(final boolean firstLoad, int readDirection) {
if (isFromReply) {
if (mPost.getThread_id() != null) {
mDataFactory.getPostFeed(mPost.getThread_id(), readDirection, mCurrentPage,
new PostFeedDataFactory.PostFeedDataFactoryCallback() {
#Override
public void onPostDataReceived(PostResponse response) {
mData = response;
if (mData.getItems() != null) {
for (int i = 0; i < mData.getItems().size(); i++) {
Posts singlePost = response.getItems().get(i);
postList.add(singlePost);
}
if (firstLoad) {
mIsLoading = false;
mData.getItems().clear();
mData.getItems().addAll(postList);
mEmoticonDataFactory.getEmoticonFeed(
new EmoticonFeedDataFactory.EmoticonFeedDataFactoryCallback() {
#Override
public void onEmoticonDataReceived(EmoticonResponse response) {
mEmoticon = response;
populateUIWithData();
}
#Override
public void onEmoticonDataFailed(Exception exception) {
}
});
} else {
mIsLoading = false;
refreshPosts(postList);
}
if (mData.getItems().size() > 0) {
if (Integer.valueOf(mData.getTotalPosts()) >= response.getItems().size()) {
mCurrentPage++;
} else {
mIsLastPage = true;
}
}
}
}
#Override
public void onPostDataFailed(Exception exception) {
customToast("Error: " + exception.toString());
}
});
}
} else {
if (mThreads.getId() != null)
mDataFactory.getPostFeed(mThreads.getId(), readDirection, mCurrentPage,
new PostFeedDataFactory.PostFeedDataFactoryCallback() {
#Override
public void onPostDataReceived(PostResponse response) {
mData = response;
if (mData.getItems() != null) {
for (int i = 0; i < mData.getItems().size(); i++) {
Posts singlePost = response.getItems().get(i);
postList.add(singlePost);
}
if (firstLoad) {
mIsLoading = false;
mData.getItems().clear();
mData.getItems().addAll(postList);
mEmoticonDataFactory.getEmoticonFeed(
new EmoticonFeedDataFactory.EmoticonFeedDataFactoryCallback() {
#Override
public void onEmoticonDataReceived(EmoticonResponse response) {
mEmoticon = response;
populateUIWithData();
}
#Override
public void onEmoticonDataFailed(Exception exception) {
}
});
} else {
mIsLoading = false;
refreshPosts(postList);
}
if (mData.getItems().size() > 0) {
if (Integer.valueOf(mData.getTotalPosts()) >= response.getItems().size()) {
mCurrentPage++;
} else {
mIsLastPage = true;
}
}
}
}
#Override
public void onPostDataFailed(Exception exception) {
customToast("Error: " + exception.toString());
}
});
}
}
private void populateUIWithData() {
ImageButton moreOptionsButton = (ImageButton) mRootView.findViewById(R.id.moreOptions);
moreOptionsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(v.getContext(), v);
popupMenu.inflate(R.menu.thread_options);
popupMenu.getMenu();
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.watch:
WatchedThreadsRequestData watchedThreadsRequestData = new WatchedThreadsRequestData(getActivity());
watchedThreadsRequestData.setWatchedThread(mThreads.getId(), new WatchedThreadsRequestData.WatchedThreadsFeedback() {
#Override
public void onWatchedRequestReceived(ThreadResponse response) {
customToast("Thread watched");
}
#Override
public void onWatchedRequestFailed(Exception exception) {
customToast("Thread wasn't watched: " + exception.toString());
}
});
return true;
case R.id.shareThread:
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.putExtra(Intent.EXTRA_TEXT, mThreads.getName() + " - " + Constants.LIVE_URL +
"talk/" + mThreads.getTopic_url() + '/' + mThreads.getThread_url());
sharingIntent.setType("text/plain");
getActivity().startActivity(Intent.createChooser(sharingIntent, "Share via"));
return true;
case R.id.hideThread:
customToast("Hide: coming soon");
return true;
default:
customToast("Somethings Wrong");
return true;
}
}
});
setForceShowIcon(popupMenu);
popupMenu.show();
}
});
if (mAdapter == null) {
mAdapter = new PostAdapter(getActivity(), mData, mEmoticon);
mRecyclerView.setAdapter(mAdapter);
} else {
mAdapter.setData(mData.getItems());
mAdapter.notifyDataSetChanged();
}
mRecyclerView.addOnScrollListener(paginationListener);
}
public static void setForceShowIcon(PopupMenu popupMenu) {
try {
Field[] fields = popupMenu.getClass().getDeclaredFields();
for (Field field : fields) {
if ("mPopup".equals(field.getName())) {
field.setAccessible(true);
Object menuPopupHelper = field.get(popupMenu);
Class<?> classPopupHelper = Class.forName(menuPopupHelper
.getClass().getName());
Method setForceIcons = classPopupHelper.getMethod(
"setForceShowIcon", boolean.class);
setForceIcons.invoke(menuPopupHelper, true);
break;
}
}
} catch (Throwable e) {
e.printStackTrace();
}
}
private RecyclerView.OnScrollListener paginationListener = new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
boolean hasEnded = newState == SCROLL_STATE_IDLE;
if (hasEnded) {
mFabMenu.show();
mFabMenu.setClickable(true);
} else {
if (mIsFabOpen)
closeMenu();
mFabMenu.hide();
mFabMenu.setClickable(false);
}
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int visibleItemCount = mLayoutManager.getChildCount();
int totalItemCount = mLayoutManager.getItemCount();
int firstVisibleItemPosition = mLayoutManager.findFirstVisibleItemPosition();
if (!mIsLoading && !mIsLastPage) {
if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount) {
loadMoreItems();
}
}
//Back to top
if (mLayoutManager.findLastVisibleItemPosition() == totalItemCount - 1) {
mBackToTop.setVisibility(View.VISIBLE);
mBackToTop.setClickable(true);
mBackToTop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mLayoutManager.scrollToPositionWithOffset(0,0);
}
});
} else {
mBackToTop.setVisibility(View.GONE);
mBackToTop.setClickable(false);
}
}
};
private void loadMoreItems() {
if (!isFlipped) {
mIsLoading = true;
loadData(false, 1);
} else {
mIsLoading = true;
loadData(false, -1);
}
}
private void refreshPosts(ArrayList<Posts> newObjects) {
postList.addAll(newObjects);
populateUIWithData();
}
#Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.fabMenu:
animateFAB();
break;
case R.id.shareFab:
share();
break;
case R.id.replyFab:
reply();
break;
case R.id.flipFab:
flip();
break;
}
}
public void animateFAB() {
if (mIsFabOpen) {
closeMenu();
} else {
mFabMenu.startAnimation(rotate_forward);
mReplyFab.startAnimation(fab_open);
mShareFab.startAnimation(fab_open);
mFlipFab.startAnimation(fab_open);
mReplyFab.setClickable(true);
mShareFab.setClickable(true);
mFlipFab.setClickable(true);
mFlipTextView.setVisibility(View.VISIBLE);
mShareTextView.setVisibility(View.VISIBLE);
mReplyTextView.setVisibility(View.VISIBLE);
mBackgroundView.setVisibility(View.VISIBLE);
mIsFabOpen = true;
}
}
private void closeMenu() {
mFabMenu.startAnimation(rotate_backward);
mReplyFab.startAnimation(fab_close);
mShareFab.startAnimation(fab_close);
mFlipFab.startAnimation(fab_close);
mReplyFab.setClickable(false);
mShareFab.setClickable(false);
mFlipFab.setClickable(false);
mFlipTextView.setVisibility(View.INVISIBLE);
mShareTextView.setVisibility(View.INVISIBLE);
mReplyTextView.setVisibility(View.INVISIBLE);
mBackgroundView.setVisibility(View.INVISIBLE);
mIsFabOpen = false;
}
private void reply() {
PreferenceConnector.writeString(getActivity().getApplicationContext(), "threadID", mThreads.getId());
PreferenceConnector.writeString(getActivity().getApplicationContext(), "threadTitle", mThreads.getName());
if (PreferenceConnector.readString(getActivity(), "authToken") == null ||
PreferenceConnector.readString(getActivity(), "authToken").equalsIgnoreCase("skip")) {
final AlertDialog.Builder loginDialog = new AlertDialog.Builder(getActivity());
loginDialog.setTitle("Please log in");
loginDialog.setMessage("You need to be logged in to reply");
loginDialog.setPositiveButton("Log in", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getActivity().getApplicationContext(), LoginActivity.class);
startActivity(intent);
}
});
loginDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
loginDialog.show();
} else {
closeMenu();
Intent intent = new Intent(getActivity().getApplicationContext(), NewPostActivity.class);
intent.putExtra("Threads", Parcels.wrap(mThreads));
getActivity().finish();
startActivityForResult(intent, REQUEST_CODE);
}
}
private void share() {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.putExtra(Intent.EXTRA_TEXT, mThreads.getName() + " - " + Constants.LIVE_URL +
"talk/" + mThreads.getTopic_url() + '/' + mThreads.getThread_url());
sharingIntent.setType("text/plain");
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
private void flip() {
if (!isFlipped) {
mAdapter.clearAll();
isFlipped = true;
mRecyclerView.startAnimation(flipAnimation);
loadData(false, -1);
closeMenu();
} else {
mAdapter.clearAll();
isFlipped = false;
mRecyclerView.startAnimation(flipAnimation);
loadData(true, 1);
closeMenu();
}
}
private void customToast(String toastMessage) {
LayoutInflater inflater = getActivity().getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) getActivity().findViewById(R.id.toastContainer));
TextView customToastText = (TextView) layout.findViewById(R.id.customToastText);
customToastText.setText(toastMessage);
Toast toast = new Toast(getActivity().getApplicationContext());
toast.setGravity(Gravity.BOTTOM, 0, 25);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
#Override
public void onResume() {
super.onResume();
if (mData != null && mAdapter != null) {
mAdapter.notifyDataSetChanged();
}
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
if (mIsFabOpen) {
closeMenu();
} else {
getActivity().finish();
}
return true;
}
return false;
}
});
}
public void updateView() {
mAdapter.notifyDataSetChanged();
}
}
Thanks in advance once again.
Your problem basically boils down to this:
private void refreshPosts(ArrayList<Posts> newObjects) {
postList.addAll(newObjects);
populateUIWithData();
}
The list can only get bigger, never smaller. If the server has lots and lots of posts, then OutOfMemory is pretty much inevitable.
One approach to solving this problem is to use an LRU (Least Recently Used) cache. There is a utility class you can use: android.util.LruCache.
An LRU Cache is essentially a Map. Items are stored with a key, like an ID. With an LRU cache, you put new items in, but once a pre-determined limit is reached, old items start getting pushed out to make room for new items.
This will save memory, but make a lot more management code for you.
Your adapter, instead of having a list of posts, will just have a list of the post IDs. This should be much easier on memory.
As the user scrolls and you collect more posts, you add the post ID to the list, and map the post into the LRU cache using the post ID.
When you bind to the list item view, you look up the post using the post's ID in the LRU cache.
If it's there, great. That's called a cache hit. Bind the post to the
list item view.
If not, then you have a cache miss. You have some work to do.
Start a server request to retrieve the post by ID. I see your current code just retrieves blocks of posts, so you'll need some new server code here.
When the request completes, put the post in the LRU cache and let the adapter know your item has changed using adapter.notifyItemChanged(). Unless the user has scrolled beyond it, the RecyclerView should try to bind with the list item view again. This time, you should get a cache hit.
This is the basic idea. I'd write some code, but I still have a lot of questions since I can't see your model classes, data factories, and adapter class.
Once you have it working, you have to tune the limit on the cache so that it's low enough not to overrun memory, but high enough that your hit/miss ratio isn't close to zero.
BTW, I noticed that you are making the mistake of creating a new adapter and handing it to the RecyclerView each time you get a block of posts. You should create your adapter once, keep a reference to it and update it. Have a method that adds a block of posts then calls notifyDataSetChanged().
Another idea for conserving memory is to use text compression. If the problem is more a result of a large average size of the post rather than a large number of posts, you might explore this idea in addition to the LRU cache.
The concept is that you could take posts over a certain size, write them into a buffer using a ZipOutputStream then save the buffer in memory. When it's time to display the post, you read the buffer with a ZipInputStream to uncompress the text. Here the issue is performance as the compression/decompression is pretty CPU-intensive. But if the problem is really long posts, this approach might be something to consider.
An even better approach: Only save the first part of the post as an "overview" display in the list. When the user clicks on the list item, retrieve the entire post from the server and display that in another page.

Disable Checkbox click in multiselectListPreference in android

I am using mutliselectlistpreference that extends DialogPreference in my application. And i have not use any adapter for building the UI. Please find the below image.
The issue here is I am able to persist the CheckBox checked for Monday and Tuesday but i am not able to make the items read only wherein user will not able to unchecked the items. I want to make both items grey out. could you please help me out on this ?
#Override
protected void onPrepareDialogBuilder(Builder builder) {
super.onPrepareDialogBuilder(builder);
if (entries == null || entryValues == null) {
throw new IllegalStateException(
"MultiSelectListPreference requires an entries array and an entryValues array.");
}
checked = new boolean[entryValues.length];
List<CharSequence> entryValuesList = Arrays.asList(entryValues);
List<CharSequence> entriesList = Arrays.asList(entries);
for (int i = 0; i < entryValues.length; ++i) {
if("Monday".equals(entriesList.get(i).toString())){
checked[i]=true;
}
}
if (values != null) {
for (String value : values) {
int index = entryValuesList.indexOf(value);
if (index != -1) {
checked[index] = true;
}
}
}
builder.setMultiChoiceItems(entries, checked,
new OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
checked[which] = isChecked;
}
});
}
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult && entryValues != null) {
for (int i = 0; i < entryValues.length; ++i) {
if (checked[i]) {
newValues.add(entryValues[i].toString());
}
}
if (callChangeListener(newValues)) {
setValues(newValues);
}
}
}
#Override
protected Object onGetDefaultValue(TypedArray a, int index) {
CharSequence[] array = a.getTextArray(index);
Set<String> set = new HashSet<String>();
for (CharSequence item : array) {
set.add(item.toString());
}
return set;
}
#Override
protected void onSetInitialValue(boolean restorePersistedValue,
Object defaultValue) {
#SuppressWarnings("unchecked")
Set<String> defaultValues = (Set<String>) defaultValue;
setValues((restorePersistedValue ? getPersistedStringSet(values)
: defaultValues));
}
private Set<String> getPersistedStringSet(Set<String> defaultReturnValue) {
String key = getKey();
//String value = getSharedPreferences().getString("4", "Generic");
return getSharedPreferences().getStringSet(key, defaultReturnValue);
}
private boolean persistStringSet(Set<String> values) {
if (shouldPersist()) {
// Shouldn't store null
if (values == getPersistedStringSet(null)) {
return true;
}
}
SharedPreferences.Editor editor = getEditor();
editor.putStringSet(getKey(), values);
editor.apply();
return true;
}
#Override
protected Parcelable onSaveInstanceState() {
if (isPersistent()) {
return super.onSaveInstanceState();
} else {
throw new IllegalStateException("Must always be persistent");
}
}
You can use them;
checkBox.setEnabled(true); // enable checkbox
checkBox.setEnabled(false); // disable checkbox
Also you can disable them after check the checkBox with this code:
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
if (isChecked){
checkBox.setEnabled(false); // disable checkbox
}
}
});

Categories