View search Result in a new Activity - java

I have a search form on a fragment which works perfectly. At the moment I have a RecyclerView at the bottom of the form but I want it to load the search result on a new activity. Please help
layout.xml:
<LinearLayout 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:layout_marginTop="55dp"
android:orientation="vertical"
tools:context="com.ranake.rana.Search">
<!-- TODO: Update blank fragment layout -->
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/linearLayout">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:orientation="vertical">
<EditText
android:id="#+id/search_field"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#drawable/input_outline2"
android:drawableLeft="#drawable/ic_make"
android:drawablePadding="10dp"
android:gravity="center_vertical"
android:hint="Make"
android:inputType="textPersonName"
android:padding="10dp"
android:textColorHint="#7f8c8d"
android:textSize="14sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="7dp"
android:orientation="vertical">
<EditText
android:id="#+id/className"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#drawable/input_outline2"
android:drawableLeft="#drawable/ic_model"
android:drawablePadding="10dp"
android:gravity="center_vertical"
android:hint="Model"
android:inputType="text"
android:padding="10dp"
android:textColorHint="#7f8c8d"
android:textSize="14sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:orientation="horizontal">
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="42dp"
android:layout_marginBottom="10dp"
android:layout_marginEnd="10dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="10dp"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:background="#drawable/button_red_border"
android:text="Clear"
android:textColor="#color/colorPrimary" />
<Button
android:id="#+id/search_btn"
android:layout_width="wrap_content"
android:layout_height="42dp"
android:layout_marginBottom="10dp"
android:layout_marginEnd="20dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="20dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:background="#drawable/button_red"
android:text="Search"
android:textColor="#android:color/white" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ProgressBar
android:layout_width="match_parent"
android:id="#+id/progressBar"
android:layout_height="match_parent" />
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/result_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="50dp"></android.support.v7.widget.RecyclerView>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</LinearLayout>
Search.java:
public class Search extends Fragment {
private EditText mSearchField;
private Button mSearchBtn;
private RecyclerView mResultList;
private DatabaseReference mUserDatabase;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_search, container, false);
mUserDatabase = FirebaseDatabase.getInstance().getReference("Cars");
mSearchField = (EditText) view.findViewById(R.id.search_field);
mSearchBtn = (Button) view.findViewById(R.id.search_btn);
mResultList = (RecyclerView) view.findViewById(R.id.result_list);
mResultList.setHasFixedSize(true);
mResultList.setNestedScrollingEnabled(false);
mResultList.setLayoutManager(new LinearLayoutManager(getContext()));
mSearchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String searchText = mSearchField.getText().toString();
firebaseUserSearch(searchText);
}
});
return view;
}
private void firebaseUserSearch(String searchText) {
Toast.makeText(getActivity(), "Started Search", Toast.LENGTH_LONG).show();
Query firebaseSearchQuery = mUserDatabase.orderByChild("title").startAt(searchText).endAt(searchText + "\uf8ff");
FirebaseRecyclerAdapter<Cars, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Cars, UsersViewHolder>(
Cars.class,
R.layout.list_layout,
UsersViewHolder.class,
firebaseSearchQuery
) {
#Override
protected void populateViewHolder(UsersViewHolder viewHolder, Cars model, int position) {
viewHolder.setDetails(getActivity().getApplicationContext(), model.getTitle(), model.getDesc(), model.getImage(), model.getMileage(), model.getTrans(), model.getFuel(), model.getPrice(), model.getLocation());
}
};
mResultList.setAdapter(firebaseRecyclerAdapter);
}
// View Holder Class
public static class UsersViewHolder extends RecyclerView.ViewHolder {
View mView;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDetails(Context ctx, String userTitle, String userDesc, String userImage, String userMileage, String userTrans, String userFuel, String userPrice, String userLocation){
TextView user_title = (TextView) mView.findViewById(R.id.name_text);
TextView user_desc = (TextView) mView.findViewById(R.id.status_text);
ImageView user_image = (ImageView) mView.findViewById(R.id.profile_image);
TextView user_mileage = (TextView) mView.findViewById(R.id.post_mileage);
TextView user_trans = (TextView) mView.findViewById(R.id.post_trans);
TextView user_fuel = (TextView) mView.findViewById(R.id.post_fuel);
TextView user_price = (TextView) mView.findViewById(R.id.post_price);
TextView user_location = (TextView) mView.findViewById(R.id.post_location);
user_title.setText(userTitle);
user_desc.setText(userDesc);
user_mileage.setText(userMileage);
user_trans.setText(userTrans);
user_fuel.setText(userFuel);
user_price.setText(userPrice);
user_location.setText(userLocation);
Glide.with(ctx).load(userImage).into(user_image);
}
}
When the search Button is clicked, I want it to open the new activity and load the results there.

