Master Detail Flow While clicking on recyclerview I get null exception - android

Well, I have recyclerView and a fragment as the examples of of Master Detail Flows
now i'm getting my data from json and i'm parsing it in the recyclerView perfectly
the problem is whenever I click on it I get null exception..
public class ItemDetailFragment extends Fragment {
/**
* The fragment argument representing the item ID that this fragment
* represents.
*/
public static final String ARG_ITEM_ID = "item_id";
/**
* The dummy content this fragment is presenting.
*/
private DummyContent.DummyItem mItem;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public ItemDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments().containsKey(ARG_ITEM_ID)) {
// Load the dummy content specified by the fragment
// arguments. In a real-world scenario, use a Loader
// to load content from a content provider.
mItem = DummyContent.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID));
Activity activity = this.getActivity();
CollapsingToolbarLayout appBarLayout = (CollapsingToolbarLayout) activity.findViewById(R.id.toolbar_layout);
if (appBarLayout != null) {
appBarLayout.setTitle(mItem.id);
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.item_detail, container, false);
// Show the dummy content as text in a TextView.
if (mItem != null) {
((TextView) rootView.findViewById(R.id.item_detail)).setText("hello");
}
return rootView;
}
and this is the Activity
public class ItemDetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own detail action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
// Show the Up button in the action bar.
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
// savedInstanceState is non-null when there is fragment state
// saved from previous configurations of this activity
// (e.g. when rotating the screen from portrait to landscape).
// In this case, the fragment will automatically be re-added
// to its container so we don't need to manually add it.
// For more information, see the Fragments API guide at:
//
// http://developer.android.com/guide/components/fragments.html
//
if (savedInstanceState == null) {
// Create the detail fragment and add it to the activity
// using a fragment transaction.
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID,
getIntent().getStringExtra(ItemDetailFragment.ARG_ITEM_ID));
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.add(R.id.item_detail_container, fragment)
.commit();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
navigateUpTo(new Intent(this, ItemListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
this is where i get the json and ItemlistActivity
public class ItemListActivity extends AppCompatActivity {
View recyclerView;
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
private boolean mTwoPane;
RequestQueue queue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_list);
queue = Volley.newRequestQueue(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getTitle());
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
recyclerView = findViewById(R.id.item_list);
assert recyclerView != null;
if (findViewById(R.id.item_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-w900dp).
// If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
}
connection();
}
private void setupRecyclerView(#NonNull RecyclerView recyclerView) {
recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(DummyContent.ITEMS));
}
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<ViewHolder> {
private final List<DummyContent.DummyItem> mValues;
public SimpleItemRecyclerViewAdapter(List<DummyContent.DummyItem> items) {
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
String profilePicUrl = mValues.get(position).profile_pic;
String full_name = mValues.get(position).full_name;
String state = mValues.get(position).state;
String city = mValues.get(position).city;
String phoneNo = mValues.get(position).phone_no;
holder.full_name.setText("Name : " +full_name);
holder.state.setText("State : " +state);
holder.city.setText("City : " +city);
holder.phone_number.setText("Phone Number : " +phoneNo);
Glide.with(getApplicationContext())
.load(profilePicUrl)
.fitCenter()
.override(500,500)
.into(holder.profile_pic);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, ItemDetailActivity.class);
Log.e("hello",holder.mItem.full_name);
intent.putExtra(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
}
public void connection(){
final String url = "aaaaa";
// prepare the Request
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
// display response
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject test = jsonArray.getJSONObject(i);
String gender = test.getString("gender");
String full_name = test.getJSONObject("name").getString("title") + " " +
test.getJSONObject("name").getString("first") + " " +
test.getJSONObject("name").getString("last");
String state = test.getJSONObject("location").getString("state");
String city = test.getJSONObject("location").getString("city");
String phone_no = test.getString("phone");
String profile_pic = test.getJSONObject("picture").getString("large");
String id = test.getJSONObject("id").getString("name");
Log.d("test2222", gender + " \n " + full_name + " \n " + state + " \n " + city + " \n " + phone_no + "\n" + profile_pic
+ "\n" + id);
addItem(new DummyContent.DummyItem(gender,profile_pic, full_name, state, city, phone_no,"hello"));
}
setupRecyclerView((RecyclerView) recyclerView);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
Toast.makeText(getApplicationContext(),"check internet connection",Toast.LENGTH_SHORT).show();
}
}
);
// add it to the RequestQueue
queue.add(getRequest);
}
and at last dummycontent
public class DummyContent {
/**
* An array of sample (dummy) items.
*/
public static final List<DummyItem> ITEMS = new ArrayList<DummyItem>();
/**
* A map of sample (dummy) items, by ID.
*/
public static final Map<String, DummyItem> ITEM_MAP = new HashMap<String, DummyItem>();
private static final int COUNT = 25;
static {
// Add some sample items.
}
public static void addItem(DummyItem item) {
ITEMS.add(item);
ITEM_MAP.put(item.full_name, item);
}
/**
* A dummy item representing a piece of content.
*/
public static class DummyItem {
public final String id;
public final String profile_pic;
public final String full_name;
public final String state;
public final String city;
public final String phone_no;
public final String data;
public DummyItem(String id ,String profile_pic, String full_name, String state ,String city,String phone_no,String data) {
this.id = id;
this.profile_pic = profile_pic;
this.full_name = full_name;
this.state = state;
this.city = city;
this.phone_no = phone_no;
this.data = data;
}
#Override
public String toString() {
return full_name;
}
}
}
now the thing is that I want to get same data (text or image) to the fragment
my problem is that I can't even show the fragment with custom "hello world" textview i get exception whenever I click on the recyclerview so explain to me where is the wrong in my code thanks
and this is the ViewHolder
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final ImageView profile_pic;
public final TextView full_name;
public final TextView state;
public final TextView city;
public final TextView phone_number;
public DummyContent.DummyItem mItem;
public ViewHolder(View view) {
super(view);
mView = view;
profile_pic = (ImageView) view.findViewById(R.id.profile_pic);
full_name = (TextView) view.findViewById(R.id.full_name_txt);
state = (TextView) view.findViewById(R.id.state_txt);
city = (TextView) view.findViewById(R.id.city_txt);
phone_number = (TextView) view.findViewById(R.id.phone_no_txt);
}
#Override
public String toString() {
return super.toString() + " '" + full_name.getText() + "'";
}
}

