Imageview turns blank, when used with gridLayoutManager in recyclerView - android

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);

Related

recycle view won't recieve a bundle data

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

Change the Icon of a Button in a Recycler View in Adapter Class Based off boolean value

I'm trying to change the icon of a button in my recycler view every time the activity starts based off a boolean value in my custom object. I assume this has to be done within the adapter since not every groups button will have the same background.
Below is the code for my recycler view adapter:
public class RecipeListAdapter extends RecyclerView.Adapter<RecipeListAdapter.ViewHolder>{
private List<Recipe> mRecipeSet;
private Button mAddToGroceriesButton;
public RecipeListAdapter(List<Recipe> recipes){
mRecipeSet = recipes;
}
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//This is what will handle what happens when you click a recipe in the recycler view
private TextView mRecipeName;
private TextView mPrepTime;
private TextView mCookTime;
private TextView mServingSize;
private RelativeLayout mRecipeTextSection;
public ViewHolder(View v) {
super(v);
mRecipeName = (TextView) v.findViewById(R.id.recipe_list_recycler_view_recipe_name);
mServingSize = (TextView) v.findViewById(R.id.recipe_list_recycler_view_serving_size);
mPrepTime = (TextView) v.findViewById(R.id.recipe_list_recycler_view_prep_time);
mCookTime = (TextView) v.findViewById(R.id.recipe_list_recycler_view_cook_time);
mRecipeTextSection = (RelativeLayout) v.findViewById(R.id.recycled_item_section_view);
mRecipeTextSection.setOnClickListener(this);
mAddToGroceriesButton = (Button) v.findViewById(R.id.add_to_grocery_list);
mAddToGroceriesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
Recipe recipeToGrocery = mRecipeSet.get(position);
//RecipeDB dbHelper = new RecipeDB(v.getContext());
//dbHelper.addGroceryItem(recipeToGrocery);
if(!recipeToGrocery.isInList()) {
RecipeDB dbHelper = new RecipeDB(v.getContext());
dbHelper.addGroceryItem(recipeToGrocery);
recipeToGrocery.setInList(true);
dbHelper.updateRecipe(recipeToGrocery);
mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_24dp);
Toast.makeText(v.getContext(), recipeToGrocery.getRecipeName() + " added to grocery list.", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(v.getContext(), "That recipe is already in the list.", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onClick(View v){
int position = getAdapterPosition();
Intent i = new Intent(v.getContext(), RecipeTextView.class);
Recipe selectedRecipe = mRecipeSet.get(position);
i.putExtra("view_recipe_key", selectedRecipe);
v.getContext().startActivity(i);
}
}
public void add(int position, Recipe item) {
mRecipeSet.add(position, item);
notifyItemInserted(position);
}
public void remove(Recipe item) {
int position = mRecipeSet.indexOf(item);
mRecipeSet.remove(position);
notifyItemRemoved(position);
}
public RecipeListAdapter(ArrayList<Recipe> myRecipeset) {
mRecipeSet = myRecipeset;
}
// Create new views (invoked by the layout manager)
#Override
public RecipeListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recipe_item_recycled, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Recipe recipe = mRecipeSet.get(position);
String recipeName = recipe.getRecipeName();
String prepTime = "Prep Time: " + String.valueOf(recipe.getPrepTime()) + " minutes";
String cookTime = "Cook Time: " + String.valueOf(recipe.getCookTime()) + " minutes";
String servingSize = "Servings: " + String.valueOf(recipe.getServings());
holder.mRecipeName.setText(recipeName);
//Only display values if they are not null
if(recipe.getServings() != null) {
holder.mServingSize.setText(servingSize);
}
if (recipe.getPrepTime() != null) {
holder.mPrepTime.setText(prepTime);
}
if(recipe.getCookTime() != null) {
holder.mCookTime.setText(cookTime);
}
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
if(mRecipeSet != null) {
return mRecipeSet.size();
}
return 0;
}
}
I know how to change the background of the button when it's clicked with
mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_24dp);
but it's obviously not going to save the state of that button when the activity restarts. I'm just not sure of how to check the boolean value for each group upon activity start up and change the button background accordingly.
I tried using
if(recipe.isInList()){
mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_24dp);
}
in the onBindViewHolder method but it didn't do anything, and I'm pretty sure that wouldn't be the correct place for it anyways. I know the boolean is working properly since I use it in other places and it works fine.
Here's the relevant XML code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/apk/res/android"
android:layout_margin="7dp"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:id="#+id/recycled_item_section_view"
android:elevation="30dp"
android:background="#drawable/background_border"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="Recipe name"
android:textSize="24dp"
android:textColor="#color/black"
android:id="#+id/recipe_list_recycler_view_recipe_name"
android:paddingBottom="3dp"
android:maxWidth="275dip"
android:singleLine="false"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18dp"
android:textColor="#color/black"
android:layout_below="#id/recipe_list_recycler_view_recipe_name"
android:id="#+id/recipe_list_recycler_view_serving_size"
android:paddingBottom="3dp"/>
<Button
android:layout_width="35dp"
android:layout_height="35dp"
android:background="#mipmap/ic_playlist_add_black_24dp"
android:height="36dp"
android:padding="8dp"
android:layout_alignParentRight="true"
android:id="#+id/add_to_grocery_list"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/recipe_list_recycler_view_serving_size"
android:layout_alignParentLeft="true"
android:textSize="18dp"
android:textColor="#color/black"
android:id="#+id/recipe_list_recycler_view_prep_time"
android:paddingBottom="3dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/recipe_list_recycler_view_prep_time"
android:textSize="18dp"
android:textColor="#color/black"
android:layout_alignParentLeft="true"
android:id="#+id/recipe_list_recycler_view_cook_time"/>
</RelativeLayout>
Recipe class:
public class Recipe implements Parcelable {
//These are all of the qualities a recipe contains, we will create an arraylist of this in the activity
private String mRecipeName;
private int mID;
private String mServings;
private String mPrepTime;
private String mCookTime;
private boolean isInList;
private List<String> mIngredients;
private List<String> mDirections;
public Recipe(){
}
public Recipe(int id, String name, String serving, String prep, String cook, List<String>
ingredientsList, List<String> directionsList, boolean inList){
this.mID = id;
this.mRecipeName = name;
this.mServings = serving;
this.mPrepTime = prep;
this.mCookTime = cook;
this.mIngredients = ingredientsList;
this.mDirections = directionsList;
this.isInList = inList;
}
public Recipe(String name, String serving, String prep, String cook, List<String>
ingredientsList, List<String> directionsList, boolean inList){
this.mRecipeName = name;
this.mServings = serving;
this.mPrepTime = prep;
this.mCookTime = cook;
this.mIngredients = ingredientsList;
this.mDirections = directionsList;
this.isInList = inList;
}
public String getRecipeName() {
return mRecipeName;
}
public int getID() {
return mID;
}
public void setID(int id){
mID = id;
}
public String getServings() {
return mServings;
}
public String getPrepTime() {
return mPrepTime;
}
public void setRecipeName(String recipeName) {
mRecipeName = recipeName;
}
public void setServingSize(String servings) {
mServings = servings;
}
public void setPrepTime(String prepTime) {
mPrepTime = prepTime;
}
public void setServings(String servings) {
mServings = servings;
}
public List<String> getIngredients() {
return mIngredients;
}
public List<String> getDirections() {
return mDirections;
}
public String getCookTime() {
return mCookTime;
}
public void setCookTime(String cookTime) {
mCookTime = cookTime;
}
public void setIngredients(List<String> ingredients) {
mIngredients = ingredients;
}
public void setDirections(List<String> directions) {
mDirections = directions;
}
public boolean isInList() {
return isInList;
}
public void setInList(boolean inList) {
isInList = inList;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.mRecipeName);
dest.writeInt(this.mID);
dest.writeString(this.mServings);
dest.writeString(this.mPrepTime);
dest.writeString(this.mCookTime);
dest.writeByte(this.isInList ? (byte) 1 : (byte) 0);
dest.writeStringList(this.mIngredients);
dest.writeStringList(this.mDirections);
}
protected Recipe(Parcel in) {
this.mRecipeName = in.readString();
this.mID = in.readInt();
this.mServings = in.readString();
this.mPrepTime = in.readString();
this.mCookTime = in.readString();
this.isInList = in.readByte() != 0;
this.mIngredients = in.createStringArrayList();
this.mDirections = in.createStringArrayList();
}
public static final Creator<Recipe> CREATOR = new Creator<Recipe>() {
#Override
public Recipe createFromParcel(Parcel source) {
return new Recipe(source);
}
#Override
public Recipe[] newArray(int size) {
return new Recipe[size];
}
};
}
And main activity class that uses the adapter:
public class RecipeList extends AppCompatActivity{
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private int REQUEST_CODE=1;
private Button mNavigateGroceryButton;
RecipeDB dbHelper = new RecipeDB(this);
List<Recipe> recipes;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
recipes = dbHelper.getAllRecipes();
setContentView(R.layout.activity_recipe_list);
mRecyclerView = (RecyclerView) findViewById(R.id.list_recycler_view);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new RecipeListAdapter(recipes);
mRecyclerView.setAdapter(mAdapter);
mNavigateGroceryButton = (Button) findViewById(R.id.navigate_to_groceries_button_list_view);
mNavigateGroceryButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent i = new Intent(RecipeList.this, ExpandableListViewActivity.class);
//Log.d("Navigate", "navigate pressed" );
startActivity(i);
}
});
}
#Override
public void onBackPressed() {
}
public boolean onOptionsItemSelected(MenuItem item){
//Handles menu buttons
switch (item.getItemId()){
case R.id.recipe_list_add_recipe_actionbar_button:
//This button creates a new empty Recipe object and passes it to the EditRecipe class
//The Recipe object is passed as a parcelable
Recipe passedRecipe = new Recipe();
Intent i = new Intent(RecipeList.this, EditRecipe.class);
i.putExtra("passed_recipe_key", (Parcelable) passedRecipe);
startActivityForResult(i, REQUEST_CODE);
return true;
default:
Log.d("Name,", "default called");
return super.onOptionsItemSelected(item);
}
}
public void addNewReRecipe(Recipe recipe){
dbHelper.addRecipe(recipe);
recipes = dbHelper.getAllRecipes();
mAdapter = new RecipeListAdapter(recipes);
mRecyclerView.setAdapter(mAdapter);
}
//Makes the menu bar appear as it is in the action_bar_recipe_list_buttons menu layout file
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_bar_recipe_list_buttons, menu);
return true;
}
//This code is called after creating a new recipe. This is only for creating, and not editing.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE){
if(resultCode == Activity.RESULT_OK) {
Recipe createdRecipe = data.getExtras().getParcelable("recipe_key");
addNewReRecipe(createdRecipe);
}
}
}
}
Looks like you need to declare your button at the top of your ViewHolder with your other views. So move the declaration from the top of your adapter:
private Button mAddToGroceriesButton;
Then in your onBindViewHolder method you can get a reference to your button through the holder and set the background:
if(recipe.isInList()) {
holder.mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_24dp);
}
Try this,
public class RecipeListAdapter extends RecyclerView.Adapter<RecipeListAdapter.ViewHolder>{
private List<Recipe> mRecipeSet;
private Button mAddToGroceriesButton;
public RecipeListAdapter(List<Recipe> recipes){
mRecipeSet = recipes;
}
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//This is what will handle what happens when you click a recipe in the recycler view
private TextView mRecipeName;
private TextView mPrepTime;
private TextView mCookTime;
private TextView mServingSize;
private RelativeLayout mRecipeTextSection;
public ViewHolder(View v) {
super(v);
mRecipeName = (TextView) v.findViewById(R.id.recipe_list_recycler_view_recipe_name);
mServingSize = (TextView) v.findViewById(R.id.recipe_list_recycler_view_serving_size);
mPrepTime = (TextView) v.findViewById(R.id.recipe_list_recycler_view_prep_time);
mCookTime = (TextView) v.findViewById(R.id.recipe_list_recycler_view_cook_time);
mRecipeTextSection = (RelativeLayout) v.findViewById(R.id.recycled_item_section_view);
mAddToGroceriesButton = (Button) v.findViewById(R.id.add_to_grocery_list);
}
}
public void add(int position, Recipe item) {
mRecipeSet.add(position, item);
notifyItemInserted(position);
}
public void remove(Recipe item) {
int position = mRecipeSet.indexOf(item);
mRecipeSet.remove(position);
notifyItemRemoved(position);
}
public RecipeListAdapter(ArrayList<Recipe> myRecipeset) {
mRecipeSet = myRecipeset;
}
// Create new views (invoked by the layout manager)
#Override
public RecipeListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recipe_item_recycled, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Recipe recipe = mRecipeSet.get(position);
String recipeName = recipe.getRecipeName();
String prepTime = "Prep Time: " + String.valueOf(recipe.getPrepTime()) + " minutes";
String cookTime = "Cook Time: " + String.valueOf(recipe.getCookTime()) + " minutes";
String servingSize = "Servings: " + String.valueOf(recipe.getServings());
holder.mRecipeName.setText(recipeName);
//Only display values if they are not null
if(recipe.getServings() != null) {
holder.mServingSize.setText(servingSize);
}
if (recipe.getPrepTime() != null) {
holder.mPrepTime.setText(prepTime);
}
if(recipe.getCookTime() != null) {
holder.mCookTime.setText(cookTime);
}
mRecipeTextSection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
Intent i = new Intent(v.getContext(), RecipeTextView.class);
Recipe selectedRecipe = mRecipeSet.get(position);
i.putExtra("view_recipe_key", selectedRecipe);
v.getContext().startActivity(i);
});
Recipe recipeToGrocery = mRecipeSet.get(position);
if(!recipeToGrocery.isInList()) {
mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_24dp);
}
else{
mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_26dp);//set another image
}
mAddToGroceriesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
Recipe recipeToGrocery = mRecipeSet.get(position);
//RecipeDB dbHelper = new RecipeDB(v.getContext());
//dbHelper.addGroceryItem(recipeToGrocery);
if(!recipeToGrocery.isInList()) {
RecipeDB dbHelper = new RecipeDB(v.getContext());
dbHelper.addGroceryItem(recipeToGrocery);
recipeToGrocery.setInList(true);
dbHelper.updateRecipe(recipeToGrocery);
notifyDataSetChanged();
}
else {
Toast.makeText(v.getContext(), "That recipe is already in the list.", Toast.LENGTH_SHORT).show();
}
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
if(mRecipeSet != null) {
return mRecipeSet.size();
}
return 0;
}
}