You can pass this searchText to the next Activity (I'm calling it ResultsActivity) by passing it as an extra on the Intent:
private void firebaseUserSearch(String searchText) {
Intent intent = new Intent(getActivity(), ResultsActivity.class);
intent.putExtra("searchText",searchText);
startActivity(intent);
}
Then receive it on the other Activity using Intent.getExtras():
String searchText = getIntent().getExtras().getString("searchText");
And finally populate the RecyclerView from that Activity:
Query firebaseSearchQuery = mUserDatabase.orderByChild("title").startAt(searchText).endAt(searchText + "\uf8ff");
FirebaseRecyclerAdapter<Cars, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Cars, UsersViewHolder>(
Cars.class,
R.layout.list_layout,
UsersViewHolder.class,
firebaseSearchQuery
) {
#Override
protected void populateViewHolder(UsersViewHolder viewHolder, Cars model, int position) {
viewHolder.setDetails(getActivity().getApplicationContext(), model.getTitle(), model.getDesc(), model.getImage(), model.getMileage(), model.getTrans(), model.getFuel(), model.getPrice(), model.getLocation());
}
};
mResultList.setAdapter(firebaseRecyclerAdapter);

Related

Can the RecyclerView scroll with the rest of the fragment layouts?

I have set up a RecyclerView adapter with ViewPager in an activity namely TvShowEpisodeDetails , it works well but there is one issue, the Layout of RecyclerView is fixed while scrolling up and down in the Fragment(TvShowEpisodeDetailsFragment). But I want it to scroll with them.
The RecyclerView and ViewPager are both set inside viewpager_with_toolbar_overlay.xml Layout , and both has been settup in The Activity.
TvShowEpisodeDetailsFragment is the fragment class which belongs to activity class TvShowEpisodeDetails , the fragment creates as many episodes as a TV Show season can offer.
And off course this issue will be gone if I set RecyclerView adapter inside fragment, but I will get non-fixable highlighting and scrolling issues , that is why I set it inside the activity because it does not give those issues.
I need to make it work somehow inside the activity.
My goal is that RecyclerView and ViewPager has to be in the same layout XML file and they both must either be in the activity or fragment class
Is it possible to make the RecyclerView scroll with rest of the fragment layouts?
or
Is it possible to do it programmatically?
Here is the activity
public class TvShowEpisodeDetails extends MizActivity{
#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);
// setting episodeslist
final ArrayList<PlanetModel> episodeslist = new ArrayList<>();
for(TvShowEpisode e : mEpisodes){
episodeslist.add(new PlanetModel(e.mEpisode));
}
// setting RecyclerView
mEpisodesList = (RecyclerView) findViewById(R.id.episodesLIST);
// Setting LinearLayoutManager
LinearLayoutManager layoutManager
= new LinearLayoutManager(this.getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
//mEpisodesList.setLayoutManager(new LinearLayoutManager(mContext));
mEpisodesList.setLayoutManager(layoutManager);
// Setting RecyclerView Adapter
PlanetAdapter.OnItemClickListener indicatorCallback = new PlanetAdapter.OnItemClickListener() {
#Override
public void onItemClick(String item) {
SharedPreferences getPref = getContext().getSharedPreferences("PlanetAdapter", Context.MODE_PRIVATE);
int pos = getPref.getInt("newPosition", 0);
mViewPager.setCurrentItem(pos,false);
}
};
final PlanetAdapter planetAdapter = new PlanetAdapter(episodeslist,indicatorCallback);
mEpisodesList.setAdapter(planetAdapter);
// Setting ViewPager
mViewPager = (ViewPager) findViewById(R.id.awesomepager);
mViewPager.setAdapter(new TvShowEpisodeDetailsAdapter(getSupportFragmentManager()));
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
planetAdapter.setSelectedIndex(position);
planetAdapter.notifyDataSetChanged();
mEpisodesList.smoothScrollToPosition(position);
//mEpisodesList.scrollToPosition(position);
for (int i=0; i<episodeslist.size(); i++)
{
episodeslist.get(i).setPlanetSelected(false);
}
episodeslist.get(position).setPlanetSelected(true);
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);
break;
}
}
}
}
}
viewpager_with_toolbar_overlay
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.ViewPager
android:id="#+id/awesomepager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="#+id/progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#068006"
android:layout_marginTop="450dp"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/episodesLIST"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:scrollbars="horizontal" />
</LinearLayout>
<include layout="#layout/toolbar_layout" />
</FrameLayout>
Here is the XML layout of the fragment which is inflated in onCreateView of the fragment class
episode_details.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:background="#color/abc_input_method_navigation_guard">
<com.miz.views.ObservableScrollView
android:id="#+id/observableScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/episodePhoto"
android:layout_width="match_parent"
android:layout_height="#dimen/backdrop_portrait_height"
android:scaleType="centerCrop"
android:src="#drawable/bg" />
<com.melnykov.fab.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/episodePhoto"
android:layout_alignParentEnd="false"
android:layout_alignParentRight="true"
android:layout_marginTop="#dimen/content_details_fab_negative_margin"
android:layout_marginRight="#dimen/content_details_baseline_margin"
android:src="#drawable/ic_play_arrow_white_36dp"
app:fab_colorNormal="#666"
app:fab_type="mini" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/fab"
android:layout_marginLeft="#dimen/content_details_baseline_margin"
android:layout_marginTop="#dimen/content_details_title_margin_top"
android:layout_marginRight="#dimen/content_details_baseline_margin"
android:layout_toLeftOf="#+id/fab"
android:orientation="vertical">
<TextView
android:id="#+id/movieTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="3"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_title" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/content_details_very_small_margin"
android:layout_marginBottom="#dimen/content_details_baseline_margin"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_subheader"
android:textStyle="bold|italic" />
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:id="#+id/details_area"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#666"
android:baselineAligned="false"
android:elevation="1dp"
android:minHeight="#dimen/content_details_large_margin"
android:orientation="horizontal"
android:paddingLeft="#dimen/content_details_baseline_margin"
android:paddingTop="#dimen/content_details_small_margin"
android:paddingRight="#dimen/content_details_baseline_margin"
android:paddingBottom="#dimen/content_details_small_margin">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:gravity="center_horizontal"
android:lines="1"
android:maxLines="1"
android:text="#string/detailsAirDate"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="#dimen/content_details_area_subheader" />
<TextView
android:id="#+id/textReleaseDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_area_header"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/textView61"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:gravity="center_horizontal"
android:lines="1"
android:maxLines="1"
android:text="#string/detailsRating"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="#dimen/content_details_area_subheader" />
<TextView
android:id="#+id/textView12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_area_header"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="#dimen/content_details_baseline_margin">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/content_details_baseline_margin"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/director"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_movie_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/writer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_edit_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/guest_stars"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_people_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_folder_open_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_body_text" />
</LinearLayout>
</LinearLayout>
</com.miz.views.ObservableScrollView>
<FrameLayout
android:id="#+id/progress_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg"
android:visibility="gone">
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</FrameLayout>
</FrameLayout>
Update
Fragment
#SuppressLint("InflateParams") public class TvShowEpisodeDetailsFragment extends Fragment {
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();
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 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);
mFab.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ViewUtils.animateFabJump(v, new SimpleAnimatorListener() {
#Override
public void onAnimationEnd(Animator animation) {
play();
}
});
}
});
...
}
...
}
I have set up a RecyclerView adapter with ViewPager in an activity namely TvShowEpisodeDetails , it works well but there is one issue, the Layout of RecyclerView is fixed while scrolling up and down in the Fragment(TvShowEpisodeDetailsFragment). But I want it to scroll with them.
It's hard to use the RecyclerView outside of the ViewPager page fragment; because you can't synchronize and link the touch/motion events when you scroll the page up/down (or when you swipe to next/previous page) between both the page fragment and a standalone (i.e. activity) RecyclerView. Even that won't be smooth.
So, the RecyclerView should be a part of the ViewPager page.
And off course this issue will be gone if I set RecyclerView adapter inside fragment, but I will get unfixable highlighting and scrolling issues
So, now the issue of adding the RecyclerView in the ViewPager fragment is the highlighting issue of the RecyclerView item when you click on any item or when you swipe the ViewPager to right/left page.
But, the main issue is that there is a RecyclerView instance per page, i.e. if you have 5 pages, then you have 5 RecyclerViews.
So, it's a cumbersome to track highlighting only within the RecyclerView adapter class. And hence manipulating that with OnClickListeners solely will have issues of linking these RecyclerView and adapter instances together to update their highlighting item.
So, a simpler approach is to pass a parameter to the RecyclerView adapter with the selected item (which is definitely equals to the current ViewPager page position).
And then do a check in the onBindViewHolder() if the position equals to the passed-in value, then highlight the item; otherwise keep items with the original color.
So, wrapping this up into actions:
Change the adapter constructor to accept a highlighted_position parameter
public PlanetAdapter(ArrayList<PlanetModel> episodeslist,
int highlightedPosition, OnItemClickListener listener)
Whenever you create the ViewPager fragment using newInstance() pass-in the current position of the page fragment:
So, in the TvShowEpisodeDetails activity:
for (int i = 0; i < mEpisodes.size(); i++)
fragments.add(TvShowEpisodeDetailsFragment
.newInstance(mShowId,
Integer.parseInt(mEpisodes.get(i).getSeason()),
Integer.parseInt(mEpisodes.get(i).getEpisode()),
i)); // The position
And in the TvShowEpisodeDetailsFragment fragment, register this into a field in the fragment argument:
public static TvShowEpisodeDetailsFragment newInstance(String showId, int season, int episode, int position) { // adding position
TvShowEpisodeDetailsFragment pageFragment = new TvShowEpisodeDetailsFragment();
Bundle bundle = new Bundle();
// trimmed code.
bundle.putInt("position", position); // <<<< into the bundle
pageFragment.setArguments(bundle);
return pageFragment;
}
And set that in the adapter creation:
int currentPosition = getArguments().getInt("position");
planetAdapter = new PlanetAdapter(episodeslist, currentPosition, new PlanetAdapter.OnItemClickListener() {
#Override
public void onItemClick(final int pos) {
mCallback.sendText(pos);
}
});
And reflect that in the adapter to highlight the item:
public class PlanetAdapter extends RecyclerView.Adapter<PlanetAdapter.PlanetViewHolder> {
private final int highlightedPos;
public PlanetAdapter(ArrayList<PlanetModel> episodeslist, int highlightedPosition, OnItemClickListener listener) {
this.episodeslist = episodeslist;
this.listener = listener;
this.highlightedPos = highlightedPosition; // <<< set the position
}
#Override
public void onBindViewHolder(PlanetAdapter.PlanetViewHolder vh, final int position) {
TextView tv = (TextView) vh.itemView;
PlanetModel planetModel = episodeslist.get(position);
tv.setText(planetModel.getPlanetName());
tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.bg, 0, 0, 0);
if (highlightedPos == position) { //<<<<< Highlight the item
vh.itemView.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimaryLight));
Log.d("LOG_TAG", "onClick: Highlight item: " + highlightedPos);
} else {
vh.itemView.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimaryDark));
Log.d("LOG_TAG", "onClick: No highlight: " + highlightedPos);
}
}
}