You are getting null value because you are using mItem from ViewHolder class without initializing, which is null.
Try this:
DummyContent.DummyItem mItem = mValues.get(position); //initialize here, not in ViewHolder class
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID, mItem.id); //use without holder
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, ItemDetailActivity.class);
Log.e("hello",holder.mItem.full_name);
intent.putExtra(ItemDetailFragment.ARG_ITEM_ID, mItem.id); //same here
context.startActivity(intent);
}
}
});

Related

ViewPager returns wrong Object

The pager returns the 1st object in the array list, and keeps returning the 1st object even if i swing left and right, did a lot of debugging, and for some reason when the pager get's to getItem(int position) it start's going crazy, it FINDS the corresponding object , then looks a the previous object(pos-1) then does some other weird things and returns the 1st obj in arrayList.
This method is called within the ViewHolder of RecyclerViewAdapter
#Override
public void onClick(View v) {
Intent i = ProductPageActivity.newIntent(v.getContext(),mProduct.getId());
v.getContext().startActivity(i);
}
}
public class ProductFragment extends Fragment {
private static final String TAG = "ProductFragment";
private static final String ARGUMENT_PROD_ID = "prod_id";
private TextView mTitle,mDesc,mImgUrl,mPrice;
private List<Product> mProducts;
private Product product;
public static Fragment newInstance(UUID productID) {
Bundle args = new Bundle();
args.putSerializable(ARGUMENT_PROD_ID,productID);
ProductFragment frag = new ProductFragment();
frag.setArguments(args);
return frag;
}
public ProductFragment() {}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getArguments() != null) {
UUID id = (UUID) getArguments().getSerializable(ARGUMENT_PROD_ID);
product = ProductHolder.get(getContext()).getProduct(id);
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.product_fragment,container,false);
setWidgets(v);
setDataOnText();
return v;
}
private void setDataOnText(){
mTitle.setText(product.getTitle());
mDesc.setText(product.getDesc());
mPrice.setText(product.getPrice());
}
private void setWidgets(View v) {
mTitle = (TextView) v.findViewById(R.id.title);
mDesc = (TextView) v.findViewById(R.id.desc);
mPrice = (TextView) v.findViewById(R.id.price);
}
}
public class ProductPageActivity extends AppCompatActivity {
private static final String PRODUCT_ID = "com.example.cmd.testproject.Activitys.ProductPageActivity.product_id";
private UUID productId;
private ViewPager mPager;
private List<Product> mProducts;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product_page_activity);
productId = (UUID) getIntent().getSerializableExtra(PRODUCT_ID);
mPager = (ViewPager) findViewById(R.id.viewPager);
mProducts = ProductHolder.get(this).getProducts();
FragmentManager fragmentManager = getSupportFragmentManager();
mPager.setAdapter(new FragmentStatePagerAdapter(fragmentManager) {
#Override
public Fragment getItem(int position) {
Product pr = mProducts.get(position);
return ProductFragment.newInstance(pr.getId());
}
#Override
public int getCount() {
return mProducts.size();
}
});
for (int i = 0; i < mProducts.size(); i++) {
if (mProducts.get(i).getId().equals(productId)) {
mPager.setCurrentItem(i);
break;
}
}
}
public static Intent newIntent(Context packageContext, UUID productID) {
Intent intent = new Intent(packageContext, ProductPageActivity.class);
intent.putExtra(PRODUCT_ID, productID);
return intent;
}
}
public class ProductHolder {
private static final String TAG = "ProductHolder";
private static ProductHolder sProductHolder;
private List<Product> mProducts;
public static ProductHolder get(Context ctx) {
if(sProductHolder == null) {
sProductHolder = new ProductHolder(ctx);
}
return sProductHolder;
}
private ProductHolder(Context ctx) {
mProducts = new ArrayList<>();
for (int i = 0; i < 4; i++) {
Product product = new Product("Product = " + i, "Desc = "
+ i, "ImgUrl = " + i, "Price = " + i + 2.2);
mProducts.add(product);
}
}
public Product getProduct(UUID prodId) {
for (Product pr:mProducts) {
if(pr.getId().equals(prodId));
return pr;
}
return null;
}
public List<Product> getProducts() {
return mProducts;
}
}