how to make Textview scrollable and also make it swipeable in android

I want to make TextView swipeable and also scrollable as above image.
below is my code , TextView is in adapter and swipe functionality in activity.
public class MsgSwipActivity extends Base {
private static final String TAG = "MainActivity";
private SwipeDeck swipe_deck;
private ImageView imgThank;
private Toolbar toolbar;
private AdView mAdView;
private int page_no = 1;
private SwipMsgAdapter adapter;
private ArrayList<MsgListData> msgListDatas;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.msgswip);
swipe_deck = (SwipeDeck) findViewById(R.id.swipe_deck);
mAdView = (AdView) findViewById(R.id.adView);
imgThank = (ImageView) findViewById(R.id.imgThank);
imgThank.setVisibility(View.GONE);
MobileAds.initialize(MsgSwipActivity.this, getString(R.string.banner_home_footer));
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
mAdView.loadAd(adRequest);
// Start loading the ad in the background.
toolbar = (Toolbar) findViewById(R.id.toolbar);
swipe_deck.setHardwareAccelerationEnabled(true);
msgList();
msgListDatas = new ArrayList<>();
adapter = new SwipMsgAdapter(MsgSwipActivity.this, R.layout.rowmsg_item, msgListDatas);
swipe_deck.setAdapter(adapter);
swipe_deck.setEventCallback(new SwipeDeck.SwipeEventCallback() {
#Override
public void cardSwipedLeft(int position) {
Log.i("MainActivity", "card was swiped left, position in adapter: " + position);
}
#Override
public void cardSwipedRight(int position) {
Log.i("MainActivity", "card was swiped right, position in adapter: " + position);
}
#Override
public void cardsDepleted() {
page_no = page_no + 1;
msgList();
msgListDatas = new ArrayList<>();
adapter = new SwipMsgAdapter(MsgSwipActivity.this, R.layout.rowmsg_item, msgListDatas);
swipe_deck.setAdapter(adapter);
Log.i("MainActivity", "no more cards");
}
#Override
public void cardActionDown() {
Log.i(TAG, "cardActionDown");
}
#Override
public void cardActionUp() {
Log.i(TAG, "cardActionUp");
}
});
}
}
public void msgList() {
String id = getIntent().getStringExtra("ID");
String cat_id = getIntent().getStringExtra("CATID");
VLogger.infoLog(cat_id);
if (Utility.checkInternetConnection(this)) {
RetrofitClient.getInstance().getRestOkClient().
msgSticky("ListingShayariSingle",
cat_id,
((VApp) getApplicationContext()).getCheck()
, id, String.valueOf(page_no), callback);
} else {
Toast.makeText(MsgSwipActivity.this, "No Intetnet please try again", Toast.LENGTH_SHORT).show();
}
}
private final retrofit.Callback callback = new retrofit.Callback() {
#Override
public void success(Object object, Response response) {
MsgList msgList = (MsgList) object;
if (msgList.getData() != null) {
for (int i = 0; i < msgList.getData().size(); i++) {
MsgListData item = new MsgListData();
item.setId(msgList.getData().get(i).getId());
item.setReg_date(msgList.getData().get(i).getReg_date());
item.setStatus(msgList.getData().get(i).getStatus());
item.setDetails(msgList.getData().get(i).getDetails());
item.setCategory(msgList.getData().get(i).getCategory());
item.setLanguage(msgList.getData().get(i).getLanguage());
item.setColor_code(msgList.getData().get(i).getColor_code());
getSupportActionBar().setTitle(msgList.getData().get(i).getC_name().toString());
msgListDatas.add(item);
}
adapter.setGridData(msgListDatas);
} else {
imgThank.setVisibility(View.VISIBLE);
}
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(MsgSwipActivity.this, "Server Error", Toast.LENGTH_SHORT).show();
}
};
}
and here is my adapter
public class SwipMsgAdapter extends ArrayAdapter<MsgListData>{
private ArrayList<MsgListData> rowDatas;
private Context context;
private int layoutResourceId;
public EditText edtSave;
public String image_Id;
private boolean checked;
Uri bmpUri;
private ImageView imgFav, imgCopy, imgFb, imgShare, imgHike;
private ImageView imgWhatsapp;
private TextView imgMain;
private View positiveAction;
CallbackManager callbackManager;
ShareDialog shareDialog;
public SwipMsgAdapter(Context context, int layoutResourceId, ArrayList<MsgListData> rowDatas) {
super(context, layoutResourceId, rowDatas);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.rowDatas = rowDatas;
}
public void setGridData(ArrayList<MsgListData> rowDatas) {
this.rowDatas = rowDatas;
notifyDataSetChanged();
}
#Override
public int getCount() {
return rowDatas.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
FacebookSdk.sdkInitialize(context.getApplicationContext());
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// normally use a viewholder
v = inflater.inflate(R.layout.rowmsg_item, parent, false);
}
callbackManager = CallbackManager.Factory.create();
shareDialog = new ShareDialog((Activity) context);
imgMain = (TextView) v.findViewById(R.id.imgMain);
imgFav = (ImageView) v.findViewById(R.id.imgFav);
imgCopy = (ImageView) v.findViewById(R.id.imgCopy);
imgHike = (ImageView) v.findViewById(R.id.imgHike);
imgWhatsapp = (ImageView) v.findViewById(R.id.imgWhatsapp);
imgFb = (ImageView) v.findViewById(R.id.imgFb);
imgShare = (ImageView) v.findViewById(R.id.imgShare);
CardView card_view = (CardView) v.findViewById(R.id.card_view);
int color = Color.parseColor(rowDatas.get(position).getColor_code());
card_view.setCardBackgroundColor(color);
image_Id = rowDatas.get(position).getId();
imgMain.setText(rowDatas.get(position).getDetails());
VLogger.infoLog("IMAGE" + String.valueOf(bmpUri));
RetrofitClient.getInstance().getRestOkClient().
checkMsgFavorite("AvailableFavoritText", VPreferences.getPreferanceDeviceID(context)
, rowDatas.get(position).getId(), checkCallback);
};
how can i implement both functionality scroll and swipe?
Scrollable TextView: Put the TextView as the child of a ScrollView.
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</ScrollView>
Remember that a ScrollView can only hold ONE object.
For Gestures, look at Detecting Common Gestures
EDIT:
You can also use this line of code in the XML and see if it works (with the textview):
android:scrollbars="vertical"
Put your textview inside scrollview in xml. Then make it "swipeable" programmatically. Stackoverflow is telling me that my answer does not meet their quality standards.

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.