Send data inside recyclerview with button in Fragment

I have 2 layouts where first layout for Fragment and second layout for RecyclerView. I have created CardView in RecyclerView, every CardView has some data. And I have created button below RecyclerView where the function of button for sending Data on CardView. My problem is I don't know how to send data when i click button in Fragment.
Fragment Layout :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:id="#+id/container_daftar_alamat"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:scrollbars="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".ui.menu.menu_signin.menu.MenuAddressFragment">
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_marginTop="15dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_width="match_parent"
android:layout_height="40dp"
android:orientation="horizontal">
<Button
android:id="#+id/buttonMoveTambahAlamat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:background="#null"
android:drawableStart="#drawable/ic_tambah_alamat"
android:drawablePadding="10dp"
android:text="Tambah Alamat"
android:textAllCaps="false"
android:textColor="#color/colorRed"
android:textSize="14sp"
android:textStyle="normal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:text="Daftar Alamat"
android:textColor="#color/colorRed"
android:textSize="14sp"
android:textStyle="bold" />
</RelativeLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rc_tambah_alamat"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/gunakanAlamat"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginStart="10dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="100dp"
android:background="#drawable/bg_button_red"
android:text="Gunakan Alamat"
android:textAllCaps="false"
android:textColor="#android:color/white"
android:textSize="16sp" />
</LinearLayout>
</androidx.core.widget.NestedScrollView>
</FrameLayout>
RecyclerView Layout :
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
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="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginTop="12dp"
android:layout_marginRight="15dp"
android:layout_marginBottom="12dp"
android:orientation="vertical"
app:cardBackgroundColor="#color/colorWhite"
app:cardCornerRadius="4dp"
app:cardElevation="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<RadioButton
android:id="#+id/radioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/radioButton">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/nameUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:justificationMode="inter_word"
android:text="Muhammad Rafi Bahrur Rizki"
android:textColor="#color/colorBlack"
android:textSize="14sp"
android:textStyle="bold"
tools:ignore="UnusedAttribute" />
<TextView
android:id="#+id/addressUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:maxLines="1"
android:text="(Alamat Kantor)"
android:textSize="14sp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/streetName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:justificationMode="inter_word"
android:text="Mangga Dua Square Lantai 1 Jakarta,"
android:textColor="#color/textColorSaksFifthAvenue"
android:textSize="14sp"
tools:ignore="UnusedAttribute" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/blokAddressUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:text="Blok C no. 148 - 150"
android:textColor="#color/textColorSaksFifthAvenue"
android:textSize="14sp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/cityAddressUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:text="DKI Jakarta - 15025"
android:textColor="#color/textColorSaksFifthAvenue"
android:textSize="14sp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/countryAddressUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:text="DKI Jakarta - 15025"
android:textColor="#color/textColorSaksFifthAvenue"
android:textSize="14sp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/phoneUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:text="0812951825"
android:textColor="#color/textColorSaksFifthAvenue"
android:textSize="14sp" />
</TableRow>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<Button
android:id="#+id/buttonEdit"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginStart="8dp"
android:drawableStart="#drawable/ic_edit"
android:text="Edit"
android:textAllCaps="false"
android:textSize="12sp" />
<Button
android:id="#+id/buttonDelete"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginStart="10dp"
android:layout_toEndOf="#id/buttonEdit"
android:drawableStart="#drawable/ic_delete"
android:text="Hapus"
android:textAllCaps="false"
android:textSize="12sp" />
</RelativeLayout>
</TableLayout>
</RelativeLayout>
</androidx.cardview.widget.CardView>
When i select RadioButton, only data in RadioButton will be obtained. And when i click button, the data will be send to another activity.
Adapter RecyclerView :
public class AdapterGetAddress extends RecyclerView.Adapter<AdapterGetAddress.ViewHolder> {
Context context;
private List<ModelGetAddress> modelGetAddressList;
private BaseApiService baseApiService;
private int previousSelected = -1;
public AdapterGetAddress(Context context, List<ModelGetAddress> modelGetAddressList) {
this.context = context;
this.modelGetAddressList = modelGetAddressList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_address, parent, false);
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
final ModelGetAddress adapterAddress = modelGetAddressList.get(position);
}
#Override
public int getItemCount() {
return modelGetAddressList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView nameUser, addressUser, streetName, blokAddressUser, cityAddressUser, countryUser, phoneUser;
private RadioButton radioButton;
public ViewHolder(#NonNull View itemView) {
super(itemView);
nameUser = itemView.findViewById(R.id.nameUser);
addressUser = itemView.findViewById(R.id.addressUser);
streetName = itemView.findViewById(R.id.streetName);
countryUser = itemView.findViewById(R.id.countryAddressUser);
blokAddressUser = itemView.findViewById(R.id.blokAddressUser);
cityAddressUser = itemView.findViewById(R.id.cityAddressUser);
phoneUser = itemView.findViewById(R.id.phoneUser);
radioButton = itemView.findViewById(R.id.radioButton);
radioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
previousSelected = getAdapterPosition();
notifyItemRangeChanged(0, modelGetAddressList.size());
// I want this All String will be send when i click button in Fragment
String getNameUser = nameUser.getText().toString();
String getAddressUser = streetName.getText().toString();
String getCountryUser = countryUser.getText().toString();
String getBlokUser = blokAddressUser.getText().toString();
String getCityUser = cityAddressUser.getText().toString();
String getPhoneUser = phoneUser.getText().toString();
}
});
}
}
}
Code in Fragment :
public class MenuAddressFragment extends Fragment {
private Button gunakanAlamat;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_menu_address, container, false);
gunakanAlamat = view.findViewById(R.id.gunakanAlamat);
gunakanAlamat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Here's were i'm stuck
}
});
return view;
}
}
You can solve this via an interface.
public interface ItemClickedCallback{
void onItemClicked(String nameUser //, the other data you wanna pass );
}
pass it through the constructor of your adapter.
Use this adapter constructor
ItemClickedCallback callback;
public AdapterGetAddress(Context context, List<ModelGetAddress> modelGetAddressList, ItemClickedCallback callback) {
this.context = context;
this.modelGetAddressList = modelGetAddressList;
this.callback= callback;
}
When checking a radio button of any item; call the interface method, like this.
radioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
previousSelected = getAdapterPosition();
notifyItemRangeChanged(0, modelGetAddressList.size());
// I want this All String will be send when i click button in Fragment
String getNameUser = nameUser.getText().toString();
String getAddressUser = streetName.getText().toString();
String getCountryUser = countryUser.getText().toString();
String getBlokUser = blokAddressUser.getText().toString();
String getCityUser = cityAddressUser.getText().toString();
String getPhoneUser = phoneUser.getText().toString();
callback.onItemClicked(getNameUser //, the rest..);
}
});
Now, when you initialize the adapter in the fragment, create the new interface via the constructor and assign the data to class variables like this.
public class MenuAddressFragment extends Fragment {
private Button gunakanAlamat;
private String nameUser_;
// the rest...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_menu_address, container, false);
AdapterGetAddress adapter = new AdapterGetAddress(getActivity, list, new ItemClickedCallback() {
#Override
public void onItemClicked(String userName //, the rest..) {
// assign to the class variable like this
nameUser_ = userName;
// the rest..
}
}););
gunakanAlamat = view.findViewById(R.id.gunakanAlamat);
gunakanAlamat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Use the data as you want..
}
});
return view;
}
}