How to get the data from the fragment in viewpager when dynamically added fragments are swiped in swipeable tabs?

I am working on an app that includes shopping feature and items are added to cart.
I have navigation drawer. In that, I have my first fragment called as "POSFragment" in which I have implemented a viewpager as data to be shown in the form of swipeable tabs. The data will be inflated dynamically. So, I have used PagerTabStrip and a viewpager. There is a common fragment called "MenuDetailFragment" in which data will be inflated dynamically through a webservice. the adapter for this fragment is "MenuPagerAdapter". Now, In this fragment the data will shown in listview. In Listview in each row items can be incremented or decremented using plus and minus Buttons in each row. Between these button there is textview where the quantity will be displayed correspondingly. I have used a Linkedhashmap on both buttons so, the items along with the quantity is saved in linkedhashmap and then in Sharedpreferences. It's working fine till now. The issue occurs when I swipe in the View pager and next fragment appears and When I click on increment button or decrement button on item there. In shared preferences, It starts saving the current fragment items and previous fragment data is not there anymore. I have already used the "yourcustomviewpager.setOffscreenPageLimit(3)" So, I can see the selected items with the quantities whe I swipe to and fro but the data i stored in sharedpreferences using Linkedhashmap is not there instead current fragment's data is saved. I want that the new data is added to previous data and data in all the fragments should persist. Is there a way to do so? I have been facing this issue for quite a long time.
Here are some screenshots and relevant code snippet.
public class PosFragment extends Fragment {
private ViewPager viewPager;
View rootview;
String code;
String name;
String desc;
String rate;
String key;
Button viewCartBtn;
static TextView displayPrice;
static TextView noOfItemsInCart;
RippleView rippleView;
//private sendPosition pos;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
Log.e("oncreateview", "called");
// Inflate the layout for this fragment
rootview = inflater.inflate(R.layout.pos_fragment_layout, container, false);
initViews();
new AsyncTaskGetMenu().execute();
return rootview;
}
public void initViews() {
Log.e("init", "called");
viewPager = (ViewPager) rootview.findViewById(R.id.viewPager);
Button viewCartButton = (Button) rootview.findViewById(R.id.view_cart_btn);
viewPager.setOffscreenPageLimit(3);
viewCartBtn = (Button) rootview.findViewById(R.id.view_cart_btn);
AppMethods.setGlametrixBoldFont(getActivity(), viewCartBtn);
displayPrice = (TextView) rootview.findViewById(R.id.textView_totalprice_cart);
noOfItemsInCart = (TextView) rootview.findViewById(R.id.cart_items_quantity);
viewCartBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), ViewCartActivity.class);
intent.putExtra(AppConstants.SUBTOTAL, Integer.parseInt(displayPrice.getText().toString()));
startActivity(intent);
}
});
LinearLayout itemsInCartLinearLayout = (LinearLayout) rootview.findViewById(R.id.ll_items_in_cart);
itemsInCartLinearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), ViewCartActivity.class);
intent.putExtra(AppConstants.SUBTOTAL, Integer.parseInt(displayPrice.getText().toString()));
startActivity(intent);
}
});
}
This is "MenuDetailFragment" class
public class MenuDetailFragment extends Fragment {
View rootview;
private ListView listView;
private ArrayList<MenuHeadingDetailsModel> menuheadingDetailList;
private Communicate comm;
LinkedHashMap<String, ViewCartDetailsModel> viewCartDetailsModelMap = new LinkedHashMap<>();
ViewCartDetailsModel viewCartDetailsModel;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootview = inflater.inflate(R.layout.menu_list, container, false);
InitializeViews();
return rootview;
}
public void InitializeViews() {
listView = (ListView) rootview.findViewById(R.id.menu_items_list);
Bundle bundle = getArguments();
menuheadingDetailList = bundle.getParcelableArrayList(AppConstants.MENU_KEY);
listView.setAdapter(new MenuAdapter(getActivity(), menuheadingDetailList));[enter image description here][1]
This is"MenuPagerAdapter" class
public class MenuPagerAdapter extends FragmentStatePagerAdapter {
List<MenuModel> menu;
public MenuPagerAdapter(FragmentManager fm, List<MenuModel> menuList) {
super(fm);
this.menu = menuList;
}
#Override
public CharSequence getPageTitle(int position) {
return menu.get(position).getHeading().toString();
}
private List<MenuHeadingDetailsModel> getMenuHeadingDetails(int pos) {
return this.menu.get(pos).getMenuHeadingDetailList();
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new MenuDetailFragment();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList(AppConstants.MENU_KEY, (ArrayList<? extends Parcelable>) getMenuHeadingDetails(position));
fragment.setArguments(bundle);
return fragment;
}
#Override
public int getCount() {
return menu.size();
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer) {
if (observer == null) {
super.unregisterDataSetObserver(observer);
}
}
#Override
public void destroyItem (ViewGroup container, int position, Object object)
{
Log.e("destroyitem","called");
}
}
class MenuAdapter extends BaseAdapter {
//ViewHolder holder;
Context context;
List<MenuHeadingDetailsModel> myItems = new ArrayList<>();
Button buttonPlus, buttonMinus;
int totalAmount = 0;
int pagePosition;
public MenuAdapter(Context context, List<MenuHeadingDetailsModel> myItems) {
this.context = context;
this.myItems = myItems;
}
#Override
public int getCount() {
return myItems.size();
}
#Override
public Object getItem(int position) {
return myItems.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder = new ViewHolder();
final LayoutInflater inflater = getActivity().getLayoutInflater();
convertView = inflater.inflate(R.layout.menu_list_item, null);
viewHolder.codeText = (TextView) convertView.findViewById(R.id.textView_code);
viewHolder.nameText = (TextView) convertView.findViewById(R.id.textView_name);
AppMethods.setGlametrixBoldFont(getActivity(), viewHolder.nameText);
viewHolder.descText = (TextView) convertView.findViewById(R.id.textView_desc);
viewHolder.rateText = (TextView) convertView.findViewById(R.id.textView_rate);
viewHolder.textViewNoOfItems = (TextView) convertView.findViewById(R.id.tv_no_of_items);
buttonMinus = (Button) convertView.findViewById(R.id.button_minus);
buttonPlus = (Button) convertView.findViewById(R.id.button_plus);
final MenuHeadingDetailsModel menu = myItems.get(position);
viewHolder.codeText.setText(menu.getCode());
viewHolder.nameText.setText(menu.getItemName());
viewHolder.descText.setText(menu.getDescription());
viewHolder.rateText.setText(menu.getRate());
viewHolder.textViewNoOfItems.setText("" + menu.getQuantity());
buttonPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MenuHeadingDetailsModel menuList = myItems.get(position);
menuList.setQuantity(menuList.getQuantity() + 1);
myItems.set(position, menuList);
int itemRate = Integer.parseInt(myItems.get(position).getRate());
int itemQuan = menuList.getQuantity();
String code = menuList.getCode();
String name = menuList.getItemName();
int totalAmountPerItem = itemQuan * itemRate;
viewCartDetailsModel = new ViewCartDetailsModel(code, name, itemQuan, itemRate);
viewCartDetailsModelMap.put(viewCartDetailsModel.getCode(), viewCartDetailsModel);
Log.e("hashmap", "size" + viewCartDetailsModelMap.size());
Gson gson = new Gson();
String hashMapToString = gson.toJson(viewCartDetailsModelMap);
AppPreferences.saveDataInSharedpreferences(getActivity(), AppConstants.VIEW_ITEMS_INT_CART_KEY, hashMapToString);
totalAmount += itemRate;
int amount = totalAmount;
onButtonPressedForAmount(amount);
notifyDataSetChanged();
int quan = 0;
TextView tv;
for (int i = 0; i < listView.getCount(); i++) {
View view = listView.getAdapter().getView(i, null, null);
tv = (TextView) view.findViewById(R.id.tv_no_of_items);
quan = quan + Integer.parseInt(tv.getText().toString());
}
onButtonClickedForQuantity(quan);
}
}
);
buttonMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MenuHeadingDetailsModel menuList = myItems.get(position);
if ((menuList.getQuantity() - 1) >= 0) {
menuList.setQuantity(menuList.getQuantity() - 1);
myItems.set(position, menuList);
int itemRate = Integer.parseInt(myItems.get(position).getRate());
int itemQuan = menuList.getQuantity();
String code = menuList.getCode();
String name = menuList.getItemName();
//int totalAmountPerItem = itemQuan * itemRate;
viewCartDetailsModel = new ViewCartDetailsModel(code, name, itemQuan, itemRate);
if (itemQuan == 0) {
viewCartDetailsModelMap.remove(code);
} else {
viewCartDetailsModelMap.put(viewCartDetailsModel.getCode(), viewCartDetailsModel);
}
Gson gson = new Gson();
String hashMapToString = gson.toJson(viewCartDetailsModelMap);
AppPreferences.saveDataInSharedpreferences(getActivity(), AppConstants.VIEW_ITEMS_INT_CART_KEY, hashMapToString);
if (totalAmount > 0) {
totalAmount -= itemRate;
Log.e("totalamount", "minus" + totalAmount);
int amount = totalAmount;
onButtonPressedForAmount(amount);
}
} else {
menuList.setQuantity(0);
myItems.set(position, menuList);
}
notifyDataSetChanged();
int quan = 0;
TextView tv;
for (int i = 0; i < listView.getCount(); i++) {
View view = listView.getAdapter().getView(i, null, null);
tv = (TextView) view.findViewById(R.id.tv_no_of_items);
quan = quan + Integer.parseInt(tv.getText().toString());
}
onButtonClickedForQuantity(quan);
}
}
);
return convertView;
}
public void onButtonPressedForAmount(int userData) {
if (comm != null) {
comm.sendAmount(userData);
}
}
public void onButtonClickedForQuantity(int quantity) {
if (comm != null) {
comm.sendQuantity(quantity);
}
}
class ViewHolder {
TextView nameText;
TextView codeText;
TextView descText;
TextView rateText;
TextView textViewNoOfItems;
}
}
//For settings fonts to the alert diaolog for customization of items
//public void setGlametrixBoldFont(TextView textView) {
//Typeface typeface = Typeface.createFromAsset(getActivity().getAssets(), "fonts/GlametrixBold.otf");
//textView.setTypeface(typeface);
// }
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
comm = (Communicate) activity;
} catch (Exception e) {
AppMethods.getStackTrace(e);
}
}
public interface Communicate {
public void sendAmount(int amount);
public void sendQuantity(int quantity);
}
// public void getPosition(int Position) {
//
// int pagePosition = Position;
// Log.e("pos", " " + pagePosition);
// }
}
You can get your current fragment inside view pager by following below way
SampleFragment sampleFr = (SampleFragment) viewPager.getAdapter().instantiateItem(viewPager, 0);
Now you can access any data you want using that fragment.
For the first time adding fragments in view pager do like below way.
BaseFragment frTimeLine = (BaseFragment) Fragment.instantiate(this, SampleFragment.class.getName());
fragments.add(frTimeLine);
BaseFragment frEarnTiqs = (BaseFragment) Fragment.instantiate(this, SampleFragment1.class.getName());
fragments.add(frEarnTiqs);
adapter = new ViewPagerAdapter(getSupportFragmentManager(), getResources(), fragments);
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(3);

