Recyclerview not scrolling to saved position after screen rotation - java

Hi I want to save Recylerview scroll position when screen rotates so that Recyclerview scrolls to that position before user sees screen.
I have tried every possible solution so far for similar questions but nothing is working. I am using GridLayoutManager with Recyclerview and displaying grid list of movies using JSON data.
Please have a look!!
MainActivity:
public class MainActivity extends AppCompatActivity implements
SharedPreferences.OnSharedPreferenceChangeListener {
private RecyclerView recyclerView;
private ArrayList<Movie> movieList;
MovieAdapter adapter;
private final String KEY_RECYCLER_STATE = "recycler_state";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
movieList = new ArrayList<>();
adapter = new MovieAdapter(this, movieList);
/*
if (getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
}
*/
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
recyclerView.setAdapter(adapter);
checkSort();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(KEY_RECYCLER_STATE, recyclerView.getLayoutManager().onSaveInstanceState());
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if(savedInstanceState != null)
{
Parcelable savedRecyclerLayoutState = savedInstanceState.getParcelable(KEY_RECYCLER_STATE);
recyclerView.getLayoutManager().onRestoreInstanceState(savedRecyclerLayoutState);
}
}
public Activity getActivity() {
Context context = this;
while (context instanceof ContextWrapper) {
if (context instanceof Activity) {
return (Activity) context;
}
context = ((ContextWrapper) context).getBaseContext();
}
return null;
}
private void JSONMostPopularMovie() {
try {
if (BuildConfig.THE_MOVIE_DB_API_TOKEN.isEmpty()) {
Toast.makeText(getApplicationContext(), "There Is No API Key!", Toast.LENGTH_SHORT).show();
return;
}
MovieApi movieapi = new MovieApi();
MovieService apiService = MovieApi.getClient().create(MovieService.class);
Call<MovieResponse> call = apiService.getPopularMovies(BuildConfig.THE_MOVIE_DB_API_TOKEN);
call.enqueue(new Callback<MovieResponse>() {
#Override
public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) {
ArrayList<Movie> movies = response.body().getResults();
adapter.setMovies(movies);
Toast.makeText(MainActivity.this, "Displaying By Most Popular Movies", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<MovieResponse> call, Throwable t) {
Log.d("Error", "" + t.getMessage());
Toast.makeText(MainActivity.this, "Error Fetching Data! And Internet Connection", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
Log.d("Error", e.getMessage());
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
}
private void JSONTopRateMovie() {
try {
if (BuildConfig.THE_MOVIE_DB_API_TOKEN.isEmpty()) {
Toast.makeText(getApplicationContext(), "There Is No API Key", Toast.LENGTH_SHORT).show();
return;
}
MovieApi movieapi = new MovieApi();
MovieService apiService = MovieApi.getClient().create(MovieService.class);
Call<MovieResponse> call = apiService.getTopRatedMovies(BuildConfig.THE_MOVIE_DB_API_TOKEN);
call.enqueue(new Callback<MovieResponse>() {
#Override
public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) {
ArrayList<Movie> movies = response.body().getResults();
adapter.setMovies(movies);
Toast.makeText(MainActivity.this, "Displaying By Top Rated Movies", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<MovieResponse> call, Throwable t) {
Log.d("Error", "" + t.getMessage());
Toast.makeText(MainActivity.this, "Error Fetching Data! And Internet Connection", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
Log.d("Error", e.getMessage());
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
Intent setting = new Intent(this, MovieSettings.class);
startActivity(setting);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
checkSort();
}
private void checkSort() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String sortOrder = preferences.getString(
this.getString(R.string.pref_sort_order_key),
this.getString(R.string.pref_most_popular)
);
if (sortOrder.equals(this.getString(R.string.pref_most_popular))) {
Log.d(LOG_TAG, "Sorting by most popular");
JSONMostPopularMovie();
} else if (sortOrder.equals(this.getString(R.string.top_rated))) {
Log.d(LOG_TAG, "Sorting by top rated");
JSONTopRateMovie();
}
}
}
Adapter:
public class MovieAdapter extends
RecyclerView.Adapter<MovieAdapter.MyViewHolder> {
private Context mContext;
private ArrayList<Movie> movieList;
public MovieAdapter(Context mContext, ArrayList<Movie> movieList) {
this.mContext = mContext;
this.movieList = movieList;
}
#Override
public MovieAdapter.MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.movie_item, viewGroup, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final MovieAdapter.MyViewHolder viewHolder, int i) {
viewHolder.title.setText(movieList.get(i).getOriginalTitle());
String vote = Double.toString(movieList.get(i).getVoteAverage());
viewHolder.userrating.setText(vote);
String poster = "https://image.tmdb.org/t/p/w185/" + movieList.get(i).getPosterPath();
Picasso.with(mContext)
.load(poster)
.into(viewHolder.thumbnail);
}
#Override
public int getItemCount() {
return movieList.size();
}
public void setMovies(ArrayList<Movie> movies){
this.movieList = movies;
notifyDataSetChanged();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, userrating;
public ImageView thumbnail;
public MyViewHolder(final View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
userrating = (TextView) view.findViewById(R.id.userrating);
thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
Intent intent = new Intent(mContext, MovieDetail.class);
intent.putExtra("movie", movieList.get(position));
intent.putExtra("id", movieList.get(position).getId());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
}
}
});
}
}
}

Related

remain same position like button in recyclerview android

I set the like button in the recycler view but when I click on the like button in a different position so it comes back to the top of the class how can I make it the same situation when I click other place in the recycler view
here is the image
https://i.stack.imgur.com/Nh0PQ.jpg
public class SocialFragment extends Fragment
Toolbar toolbar;
RecyclerView post_rv;
List<PostModel> list;
PostAdapter adapter;
public SocialFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle saved instance state) {
// Inflate the layout for this fragment
View view inflater.inflate(R.layout.fragment_social, container, false);
toolbar = view.findViewById(R.id.social_header);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
ActionBar actionBar = activity.getSupportActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayUseLogoEnabled(true);
post_rv = view.findViewById(R.id.post_rv);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setStackFromEnd(true);
linearLayoutManager.setReverseLayout(true);
post_rv.setLayoutManager(linearLayoutManager);
list = new ArrayList<>();
loadPost();
return view;
}
private void loadPost() {
DatabaseReference database reference = FirebaseDatabase.getInstance().getReference("Posts");
database reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
list.clear();
for (DataSnapshot ds: snapshot.getChildren())
{
PostModel postModel = ds.getValue(PostModel.class);
list.add(postModel);
adapter = new PostAdapter(getActivity(),list);
post_rv.setAdapter(adapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(getActivity(), ""+error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void searchPost(String searchQuary){
DatabaseReference database reference = FirebaseDatabase.getInstance().getReference("Posts");
database reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
list.clear();
for (DataSnapshot ds: snapshot.getChildren())
{
PostModel postModel = ds.getValue(PostModel.class);
if (postModel.getuName().toLowerCase().contains(searchQuary.toLowerCase()) || postModel.getpDesc().toLowerCase().contains(searchQuary.toLowerCase()))
{
list.add(postModel);
}
adapter = new PostAdapter(getActivity(),list);
post_rv.setAdapter(adapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(getActivity(), ""+error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
inflater.inflate(R.menu.search_menu,menu);
MenuItem item = menu.findItem(R.id.search_users);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
if (!TextUtils.isEmpty(query))
{
searchPost(query);
}else {
loadPost();
}
return false;
}
#Override
public boolean onQueryTextChange(String query) {
if (!TextUtils.isEmpty(query))
{
searchPost(query);
}else {
loadPost();
}
return false;
}
});
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id==R.id.post_add){
Intent intent = new Intent(getActivity(),AddPostActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
Adapter
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
Context context;
List<PostModel> postList;
String myUid;
private DatabaseReference likeRef;
private DatabaseReference postRef;
boolean mProcessLikes = false;
public PostAdapter(Context context, List<PostModel> postList) {
this.context = context;
this.postList = postList;
myUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
likeRef = FirebaseDatabase.getInstance().getReference().child("Likes");
postRef = FirebaseDatabase.getInstance().getReference().child("Posts");
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.social_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final String uid = postList.get(position).getUid();
String uName = postList.get(position).getuName();
String uEmail = postList.get(position).getuEmail();
String dp = postList.get(position).getDp();
final String pId = postList.get(position).getpId();
String pDesc = postList.get(position).getpDesc();
final String pImage = postList.get(position).getpImage();
String pTime = postList.get(position).getpTime();
String pLike = postList.get(position).getpLikes();
String pComments = postList.get(position).getpComments();
Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
calendar.setTimeInMillis(Long.parseLong(pTime));
String dateTime = DateFormat.format("dd/MM/yyyy hh:mm aa", calendar).toString();
holder.user_post_name.setText(uName);
holder.user_post_desc.setText(pDesc);
holder.user_post_time.setText(dateTime);
holder.count_likes.setText(pLike + "Likes");
holder.count_comments.setText(pComments + "Comments");
holder.user_post_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, FullScreenImage.class);
intent.putExtra("url",postList.get(position).getpImage());
context.startActivity(intent);
}
});
setLikes(holder, pId);
try {
Picasso.get().load(dp).placeholder(R.drawable.profile).into(holder.user_post_dp);
} catch (Exception e) {
Picasso.get().load(R.drawable.profile).placeholder(R.drawable.profile).into(holder.user_post_dp);
e.printStackTrace();
}
if (pImage.equals("noImage")) {
holder.user_post_image.setVisibility(View.GONE);
} else {
holder.user_post_image.setVisibility(View.VISIBLE);
try {
Picasso.get().load(pImage).into(holder.user_post_image);
} catch (Exception e) {
e.printStackTrace();
}
}
holder.likeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int pLike = Integer.parseInt(postList.get(position).getpLikes());
mProcessLikes = true;
String postIde = postList.get(position).getpId();
likeRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (mProcessLikes) {
if (snapshot.child(postIde).hasChild(myUid)) {
posted.child(postIde).child("likes").setValue("" + (like - 1));
like.child(postIde).child(myUid).removeValue();
mProcessLikes = false;
} else {
postRef.child(postIde).child("pLikes").setValue("" + (pLike + 1));
likeRef.child(postIde).child(myUid).setValue("Liked");
mProcessLikes = false;
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
holder.commentBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, PostDetailActivity.class);
intent.putExtra("postId", pId);
context.startActivity(intent);
}
});
holder.shareBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) holder.user_post_image.getDrawable();
if (bitmapDrawable==null)
{ //share without image
sharedTextOnly(press);
}else {
// share with image
Bitmap bitmap = bitmapDrawable.getBitmap();
shareImageAndText(pDesc,bitmap);
}
}
});
holder.profileLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, UserProfileActivity.class);
intent.putExtra("uid", uid);
context.startActivity(intent);
}
});
holder.morebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showMoreButtonOption(holder.morebtn, uid, myUid, pId, pImage);
}
});
}
private void sharedTextOnly(String pDesc) {
String shareBody = pDesc;
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT,"Subject here");
intent.putExtra(Intent.EXTRA_TEXT,shareBody);
context.startActivity(Intent.createChooser(intent,"Share Via"));
}
private void shareImageAndText(String pDesc, Bitmap bitmap) {
String shareBody = pDesc;
Uri uri = savedImageToShare(bitmap);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM,uri);
intent.putExtra(Intent.EXTRA_TEXT,shareBody);
intent.putExtra(Intent.EXTRA_SUBJECT,"Subject here");
intent.setType("image/png");
context.startActivity(Intent.createChooser(intent,"Share Via"));
}
private Uri savedImageToShare(Bitmap bitmap) {
File imageFolder = new File(context.getCacheDir(),"images");
Uri uri = null;
try {
imageFolder.mkdirs();
File file = new File(imageFolder,"share_image.png");
FileOutputStream stream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG,90,stream);
stream.flush();
stream.close();
uri = FileProvider.getUriForFile(context,"com.example.fire_safety.fileprovider",file);
} catch (Exception e) {
Toast.makeText(context, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
return URI;
}
private void setLikes(final ViewHolder myHolder, final String postKey) {
likeRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.child(postKey).hasChild(myUid)) {
myHolder.likeBtn.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like_iocn, 0, 0, 0);
myHolder.likeBtn.setText("Liked");
} else {
myHolder.likeBtn.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like_black, 0, 0, 0);
myHolder.likeBtn.setText("Like");
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void showMoreButtonOption(ImageButton morebtn, String uid, String myUid, String pId, String pImage) {
PopupMenu popupMenu = new PopupMenu(context, morebtn, Gravity.END);
if (uid.equals(myUid)) {
popupMenu.getMenu().add(Menu.NONE, 0, 0, "Delete");
// popupMenu.getMenu().add(Menu.NONE, 1, 0, "Edit");
}
popupMenu.getMenu().add(Menu.NONE, 1, 0, "View Details");
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
int id = menuItem.getItemId();
if (id == 0) {
beginDelete(pId, pImage);
} else if (id == 1) {
Intent intent = new Intent(context, PostDetailActivity.class);
intent.putExtra("postId", pId);
context.startActivity(intent);
}
return false;
}
});
popupMenu.show();
}
private void beginDelete(String pId, String pImage) {
if (pImage.equals("noImage")) {
deleteWithoutImage(pId);
} else {
deleteWithImage(pId, pImage);
}
}
private void deleteWithImage(String pId, String pImage) {
ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Deleting...");
StorageReference picRef = FirebaseStorage.getInstance().getReferenceFromUrl(pImage);
picRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Query query = FirebaseDatabase.getInstance().getReference("Posts").orderByChild("pId").equalTo(pId);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds: snapshot.getChildren()) {
ds.getRef().removeValue(); // remove value from database where pid matches
}
Toast.makeText(context, "Deleted Successfully", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(context, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void deleteWithoutImage(String pId) {
ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Deleting...");
Query query = FirebaseDatabase.getInstance().getReference("Posts").orderByChild("pId").equalTo(pId);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds: snapshot.getChildren()) {
ds.getRef().removeValue(); // remove value from database where pid matches
}
Toast.makeText(context, "Deleted Successfully", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public int getItemCount() {
return postList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CircleImageView user_post_dp;
ImageView user_post_image;
TextView user_post_name, user_post_time, user_post_desc, count_likes,count_comments;
Button likeBtn, commentBtn, shareBtn;
ImageButton more in;
LinearLayout profile layout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
user_post_dp = itemView.findViewById(R.id.user_post_dp);
user_post_image = itemView.findViewById(R.id.user_post_image);
user_post_name = itemView.findViewById(R.id.user_post_name);
user_post_time = itemView.findViewById(R.id.user_post_time);
user_post_desc = itemView.findViewById(R.id.user_post_desc);
count_likes = itemView.findViewById(R.id.count_likes);
count_comments = itemView.findViewById(R.id.count_comments);
likeBtn = itemView.findViewById(R.id.likeBtn);
commentBtn = itemView.findViewById(R.id.commentBtn);
shareBtn = itemView.findViewById(R.id.shareBtn);
profileLayout = itemView.findViewById(R.id.profileLayout);
morebtn = itemView.findViewById(R.id.morebtn);
}
}

Is it possible to set ViewPager inside a fragment class?

I have a Fragment class and an Activity class which is related to that fragment, ViewPager has been initialized inside the Activity of MizActivity
My question is it possible to move ViewPager initialization from Activity class to the Fragment class So that I have better control?
Thanks in advance
Fragment
#SuppressLint("InflateParams") public class TvShowEpisodeDetailsFragment extends Fragment {
TextClicked mCallback;
public interface TextClicked{
void sendText(int position);
}
private Activity mContext;
private TvShowEpisode mEpisode;
private ImageView mBackdrop, mEpisodePhoto;
private TextView mTitle, mDescription, mFileSource, mAirDate, mRating, mDirector, mWriter, mGuestStars, mSeasonEpisodeNumber;
private View mDetailsArea;
private Picasso mPicasso;
private Typeface mMediumItalic, mMedium, mCondensedRegular;
private DbAdapterTvShowEpisodes mDatabaseHelper;
private long mVideoPlaybackStarted, mVideoPlaybackEnded;
private boolean mShowFileLocation;
private Bus mBus;
private int mToolbarColor = 0;
private FloatingActionButton mFab;
private PaletteLoader mPaletteLoader;
private ObservableScrollView mScrollView;
private RecyclerView mEpisodesList;
private String mShowId;
private ArrayList<TvShowEpisode> mEpisodes = new ArrayList<TvShowEpisode>();
private static final String SHOW_ID = "showId";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ViewPager mViewPager;
public PlanetAdapter.OnItemClickListener listener;
/**
* Empty constructor as per the Fragment documentation
*/
public TvShowEpisodeDetailsFragment() {}
public static TvShowEpisodeDetailsFragment newInstance(String showId, int season, int episode) {
TvShowEpisodeDetailsFragment pageFragment = new TvShowEpisodeDetailsFragment();
Bundle bundle = new Bundle();
bundle.putString("showId", showId);
bundle.putInt("season", season);
bundle.putInt("episode", episode);
pageFragment.setArguments(bundle);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
mContext = getActivity();
mBus = MizuuApplication.getBus();
mShowFileLocation = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean(SHOW_FILE_LOCATION, true);
mPicasso = MizuuApplication.getPicassoDetailsView(getActivity());
mMediumItalic = TypefaceUtils.getRobotoMediumItalic(mContext);
mMedium = TypefaceUtils.getRobotoMedium(mContext);
mCondensedRegular = TypefaceUtils.getRobotoCondensedRegular(mContext);
mDatabaseHelper = MizuuApplication.getTvEpisodeDbAdapter();
// initializing mEpisodes
mShowId = getActivity().getIntent().getExtras().getString(SHOW_ID);
Cursor cursor = mDatabaseHelper.getEpisodes(mShowId);
try {
while (cursor.moveToNext()) {
mEpisodes.add(new TvShowEpisode(mContext, mShowId,
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_TITLE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_PLOT)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_AIRDATE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_DIRECTOR)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_WRITER)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_GUESTSTARS)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_RATING)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_HAS_WATCHED)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_FAVOURITE))
));
}
} catch (Exception e) {
} finally {
cursor.close();
} // mEpisodes initialized
LocalBroadcastManager.getInstance(mContext).registerReceiver(mBroadcastReceiver,
new IntentFilter(LocalBroadcastUtils.UPDATE_TV_SHOW_EPISODE_DETAILS_OVERVIEW));
loadEpisode();
}
#Override
public void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mBroadcastReceiver);
}
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
loadEpisode();
loadData();
}
};
private void loadEpisode() {
if (!getArguments().getString("showId").isEmpty() && getArguments().getInt("season") >= 0 && getArguments().getInt("episode") >= 0) {
Cursor cursor = mDatabaseHelper.getEpisode(getArguments().getString("showId"), getArguments().getInt("season"), getArguments().getInt("episode"));
if (cursor.moveToFirst()) {
mEpisode = new TvShowEpisode(getActivity(),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SHOW_ID)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_TITLE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_PLOT)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_AIRDATE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_DIRECTOR)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_WRITER)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_GUESTSTARS)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_RATING)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_HAS_WATCHED)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_FAVOURITE))
);
mEpisode.setFilepaths(MizuuApplication.getTvShowEpisodeMappingsDbAdapter().getFilepathsForEpisode(
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SHOW_ID)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE))
));
}
cursor.close();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.episode_details, container, false);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (TextClicked) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement TextClicked");
}
}
#Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mBackdrop = (ImageView) view.findViewById(R.id.imageBackground);
mEpisodePhoto = (ImageView) view.findViewById(R.id.episodePhoto);
mDetailsArea = view.findViewById(R.id.details_area);
mTitle = (TextView) view.findViewById(R.id.movieTitle);
mSeasonEpisodeNumber = (TextView) view.findViewById(R.id.textView7);
mDescription = (TextView) view.findViewById(R.id.textView2);
mFileSource = (TextView) view.findViewById(R.id.textView3);
mAirDate = (TextView) view.findViewById(R.id.textReleaseDate);
mRating = (TextView) view.findViewById(R.id.textView12);
mDirector = (TextView) view.findViewById(R.id.director);
mWriter = (TextView) view.findViewById(R.id.writer);
mGuestStars = (TextView) view.findViewById(R.id.guest_stars);
mScrollView = (ObservableScrollView) view.findViewById(R.id.observableScrollView);
mFab = (FloatingActionButton) view.findViewById(R.id.fab);
// setting RecyclerView
mEpisodesList = (RecyclerView) view.findViewById(R.id.episodesLIST);
// getting episodeslist
ArrayList<PlanetModel> episodeslist = new ArrayList<>();
for(TvShowEpisode e : mEpisodes){
episodeslist.add(new PlanetModel(e.mEpisode));
}
// Setting LinearLayoutManager
LinearLayoutManager layoutManager
= new LinearLayoutManager(mContext.getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
//mEpisodesList.setLayoutManager(new LinearLayoutManager(mContext));
mEpisodesList.setLayoutManager(layoutManager);
// Setting RecyclerView Adapter
mEpisodesList.setAdapter(new PlanetAdapter(episodeslist, new PlanetAdapter.OnItemClickListener() {
#Override public void onItemClick(String item) {
SharedPreferences getPref = getActivity ().getSharedPreferences("PlanetAdapter", Context.MODE_PRIVATE);
int pos = getPref.getInt("newPosition",0);
mCallback.sendText(pos);
}
}));
mFab.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ViewUtils.animateFabJump(v, new SimpleAnimatorListener() {
#Override
public void onAnimationEnd(Animator animation) {
play();
}
});
}
});
if (MizLib.isTablet(mContext))
mFab.setType(FloatingActionButton.TYPE_NORMAL);
final int height = MizLib.getActionBarAndStatusBarHeight(getActivity());
mScrollView = (ObservableScrollView) view.findViewById(R.id.observableScrollView);
mScrollView.setOnScrollChangedListener(new OnScrollChangedListener() {
#Override
public void onScrollChanged(ScrollView who, int l, int t, int oldl, int oldt) {
final int headerHeight = mEpisodePhoto.getHeight() - height;
final float ratio = (float) Math.min(Math.max(t, 0), headerHeight) / headerHeight;
final int newAlpha = (int) (ratio * 255);
mBus.post(new BusToolbarColorObject(mToolbarColor, newAlpha));
if (MizLib.isPortrait(mContext)) {
// Such parallax, much wow
mEpisodePhoto.setPadding(0, (int) (t / 1.5), 0, 0);
}
}
});
mScrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
ViewUtils.setLayoutParamsForDetailsEmptyView(mContext, view,
mBackdrop, mScrollView, this);
}
});
loadData();
mPicasso.load(mEpisode.getEpisodePhoto()).placeholder(R.drawable.bg).config(MizuuApplication.getBitmapConfig()).into(mEpisodePhoto, new Callback() {
#Override
public void onError() {
if (!isAdded())
return;
int width = getActivity().getResources().getDimensionPixelSize(R.dimen.episode_details_background_overlay_width);
int height = getActivity().getResources().getDimensionPixelSize(R.dimen.episode_details_background_overlay_height);
mPicasso.load(mEpisode.getTvShowBackdrop()).placeholder(R.drawable.bg).error(R.drawable.nobackdrop).resize(width, height).config(MizuuApplication.getBitmapConfig()).into(mEpisodePhoto);
}
#Override
public void onSuccess() {
if (mPaletteLoader == null) {
mPaletteLoader = new PaletteLoader(mPicasso, Uri.fromFile(mEpisode.getEpisodePhoto()), new PaletteLoader.OnPaletteLoadedCallback() {
#Override
public void onPaletteLoaded(int swatchColor) {
mToolbarColor = swatchColor;
}
});
mPaletteLoader.addView(mDetailsArea);
mPaletteLoader.setFab(mFab);
mPaletteLoader.execute();
} else {
// Clear old views after configuration change
mPaletteLoader.clearViews();
// Add views after configuration change
mPaletteLoader.addView(mDetailsArea);
mPaletteLoader.setFab(mFab);
// Re-color the views
mPaletteLoader.colorViews();
}
}
});
if (!MizLib.isPortrait(getActivity()))
mPicasso.load(mEpisode.getEpisodePhoto()).placeholder(R.drawable.bg).error(R.drawable.bg).transform(new BlurTransformation(getActivity().getApplicationContext(), mEpisode.getEpisodePhoto().getAbsolutePath() + "-blur", 4)).into(mBackdrop, new Callback() {
#Override public void onError() {
if (!isAdded())
return;
mPicasso.load(mEpisode.getTvShowBackdrop()).placeholder(R.drawable.bg).error(R.drawable.nobackdrop).transform(new BlurTransformation(getActivity().getApplicationContext(), mEpisode.getTvShowBackdrop().getAbsolutePath() + "-blur", 4)).into(mBackdrop, new Callback() {
#Override
public void onError() {}
#Override
public void onSuccess() {
if (!isAdded())
return;
mBackdrop.setColorFilter(Color.parseColor("#aa181818"), android.graphics.PorterDuff.Mode.SRC_OVER);
}
});
}
#Override
public void onSuccess() {
if (!isAdded())
return;
mBackdrop.setColorFilter(Color.parseColor("#aa181818"), android.graphics.PorterDuff.Mode.SRC_OVER);
}
});
}
#Override
public void onDetach() {
mCallback = null; // => avoid leaking, thanks #Deepscorn
super.onDetach();
}
private void loadData() {
// Set the episode title
mTitle.setVisibility(View.VISIBLE);
mTitle.setText(mEpisode.getTitle());
mTitle.setTypeface(mCondensedRegular);
mDescription.setTypeface(mCondensedRegular);
mFileSource.setTypeface(mCondensedRegular);
mDirector.setTypeface(mCondensedRegular);
mWriter.setTypeface(mCondensedRegular);
mGuestStars.setTypeface(mCondensedRegular);
mAirDate.setTypeface(mMedium);
mRating.setTypeface(mMedium);
mSeasonEpisodeNumber.setTypeface(mMediumItalic);
mSeasonEpisodeNumber.setText(getString(R.string.showSeason) + " " + mEpisode.getSeason() + ", " + getString(R.string.showEpisode) + " " + mEpisode.getEpisode());
// Set the movie plot
if (!MizLib.isPortrait(getActivity())) {
mDescription.setBackgroundResource(R.drawable.selectable_background);
mDescription.setMaxLines(getActivity().getResources().getInteger(R.integer.episode_details_max_lines));
mDescription.setTag(true); // true = collapsed
mDescription.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((Boolean) mDescription.getTag())) {
mDescription.setMaxLines(1000);
mDescription.setTag(false);
} else {
mDescription.setMaxLines(getActivity().getResources().getInteger(R.integer.episode_details_max_lines));
mDescription.setTag(true);
}
}
});
mDescription.setEllipsize(TextUtils.TruncateAt.END);
mDescription.setFocusable(true);
} else {
if (MizLib.isTablet(getActivity()))
mDescription.setLineSpacing(0, 1.15f);
}
mDescription.setText(mEpisode.getDescription());
if (mShowFileLocation) {
mFileSource.setText(mEpisode.getAllFilepaths());
} else {
mFileSource.setVisibility(View.GONE);
}
// Set the episode air date
mAirDate.setText(MizLib.getPrettyDatePrecise(getActivity(), mEpisode.getReleasedate()));
// Set the movie rating
if (!mEpisode.getRating().equals("0.0")) {
try {
int rating = (int) (Double.parseDouble(mEpisode.getRating()) * 10);
mRating.setText(Html.fromHtml(rating + "<small> %</small>"));
} catch (NumberFormatException e) {
mRating.setText(mEpisode.getRating());
}
} else {
mRating.setText(R.string.stringNA);
}
if (TextUtils.isEmpty(mEpisode.getDirector()) || mEpisode.getDirector().equals(getString(R.string.stringNA))) {
mDirector.setVisibility(View.GONE);
} else {
mDirector.setText(mEpisode.getDirector());
}
if (TextUtils.isEmpty(mEpisode.getWriter()) || mEpisode.getWriter().equals(getString(R.string.stringNA))) {
mWriter.setVisibility(View.GONE);
} else {
mWriter.setText(mEpisode.getWriter());
}
if (TextUtils.isEmpty(mEpisode.getGuestStars()) || mEpisode.getGuestStars().equals(getString(R.string.stringNA))) {
mGuestStars.setVisibility(View.GONE);
} else {
mGuestStars.setText(mEpisode.getGuestStars());
}
}
Rest of the code
}
Activity
public class TvShowEpisodeDetails extends MizActivity implements TvShowEpisodeDetailsFragment.TextClicked{
private static final String SHOW_ID = "showId";
private ArrayList<TvShowEpisode> mEpisodes = new ArrayList<TvShowEpisode>();
private int mSeason, mEpisode;
private String mShowId, mShowTitle;
private ViewPager mViewPager;
private DbAdapterTvShowEpisodes mDatabaseHelper;
private Bus mBus;
#Override
protected int getLayoutResource() {
return R.layout.viewpager_with_toolbar_overlay;
}
#Override
public void onCreate(Bundle savedInstanceState) {
mBus = MizuuApplication.getBus();
super.onCreate(savedInstanceState);
// Set theme
setTheme(R.style.Mizuu_Theme_NoBackground);
ViewUtils.setupWindowFlagsForStatusbarOverlay(getWindow(), true);
ViewUtils.setProperToolbarSize(this, mToolbar);
mShowId = getIntent().getExtras().getString(SHOW_ID);
mSeason = getIntent().getExtras().getInt("season");
mEpisode = getIntent().getExtras().getInt("episode");
mDatabaseHelper = MizuuApplication.getTvEpisodeDbAdapter();
Cursor cursor = mDatabaseHelper.getEpisodes(mShowId);
try {
while (cursor.moveToNext()) {
mEpisodes.add(new TvShowEpisode(this, mShowId,
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_TITLE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_PLOT)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_AIRDATE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_DIRECTOR)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_WRITER)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_GUESTSTARS)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_RATING)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_HAS_WATCHED)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_FAVOURITE))
));
}
} catch (Exception e) {
} finally {
cursor.close();
}
final ArrayList<PlanetModel> episodeslist = new ArrayList<>();
for(TvShowEpisode e : mEpisodes){
episodeslist.add(new PlanetModel(e.mEpisode));
}
mShowTitle = MizuuApplication.getTvDbAdapter().getShowTitle(mShowId);
setTitle(mShowTitle);
mViewPager = (ViewPager) findViewById(R.id.awesomepager);
mViewPager.setAdapter(new TvShowEpisodeDetailsAdapter(getSupportFragmentManager()));
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
for (int i=0; i<episodeslist.size(); i++)
{
episodeslist.get(i).setPlanetSelected(false);
}
episodeslist.get(position).setPlanetSelected(true);
//notify your recycler views adaper
ViewUtils.updateToolbarBackground(TvShowEpisodeDetails.this, mToolbar, 0, mEpisodes.get(position).getTitle(), Color.TRANSPARENT);
}
});
if (savedInstanceState != null) {
mViewPager.setCurrentItem(savedInstanceState.getInt("tab", 0));
} else {
for (int i = 0; i < mEpisodes.size(); i++) {
if (mEpisodes.get(i).getSeason().equals(MizLib.addIndexZero(mSeason)) && mEpisodes.get(i).getEpisode().equals(MizLib.addIndexZero(mEpisode))) {
mViewPager.setCurrentItem(i);
SharedPreferences setPref = this.getSharedPreferences("TvShowEpisodeDetails", Context.MODE_PRIVATE);
setPref.edit().putInt("i", i).apply();
break;
}
}
}
}
#Subscribe
public void onScrollChanged(TvShowEpisodeDetailsFragment.BusToolbarColorObject object) {
ViewUtils.updateToolbarBackground(this, mToolbar, object.getAlpha(),
mEpisodes.get(mViewPager.getCurrentItem()).getTitle(), object.getToolbarColor());
}
public void onResume() {
super.onResume();
mBus.register(this);
ViewUtils.updateToolbarBackground(this, mToolbar, 0, mShowTitle, Color.TRANSPARENT);
}
#Override
public void onPause() {
super.onPause();
mBus.unregister(this);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onStart() {
super.onStart();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tab", mViewPager.getCurrentItem());
}
#Override
public void sendText(int position) {
mViewPager.setCurrentItem(position,false);
//Toast.makeText(getContext(), "Item Clicked " + text, Toast.LENGTH_SHORT).show();
}
private class TvShowEpisodeDetailsAdapter extends FragmentPagerAdapter {
public TvShowEpisodeDetailsAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
return TvShowEpisodeDetailsFragment.newInstance(mShowId, Integer.parseInt(mEpisodes.get(index).getSeason()), Integer.parseInt(mEpisodes.get(index).getEpisode()));
}
#Override
public int getCount() {
return mEpisodes.size();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode == Activity.RESULT_OK) {
setResult(Activity.RESULT_OK);
finish();
}
}
}
}
Yes, a Viewpager can be setup in a Fragment.
You just need to get the right FragmentManager when constructing it i.e use getChildFragmentManager() in mViewPager.setAdapter(new TvShowEpisodeDetailsAdapter(getSupportFragmentManager()));
From https://developer.android.com/guide/fragments/fragmentmanager
Access the FragmentManager
Accessing in an activity
Every FragmentActivity and subclasses thereof, such as
AppCompatActivity, have access to the FragmentManager through the
getSupportFragmentManager() method.
Accessing in a Fragment
Fragments are also capable of hosting one or more child fragments.
Inside a fragment, you can get a reference to the FragmentManager that
manages the fragment's children through getChildFragmentManager().