How to show the time when an item in a recyclerview was created?

I want to make this:
I have a RecyclerView, wherein for each item I create I want to show the time when the item was created. I want to display the time within this item.
My code:
public class VerIncidencia extends AppCompatActivity {
private FirebaseRecyclerAdapter mAdapter;
private DatabaseReference mDatabase;
String idIncidencia;
String idEmpresa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ver_incidencia);
String uid = FirebaseAuth.getInstance().getUid();
idIncidencia = getIntent().getStringExtra("INCIDENCIA_KEY");
idEmpresa = getIntent().getStringExtra("EMPRESA_KEY");
mDatabase = FirebaseDatabase.getInstance().getReference().child("incidencia").child(uid);
RecyclerView recyclerView = findViewById(R.id.list_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
Query postsQuery = mDatabase;
FirebaseRecyclerOptions options = new FirebaseRecyclerOptions.Builder<Incidencia>()
.setQuery(postsQuery, Incidencia.class)
.setLifecycleOwner(this)
.build();
mAdapter = new FirebaseRecyclerAdapter<Incidencia, IncidenciaViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull IncidenciaViewHolder holder, final int position, #NonNull final Incidencia empresa) {
holder.departamento.setText(empresa.departamento);
holder.prioridad.setText(empresa.prioridad);
holder.motivo.setText(empresa.motivo);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(VerIncidencia.this, VerIncidenciaCompleta.class);
intent.putExtra("INCIDENCIA_KEY", getRef(position).getKey());
startActivity(intent);
}
});
}
#Override
public IncidenciaViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_incidencia, parent, false);
return new IncidenciaViewHolder(view);
}
};
recyclerView.setAdapter(mAdapter);
}
}
ViewHolder:
public class IncidenciaViewHolder extends RecyclerView.ViewHolder{
TextView departamento;
TextView prioridad;
TextView motivo;
public IncidenciaViewHolder(View itemView) {
super(itemView);
departamento = itemView.findViewById(R.id.departamento);
prioridad = itemView.findViewById(R.id.prioridad);
motivo = itemView.findViewById(R.id.motivo);
}
}
XML:
<?xml version="1.0" encoding="utf-8"?><android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/departamento"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_marginTop="-40dp"
android:textStyle="bold"
android:textColor="#android:color/black"
android:textSize="25sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/prioridad"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_marginTop="30dp"
android:textColor="#android:color/black"
android:textSize="25sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/motivo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_marginTop="85dp"
android:textColor="#android:color/black"
android:textSize="25sp" />
</LinearLayout>