Maintaining RecyclerView and fragment back button [closed]

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.

Tabbed Fragment Only Displays First Fragment

I have a tabbed fragment outlined by the class below.
There are two tabs with lists of information, Friends and Groups. The issue I am having, is that the Group list renders first within the Friends tab, then disappears allowing the Friends list to render within the Friends tab. However, the upon swiping to the Groups tab, the groups list never renders.
How can this be resolved?
Tabbed Activity:
public class InvitingFriendsGroupsToEvents extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inviting_friends_groups_to_events);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#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_inviting_friends_groups_to_events, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_inviting_friends_groups_to_events, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 2;
}
#Override
public Fragment getItem(int position) {
// Need to build
// Order/first appearing will be specific to time of day, ie. if in morning, then breakfast/brunch, if midday then lunch, late then dinner
switch (position) {
case 0:
return new InviteFriendsToEventsFragment();
case 1:
return new InviteGroupsToEventsFragment();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Friends";
case 1:
return "Groups";
}
return null;
}
}
}
Friend Tab:
public class InviteFriendsToEventsFragment extends Fragment {
// ie. once a fiend is invited, it will show their group on the second tab, the name, who invite them
MyCustomAdapter dataAdapter = null;
SaveSharedPreference preference = new SaveSharedPreference();
final Firebase myFeastFirebase = new Firebase(Constants.getFirebaseUrl());
Firebase presentEventMembers;
Firebase myFriends;
Firebase sentFriendEventInvites; // this will be the grayed out standing invitation
Firebase eventMemberInviteNeedSync;
ValueEventListener getFriendsListener;
ValueEventListener getEventMembersListener;
ValueEventListener getAlreadyInvitedFriendsListener;
String eventID;
String eventName;
ArrayList<Member> mEventMembers = new ArrayList<>();
ArrayList<Member> mFriends = new ArrayList<>();
ArrayList<Member> mAlreadyInvited = new ArrayList<>();
ArrayList<FriendInvite> mFriendsFinalInviteStatuses = new ArrayList<>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.invite_friends_to_events, container, false);
Bundle extras = getActivity().getIntent().getExtras();
eventID = extras.getString("eventID");
eventName = extras.getString("eventName");
Log.v("InvitingFriendsToEvents", "Event ID: " + eventID);
Log.v("InvitingFriendsToEvents", "Event Name" + eventName);
//Generate list View from ArrayList
// Get present group members
presentEventMembers = myFeastFirebase.child("eventMembers").child(eventID);
myFriends = myFeastFirebase.child("friends").child(preference.getUserSyncID(getContext()));
sentFriendEventInvites = myFeastFirebase.child("userEventMemberInviteSent").child(preference.getUserSyncID(getContext())).child(eventID);
eventMemberInviteNeedSync = myFeastFirebase.child("eventMemberInviteNeedSync");
getAlreadyInvitedFriendsListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot inviteSnapshot : dataSnapshot.getChildren()) {
Member invitedFriend = new Member();
invitedFriend.setUserUID(inviteSnapshot.getKey());
invitedFriend.setUserName(inviteSnapshot.getValue().toString());
mAlreadyInvited.add(invitedFriend);
Log.v("InvitingFriendsToEvents", "Invite Sent userName is: " + inviteSnapshot.getValue().toString());
Log.v("InvitingFriendsToEvents", "Invite Sent ID is: " + inviteSnapshot.getKey().toString());
}
// Here will be the operation to get the proper setting for
// First: remove from friends, those already in the group:
mFriends.removeAll(mEventMembers);
// Then add to the invite group
for (Member friend : mFriends) {
FriendInvite groupMemberInvite = new FriendInvite();
groupMemberInvite.setUserName(friend.getUserName());
groupMemberInvite.setUserUID(friend.getUserUID());
if (mAlreadyInvited.contains(friend)) {
groupMemberInvite.setInvitedAlready(true);
}
mFriendsFinalInviteStatuses.add(groupMemberInvite);
Log.v("InvitingFriendsToEvents", "Final List UserName is: " + groupMemberInvite.getUserName());
Log.v("InvitingFriendsToEvents", "Final List UserID is: " + groupMemberInvite.getUserUID());
Log.v("InvitingFriendsToEvents", "Final List InviteStatus is: " + groupMemberInvite.isInvitedAlready());
}
//dataAdapter.notifyDataSetChanged();
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(getActivity(),
R.layout.country_info, mFriendsFinalInviteStatuses);
ListView listView = (ListView) getActivity().findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
dataAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
};
getFriendsListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot friendSnapshot : dataSnapshot.getChildren()) {
if (!friendSnapshot.getKey().equals(preference.getUserSyncID(getContext()))) {
Member friend = new Member();
friend.setUserUID(friendSnapshot.getKey());
friend.setUserName(friendSnapshot.child("userName").getValue().toString());
mFriends.add(friend);
Log.v("InvitingFriendsToEvents", "Friend userName is: " + friendSnapshot.child("userName").getValue().toString());
Log.v("InvitingFriendsToEvents", "Friend user ID is: " + friendSnapshot.getKey().toString());
}
}
// after getting friends
sentFriendEventInvites.addListenerForSingleValueEvent(getAlreadyInvitedFriendsListener);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.v("InvitingFriendsToEvents", "Firebase Error: " + firebaseError.toString());
}
};
getEventMembersListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot groupMemberSnapshot : dataSnapshot.getChildren()) {
if (!groupMemberSnapshot.getKey().equals(preference.getUserSyncID(getContext()))) {
Member groupMember = new Member();
groupMember.setUserUID(groupMemberSnapshot.getKey());
groupMember.setUserName(groupMemberSnapshot.getValue().toString());
mEventMembers.add(groupMember);
Log.v("InvitingFriendsToEvents", "Group member userName is: " + groupMemberSnapshot.getValue().toString());
Log.v("InvitingFriendsToEvents", "Group member user ID is: " + groupMemberSnapshot.getKey().toString());
}
}
// upon completion of getting groups
myFriends.addListenerForSingleValueEvent(getFriendsListener);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.v("InvitingFriendsToEvents", "Firebase Error: " + firebaseError.toString());
}
};
presentEventMembers.addListenerForSingleValueEvent(getEventMembersListener);
//confirmFriendInvites();
return view;
}
private class MyCustomAdapter extends ArrayAdapter<FriendInvite> {
private ArrayList<FriendInvite> groupMemberInviteList;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<FriendInvite> groupMemberInviteList) {
super(context, textViewResourceId, groupMemberInviteList);
this.groupMemberInviteList = new ArrayList<>();
this.groupMemberInviteList.addAll(groupMemberInviteList);
}
private class ViewHolder {
TextView inviteSent;
CheckBox checkBox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.country_info, null);
holder = new ViewHolder();
holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox1); // here it is
holder.inviteSent = (TextView) convertView.findViewById(R.id.invite_already_sent);
convertView.setTag(holder);
holder.checkBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
FriendInvite groupMemberInivited = (FriendInvite) cb.getTag();
Toast.makeText(getActivity(),
"Clicked on Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show();
groupMemberInivited.setSelected(cb.isChecked());
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
FriendInvite groupMemberInvite = groupMemberInviteList.get(position);
holder.checkBox.setText(groupMemberInvite.getUserName());
holder.checkBox.setChecked(groupMemberInvite.isSelected());
holder.checkBox.setTag(groupMemberInvite);
// Check if already invited, if so, should remove
if (groupMemberInvite.isInvitedAlready() == true) {
holder.checkBox.setTextColor(Color.GRAY);
holder.checkBox.setClickable(false);
holder.inviteSent.setText("Invite Already Sent");
} else {
holder.inviteSent.setText("");
}
return convertView;
}
}
}
Group Tab:
public class InviteGroupsToEventsFragment extends Fragment {
// ie. once a fiend is invited, it will show their group on the second tab, the name, who invite them
GroupInviteCustomAdapter dataAdapter = null;
SaveSharedPreference preference = new SaveSharedPreference();
final Firebase myFeastFirebase = new Firebase(Constants.getFirebaseUrl());
Firebase presentEventMembers;
Firebase sentFriendEventInvites; // this will be the grayed out standing invitation
Firebase mGroups;
Firebase mGroupMembers;
Firebase eventMemberInviteNeedSync;
ValueEventListener getFriendsListener;
ValueEventListener getEventMembersListener;
ValueEventListener getAlreadyInvitedFriendsListener;
ValueEventListener getUsersGroups;
String eventID;
String eventName;
ArrayList<Member> mEventMembers = new ArrayList<>();
ArrayList<Member> mFriends = new ArrayList<>();
ArrayList<Member> mAlreadyInvited = new ArrayList<>();
ArrayList<FriendInvite> mFriendsFinalInviteStatuses = new ArrayList<>();
ArrayList<GroupInvite> mUsersGroups = new ArrayList<>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.invite_groups_to_events, container, false);
Bundle extras = getActivity().getIntent().getExtras();
eventID = extras.getString("eventID");
eventName = extras.getString("eventName");
Log.v("InvitingFriendsToEvents", "Event ID: " + eventID);
Log.v("InvitingFriendsToEvents", "Event Name" + eventName);
//Generate list View from ArrayList
// Get present group members
presentEventMembers = myFeastFirebase.child("eventMembers").child(eventID);
mGroupMembers = myFeastFirebase.child("groupMembers"); // will append: .child("")
mGroups = myFeastFirebase.child("usersGroups").child(preference.getUserSyncID(getContext()));
sentFriendEventInvites = myFeastFirebase.child("userEventMemberInviteSent").child(preference.getUserSyncID(getContext())).child(eventID);
eventMemberInviteNeedSync = myFeastFirebase.child("eventMemberInviteNeedSync");
getUsersGroups = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot inviteSnapshot : dataSnapshot.getChildren()) {
GroupInvite invitedGroup = new GroupInvite();
invitedGroup.setGroupSyncID(inviteSnapshot.getKey());
invitedGroup.setGroupName(inviteSnapshot.getValue().toString());
mUsersGroups.add(invitedGroup);
Log.v("InvitingFriendsToEvents", "Invite Sent userName is: " + inviteSnapshot.getValue().toString());
Log.v("InvitingFriendsToEvents", "Invite Sent ID is: " + inviteSnapshot.getKey().toString());
}
dataAdapter = new GroupInviteCustomAdapter(getActivity(),
R.layout.event_invites_groups, mUsersGroups);
ListView listView = (ListView) getActivity().findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
dataAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
};
mGroups.addListenerForSingleValueEvent(getUsersGroups);
return view;
}
private class GroupInviteCustomAdapter extends ArrayAdapter<GroupInvite> {
private ArrayList<GroupInvite> groupInviteList;
public GroupInviteCustomAdapter(Context context, int textViewResourceId,
ArrayList<GroupInvite> groupInviteList) {
super(context, textViewResourceId, groupInviteList);
this.groupInviteList = new ArrayList<>();
this.groupInviteList.addAll(groupInviteList);
}
private class ViewHolder {
TextView inviteSent;
CheckBox checkBox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.event_invites_groups, null);
holder = new ViewHolder();
holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox1); // here it is
holder.inviteSent = (TextView) convertView.findViewById(R.id.invite_already_sent);
convertView.setTag(holder);
holder.checkBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
GroupInvite groupInvited = (GroupInvite) cb.getTag();
Toast.makeText(getActivity(),
"Clicked on Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show();
groupInvited.setSelected(cb.isChecked());
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
GroupInvite groupInvite = groupInviteList.get(position);
holder.checkBox.setText(groupInvite.getName());
holder.checkBox.setChecked(groupInvite.isSelected());
holder.checkBox.setTag(groupInvite);
// Check if already invited, if so, should remove
if (groupInvite.isInvitedAlready() == true) {
holder.checkBox.setTextColor(Color.GRAY);
holder.checkBox.setClickable(false);
holder.inviteSent.setText("Invite Already Sent");
} else {
holder.inviteSent.setText("");
}
return convertView;
}
}
}
Move the below block of code outside getUsersGroups = new ValueEventListener()
dataAdapter = new GroupInviteCustomAdapter(getActivity(),
R.layout.event_invites_groups, mUsersGroups);
ListView listView = (ListView) getActivity().findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
dataAdapter.notifyDataSetChanged();
ValueEventListener() only executes the override methods. My guess is that the above code never runs.Try and let me know if it works. If it doesnt will debug further.

