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.
Related
I am building an app which has a RecyclerView which holds Objects that are retrieved from SharedPreferences.
Unfortunately the RecyclerView is lagging when it is binded.
This is my Adapter
public class ShiftAdapter extends RecyclerView.Adapter<ShiftAdapter.ViewHolder>{
private List<Shift> mDataSet;
private Context mContext;
private static final String TAG = "ShiftAdapter";
public int previousExpandedPosition = -1;
public int mExpandedPosition = -1;
private static SharedPreferences mPrefs;
private LinearLayout mShiftIn;
private LinearLayout mShiftOut;
private Boolean isStart;
private Date shiftIn;
private Date shiftOut;
private Date mDate;
public EditText mshiftInText;
public EditText mshiftOutText;
public Date date;
public ShiftAdapter(Context context, List<Shift> list) {
mDataSet = list;
mContext = context;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mDate;
public TextView mTime;
public TextView mPay;
public RelativeLayout mRelativeLayout;
public LinearLayout mExepandableLayout;
public Date mshiftIn;
public Date mshiftOut;
public EditText mshiftInText;
public EditText mshiftOutText;
public Button mUpdateButton;
public Button mDeleteButton;
public ViewHolder(View v) {
super(v);
mDate = (TextView) v.findViewById(R.id.date_TV);
mTime = (TextView) v.findViewById(R.id.time_TV);
mPay = (TextView) v.findViewById(R.id.pay_TV);
mRelativeLayout = (RelativeLayout) v.findViewById(R.id.rel_layout);
mExepandableLayout = (LinearLayout) v.findViewById(R.id.expandableLayout);
mshiftInText = (EditText) v.findViewById(R.id.setShiftIn);
mshiftOutText = (EditText) v.findViewById(R.id.setShiftOut);
mUpdateButton = (Button) v.findViewById(R.id.updateButton);
mDeleteButton = (Button) v.findViewById(R.id.deleteButton);
}
}
#Override
public ShiftAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(mContext)
.inflate(R.layout.shift, parent, false);
ViewHolder vh = new ViewHolder(itemView);
return vh;
}
//TODO:Bind all the view elements to Shift Properties
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int i) {
// Format double
String hours = new DecimalFormat("##.##").format(mDataSet.get(i).getHours());
String pay = new DecimalFormat("##.##").format(mDataSet.get(i).getPay());
//set the Text
holder.mTime.setText(hours);
holder.mDate.setText(mDataSet.get(i).dateToString());
holder.mPay.setText(pay);
Log.d(TAG, "onBindViewHolder: called");
// new AsyncTask<>().ex
//Expand mExapndableLayout
final int position = i;
final boolean isExpanded = position ==mExpandedPosition;
holder.mExepandableLayout.setVisibility(isExpanded?View.VISIBLE:View.GONE);
holder.itemView.setActivated(isExpanded);
// //set shift Times
// shiftIn = mDataSet.get(position).getInDate();
// shiftOut = mDataSet.get(position).getInDate();
if (isExpanded)
previousExpandedPosition = position;
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mExpandedPosition = isExpanded ? -1:position;
notifyItemChanged(previousExpandedPosition);
notifyItemChanged(position);
}
});
//fill expandable layout
holder.mshiftInText.setText(mDataSet.get(position).fullTimeToString(0));
final EditText in = holder.mshiftInText;
final EditText out = holder.mshiftOutText;
//edit mShiftIn Text
holder.mshiftInText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
isStart =true;
timePickerDialog(in,out);
}
});
holder.mshiftOutText.setText(mDataSet.get(position).fullTimeToString(1));
//edit MshiftOut Text
holder.mshiftOutText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
isStart =false;
timePickerDialog(in,out);
}
});
//updateButton onClick
holder.mUpdateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
shiftIn = mDataSet.get(position).getInDate();
shiftOut = mDataSet.get(position).getOutDate();
if(Validate.getValidate().isDateValid(shiftIn,shiftOut)) {
SharedPrefs.getInstance(mContext).editShift(newShift(shiftIn, shiftOut),Integer.toString(position));
int length = SharedPrefs.getInstance(mContext).getLength() - 1;
if (SharedPrefs.getInstance(mContext).getShift(length) != null) {
Log.d(TAG, "Edit Shift onClick: Success");
SharedPrefs.getInstance(mContext).saveShiftList(SharedPrefs.getInstance(mContext).sortList(SharedPrefs.getInstance(mContext).getShiftList()));
ShiftsFragment.updateUI();
Toast.makeText(mContext, "success", Toast.LENGTH_SHORT).show();
}
} else {
mShiftOut.setBackgroundResource(R.drawable.red_border);
Toast.makeText(mContext, "error", Toast.LENGTH_SHORT).show(); }
} catch(Exception e){
Log.d(TAG, "onDateSelected: "+e.toString());
Toast.makeText(mContext,"update FAIL", Toast.LENGTH_SHORT).show();
}
// update the Shift
}
});
holder.mDeleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
areYouSure(mExpandedPosition);
}
});
}
#Override
public int getItemCount() {
return mDataSet.size();
}
public Date timePickerDialog(EditText in,EditText out) {
mshiftInText = in;
mshiftOutText = out;
new SingleDateAndTimePickerDialog.Builder(mContext)
.title(mContext.getResources().getString(R.string.choose_time))
.displayListener(new SingleDateAndTimePickerDialog.DisplayListener() {
#Override
public void onDisplayed(SingleDateAndTimePicker picker) {
if(!isStart) {
date = mDate;
}
}
}).defaultDate(returnDate(date))
.listener(new SingleDateAndTimePickerDialog.Listener() {
#Override
public void onDateSelected(Date date) {
mDate = date;
if (isStart) {
updateShiftIn(mDate);
mshiftInText.setText(dateToString(mDate));
} else {
updateShiftOut(mDate);
mshiftOutText.setText(dateToString(mDate));
}
}
}).display();
return mDate;
}
public String dateToString(Date date)
{
DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm");
String string = df.format(date);
return string;
}
private void updateShiftIn(Date date) {
shiftIn = date;
}
private void updateShiftOut(Date date) {
shiftOut = date;
}
private Date returnDate(Date date)
{
if(date!=null)
{
return date;
}
else return mDate;
}
private void areYouSure(int i)
{
final String position = Integer.toString(i);
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
Log.d(TAG, "onClick: isSure=true;");
SharedPrefs.getInstance(mContext).removeShift(position);
ShiftsFragment.updateUI();
case DialogInterface.BUTTON_NEGATIVE:
Log.d(TAG, "onClick: isSure= false");
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage(mContext.getResources().getString(R.string.are_you_sure)).setPositiveButton(mContext.getResources().getString(R.string.confirm), dialogClickListener)
.setNegativeButton(mContext.getResources().getString(R.string.cancel), dialogClickListener).show();
}
private Shift newShift(Date start,Date stop)
{
int id = SharedPrefs.getInstance(mContext).getLength();
Shift shift = new Shift(dateToCalendar(start),dateToCalendar(stop),id);
return shift;
}
and this is the Fragment that has the RecyclerView
public class ShiftsFragment extends Fragment {
private Toolbar mToolbar;
private TimePicker timePicker1;
private List<Shift> shiftList = new ArrayList<>();
private RecyclerView recyclerView;
private RelativeLayout relativeLayout;
private RecyclerView.LayoutManager layoutManager;
private LinearLayout mShiftIn;
private LinearLayout mShiftOut;
private Context mContext;
private ShiftAdapter mAdapter;
private MenuItem mAdd;
private Menu optionsMenu;
private LinearLayout mShiftAddLL;
private SharedPreferences mPrefs;
private static FragmentManager mFragmentManager;
private static final String TAG = "ShiftsFragment";
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.d(TAG,"Clicked");
final View view = inflater.inflate(R.layout.shifts_layout,container,false);
mToolbar = view.findViewById(R.id.topbar);
mToolbar.inflateMenu(R.menu.toolbarmenu);
mShiftAddLL = view.findViewById(R.id.add_shiftLayout);
mAdd = mToolbar.getMenu().getItem(0);
timePicker1 = (TimePicker) view.findViewById(R.id.timePicker);
mFragmentManager = getFragmentManager();
//TODO:Add a summary bar on the bottom.
//get the context
mContext = getContext();
recyclerView = (RecyclerView) view.findViewById(R.id.shift_list);
// Define a layout for RecyclerView
layoutManager = new GridLayoutManager(mContext,1);
recyclerView.setLayoutManager(layoutManager);
// Initialize a new Shift array
List<Shift> shiftList = initShifts();
Log.d(TAG,"shift array initiated");
// Initialize an array list from array
// Initialize a new instance of RecyclerView Adapter instance
mAdapter = new ShiftAdapter(mContext,shiftList);
// Set the adapter for RecyclerView
recyclerView.setAdapter(mAdapter);
recyclerView.setNestedScrollingEnabled(false);
recyclerView.setHasFixedSize(true);
//Menu add button onClick
//Opens Add_Shift_Fragment
mAdd.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
Fragment selectedFragment = new Add_Shift_Fragment();
getFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return false;
}
});
return view;
}
//Initializes the Shift list from SharedPreferences and returns it.
private List<Shift> initShifts() {
return SharedPrefs.getInstance(mContext).getShiftList();
}
public static void updateUI()
{
Fragment selectedFragment = new ShiftsFragment();
mFragmentManager.beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
}
}
Everytime i launch the ShiftsFragment there are some frame skips, and the scrolling is choppy and laggy.
Maybe my SharedPreferences handling is what is slowing things down?
public class SharedPrefs {
private static SharedPrefs mSharedPrefs;
private SharedPreferences mPrefs;
private SharedPreferences.Editor mPrefsEditor;
protected Context mContext;
public static final String ID = "shiftList";
private SharedPrefs(Context context) {
mContext = context;
mPrefs = context.getSharedPreferences(ID, Context.MODE_PRIVATE);
mPrefsEditor = mPrefs.edit();
}
public static SharedPrefs getInstance(Context context) {
if (mSharedPrefs == null) {
mSharedPrefs = new SharedPrefs(context.getApplicationContext());
}
return mSharedPrefs;
}
public void saveShiftList(List<Shift> shiftList) {
Gson gson = new Gson();
String json = gson.toJson(shiftList);
mPrefsEditor.putString(ID, json);
mPrefsEditor.apply();
}
public void addShift (Shift shift)
{
List<Shift> shiftList= getShiftList();
shiftList.add(shift);
saveShiftList(shiftList);
}
//Replaced the shift#id with shift
public void editShift(Shift shift,String id)
{
removeShift(id);
addShift(shift);
}
public void removeShift(String id) {
List<Shift> shiftList = getShiftList();
int pos = Integer.parseInt(id);
shiftList.remove(pos);
saveShiftList(shiftList);
}
public void removeShift(int id) {
List<Shift> shiftList = getShiftList();
shiftList.remove(id);
saveShiftList(shiftList);
}
public Shift getShift(int id) {
Gson gson = new Gson();
List<Shift> shiftList;
String json = mPrefs.getString(ID, null);
Type type = new TypeToken<List<Shift>>() {
}.getType();
shiftList = gson.fromJson(json, type);
Shift shift = shiftList.get(id);
return shift;
}
public List<Shift> getShiftList() {
Gson gson = new Gson();
List<Shift> shiftList;
String json = mPrefs.getString(ID, null);
Type type = new TypeToken<List<Shift>>() {
}.getType();
shiftList = gson.fromJson(json, type);
if (shiftList!=null) {
return shiftList;
} else{
shiftList = new ArrayList<>();
return shiftList;
}
}
public List<Shift> sortList(List<Shift> shiftList)
{
Collections.sort(shiftList, new Comparator<Shift>() {
public int compare(Shift shift1, Shift shift2) {
if (shift1.getShiftStart() == null || shift2.getShiftStart() == null)
return 0;
return shift1.getShiftStart().compareTo(shift2.getShiftStart());
}
});
return shiftList;
}
public int getLength()
{
return getShiftList().size();
}
}
I have only found this problem with image loading, not just Strings from Object from SharedPrefs.
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);
}
}
});
i'm trying to pass a bundle from a product detail activity to a cart with a recycle view but when i click on add to cart the cart is opened but remains empty i don't know what's wrong with the code
here is the first activity
public class product_details extends AppCompatActivity {
ImageView product_img, share;
TextView name, price;
public int img;
public int price1;
public String name1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_details);
product_img = (ImageView) findViewById(R.id.Product_Img);
name = (TextView) findViewById(R.id.product_name);
price = (TextView) findViewById(R.id.product_price);
share = (ImageView) findViewById(R.id.share);
img = getIntent().getIntExtra("img", 00);
Glide.with(this).load(img).into(product_img);
name1 = getIntent().getStringExtra("name");
name.setText(name1);
price1 = getIntent().getIntExtra("price", 0);
price.setText(String.valueOf(price1));
ImageView cart = (ImageView) findViewById(R.id.add_cart);
cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), CartActivity.class);
Bundle extras = new Bundle();
extras.putString("price1", String.valueOf((price1)));
extras.putString("name1", name1);
extras.putString("img1",String.valueOf(img));
intent.putExtras(extras);
startActivity(intent);
}
my second activity class
public class CartRecycler {
int images_id;
String productname,productprice,productquantity;
public String getProductquantity() {
return productquantity;
}
public CartRecycler(int images_id , String productname , String productprice , String productquantity){
this.setImages_id(images_id);
this.setProductname(productname);
this.setProductprice(productprice);
this.setProductquantity(productquantity);
}
public CartRecycler(String productname, int images_id, String productprice) {
this.productname = productname;
this.images_id = images_id;
this.productprice = productprice;
}
public int getImages_id() {
return images_id;
}
public void setImages_id(int images_id) {
this.images_id = images_id;
}
public String getProductname() {
return productname;
}
public void setProductname(String productname) {
this.productname = productname;
}
public String getProductprice() {
return productprice;
}
public void setProductprice(String productprice) {
this.productprice = productprice;
}
public void setProductquantity(String productquantity) {
this.productquantity = productquantity;
}
}
cart adapter
public class CartAdapter extends RecyclerView.Adapter<CartAdapter.CartViewHolder> {
ArrayList<CartRecycler> adapterlist = new ArrayList<>();
CartActivity cartactivity;
Context cnx;
public CartAdapter(ArrayList<CartRecycler> adapterlist,Context cnx){
this.adapterlist =adapterlist;
this.cnx =cnx;
cartactivity = (CartActivity) cnx;
}
#Override
public CartViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_cards,parent,false);
CartViewHolder cartviewholder = new CartViewHolder(v,cartactivity);
return cartviewholder;
}
#Override
public void onBindViewHolder(CartViewHolder holder, int position) {
holder.image.setImageResource(adapterlist.get(position).getImages_id());
holder.name.setText(adapterlist.get(position).getProductname());
holder.price.setText(adapterlist.get(position).getProductprice());
holder.quantity.setText(adapterlist.get(position).getProductquantity());
if(!cartactivity.edit_mode){
holder.checkornot.setVisibility(View.GONE);
}
else {
holder.checkornot.setVisibility(View.VISIBLE);
holder.checkornot.setChecked(false);
}
}
#Override
public int getItemCount() {
return adapterlist.size();
}
public static class CartViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView image;
TextView price,quantity,name;
CheckBox checkornot;
CartActivity cartactivity;
CardView cardv;
public CartViewHolder(View itemView, CartActivity cartactivity) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.cartimage);
name = (TextView) itemView.findViewById(R.id.pn);
price = (TextView) itemView.findViewById(R.id.p);
quantity = (TextView) itemView.findViewById(R.id.q);
checkornot = (CheckBox) itemView.findViewById(R.id.ckbox);
this.cartactivity= cartactivity;
cardv = (CardView) itemView.findViewById(R.id.cardd);
cardv.setOnLongClickListener((View.OnLongClickListener) cartactivity);
checkornot.setOnClickListener(this);
}
#Override
public void onClick(View view) {
cartactivity.prepareselection(view,getAdapterPosition());
}
}
public void updateadapter(ArrayList<CartRecycler> list){
for(CartRecycler cartRecycler:list){
adapterlist.remove(cartRecycler);
}
notifyDataSetChanged();
}
}
second activity
public class CartActivity extends AppCompatActivity implements View.OnLongClickListener{
Button l;
ImageView imv;
Toolbar t;
RecyclerView rv;
RecyclerView.LayoutManager layoutmanager;
RecyclerView.Adapter adapter;
ArrayList<CartRecycler> cartitems = new ArrayList<>();
ArrayList<CartRecycler> selected_items_list = new ArrayList<>();
int countt =0;
boolean edit_mode =false;
TextView counterr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
t = (Toolbar) findViewById(R.id.toolb);
setSupportActionBar(t);
getSupportActionBar().setDisplayShowTitleEnabled(false);
l = (Button) findViewById(R.id.checkoutsummary);
l.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent n = new Intent(CartActivity.this,SummaryActivity.class);
startActivity(n);
}
});
rv = (RecyclerView) findViewById(R.id.mycartrecycler);
layoutmanager = new LinearLayoutManager(this);
rv.setLayoutManager(layoutmanager);
rv.setHasFixedSize(true);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String price = extras.getString("price1");
String img1 = extras.getString("img1");
int imag1 = Integer.parseInt(img1);
String name = extras.getString("name1");
for (int i = 0; i < cartitems.size(); i++) {
CartRecycler cart = new CartRecycler(name, imag1, price);
cartitems.add(cart);
adapter.notifyDataSetChanged();
i++;
}
} else {
Intent intent = new Intent(this, test.class);
startActivity(intent);
}
adapter = new CartAdapter(cartitems,CartActivity.this);
rv.setAdapter(adapter);
counterr = (TextView) findViewById(R.id.selecteditemcounter);
counterr.setVisibility(View.GONE);
}
#Override
public boolean onLongClick(View view) {
t.getMenu().clear();
t.inflateMenu(R.menu.cart_edit_mode);
counterr.setVisibility(View.VISIBLE);
edit_mode = true;
adapter.notifyDataSetChanged();
return true;
}
public void prepareselection(View view,int position){
if(((CheckBox)view).isChecked()){
selected_items_list.add(cartitems.get(position));
countt = countt+1;
updatecounter(countt);
}
else {
selected_items_list.remove(cartitems.get(position));
countt = countt -1;
updatecounter(countt);
}
}
public void updatecounter(int counter){
if(counter==0){
counterr.setText("0 items selected");
}
else {
counterr.setText(counter+" item selected");
}
}
public boolean onOptionsItemSelected(MenuItem item){
if(item.getItemId()==R.id.item_delete){
CartAdapter cartAdapter = (CartAdapter) adapter;
cartAdapter.updateadapter(selected_items_list);
}
else if(item.getItemId()== android.R.id.home)
{
adapter.notifyDataSetChanged();
}
return true;
}
}
for (int i = 0; i < cartitems.size(); i++) This loop will not run until and unless size of cartitems is greater than 0 and hence all the code under it's scope will never get executed
I have two activities, one shows the movie list, and the other shows movie details. I have a shared element transition on a movie's poster. It works fine when I use with linearlayoutmanager, but when I use a gridLayoutManager for the recyclerView, after I press back button get back from the detail activity, the other image becomes blank as shown here.image
In this picture, I clicked on x-men's movie poster, but the image next to it becomes blank.
I have set a unique transitionName for every item. It's probably not the reason.
this is my activity
public class MainActivity extends AppCompatActivity implements MovieGridAdapter.OnItemClickListener {
private MovieGridAdapter mAdapter;
private int mPosition;
private Toolbar mToolbar;
private RecyclerView mMovieGridLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().register(this);
PreferenceManager.setDefaultValues(this, R.xml.pref_general, false);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
mMovieGridLayout = (RecyclerView) findViewById(R.id.movie_grid);
GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
mMovieGridLayout.setLayoutManager(gridLayoutManager);
mAdapter = new MovieGridAdapter();
mAdapter.setOnItemClickListener(this);
mMovieGridLayout.setAdapter(mAdapter);
}
#Override
protected void onStart() {
super.onStart();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String sortBy = sharedPreferences.getString(getString(R.string.sort_by_key), getString(R.string.popularity));
MoviePuller.getMoviePuller().discoverMovies(sortBy);
}
#Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent intent = new Intent(this, SettingActivity.class);
startActivity(intent);
return true;
} else if (id == R.id.action_refresh) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String sortBy = sharedPreferences.getString(getString(R.string.sort_by_key), getString(R.string.popularity));
MoviePuller.getMoviePuller().discoverMovies(sortBy);
}
return super.onOptionsItemSelected(item);
}
#Subscribe
public void onPullSuccessEvent(Integer eventId) {
if (eventId == EventId.PULL_SUCCESS) {
mAdapter.notifyDataSetChanged();
}
}
#Override
public void onItemClick(View v, int position) {
mPosition = position;
Intent intent = new Intent(this, MovieDetailActivity.class);
ImageView imageView = (ImageView) v.findViewById(R.id.poster);
TextView title = (TextView) v.findViewById(R.id.title);
ActivityOptionsCompat scaleUpAnimationOptions = createScaleUpAnimationOptions(imageView,title);
intent.putExtra(Constants.POSITION, position);
ActivityCompat.startActivity(this, intent, scaleUpAnimationOptions.toBundle());
}
private ActivityOptionsCompat createScaleUpAnimationOptions(View view, View view2) {
Pair<View,String> pair = new Pair<>(view,view.getTransitionName());
Pair<View,String> pair2 = new Pair<>(view2,view2.getTransitionName());
Pair<View,String> pair3 = new Pair<View, String>(mToolbar,mToolbar.getTransitionName());
// View statusBar = getWindow().getDecorView().findViewById(android.R.id.navigationBarBackground);
// Pair<View,String> pair4 = new Pair<>(statusBar, ViewCompat.getTransitionName(statusBar));
return ActivityOptionsCompat.makeSceneTransitionAnimation(this,pair,pair2,pair3);
}
}
this is my adapter
public class MovieGridAdapter extends RecyclerView.Adapter<MovieGridAdapter.MyHolder> {
private JSONArray mMovies;
private OnItemClickListener mOnItemClickListener;
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
CardView cardView = (CardView) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_movie, parent, false);
return new MyHolder(cardView,mOnItemClickListener);
}
#Override
public void onBindViewHolder(MyHolder holder, int position) {
holder.bind(position);
}
#Override
public int getItemCount() {
mMovies = MoviePuller.getMovies();
if (mMovies != null) {
return mMovies.length();
}
return 0;
}
public interface OnItemClickListener {
void onItemClick(View v, int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mOnItemClickListener = listener;
}
class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView mPoster;
public TextView mTitle;
private OnItemClickListener mOnItemClickListener;
public MyHolder(View itemView, OnItemClickListener listener) {
super(itemView);
mOnItemClickListener = listener;
mTitle = (TextView) itemView.findViewById(R.id.title);
mPoster = (ImageView) itemView.findViewById(R.id.poster);
itemView.setOnClickListener(this);
}
public void bind(int position) {
if (mMovies != null) {
try {
JSONObject movie = mMovies.getJSONObject(position);
String title = movie.getString(Constants.KEY_TITLE);
String posterPath = movie.getString(Constants.KEY_POSTER_PATH);
Picasso.with(itemView.getContext()).
load(MoviePuller.POSTER_BASE_URL + posterPath).into(mPoster);
mPoster.setTransitionName(itemView.getResources().getString(R.string.transition_poster) + position);
mTitle.setText(title);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(v, getAdapterPosition());
}
}
}
}
this is my detail activity
public class MovieDetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_moviedetail);
Slide slide = new Slide(Gravity.BOTTOM);
slide.addTarget(R.id.divider);
slide.addTarget(R.id.vote_average);
slide.addTarget(R.id.release_date);
slide.addTarget(R.id.plot_synopsis);
slide.addTarget(R.id.rating);
slide.addTarget(R.id.divider1);
getWindow().setEnterTransition(slide);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
ImageView poster = (ImageView) findViewById(R.id.poster);
TextView tvTitle = (TextView) findViewById(R.id.title);
RatingBar voteAverage = (RatingBar) findViewById(R.id.vote_average);
TextView tvReleaseDate = (TextView) findViewById(R.id.release_date);
TextView tvPlotSynopsis = (TextView) findViewById(R.id.plot_synopsis);
TextView tvRating = (TextView) findViewById(R.id.rating);
int position = getIntent().getIntExtra(Constants.POSITION, -1);
poster.setTransitionName(getString(R.string.transition_poster) + position);
JSONArray movies = MoviePuller.getMovies();
if(movies != null && movies.length() > position) {
try {
JSONObject movie = movies.getJSONObject(position);
String title = movie.getString(Constants.KEY_TITLE);
String poster_path = movie.getString(Constants.KEY_POSTER_PATH);
String release_date = movie.getString(Constants.KEY_RELEASE_DATE);
String vote_average = movie.getString(Constants.KEY_VOTE_AVERAGE);
String overview = movie.getString(Constants.KEY_OVERVIEW);
String id = movie.getString(Constants.KEY_ID);
MoviePuller.getMoviePuller().getTrailers(id);
MoviePuller.getMoviePuller().getReviews(id);
toolbar.setTitle(title);
setSupportActionBar(toolbar);
Picasso.with(this).load(MoviePuller.POSTER_BASE_URL+poster_path).into(poster);
tvTitle.setText(title);
tvReleaseDate.setText(release_date);
tvPlotSynopsis.setText(overview);
voteAverage.setRating(Float.parseFloat(vote_average)/2);
tvRating.setText(vote_average);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Subscribe
public void onEvent(EventId eventId){
if(eventId.mId == EventId.GET_TRAILER_SUCCESS){
JSONArray trailerArray = (JSONArray) eventId.mEventObject;
}else if(eventId.mId == EventId.GET_REVIEW_SUCCESS){
JSONArray reviewArray = (JSONArray) eventId.mEventObject;
}
}
}
the recyclerView xml is like this
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".activities.MainActivity"
tools:showIn="#layout/activity_main">
<android.support.v7.widget.RecyclerView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/movie_grid"/>
</RelativeLayout>
What should i do to avoid this?
i record a gif
I guess the problem is with the way you are passing positions of the views between DetailActivity and the MainActivity.
In MainActivity onItemClick() method replace this
intent.putExtra(Constants.POSITION, position);
with this
Bundle bundle = new Bundle();
bundle.putInt(Constants.POSITION, position);
intent.putExtras(bundle);
And in DetailActivity replace this
int position = getIntent().getIntExtra(Constants.POSITION, -1);
with this
int position = getIntent().getExtras().getInt(Constants.POSITION);
Also, what is itemView in MyHolder class, bind() method. You need to pass context to the adapter and use that.
Create this constructor in MovieGridAdapter :
public MovieGridAdapter(Context context) {
this.context = context;
}
and In bind() method replace occurences of itemView:
Picasso.with(context).load(MoviePuller.POSTER_BASE_URL + posterPath).into(mPoster);
mPoster.setTransitionName(context.getString(R.string.transition_poster) + position);
Initialize MovieGridAdapter in MainActivity in this way:
mAdapter = new MovieGridAdapter(this);
I am having some trouble with my app, I am trying to develop a list app that you have the option to add new "Goals" to as well as new lists so that you can categorize goals to a list like the list object title can be "Eat healthy" and then you'll have goals inside like "Eat more vegetables", etc. So in order to do this I have set up a ViewPagerHost class that grabs all the List objects from a SQLite database and initializes a factory developed "List fragment" that handles all the logic of adding a goal, editing and deleting, etc. I believe I've gotten this to work correctly because everything on the database side seems to work fine, and then the other classes are just supposed to display and manipulate that information. But everything on the display side seems to be going wrong. I have each view in the recyclerview display a star next to any goal marked as "important" or "life changing" but it displays the star wherever it wants. Also the list does not load until I've click on something.
public class ViewPagerHost extends Activity_Logger {
private static final String ARG_TITLE = "title";
private ViewPager mViewPager;
private ArrayList<Fragment> mFragmentList;
private ArrayList<GoalList> goalList;
private ArrayList<Goal> goalArrayList;
Database_Controller controller;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_pager_host);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
MobileAds.initialize(getApplicationContext(), "ad-String");
AdView adView = (AdView) findViewById(R.id.ad);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
setSupportActionBar(toolbar);
toolbar.setTitle("Ambition");
FragmentManager fragmentManager = getSupportFragmentManager();
controller = Database_Controller.get(getApplicationContext());
goalList = controller.getAllLists();
goalArrayList = controller.getAllGoals();
mViewPager = (ViewPager)findViewById(R.id.view_fragments);
if(goalList.get(0) == null){
GoalList listOne = new GoalList();
listOne.setTitle("DEFAULT");
controller.insertList(listOne);
for(int i =0; i< goalArrayList.size(); i++){
goalArrayList.get(i).setWhich_List(listOne.getTitle());
controller.updateGoal(goalArrayList.get(i));
}
}
mFragmentList = getFragmentList(goalList);
ViewPagerAdapter adapter = new ViewPagerAdapter(fragmentManager, mFragmentList);
if(adapter == null){
}else{
mViewPager.setAdapter(adapter);
}
}
public ArrayList<Fragment> getFragmentList(ArrayList<GoalList> list){
mFragmentList = new ArrayList<>();
Bundle bundle = new Bundle();
for(int i = 0; i< list.size(); i++){
List_Fragment list_fragment = new List_Fragment();
bundle.putString(ARG_TITLE, goalList.get(i).getTitle());
list_fragment.setArguments(bundle);
mFragmentList.add(list_fragment);
}
return mFragmentList;
}
}
Here is my ViewPagerHost class that creates the factory list.
public class List_Fragment extends Fragment {
private RecyclerView mRecyclerView;
private static final String ARG_TITLE = "title";
private static final String ARG_GOALNAME ="Goal";
private static final String ARG_IMPORTANT = "Important";
private Database_Controller mDatabaseController;
private static final String ARG_ID = "ID";
ArrayList<Goal> goalList;
LinearLayoutManager manager;
public RecyclerView.Adapter adapter;
public ReceiverThread UiThread;
FragmentManager fragmentManager;
String list_title;
public List_Fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_list_, container, false);
Bundle bundle = getArguments();
if(bundle != null){
list_title= bundle.getString(ARG_TITLE);
}
mDatabaseController = mDatabaseController.get(getContext());
goalList = mDatabaseController.getAllListsGoals(list_title);
mRecyclerView = (RecyclerView)view.findViewById(R.id.recyclerview);
manager = new LinearLayoutManager(getActivity());
UiThread = new ReceiverThread();
mRecyclerView.setLayoutManager(manager);
final RecyclerView_Adapter wrapperClass = new RecyclerView_Adapter(goalList,getContext(),this);
adapter = wrapperClass.adapter;
for(int counter =0; counter < goalList.size(); counter++){
System.out.println(goalList.get(counter).getWhich_List());
}
mRecyclerView.setAdapter(adapter);
fragmentManager= getFragmentManager();
//adapter goes here
final FloatingActionButton fab = (FloatingActionButton)view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment fragment = List_Fragment.this;
AddNew_PopUp popUp = AddNew_PopUp.newInstance(fragment);
popUp.setTargetFragment(fragment, 0);
popUp.show(fragmentManager, "PopUpDialog");
}
});
return view;
}
public class ReceiverThread extends Thread {
#Override
public void run() {
super.run();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
goalList.clear();
ArrayList<Goal>newGoalList = mDatabaseController.getAllGoals();
goalList.addAll(newGoalList);
adapter.notifyDataSetChanged();
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 0){
if(resultCode == Activity.RESULT_OK){
Goal newGoal = new Goal();
String GoalName = data.getStringExtra(ARG_GOALNAME);
if (GoalName.isEmpty()) {
Toast.makeText(getContext(), R.string.NoGoal, Toast.LENGTH_SHORT).show();
} else {
newGoal.setmIsImportant(data.getBooleanExtra(ARG_IMPORTANT, false));
newGoal.setmGoalName(GoalName);
newGoal.setWhich_List(ARG_TITLE);
mDatabaseController.insertGoal(newGoal);
}
}
}else{
if(requestCode == 1){
if(resultCode == Activity.RESULT_OK){
String id = data.getStringExtra(ARG_ID);
Toast.makeText(getContext(),R.string.flush, Toast.LENGTH_LONG).show();
mDatabaseController.deleteGoal(id);
}
}else{
if(requestCode == 2){
if(resultCode == Activity.RESULT_OK){
String goalName = data.getStringExtra(ARG_GOALNAME);
Boolean isImportant = data.getBooleanExtra(ARG_IMPORTANT, false);
UUID id = UUID.fromString(data.getStringExtra(ARG_ID));
Goal goal = mDatabaseController.getGoal(id.toString());
goal.setmIsImportant(isImportant);
goal.setmGoalName(goalName);
mDatabaseController.updateGoal(goal);
}
}
}
}
UiThread.run();
}
public ReceiverThread getUiThread() {
return UiThread;
}
}
This is the list fragment that is created for every list in the database. It calls methods and manipulates data based off the user's actions.
public class RecyclerView_Adapter{
private ArrayList<Goal> mGoals;
MyAdapter adapter;
Context context;
private Database_Controller mDatabaseController;
MediaPlayer mediaPlayer;
Fragment fragment;
public RecyclerView_Adapter(ArrayList<Goal> goals, Context cntxt, Fragment fragments) {
mGoals = goals;
adapter = new MyAdapter(mGoals);
context = cntxt;
mediaPlayer = new MediaPlayer();
fragment = fragments;
mDatabaseController = Database_Controller.get(context);
}
//////////////////////////////////ADAPTER\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
private class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
private List<Goal> mGoals;
public MyAdapter(List<Goal> goals) {
mGoals = goals;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.recycler_view_item_layout, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final Goal goal = mGoals.get(position);
holder.bindGoal(goal);
}
#Override
public int getItemCount() {
return mGoals.size();
}
}
////////////////////////////////////ADAPTER\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
///////////////////////////////////VIEW HOLDER\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView mTextView, importantTXT;
private CheckBox mCheckBox;
private Goal mGoal;
private ImageView imgView;
public MyViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AppCompatActivity context = (AppCompatActivity) v.getContext();
FragmentManager manager = context.getSupportFragmentManager();
Edit_PopUp dialog = Edit_PopUp.newInstance(mGoal);
dialog.setTargetFragment(fragment, 2);
dialog.show(manager, "EditDialog");
}
});
itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
//Add delete thingy
AppCompatActivity context = (AppCompatActivity) v.getContext();
FragmentManager manager = context.getSupportFragmentManager();
MoreOptions_PopUp dialog = MoreOptions_PopUp.newInstance(mGoal);
dialog.setTargetFragment(fragment, 1);
dialog.show(manager, "GoalDialog");
return true;
}
});
mTextView = (TextView) itemView.findViewById(R.id.text);
mCheckBox = (CheckBox) itemView.findViewById(R.id.checkbox);
imgView = (ImageView) itemView.findViewById(R.id.imageView);
importantTXT = (TextView) itemView.findViewById(R.id.Important_textView);
mCheckBox.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
mGoal.setFinished(mCheckBox.isChecked());
mDatabaseController.updateGoal(mGoal);
if (mCheckBox.isChecked() == true) {
boolean value = checkWinning(mGoals,context);
PlaySound(value, mGoal.ismIsImportant(), v);
}
}
});
}
public void bindGoal(Goal goal) {
mGoal = goal;
mCheckBox.setChecked(mGoal.isFinished());
mTextView.setText(mGoal.getmGoalName());
if (mGoal.ismIsImportant()) {
imgView.setImageResource(R.mipmap.ic_stars_pressed);
importantTXT.setText(R.string.isImportant);
}
}
public boolean checkWinning(ArrayList<Goal> goals, Context context) {
for (int i = 0; i < goals.size(); i++) {
if (goals.get(i).isFinished() == false) {
return false;
}
}
return true;
}
public void PlaySound(Boolean winningSound, boolean isImportant, View view) {
if(winningSound){
mediaPlayer = MediaPlayer.create(context,R.raw.victory);
Snackbar snackbar = Snackbar.make(view, R.string.completion, Snackbar.LENGTH_LONG);
snackbar.show();
mediaPlayer.start();
}else {
if (isImportant) {
mediaPlayer = MediaPlayer.create(context, R.raw.collect);
mediaPlayer.start();
Snackbar snackbar = Snackbar.make(view, R.string.congrats, Snackbar.LENGTH_SHORT);
snackbar.show();
} else {
mediaPlayer = MediaPlayer.create(context, R.raw.success);
Snackbar snackbar = Snackbar.make(view, R.string.lessCongrats, Snackbar.LENGTH_SHORT);
snackbar.show();
mediaPlayer.start();
}
}
}
}
////////////////////////////////////VIEW HOLDER\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
public MyAdapter getAdapter() {
return adapter;
}
public Fragment getFragment() {
return fragment;
}
}
Here is my adapter class that plays sounds OnClick and binds the view to the Recyclerview.
Any help would be greatly appreciated!
The problem with the stars displayed in every row will be caused because you might be setting them when needed but not hiding them when not needed.
You will have to implement something like this in the getView() method of your adapter.
ImageView starView = (ImageView) v.findViewById(R.id.starView);
starView.setVisibility(goals.get(position).isSpecial() ? View.Visible : View.Gone);