error for retrieving an images from firebase

I am having this error while deleting an image from application
E/InputEventReceiver: Exception dispatching input event.
E/MessageQueue-JNI: Exception in MessageQueue callback:
handleReceiveCallback E/MessageQueue-JNI:
java.lang.IllegalArgumentException: The storage Uri could not be
parsed.
This i my code i write it for deletion
Images_Actvity.java:
public class Images_Avctivity extends AppCompatActivity implements Image_adapter.OnItemClickListener {
private RecyclerView mRecyclerView;
private Image_adapter mAdapter;
private ProgressBar mProgressCircle;
private FirebaseStorage mStorage;
private DatabaseReference mDatabaseRef;
private ValueEventListener mDBListener;
private List<Upload> mUploads;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_images__avctivity);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mProgressCircle = findViewById(R.id.progress_circle);
mUploads = new ArrayList<>();
mAdapter = new Image_adapter(Images_Avctivity.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(Images_Avctivity.this);
mStorage = FirebaseStorage.getInstance();
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
mDBListener = mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUploads.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Upload upload = postSnapshot.getValue(Upload.class);
upload.setKey(postSnapshot.getKey());
mUploads.add(upload);
}
mAdapter.notifyDataSetChanged();
mProgressCircle.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(Images_Avctivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
mProgressCircle.setVisibility(View.INVISIBLE);
}
});
}
#Override
public void onItemClick(int position) {
Toast.makeText(this, "Normal click at position: " + position, Toast.LENGTH_SHORT).show();
}
#Override
public void onWhatEverClick(int position) {
Toast.makeText(this, "Whatever click at position: " + position, Toast.LENGTH_SHORT).show();
}
#Override
public void onDeleteClick(int position) {
Upload selectedItem = mUploads.get(position);
final String selectedKey = selectedItem.getKey();
StorageReference imageRef = mStorage.getReferenceFromUrl(selectedItem.getImageUrl());
imageRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mDatabaseRef.child(selectedKey).removeValue();
Toast.makeText(Images_Avctivity.this, "Item deleted", Toast.LENGTH_SHORT).show();
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
mDatabaseRef.removeEventListener(mDBListener);
}
}
This is adpater code:
Image_adapter.java:
public class Image_adapter extends RecyclerView.Adapter<Image_adapter.ImageViewHolder> {
private Context mContext;
private List<Upload> mUploads;
private OnItemClickListener mListener;
public Image_adapter(Context context, List<Upload> uploads) {
mContext = context;
mUploads = uploads;
}
#Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.image_item, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getName());
Picasso.with(mContext)
.load(uploadCurrent.getImageUrl())
.placeholder(R.mipmap.ic_launcher)
.fit()
.centerCrop()
.into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
public TextView textViewName;
public ImageView imageView;
public ImageViewHolder(View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.text_view_name);
imageView = itemView.findViewById(R.id.image_view_upload);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select Action");
MenuItem doWhatever = menu.add(Menu.NONE, 1, 1, "Do whatever");
MenuItem delete = menu.add(Menu.NONE, 2, 2, "Delete");
doWhatever.setOnMenuItemClickListener(this);
delete.setOnMenuItemClickListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
switch (item.getItemId()) {
case 1:
mListener.onWhatEverClick(position);
return true;
case 2:
mListener.onDeleteClick(position);
return true;
}
}
}
return false;
}
}
public interface OnItemClickListener {
void onItemClick(int position);
void onWhatEverClick(int position);
void onDeleteClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
}
StorageReference storageReference = FirebaseStorage.getInstance().getReferenceFromUrl("https://firebasestorage.googleapis.com/v0/b/***********************-5fac-45b6-bbda-ed4e8a3a62ab");
storageReference.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// File deleted successfully
Log.e("firebasestorage", "onSuccess: deleted file");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Uh-oh, an error occurred!
Log.e("firebasestorage", "onFailure: did not delete file");
}
});