Android - OnClick inside gridview row

I'm trying to launch a activity from a button inside my gridview item, meaning that when user click on gridview Item it should do one function and when the user click on the button inside the gridview item it should do another function, let me elaborate, here is my single item layout that is being populated inside of my gridview;
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:foreground="?android:attr/selectableItemBackground"
android:orientation="horizontal"
app:cardCornerRadius="5dp"
app:cardElevation="3dp"
app:cardPreventCornerOverlap="false"
app:cardUseCompatPadding="true">
<RelativeLayout
android:id="#+id/single_row"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingTop="10dp">
<com.mikhaellopez.circularimageview.CircularImageView
android:id="#+id/imgFood"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
app:civ_border_color="#ffffff"
app:civ_border_width="2dp"
app:civ_shadow="true"
app:civ_shadow_color="#000000"
app:civ_shadow_radius="10" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/imgFood">
<TextView
android:id="#+id/txtName"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="16sp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/currentid"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:layout_below="#+id/txtName"
android:text="Current ID : "
android:visibility="visible"
/>
<TextView
android:id="#+id/studentid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ID"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="16sp"
android:layout_below="#+id/txtName"
android:layout_toRightOf="#+id/currentid"
android:layout_marginEnd="30dp"
android:layout_marginRight="30dp"
/>
</RelativeLayout>
<Button
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="end"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/editit"
android:background="#android:drawable/btn_dialog"/>
</RelativeLayout>
here is how the above layout looks:
and here is my adapter getview from where I try to do the intent/actions from;
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
View row = view;
ViewHolder holder = new ViewHolder();
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(layout, null);
holder.txtName = (TextView) row.findViewById(R.id.txtName);
holder.txtPrice = (TextView) row.findViewById(R.id.studentid);
holder.imageView = (CircularImageView) row.findViewById(R.id.imgFood);
holder.dit = (Button) row.findViewById(R.id.editit);
final ViewHolder finalHolder = holder;
holder.dit.setOnClickListener(new View.OnClickListener() {
String getname = finalHolder.txtName.getText().toString();
String gethandicap = finalHolder.txtPrice.getText().toString();
#Override
public void onClick(View v) {
// Do something
Intent editintent = new Intent(context, MainActivity.class);
editintent.putExtra("studentname", getname);
editintent.putExtra("studentid", getID);
context.startActivity(editintent);
}
});
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
Sudentdb student = studentsList.get(position);
holder.txtName.setText(student.getName());
holder.txtPrice.setText(student.getID());
if (student.getImage() != null && student.getImage().length > 0) {
Glide.with(context)
.load(student.getImage())
.into(holder.imageView);
} else {
holder.imageView.setImageBitmap(null);
}
return row;
}
The problem I'm having is that the button inside the gridview item is not performing any actions, in log it only says ACTION_DOWN and since I added a button inside the item the item onclick also doesn't work.
EDIT; ADDING GRIDVIEW ONCLICK AND LAYOUT
gridView = (GridView) findViewById(R.id.gridView);
list = new ArrayList<>();
adapter = new StudentListAdapter(this, R.layout.food_items, list);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String dataFromGrid;
dataFromGrid = ((TextView)(view.findViewById(R.id.txtName))).getText().toString();
Intent i = new Intent(getApplicationContext(), Student.class);
i.putExtra("unfromstudent",dataFromGrid);
startActivity(i);
gridview layout (I have tried focusable and clickable)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:focusable="true"
>
<GridView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:id="#+id/gridView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:columnWidth="120dp"
android:gravity="center"
android:layout_margin="2dp"
android:numColumns="1"
/>
</RelativeLayout>
Change you XML, i have tested below xml its works fine with
GridView
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:foreground="?android:attr/selectableItemBackground"
android:orientation="horizontal"
app:cardCornerRadius="5dp"
app:cardElevation="3dp"
app:cardPreventCornerOverlap="false"
app:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="false"
android:orientation="horizontal">
<com.mikhaellopez.circularimageview.CircularImageView
android:id="#+id/imgFood"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_margin="10dp"
app:civ_border_color="#ffffff"
app:civ_border_width="2dp"
app:civ_shadow="true"
app:civ_shadow_color="#000000"
app:civ_shadow_radius="10" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
android:layout_weight="1"
android:gravity="center_horizontal|center_vertical"
android:orientation="vertical">
<TextView
android:id="#+id/txtName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="16sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/currentid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtName"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:text="Current ID : "
android:visibility="visible" />
<TextView
android:id="#+id/studentid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtName"
android:layout_marginEnd="30dp"
android:layout_marginRight="30dp"
android:layout_toRightOf="#+id/currentid"
android:text="ID"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="16sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="30dp"
android:layout_height="30dp">
<Button
android:id="#+id/editit"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="end"
android:background="#android:drawable/btn_dialog"
android:focusable="false" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
Your Grid View XML will be Like this.
<GridView
android:id="#+id/grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true">
</GridView>
I don't have enough reputation so i can't comment your question, why don't you use a recyclerview with a gridLayoutManager? You can see a basic example here .
After that you can implement your recyclerview adapter this way:
public class StudentsAdapter extends RecyclerView.Adapter<StudentsAdapter.ViewHolder> {
private final OnStudentItemClickListener mListener;
private Context mContext;
private List<Student> mStudents;
public StudentsAdapter(Context context, List<Student> items, OnStudentItemClickListener listener) {
mContext = context;
mStudents =items;
mListener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_student, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
Student student = mStudents.get(position);
holder.mTextName.setText(student.getName());
holder.mTextPrice.setText(student.getID());
if (student.getImage() != null && student.getImage().length > 0) {
Glide.with(context)
.load(student.getImage())
.into(holder.imageView);
} else {
holder.imageView.setImageBitmap(null);
}
}
#Override
public int getItemCount() {
return mStudents.size();
}
public interface OnStudentItemClickListener {
void onStudentItemClick(Student student);
void onStudentButtonClick(Student student);
}
public class ViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
TextView mTextName;
TextView mTextPrice;
CircleImageView mImageView;
Button mDit;
public ViewHolder(View view) {
super(view);
mTextName = (TextView) view.findViewById(R.id.txtName);
mTextPrice = (TextView) view.findViewById(R.id.studentid);
mImageView = (CircleImageView) view.findViewById(R.id.imgFood);
mDit = (Button) view.findViewById(R.id.editit);
mDit.setOnClickListener(view1 -> {
if (null != mListener) {
mListener.onStudentButtonClick(mStudents.get(getAdapterPosition()));
}
});
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (null != mListener) {
mListener.onStudentItemClick(mStudents.get(getAdapterPosition()));
}
}
}
}