Android getActivity().setTitle() gets String field from wrong object in ArrayList

I wish to set the titlebar in this fragment's activity to the HelpItem's description field.
On line 10, I set the title of the activity with a String representing a HelpItem's description.
Instead of getting the description of the retrieved HelpItem on line 9 I get the description of the next HelpItem.
I.E. in an ArrayList of five HelpItem objects with the helpDescriptions "aaa", "bbb", "ccc", "ddd", "eee" clicking on "bbb" in the
list displays "bbb" and the information text associated with it. The title is set to "ccc".
On line 19 the same call to helpItem.getHelpDescription() returns the description field of the "bbb" object.
When moving through the list via a ViewPager the next object in the list has the same issue until I reach the end of the list,
where the correct helpDescription field is displayed. I can also move back to the start of the list and it will display the correct
helpDescription, but this is then lost when I move forward and backward through the list again.
Any ideas why this is happening? Thanks.
public class HelpFragment extends Fragment {
private HelpItem helpItem;
private TextView mHelpDetails;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
UUID helpItemId = (UUID) getArguments().getSerializable(EXTRA_HELP_ITEM_ID);
helpItem = HelpList.get(getActivity()).getHelpItem(helpItemId);
getActivity().setTitle(helpItem.getHelpDescription());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View userView = inflater.inflate(R.layout.fragment_help_item, parent, false);
mHelpDetails = (TextView) userView.findViewById(R.id.help_details);
String displayInfo = "";
if ((helpItem.getHelpDescription() != null) &&
(helpItem.getHelpInformation() != null)) {
displayInfo = helpItem.getHelpDescription() + "\n\n\n" +
helpItem.getHelpInformation();
mHelpDetails.setText(displayInfo);
Log.d(TAG, "3 " + helpItem.getHelpDescription() + " "
+ helpItem.getHelpInformation());
}
return userView;
}
}
..
public class HelpItem {
private UUID mId;
private String helpDescription;
private String helpInformation;
public HelpItem(String hDesc, String hInfo) {
mId = UUID.randomUUID();
helpDescription = hDesc;
helpInformation = hInfo;
}
public UUID getId() {
return mId;
}
public void setId(UUID id) {
mId = id;
}
#Override
public String toString() {
return helpDescription;
}
public String getHelpDescription() {
return helpDescription;
}
public void setHelpDescription(String hDescription) {
this.helpDescription = hDescription;
}
public String getHelpInformation() {
return helpInformation;
}
public void setHelpInformation(String hInformation) {
this.helpInformation = hInformation;
}
}
..
public class HelpListItemPagerActivity extends FragmentActivity {
private ViewPager mViewPager;
private ArrayList<HelpItem> mHelpList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.viewPager);
setContentView(mViewPager);
mHelpList = HelpList.get(this).getHelpList();
FragmentManager fragManager = getSupportFragmentManager();
mViewPager.setAdapter(new FragmentStatePagerAdapter(fragManager) {
#Override
public int getCount() {
return mHelpList.size();
}
#Override
public Fragment getItem(int position) {
HelpItem hItem = mHelpList.get(position);
return HelpFragment.newInstance(hItem.getId());
}
});
UUID helpItemId = (UUID)getIntent().getSerializableExtra(HelpFragment.EXTRA_HELP_ITEM_ID);
for (int i = 0; i < mHelpList.size(); i++) {
if (mHelpList.get(i).getId().equals(helpItemId)) {
mViewPager.setCurrentItem(i);
break;
}
}
}
}

Categories

Resources