EditText not working in RecyclerView Adapter. Random Data is displayed on device

Im currently making an app that takes movie name as input from user, after that input a new screen will be displayed showing list items of movie, the list of that movie is shown from "http://www.omdbapi.com/" just like IMDB. On clicking any list item(movie name) details of that movie will be shown in another screen, everything was working fine before getting input, I hard code the movie name before but now i want user to give inout but I think there's a problem in Edit Text I'm unable to get input from user.
MainActivity Class
public class MainActivity extends AppCompatActivity {
private static String LOG_TAG = MainActivity.class.getSimpleName();
private EditText editText;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validateInput();
}
});
}
private void validateInput() {
String input = editText.getText().toString();
if (input != null || !input.equals("")) {
Intent intent = new Intent(this, MovieFragment.class);
intent.putExtra(Intent.EXTRA_TEXT, input);
startActivity(intent);
}
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.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 action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#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_main, 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);
}
MovieFragment Class
public class MovieFragment extends Fragment implements OnNetworkCallHandled, RecyclerViewAdapter.OnClickListener {
private String movieName;
private Button button;
private RecyclerViewAdapter adapter;
private RecyclerView recyclerView;
private EditText editText;
private DataWrapper list;
public MovieFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Intent intent = getActivity().getIntent();
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
movieName = intent.getStringExtra(Intent.EXTRA_TEXT);
((TextView) rootView.findViewById(R.id.detail_text)).setText(movieName);
}
getMovieDetails();
return rootView;
}
private void getMovieDetails() {
MovieTask movieAsyncTask = new MovieTask(this, movieName);
movieAsyncTask.execute();
}
#Override
public void onNetworkcallSuccess(Object object) {
System.out.println("On success");
String result = (String) object;
Gson gson = new Gson();
list = gson.fromJson(result, DataWrapper.class);
adapter = new RecyclerViewAdapter(list.getSearch(), getContext(), this);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(adapter);
System.out.println("On success");
}
#Override
public void onNetworkcallFailure(Object object) {
System.out.println("On failure");
}
#Override
public void onClick(View view, int position, long itemId) {
startActivity(position);
System.out.println();
}
private void startActivity(int position) {
Intent intent = new Intent(getActivity(), DetailActivity.class);
Bundle extras = new Bundle();
extras.putString("Title",list.getSearch().get(position).getTitle());
extras.putString("Year", list.getSearch().get(position).getYear());
intent.putExtras(extras);
startActivity(intent);
}
}
DetailActivity Class
public class DetailActivity extends AppCompatActivity {
private TextView Title;
private TextView Year;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
Title = (TextView) findViewById(R.id.Title);
Year = (TextView) findViewById(R.id.Year);
if (intent != null) {
String title = extras.getString("Title");
String year=extras.getString("Year");
Title.setText(title);
Year.setText(year);
System.out.println();
}
}
#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_main, menu);
return true;
}
}
MovieTask extending AsyncTask Class
public class MovieTask extends AsyncTask<Void, Void, String> {
private String LOG_TAG = MovieTask.class.getSimpleName();
private String response = "";
private String movieName;
private OnNetworkCallHandled onNetworkCallHandled;
public MovieTask(OnNetworkCallHandled onNetworkCallHandled, String movieName) {
this.onNetworkCallHandled = onNetworkCallHandled;
this.movieName = movieName;
}
#Override
protected String doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String MovieJsonStr = null;
try {
final String MOVIE_BASE_URL = "http://www.omdbapi.com/?";
final String s = "s";
final String plot = "plot";
final String r = "r";
final String page = "page";
Uri builtUri = Uri.parse(MOVIE_BASE_URL).buildUpon()
.appendQueryParameter(s, movieName)
.appendQueryParameter(plot, "full")
.appendQueryParameter(r, "json")
.appendQueryParameter(page, "1")
.build();
URL url = new URL(builtUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
response = buffer.toString();
} catch (Exception e) {
}
return response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null || !result.equals("")) {
onNetworkCallHandled.onNetworkcallSuccess(result);
} else {
onNetworkCallHandled.onNetworkcallFailure(true);
}
}
}
RecyclerViewAdapter class
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MovieDetailsHolder> {
private ArrayList<MovieDetails> movieDetails;
private Context context;
private OnClickListener onClick;
RecyclerViewAdapter(ArrayList<MovieDetails> movieDetails, Context context, OnClickListener onClick) {
this.onClick = onClick;
this.movieDetails = movieDetails;
this.context = context;
}
#Override
public MovieDetailsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view, parent, false);
return new MovieDetailsHolder(view);
}
#Override
public void onBindViewHolder(MovieDetailsHolder holder, final int position) {
holder.tVMovieName.setText(movieDetails.get(position).getTitle());
Picasso
.with(context)
.load(movieDetails.get(position).getPoster())
.into(holder.iVPoster);
holder.setOnClickListener(onClick);
}
#Override
public int getItemCount() {
return movieDetails.size();
}
public static class MovieDetailsHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private OnClickListener onClickListener;
CardView cv;
TextView tVMovieName;
ImageView iVPoster;
MovieDetailsHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.cardView);
tVMovieName = (TextView) itemView.findViewById(R.id.tVMovieName);
iVPoster = (ImageView) itemView.findViewById(R.id.iVPoster);
itemView.setOnClickListener(this);
}
public void setOnClickListener(OnClickListener onClickListener) {
this.onClickListener = onClickListener;
}
#Override
public void onClick(View v) {
onClickListener.onClick(v, getPosition(), getItemId());
}
}
public interface OnClickListener {
public void onClick(View view, int position, long itemId);
}
}
You are treating MovieFragment as an activity
Intent intent = new Intent(this, MovieFragment.class);
intent.putExtra(Intent.EXTRA_TEXT, input);
startActivity(intent);
But MovieFragment is a fragment. You need to add/replace the MovieFragment in your activity.
Also, there is no need to setContentView(R.layout.activity_main); again in validateInput()

Categories

Resources