Update TAB 2 Recyclerview When Data Added in TAB 1's RecyclerView

I have kind of to-do app. In profile activity, there are 2 tabs.
To-do and Done. In Tab 1, user can check as "done" of their "to-do". In this case, I want to update TAB 2's recyclerview.
I tried several things, but didn't work. Here is TAB 1 codes, it's almost same as TAB 2.
TAB 1 Class
public class Tab_Profile_1 extends Fragment {
private RecyclerView recyclerView_tab_todo;
private List<Model_ListItem> itemList;
private Adapter_Profile_ToDo adapter_profile_toDo;
SharedPreferences mSharedPref;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile_tab_1, container, false);
//TO-DO
//
recyclerView_tab_todo = view.findViewById(R.id.recyclerView_tab_todo);
//
fetchUserToDo();
return view;
}
public void fetchUserToDo() {
itemList = new ArrayList<>();
//First Settings
mSharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
String session_user_id = mSharedPref.getString("session_user_id", "");
API_Service api_service = Client.getRetrofitInstance().create(API_Service.class);
Call<List<Model_ListItem>> call = api_service.fetchUserToDo(session_user_id);
call.enqueue(new Callback<List<Model_ListItem>>() {
#Override
public void onResponse(Call<List<Model_ListItem>> call, Response<List<Model_ListItem>> response) {
itemList = response.body();
adapter_profile_toDo = new Adapter_Profile_ToDo(getContext(), itemList);
recyclerView_tab_todo.setHasFixedSize(true);
LinearLayoutManager layoutManager
= new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
recyclerView_tab_todo.setLayoutManager(layoutManager);
recyclerView_tab_todo.setAdapter(adapter_profile_toDo);
}
#Override
public void onFailure(Call<List<Model_ListItem>> call, Throwable t) {
}
});
}}
TAB 1 RecyclerView Adapter
public class Adapter_Profile_ToDo extends RecyclerView.Adapter {
private Context context;
private List<Model_ListItem> itemList;
private String url_extension_images = URL_Extension.url_extension_images;
SharedPreferences mSharedPref;
ProgressDialog progressDialog;
View view;
public Adapter_Profile_ToDo(Context context, List<Model_ListItem> itemList) {
this.context = context;
this.itemList = itemList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_profile_todo, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
Glide.with(context).load(url_extension_images + itemList.get(position).getItem_image()).into(holder.imageView_profile_todo);
holder.textView_profile_todo_name.setText(itemList.get(position).getItem_name());
holder.textView_profile_todo_desc.setText(itemList.get(position).getItem_description());
holder.layout_profile_todo_detail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//detail
}
});
holder.layout_profile_todo_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder builder = new AlertDialog.Builder(view.getRootView().getContext(), R.style.AlertStyle);
builder.setTitle("\"" + itemList.get(position).getItem_name() + "\"" + "\n");
builder.setIcon(R.drawable.ic_bookmark);
builder.setPositiveButton("YAPTIM", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
showProgressDialog();
addDone("" + itemList.get(position).getItem_id(), position);
}
});
builder.setNegativeButton("SİL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
showProgressDialog();
deleteUserToDo("" + itemList.get(position).getItem_id(), position);
}
});
builder.setNeutralButton("İptal", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
});
}
#Override
public int getItemCount() {
return itemList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView_profile_todo;
TextView textView_profile_todo_name, textView_profile_todo_desc;
LinearLayout layout_profile_todo_detail, layout_profile_todo_add;
public ViewHolder(View itemView) {
super(itemView);
imageView_profile_todo = itemView.findViewById(R.id.imageView_profile_todo);
textView_profile_todo_name = itemView.findViewById(R.id.textView_profile_todo_name);
textView_profile_todo_desc = itemView.findViewById(R.id.textView_profile_todo_desc);
layout_profile_todo_detail = itemView.findViewById(R.id.layout_profile_todo_detail);
layout_profile_todo_add = itemView.findViewById(R.id.layout_profile_todo_add);
}
}
public void deleteUserToDo(final String listId, final int clicked) {
mSharedPref = PreferenceManager.getDefaultSharedPreferences(context);
String session_user_id = mSharedPref.getString("session_user_id", "");
API_Service api_service = Client.getRetrofitInstance().create(API_Service.class);
Call<Response_Success> call = api_service.deleteUserToDo(session_user_id, listId);
call.enqueue(new Callback<Response_Success>() {
#Override
public void onResponse(Call<Response_Success> call, Response<Response_Success> response) {
if (response.code() == 200) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
if (response.body().getSuccess().matches("true")) {
Toast.makeText(context, "Silindi!", Toast.LENGTH_SHORT).show();
itemList.remove(itemList.get(clicked));
notifyItemRemoved(clicked);
notifyItemRangeChanged(clicked, itemList.size());
} else {
Toast.makeText(context, "Bilinmeyen bir hata oluştu!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onFailure(Call<Response_Success> call, Throwable t) {
Toast.makeText(context, "Bilinmeyen bir hata oluştu!", Toast.LENGTH_SHORT).show();
}
});
}
public void addDone(String listId, final int clicked) {
mSharedPref = PreferenceManager.getDefaultSharedPreferences(context);
String session_user_id = mSharedPref.getString("session_user_id", "");
API_Service apiService = Client.getRetrofitInstance().create(API_Service.class);
Call<Response_Success> call = apiService.addDone(session_user_id, listId);
call.enqueue(new Callback<Response_Success>() {
#Override
public void onResponse(Call<Response_Success> call, Response<Response_Success> response) {
if (response.code() == 200) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
if (response.body().getSuccess().matches("true")) {
Toast.makeText(context, "Eklendi", Toast.LENGTH_SHORT).show();
itemList.remove(itemList.get(clicked));
notifyItemRemoved(clicked);
notifyItemRangeChanged(clicked, itemList.size());
} else {
Toast.makeText(context, "Bilinmeyen bir hata oluştu!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onFailure(Call<Response_Success> call, Throwable t) {
}
});
}
public void showProgressDialog() {
progressDialog = new ProgressDialog(view.getRootView().getContext());
progressDialog.setMessage("Yükleniyor");
progressDialog.setCancelable(false);
progressDialog.show();
}
}
If i'm reading this correctly, you have two tabs and a backend database that stores the to do items and their state? To get the second list to update, you just need to do the same thing that you're doing in your first list, and update the adapter's data set and notify that the data set changed. How you trigger this action in your second tab is really the question.
You can either use an interface and have your adapter notify your activity that recycler view 1 had an action on it, and you can then tell adapter 2 to update its data. You can either pass back the data and only notify one row, or you could notify the entire data set. If you're doing this all service based, you could just reload the recycler view from the service and it will have the new data.
I think all you need to figure out is how you want to notify tab 2 that it needs to update its data. My recommendation is:
public interface AdapterInterface
{
void itemCompleted(Item hereIsTheItemThatNeedsToBeAddedTo2);
}
Then inside your adapter have a property with getters/setters such as:
private AdapterInterface adapterInterfaceListener;
Inside your Fragment/Activity implement AdapterInterface and implement the itemCompleted function.
And then set your adapter.setAdapterInterfaceLisetener to that function that you implemented. Then inside your adapter when the user clicks the checkbook to mark it as done, you can call the adapterInterfaceListener.itemCompleted() function, and it will send that information to your Fragment/Activity. From there you can give that new data to adapter2, or recall the API, however you want to get the new data.
Does this help?

Material Dialog Error I am working on listview,

I want to show a Dialog Window inside an adapter but i get this error: Bad window token, you cannot show a dialog before an Activity is created or after it's hidden. This is MainActivity
public class Order extends AppCompatActivity {
private ListView OrderList;
Button Mbyll;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private OrderAdapter adapter;
public static final String KEY_ORDER_DATA = "oder_data";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
Mbyll = (Button)findViewById(R.id.mbyll_porosine);
//OrderList = (ListView.(R.id.list);
// ListView listView = (ListView) findViewById(R.id.listView);
Mbyll.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), com.android.restaurant.activity.Home.class);
volley_dergo_rregjistrim();
startActivity(i);
}
});
OrderList = (ListView) findViewById(R.id.listView);
displayData();
}
private void displayData() {
adapter = new OrderAdapter(getApplication(), DatabaseManager.INSTANCE.getAllCartData() );
OrderList.setAdapter(adapter);
}
public void volley_dergo_rregjistrim(){
// Tag used to cancel the request
String url = "My Url";
StringRequest strReq = new StringRequest(Request.Method.POST,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Toast.makeText(getApplicationContext(),response,Toast.LENGTH_LONG).show();
try {
//Do it with this it will work
JSONObject obj = new JSONObject(response);
boolean trueOrFalse = obj.getBoolean("error");
if(trueOrFalse){
//String userId = obj.getString("id");
//Toast.makeText(getApplicationContext(),userId.toString(),Toast.LENGTH_LONG).show();
}else{
JSONObject obj1 = new JSONObject(response);
String msg = obj1.getString("message");
Toast.makeText(getApplicationContext(),msg.toString(),Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Error 1 :"+e.toString(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Error2",Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
OrderRequest order = new OrderRequest();
order.setOrder_type("2");
order.setId_reservation(138);
order.fillRestProductList(DatabaseManager.INSTANCE.getAllCartData());
Map<String,String> params=new HashMap<String,String>();
params.put(KEY_ORDER_DATA,new Gson().toJson(order));
return params;
}
};
VolleyApplication.getInstance().getRequestQueue().add(strReq);
}
}
This is the adapter
public class OrderAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<DbProductModel> items;
private FragmentManager fMan;
int index;
public OrderAdapter(Context c, ArrayList<DbProductModel> items ) {
this.mContext = c;
this.items = items;
}
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(final int pos, View child, ViewGroup parent) {
Holder mHolder;
index = pos;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.card_structure, null);
mHolder = new Holder();
mHolder.txt_title = (TextView) child.findViewById(R.id.card_title);
mHolder.txt_price = (TextView) child.findViewById(R.id.card_price);
mHolder.txt_total_price = (TextView) child.findViewById(R.id.card_total_price);
mHolder.txt_total = (TextView) child.findViewById(R.id.total);
mHolder.txt_description = (TextView) child.findViewById(R.id.description_txt);
mHolder.delete_order = (Button) child.findViewById(R.id.delete);
mHolder.add = (Button) child.findViewById(R.id.add);
mHolder.remove = (Button) child.findViewById(R.id.remove);
mHolder.note = (Button) child.findViewById(R.id.btn_add_note);
mHolder.pza_image = (ImageView) child.findViewById(R.id.card_imagee);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.delete_order.setOnClickListener(new View.OnClickListener() {
//DbProductModel products = id_list.get(index);
#Override
public void onClick(View v) {
DatabaseManager.INSTANCE.removeProductFromCart(items.get(pos).getId_dish());
items.remove(pos);
Toast.makeText(v.getContext(), "Delete", Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
}
});
mHolder.add.setOnClickListener(new View.OnClickListener() {
//DbProductModel products = id_list.get(index);
#Override
public void onClick(View v) {
DatabaseManager.INSTANCE.addToCart(items.get(pos));
items.get(pos).setQuantity(items.get(pos).getQuantity() + 1);
Toast.makeText(v.getContext(), "added quantity", Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
}
});
mHolder.remove.setOnClickListener(new View.OnClickListener() {
//DbProductModel products = id_list.get(index);
#Override
public void onClick(View v) {
if (items.get(pos).getQuantity() > 1) {
boolean couldDecrement = DatabaseManager.INSTANCE.decrementQuantityOfProdInCart(items.get(pos).getId_dish());
if (couldDecrement) {
items.get(pos).setQuantity(items.get(pos).getQuantity() - 1);
Toast.makeText(v.getContext(), "decreased quantity", Toast.LENGTH_SHORT).show();
}
notifyDataSetChanged();
}
}
});
mHolder.note.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//NotesDialogFragment.newInstance(items.get(pos).getId_dish()).show(fMan, NotesDialogFragment.class.getSimpleName());
/// Demo.newInstance(items.get(pos).getId_dish());
// showInputDialog(v.getContext());
showInputDialog();
//showBasicLongContent("","titull");
}
});
mHolder.txt_title.setText(items.get(pos).getName());
mHolder.txt_price.setText("Cmimi: "+items.get(pos).getPrice());
mHolder.txt_total_price.setText("Cmimi Total: "+items.get(pos).getPrice_total());
mHolder.txt_total.setText(""+ items.get(pos).getQuantity());
mHolder.txt_description.setText(""+ items.get(pos).getDescription());
Glide.with(mContext)
.load(My Url"+items.get(pos).getImage())
.centerCrop()
.placeholder(R.drawable.placeholder)
.crossFade()
.into(mHolder.pza_image);
return child;
}
public class Holder {
// TextView txt_id;
TextView txt_title;
TextView txt_price;
TextView txt_total_price;
TextView txt_total;
TextView txt_description;
ImageView pza_image;
Button delete_order;
Button remove;
Button add;
Button note;
}
public void showInputDialog() {
new MaterialDialog.Builder(mContext)
.title("TEST")
.content("TEST")
.inputType(InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_PERSON_NAME |
InputType.TYPE_TEXT_FLAG_CAP_WORDS)
.inputRange(2, 16)
.positiveText("TEST")
.input("TEST", "TEST", false, new MaterialDialog.InputCallback() {
#Override
public void onInput(#NonNull MaterialDialog dialog, CharSequence input) {
//showToast("Hello, " + input.toString() + "!");
}
}).show();
}
}
this is my error
06-04 10:52:31.844 12468-12468/com.android.restaurant E/libEGL: call to OpenGL ES API with no current context (logged once per thread)
06-04 10:52:40.252 12468-12468/com.android.restaurant E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.restaurant, PID: 12468
com.afollestad.materialdialogs.MaterialDialog$DialogException: Bad window token, you cannot show a dialog before an Activity is created or after it's hidden.
at com.afollestad.materialdialogs.MaterialDialog.show(MaterialDialog.java:1352)
at com.afollestad.materialdialogs.MaterialDialog$Builder.show(MaterialDialog.java:1341)
at com.android.restaurant.Adapter.OrderAdapter.showBasicLongContent(OrderAdapter.java:193)
at com.android.restaurant.Adapter.OrderAdapter$2.onClick(OrderAdapter.java:107)
at android.view.View.performClick(View.java:5197)
at android.view.View$PerformClick.run(View.java:20926)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

Categories

Resources