Errors on Adding ListView to Fragment

I am trying to add a listview to an existing android fragment. I made a layout xml file for items in the listview, modified the previous fragment.xml, wrote a new arrayadapter and added something to the fragment.java. But whenever I call the notifyDataSetChanged() method in the fragment.java, I got an error: android.content.res.Resources$NotFoundException: String resource ID #0x0, and then the app crashes. Below please find my codes.
layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="7dp">
<ImageView
android:layout_width="72dp"
android:layout_height="72dp"
android:id="#+id/iv_checkIcon"
android:layout_margin="7dp"
android:background="#EEEEEE"
android:contentDescription="Provider icon"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_toRightOf="#id/iv_checkIcon"
android:layout_marginTop="4dp"
android:layout_marginBottom="4dp"
android:layout_marginLeft="5dp"
>
<TextView
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/tv_checkName"
android:text="Provider name"
android:textSize="20dp"
/>
<TextView
android:layout_width="250dp"
android:layout_height="wrap_content"
android:id="#+id/tv_checkInDate"
android:text="Check In Date"
android:textSize="14dp"
android:textColor="#888888"
android:layout_marginTop="4dp"/>
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_checkPoints"
android:layout_alignParentRight="true"
android:text="100分"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:textSize="18dp"
android:textColor="#CF1A12"
/>
</RelativeLayout>
fragment.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragment.MeActivity">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/me_bg2"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/fake_head"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:id="#+id/iv_fake_head"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/iv_fake_head"
android:text="--"
android:textSize="22dp"
android:textColor="#ffffff"
android:layout_marginTop="15dp"
android:id="#+id/tv_name"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/tv_name"
android:text="积分"
android:textColor="#ffffff"
android:layout_marginTop="15dp"
android:textSize="20dp"
android:background="#drawable/me_points_bg"
android:id="#+id/tv_points"
/>
</RelativeLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lv_histories"
android:layout_gravity="bottom" />
</FrameLayout>
Arrayadapter.java
public class RecordArrayAdapter extends ArrayAdapter<CheckInRecord.CheckInRec> {
private int resourceId;
private Context context;
private List<CheckInRecord.CheckInRec> checkInRecList;
public RecordArrayAdapter(Context context, int resourceId, List<CheckInRecord.CheckInRec> checkInRecList)
{
super(context, resourceId, checkInRecList);
this.resourceId = resourceId;
this.context = context;
this.checkInRecList = checkInRecList;
}
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null){
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
convertView = inflater.inflate(resourceId, parent, false);
}
TextView textViewName = (TextView) convertView.findViewById(R.id.tv_checkName);
TextView textViewCheckInDate = (TextView) convertView.findViewById(R.id.tv_checkInDate);
TextView textViewPoints = (TextView) convertView.findViewById(R.id.tv_checkPoints);
ImageView imageViewIcon = (ImageView) convertView.findViewById(R.id.iv_checkIcon);
CheckInRecord.CheckInRec checkInRec = checkInRecList.get(position);
textViewName.setText(checkInRec.providerName);
textViewCheckInDate.setText(checkInRec.checkInDate);
textViewPoints.setText(checkInRec.providerPoints);
ImageLoader.getInstance().displayImage(checkInRec.providerIcon, imageViewIcon, Utility.displayImageOptions);
return convertView;
}
public int getIsPrize(int position) {return (this.checkInRecList.get(position).isPrize);}
}
fragment.java
public class MeFragment extends Fragment implements ApiRequestDelegate {
private TextView textViewName;
private TextView textViewPoints;
private ProgressDialog progressDialog;
private RecordArrayAdapter recordArrayAdapter;
private List<CheckInRecord.CheckInRec> checkInRecList = new ArrayList<CheckInRecord.CheckInRec>();
public MeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ApiManager.getInstance().checkInHistories(AppDataManager.getInstance().getUserToken(), AppDataManager.getInstance().getUserPhone(),
Utility.getPictureSize(), this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View fragmentView = inflater.inflate(R.layout.fragment_me, container, false);
textViewName = (TextView) fragmentView.findViewById(R.id.tv_name);
textViewPoints = (TextView) fragmentView.findViewById(R.id.tv_points);
ListView listViewRec = (ListView) fragmentView.findViewById(R.id.lv_histories);
recordArrayAdapter = new RecordArrayAdapter(this.getActivity(), R.layout.row_record, checkInRecList);
listViewRec.setAdapter(recordArrayAdapter);
return fragmentView;
}
#Override
public void apiCompleted(ApiResult apiResult, HttpRequest httpRequest) {
if (progressDialog!=null){
progressDialog.dismiss();
}
if (!apiResult.success){
ApiManager.handleMessageForReason(apiResult.failReason, getActivity());
return;
}
CheckInRecord checkInRecord = (CheckInRecord) apiResult.valueObject;
if (checkInRecord != null){
textViewName.setText(checkInRecord.userName);
textViewPoints.setText(String.format("积分%d分", checkInRecord.userPoints));
this.checkInRecList.clear();
this.checkInRecList.addAll(checkInRecord.checkInRecList);
recordArrayAdapter.notifyDataSetChanged();
}
}
}
Make sure checkInRec.providerName, checkInRec.checkInDate and checkInRec.providerPoints values that you set as TextView text have a type of String and cast it to String if it's integer.
// cast to String if checkInRec.checkInDate is integer
textViewPoints.setText(String.valueOf(checkInRec.providerPoints));
UPD:
It seems ListView is located behind header view. Try to change root view of fragment.xml from FrameLayout to LinearLayout with android:orientation="vertical" attribute. Like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".fragment.MeActivity">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/me_bg2"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/fake_head"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:id="#+id/iv_fake_head"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/iv_fake_head"
android:text="--"
android:textSize="22dp"
android:textColor="#ffffff"
android:layout_marginTop="15dp"
android:id="#+id/tv_name"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/tv_name"
android:text="积分"
android:textColor="#ffffff"
android:layout_marginTop="15dp"
android:textSize="20dp"
android:background="#drawable/me_points_bg"
android:id="#+id/tv_points"
/>
</RelativeLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lv_histories"
android:layout_gravity="bottom" />
</LinearLayout>

Categories