Related
Add some fragment continuously then RecyclerView scroll lagging
I am remove image load library but not any improvement i am face same
problem.
I am also check this link click
add fragment then facing this problem. but replace fragment then not facing this problem
more add fragment then RecyclerView lagging. i think fragment memory issue
add more then three fragment continuously then face this problem
fragment xml
<FrameLayout
android:id="#+id/frameLayout_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar_main"
android:layout_above="#+id/linearLayout_adView_main" />
call fragment data
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelatedFragment relatedFragment = new RelatedFragment();
Bundle bundle = new Bundle();
bundle.putString("type", "related");
bundle.putString("post_id", statusLists.getId());
bundle.putString("cat_id", statusLists.getCid());
bundle.putString("typeLayout", "Landscape");
relatedFragment.setArguments(bundle);
getActivity().getSupportFragmentManager().beginTransaction().add(R.id.frameLayout_main, relatedFragment, string).addToBackStack(string).commitAllowingStateLoss();
}
});
xml file
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView_sub_category"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp" />
Fragment
public class RelatedFragment extends Fragment {
private Method method;
private OnClick onClick;
private String type, post_id, cat_id, typeLayout;
private ProgressBar progressBar;
private MaterialTextView textView_noData;
private RecyclerView recyclerView;
private List<SubCategoryList> relatedLists;
private SubCategoryAdapter subCategoryAdapter;
private LayoutAnimationController animation;
private Boolean isOver = false;
private int pagination_index = 1;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = LayoutInflater.from(getActivity()).inflate(R.layout.portrait_fragment, container, false);
GlobalBus.getBus().register(this);
MainActivity.toolbar.setTitle(getResources().getString(R.string.related_status));
relatedLists = new ArrayList<>();
onClick = new OnClick() {
#Override
public void position(int position, String title, String type, String status_type, String id, String tag) {
SCDetailFragment scDetailFragment = new SCDetailFragment();
Bundle bundle = new Bundle();
bundle.putString("id", id);
bundle.putString("type", type);
bundle.putString("status_type", status_type);
bundle.putInt("position", position);
scDetailFragment.setArguments(bundle);
getActivity().getSupportFragmentManager().beginTransaction().add(R.id.frameLayout_main, scDetailFragment, title).addToBackStack(title).commitAllowingStateLoss();
}
};
method = new Method(getActivity(), onClick);
assert getArguments() != null;
type = getArguments().getString("type");
post_id = getArguments().getString("post_id");
cat_id = getArguments().getString("cat_id");
typeLayout = getArguments().getString("typeLayout");
int resId = R.anim.layout_animation_fall_down;
animation = AnimationUtils.loadLayoutAnimation(getActivity(), resId);
progressBar = view.findViewById(R.id.progressbar_portrait_fragment);
textView_noData = view.findViewById(R.id.textView_portrait_fragment);
recyclerView = view.findViewById(R.id.recyclerView_portrait_fragment);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.addOnScrollListener(new EndlessRecyclerViewScrollListener(layoutManager) {
#Override
public void onLoadMore(int page, int totalItemsCount) {
if (!isOver) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
pagination_index++;
callData();
}
}, 1000);
} else {
subCategoryAdapter.hideHeader();
}
}
});
callData();
setHasOptionsMenu(true);
return view;
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.search_menu, menu);
MenuItem searchItem = menu.findItem(R.id.ic_searchView);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener((new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
if (method.isNetworkAvailable()) {
backStackRemove();
SearchFragment searchFragment = new SearchFragment();
Bundle bundle = new Bundle();
bundle.putString("search_menu", query);
bundle.putString("typeLayout", "Landscape");
searchFragment.setArguments(bundle);
getActivity().getSupportFragmentManager()
.beginTransaction().replace(R.id.frameLayout_main, searchFragment, query).commitAllowingStateLoss();
return false;
} else {
method.alertBox(getResources().getString(R.string.internet_connection));
}
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return true;
}
}));
super.onCreateOptionsMenu(menu, inflater);
}
private void backStackRemove() {
for (int i = 0; i < getActivity().getSupportFragmentManager().getBackStackEntryCount(); i++) {
getActivity().getSupportFragmentManager().popBackStack();
}
}
#Subscribe
public void getNotify(Events.FavouriteNotify favouriteNotify) {
for (int i = 0; i < relatedLists.size(); i++) {
if (relatedLists.get(i).getId().equals(favouriteNotify.getId())) {
if (relatedLists.get(i).getStatus_type().equals(favouriteNotify.getStatus_type())) {
relatedLists.get(i).setIs_favourite(favouriteNotify.getIs_favourite());
subCategoryAdapter.notifyItemChanged(i);
}
}
}
}
#Subscribe
public void getMessage(Events.InfoUpdate infoUpdate) {
if (subCategoryAdapter != null) {
for (int i = 0; i < relatedLists.size(); i++) {
if (relatedLists.get(i).getId().equals(infoUpdate.getId())) {
if (relatedLists.get(i).getStatus_type().equals(infoUpdate.getStatus_type())) {
switch (infoUpdate.getType()) {
case "all":
relatedLists.get(i).setTotal_viewer(infoUpdate.getView());
relatedLists.get(i).setTotal_likes(infoUpdate.getTotal_like());
relatedLists.get(i).setAlready_like(infoUpdate.getAlready_like());
break;
case "view":
relatedLists.get(i).setTotal_viewer(infoUpdate.getView());
break;
case "like":
relatedLists.get(i).setTotal_likes(infoUpdate.getTotal_like());
relatedLists.get(i).setAlready_like(infoUpdate.getAlready_like());
break;
}
subCategoryAdapter.notifyItemChanged(i);
}
}
}
}
}
private void callData() {
if (getActivity() != null) {
if (method.isNetworkAvailable()) {
if (method.pref.getBoolean(method.pref_login, false)) {
related(method.pref.getString(method.profileId, null), post_id, cat_id, typeLayout);
} else {
related("0", post_id, cat_id, typeLayout);
}
} else {
method.alertBox(getResources().getString(R.string.internet_connection));
}
}
}
private void related(String userId, String post_id, String cat_id, String typeLayout) {
if (subCategoryAdapter == null) {
relatedLists.clear();
progressBar.setVisibility(View.VISIBLE);
}
if (getActivity() != null) {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
JsonObject jsObj = (JsonObject) new Gson().toJsonTree(new API(getActivity()));
jsObj.addProperty("method_name", "related_status");
jsObj.addProperty("post_id", post_id);
jsObj.addProperty("cat_id", cat_id);
jsObj.addProperty("user_id", userId);
jsObj.addProperty("page", pagination_index);
jsObj.addProperty("filter_value", typeLayout);
jsObj.addProperty("lang_ids", method.pref.getString(method.language_ids, ""));
params.put("data", API.toBase64(jsObj.toString()));
client.post(Constant_Api.url, params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
if (getActivity() != null) {
String res = new String(responseBody);
try {
JSONObject jsonObject = new JSONObject(res);
if (jsonObject.has(Constant_Api.STATUS)) {
String status = jsonObject.getString("status");
String message = jsonObject.getString("message");
if (status.equals("-2")) {
method.suspend(message);
} else {
method.alertBox(message);
}
} else {
JSONArray jsonArray = jsonObject.getJSONArray(Constant_Api.tag);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String id = object.getString("id");
String status_type = object.getString("status_type");
String status_title = object.getString("status_title");
String status_layout = object.getString("status_layout");
String status_thumbnail_b = object.getString("status_thumbnail_b");
String status_thumbnail_s = object.getString("status_thumbnail_s");
String total_likes = object.getString("total_likes");
String total_viewer = object.getString("total_viewer");
String category_name = object.getString("category_name");
String already_like = object.getString("already_like");
String quote_bg = object.getString("quote_bg");
String quote_font = object.getString("quote_font");
String is_favourite = object.getString("is_favourite");
relatedLists.add(new SubCategoryList("", id, status_type, status_title, status_layout, status_thumbnail_b, status_thumbnail_s, total_viewer, total_likes, already_like, category_name, quote_bg, quote_font, is_favourite, "", ""));
}
if (jsonArray.length() == 0) {
if (subCategoryAdapter != null) {
isOver = true;
subCategoryAdapter.hideHeader();
}
}
if (subCategoryAdapter == null) {
if (relatedLists.size() == 0) {
textView_noData.setVisibility(View.VISIBLE);
} else {
textView_noData.setVisibility(View.GONE);
subCategoryAdapter = new SubCategoryAdapter(getActivity(), relatedLists, onClick, type);
recyclerView.setAdapter(subCategoryAdapter);
recyclerView.setLayoutAnimation(animation);
}
} else {
subCategoryAdapter.notifyDataSetChanged();
}
}
} catch (JSONException e) {
e.printStackTrace();
method.alertBox(getResources().getString(R.string.failed_try_again));
}
}
progressBar.setVisibility(View.GONE);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
progressBar.setVisibility(View.GONE);
method.alertBox(getResources().getString(R.string.failed_try_again));
}
});
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
// Unregister the registered event.
GlobalBus.getBus().unregister(this);
}
}
Adapter
public class SubCategoryAdapter extends RecyclerView.Adapter {
private Activity activity;
private Method method;
private int columnWidth;
private String type;
private Animation myAnim;
private List<SubCategoryList> subCategoryLists;
private final int VIEW_TYPE_LOADING = 0;
private final int VIEW_TYPE_ITEM = 1;
private final int VIEW_TYPE_QUOTES = 2;
public SubCategoryAdapter(Activity activity, List<SubCategoryList> subCategoryLists, OnClick interstitialAdView, String type) {
this.activity = activity;
this.type = type;
this.subCategoryLists = subCategoryLists;
method = new Method(activity, interstitialAdView);
columnWidth = (method.getScreenWidth());
myAnim = AnimationUtils.loadAnimation(activity, R.anim.bounce);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_ITEM) {
View view = LayoutInflater.from(activity).inflate(R.layout.sub_category_adapter, parent, false);
return new ViewHolder(view);
} else if (viewType == VIEW_TYPE_QUOTES) {
View v = LayoutInflater.from(activity).inflate(R.layout.quotes_adapter, parent, false);
return new Quotes(v);
} else if (viewType == VIEW_TYPE_LOADING) {
View v = LayoutInflater.from(activity).inflate(R.layout.layout_loading_item, parent, false);
return new ProgressViewHolder(v);
}
return null;
}
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, #SuppressLint("RecyclerView") final int position) {
if (holder.getItemViewType() == VIEW_TYPE_ITEM) {
final ViewHolder viewHolder = (ViewHolder) holder;
if (status_type.equals("gif")) {
Glide.with(activity)
.asBitmap()
.load(subCategoryLists.get(position).getStatus_thumbnail_s())
.placeholder(R.drawable.placeholder_landscape).into(viewHolder.imageView);
} else {
Glide.with(activity)
.load(subCategoryLists.get(position).getStatus_thumbnail_s())
.placeholder(R.drawable.placeholder_landscape).into(viewHolder.imageView);
}
viewHolder.imageView.setLayoutParams(new RelativeLayout.LayoutParams(columnWidth, columnWidth / 2 - 60));
viewHolder.textView_title.setText(subCategoryLists.get(position).getStatus_title());
viewHolder.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
method.onClickData(position, subCategoryLists.get(position).getStatus_title(), type, subCategoryLists.get(position).getStatus_type(), subCategoryLists.get(position).getId(), "");
}
});
} else if (holder.getItemViewType() == VIEW_TYPE_QUOTES) {
final Quotes quotes = (Quotes) holder;
quotes.relativeLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, columnWidth / 2));
Typeface typeface = Typeface.createFromAsset(activity.getAssets(), "text_font/" + subCategoryLists.get(position).getQuote_font());
quotes.textView.setTypeface(typeface);
quotes.textView.setText(subCategoryLists.get(position).getStatus_title());
quotes.textView.post(new Runnable() {
#Override
public void run() {
ViewGroup.LayoutParams params = quotes.textView.getLayoutParams();
if (params == null) {
params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}
final int widthSpec = View.MeasureSpec.makeMeasureSpec(quotes.textView.getWidth(), View.MeasureSpec.UNSPECIFIED);
final int heightSpec = View.MeasureSpec.makeMeasureSpec(quotes.textView.getHeight(), View.MeasureSpec.UNSPECIFIED);
quotes.textView.measure(widthSpec, heightSpec);
quotes.textView.setMaxLines(heightSpec / quotes.textView.getLineHeight());
quotes.textView.setEllipsize(TextUtils.TruncateAt.END);
}
});
quotes.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
method.onClickData(position, subCategoryLists.get(position).getStatus_title(), type, subCategoryLists.get(position).getStatus_type(), subCategoryLists.get(position).getId(), "");
}
});
}
}
#Override
public int getItemCount() {
return subCategoryLists.size() + 1;
}
public void hideHeader() {
ProgressViewHolder.progressBar.setVisibility(View.GONE);
}
#Override
public int getItemViewType(int position) {
if (position != subCategoryLists.size()) {
if (subCategoryLists.get(position).getStatus_type().equals("quote")) {
return VIEW_TYPE_QUOTES;
} else {
return VIEW_TYPE_ITEM;
}
} else {
return VIEW_TYPE_LOADING;
}
}
public class ViewHolder extends RecyclerView.ViewHolder {
private RelativeLayout relativeLayout;
private ImageView imageView;
private MaterialTextView textView_title;
public ViewHolder(View itemView) {
super(itemView);
relativeLayout = itemView.findViewById(R.id.relativeLayout_subCat_adapter);
imageView = itemView.findViewById(R.id.imageView_subCat_adapter);
textView_title = itemView.findViewById(R.id.textView_title_subCat_adapter);
}
}
public class Quotes extends RecyclerView.ViewHolder {
private LinearLayout linearLayout;
private RelativeLayout relativeLayout;
private MaterialTextView textView;
public Quotes(#NonNull View itemView) {
super(itemView);
linearLayout = itemView.findViewById(R.id.ll_quotes_adapter);
textView = itemView.findViewById(R.id.textView_quotes_adapter);
relativeLayout = itemView.findViewById(R.id.rel_quotes_adapter);
}
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder {
public static ProgressBar progressBar;
public ProgressViewHolder(View v) {
super(v);
progressBar = v.findViewById(R.id.progressBar);
}
} }
When I scroll my list it follows the pagination as expected.
But when I open my search view and type something and reset the editText and try to load next list it does not update in adapter unless I swipe my fragments or hide the searchview.
In both the cases i set my edittext to null so it gets updated on that call thats where i think but need your help.
I did lots of search yesterday but unfortunately found nothing. Hope I'll find help here. Thanks
MainActivity
public class MainActivity extends AppCompatActivity {
#BindView(R.id.vp_horizontal_ntb)
ViewPager viewPager;
#BindView(R.id.ntb_horizontal)
TabLayout topNavigationBar;
#BindView(R.id.toolbar)
Toolbar toolbar;
#BindView(R.id.appbar)
AppBarLayout mAppBar;
#BindView(R.id.searchIcon)
ImageView search;
#BindView(R.id.searchBoxLinOut)
LinearLayout searchBox;
#BindView(R.id.deleteSearchText)
ImageView deleteText;
#BindView(R.id.searchtext)
EditText et_search;
#BindView(R.id.imageView)
ImageView backButton;
String target = "nothing";
Context context;
Received_Fragment rf = new Received_Fragment();
Given_Fragment gf = new Given_Fragment();
InputMethodManager imm;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//StatusBarCompat.setStatusBarColor(this,
getResources().getColor(R.color.md_grey_300));
setContentView(R.layout.layouot_all_reviews);
ButterKnife.bind(this);
context = this;
viewPager.setOffscreenPageLimit(2);
viewPager.setCurrentItem(0);
viewPager.postDelayed(new Runnable() {
#Override
public void run() {
setPosition();
}
}, 100);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window w = getWindow(); // in Activity's onCreate() for instance
w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);
imm = (InputMethodManager)
context.getSystemService(Context.INPUT_METHOD_SERVICE);
setUpTabs();
handleClicks();
}
private void handleClicks() {
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int
positionOffsetPixels) {
et_search.setText(null);
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
et_search.setText(null);
}
});
backButton.setOnClickListener(v -> {
onBackPressed();
});
search.setOnClickListener(v -> {
searchBox.bringToFront();
if (searchBox.getVisibility() == View.VISIBLE) {
hideSearch(searchBox);
} else {
showSearch(searchBox);
}
});
deleteText.setOnClickListener(v -> {
if (et_search.getText().length() > 1) {
et_search.setText(null);
} else hideSearch(searchBox);
});
et_search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int
count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (s.toString().trim().length() == 0) {
rf.update();
gf.update();
}
}
#Override
public void afterTextChanged(Editable s) {
if (viewPager.getCurrentItem() == 0) {
rf.filter(s.toString());
} else
gf.filter(s.toString());
}
});
}
private void showSearch(View view) {
TranslateAnimation animate = new TranslateAnimation(
0, // fromXDelta
0, // toXDelta
-view.getHeight() * 2, // fromYDelta
0); // toYDelta
animate.setDuration(500);
animate.setFillAfter(false);
view.startAnimation(animate);
view.requestFocus();
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
view.setVisibility(View.VISIBLE);
backButton.setEnabled(false);
}
private void hideSearch(View view) {
TranslateAnimation animate = new TranslateAnimation(
0, // fromXDelta
0, // toXDelta
0, // fromYDelta
-view.getHeight() * 3); // toYDelta
animate.setDuration(500);
animate.setFillAfter(false);
view.startAnimation(animate);
view.setVisibility(View.INVISIBLE);
backButton.setEnabled(true);
et_search.setText(null);
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
private void setPosition() {
target = getIntent().getStringExtra("WHERE");
if (target.equals("given")) {
switchFragment(1);
} else {
viewPager.setCurrentItem(0);
}
}
public void switchFragment(int target) {
viewPager.setCurrentItem(target);
}
private void setUpTabs() {
viewPager.setAdapter(new
FragmentPagerAdapter(getSupportFragmentManager()) {
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return rrf;
case 1:
return rgf;
default:
return new Default_Fragment();
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Received";
case 1:
return "Given";
default:
return "Error";
}
}
});
topNavigationBar.setupWithViewPager(viewPager);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
for (Fragment fragment : getSupportFragmentManager().getFragments()) {
fragment.onActivityResult(requestCode, resultCode, data);
}
}
}
Received_Fragment
public class Received_Fragment extends Fragment {
#BindView(R.id.recyclerView)
RecyclerView recyclerView;
#BindView(R.id.shimmer_view_container)
ShimmerFrameLayout shimmerLayout;
#BindView(R.id.msg)
TextView message;
//Initialization of Classes
SessionManager session;
ApiClient apiClient;
List<ClassName> List = new ArrayList<>();
Boolean isScrolling = false;
boolean isDataLoaded = false;
int currentItem, totalItem, scrollOutItem;
//Properties to access
Context context;
String email;
String userId;
String access_token;
RecievedAdapter adapter;
BottomSheetBehavior sheetBehavior;
LinearLayoutManager linearLayoutManager;
private boolean isLastPage = false;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable
ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.recycler_view_layout,
container, false);
ButterKnife.bind(this, view);
context = getContext();
session = new SessionManager(context);
HashMap<String, String> user = session.getUserDetails();
email = user.get(SessionManager.KEY_EMAIL);
access_token = user.get(SessionManager.KEY_ACCESS_TOKEN);
userId = user.get(SessionManager.KEY_USER_ID);
apiClient = ((Common)
getActivity().getApplication()).getClient().create(ApiClient.class);
shimmerLayout.startShimmerAnimation();
linearLayoutManager = new LinearLayoutManager(getContext());
adapter = new RecievedAdapter(List, context,
recyclerView);
adapter.setHasStableIds(true);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(feedsAdapter);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int
newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
currentItem = linearLayoutManager.getChildCount();
totalItem = linearLayoutManager.getItemCount();
scrollOutItem = linearLayoutManager.findFirstVisibleItemPosition();
if (!isScrolling && !isLastPage) {
if ((currentItem + scrollOutItem) >= totalItem && scrollOutItem >= 0) {
LoadMoreData();
}
}
}
});
getData();
return view;
}
public void filter(String text) {
feedsAdapter.notifyDataSetChanged();
List<Rating> temp = new ArrayList();
for (Rating d : feedsList) {
String tempF = "";
for (int i = 0; i < d.getFeatures().size(); i++) {
if (d.getFeatures().get(i).getName()!=null) {
tempF += d.getFeatures().get(i).getName()+",";
Log.d("This is name ", " Feature " + tempF);
if (tempF.toLowerCase().contains(text.toLowerCase())){
if (!temp.contains(d)){
temp.add(d);
}
}
}
}
if (d.getName().toLowerCase().contains(text.toLowerCase())&& !d.getAnonymous()) {
if (!temp.contains(d)){
temp.add(d);
}
}
}
//update recyclerview
feedsAdapter.updateList(temp);
}
private void getData() {
List.addAll(allRecieved);
List.remove(0);
adapter = new RecievedAdapter(List, context, recyclerView);
shimmerLayout.setVisibility(View.GONE);
recyclerView.setAdapter(feedsAdapter);
recyclerView.invalidate();
}
private void LoadMoreData() {
//Log.d("LoadMoreData", "Executing");
isScrolling = true;
if (allRecieved.get(0).getSize() == 0) {
isLastPage = true;
Toast.makeText(context, "That's All", Toast.LENGTH_SHORT).show();
} else {
isScrolling = false;
allGiven.remove(0);
if (!List.contains(allRecieved)) {
List.addAll(allRecieved);
adapter.notifyDataSetChanged();
} else {
Toast.makeText(context, "Call Repeated", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (adapter != null) {
adapter.onActivityResult(requestCode, resultCode, data);
}
}
public void update() {
adapter.updateOriginalList();
}
}
Given_Fragment
public class Given_Fragment extends Fragment {
#BindView(R.id.recyclerView)
RecyclerView recyclerView;
#BindView(R.id.shimmer_view_container)
ShimmerFrameLayout shimmerLayout;
#BindView(R.id.msg)
TextView message;
//Initialization of Classes
SessionManager session;
ApiClient apiClient;
List<ClassName> List = new ArrayList<>();
Boolean isScrolling = false;
boolean isDataLoaded = false;
int currentItem, totalItem, scrollOutItem;
//Properties to access
Context context;
String email;
String userId;
String access_token;
GivenAdapter adapter;
BottomSheetBehavior sheetBehavior;
LinearLayoutManager linearLayoutManager;
private boolean isLastPage = false;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable
ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.recycler_view_layout,
container, false);
ButterKnife.bind(this, view);
context = getContext();
session = new SessionManager(context);
HashMap<String, String> user = session.getUserDetails();
email = user.get(SessionManager.KEY_EMAIL);
access_token = user.get(SessionManager.KEY_ACCESS_TOKEN);
userId = user.get(SessionManager.KEY_USER_ID);
apiClient = ((Common)
getActivity().getApplication()).getClient().create(ApiClient.class);
shimmerLayout.startShimmerAnimation();
linearLayoutManager = new LinearLayoutManager(getContext());
adapter = new GivenAdapter(List, context,
recyclerView);
adapter.setHasStableIds(true);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(feedsAdapter);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int
newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
currentItem = linearLayoutManager.getChildCount();
totalItem = linearLayoutManager.getItemCount();
scrollOutItem = linearLayoutManager.findFirstVisibleItemPosition();
if (!isScrolling && !isLastPage) {
if ((currentItem + scrollOutItem) >= totalItem && scrollOutItem >= 0) {
LoadMoreData();
}
}
}
});
getData();
return view;
}
public void filter(String text) {
feedsAdapter.notifyDataSetChanged();
List<Rating> temp = new ArrayList();
for (Rating d : feedsList) {
String tempF = "";
for (int i = 0; i < d.getFeatures().size(); i++) {
if (d.getFeatures().get(i).getName()!=null) {
tempF += d.getFeatures().get(i).getName()+",";
Log.d("This is name ", " Feature " + tempF);
if (tempF.toLowerCase().contains(text.toLowerCase())){
if (!temp.contains(d)){
temp.add(d);
}
}
}
}
if (d.getName().toLowerCase().contains(text.toLowerCase())&& !d.getAnonymous()) {
if (!temp.contains(d)){
temp.add(d);
}
}
}
//update recyclerview
feedsAdapter.updateList(temp);
}
private void getData() {
List.addAll(allgiven);
List.remove(0);
adapter = new GivenAdapter(List, context, recyclerView);
shimmerLayout.setVisibility(View.GONE);
recyclerView.setAdapter(feedsAdapter);
recyclerView.invalidate();
}
private void LoadMoreData() {
//Log.d("LoadMoreData", "Executing");
isScrolling = true;
if (allgiven.get(0).getSize() == 0) {
isLastPage = true;
Toast.makeText(context, "That's All", Toast.LENGTH_SHORT).show();
} else {
isScrolling = false;
allGiven.remove(0);
if (!List.contains(allgiven)) {
List.addAll(allgiven);
adapter.notifyDataSetChanged();
} else {
Toast.makeText(context, "Call Repeated", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (adapter != null) {
adapter.onActivityResult(requestCode, resultCode, data);
}
}
public void update() {
adapter.updateOriginalList();
}
}
Both Adapters are same am attaching only one
AllRecievedAdapter
public class AllRecievedAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
public int layout_feed = R.layout.layout_feed;
private List<ClassName> list = new ArrayList<>();
private Context context;
private SessionManager session;
private ApiClient apiClient;
private String email, access_token;
private UpvotesAdapter adapter;
private BottomSheetDialog bottomSheetDialog;
EditText location;
EditText dateView;
private Activity activity;
public AllRecievedAdapter(List<ClassName> listList, Context applicationContext, RecyclerView recyclerView) {
this.list = listList;
this.context = applicationContext;
this.activity = (Activity) context;
this.templist = listList;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
session = new SessionManager(context);
apiClient = ((Common) ((Activity) context).getApplication()).getClient().create(ApiClient.class);
HashMap<String, String> user = session.getUserDetails();
email = user.get(SessionManager.KEY_EMAIL);
access_token = user.get(SessionManager.KEY_ACCESS_TOKEN);
View view = LayoutInflater.from(parent.getContext()).inflate(layout_feed, parent, false);
AllRecievedAdapter.ViewHolderReview listViewHolder = new AllRecievedAdapter.ViewHolderReview(view);
return listViewHolder;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
holder.userName.setText(list.get(holder.getAdapterPosition()).getName());
GlideApp.with(context).load(list.get(holder.getAdapterPosition()).getImage()).into(holder.userImage);
}
#Override
public int getItemCount() {
return list.size();
}
public void updateList(List<Rating> temp) {
list = temp;
notifyDataSetChanged();
}
public void updateOriginalList(){
list = templist;
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.userName)
TextView userName;
#BindView(R.id.userImage)
CircleImageView userImage;
public ViewHolderReview(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
If you need any extra information please let me know.
Call feedsAdapter.notifyDataSetChanged(); after updating the List. You are calling notifyDataSetChanged() before the list gets updated when the edittext is reset. Your filter method updates the list in the adapter but you are doing notifyDataSetChanged before the list is getting updated. You need to do it after
I need to update the textview which is inside view pager adpater's fragment
I have 2 fragments inside viewpager adapter.
and adapter itself is within the fragment.
Main fragment is initialize from MainActivity.
I used Greenrobot approach.for updating textview values on runtime.i get that value but UI is flickering means not getting good UI.
So Shall i used another approach please suggest me.
Adapter Code:-
public class SamplePagerAdapter extends FragmentPagerAdapter {
private final Random random = new Random();
private int mSize = 2;
private int heart_rate;
FragmentManager fm;
public SamplePagerAdapter(FragmentActivity activity, FragmentManager supportFragmentManager, int heart) {
super(supportFragmentManager);
fm = supportFragmentManager;
heart_rate = heart;
}
#Override
public int getCount() {
return mSize;
}
#Override
public Fragment getItem(int position) {
Fragment f = null;
if (position == 0) {
f = new MyFragment();
} else if (position == 1) {
f = new SecondFragment();
}
return f;
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
private boolean loadFragment(Fragment fragment) {
//switching fragment
if (fragment != null) {
fm.beginTransaction()
.replace(R.id.fragment_container, fragment)
.addToBackStack(null)
.commit();
return true;
}
return false;
}
}
//code for loading main Fragment:-MeasureFragment
private boolean loadFragment(Fragment fragment) {
//switching fragment
if (fragment != null) {
Bundle bundle = new Bundle();
bundle.putString("ble_address",bleAddress);
fragment.setArguments(bundle);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container,fragment)
.addToBackStack(null)
.commit();
return true;
}
return false;
}
//also add measure fragment code:-
public class MeasureFragment extends Fragment implements ISmctAlgoCallback, IBleOperateCallback {
protected boolean measureSwitch = false;
private EcgAlgo ecgAlgo;
private BluetoothLeService mBluetoothLeService;
protected ProgressDialog mProgressDialog;
protected boolean isContecting = false;
private TextView btn_start;
private TextView tv_heartrate, tv_time, tv_pauseorresume;
private RelativeLayout linear, linear1;
private LinearLayout linear_pause, linear_stop;
private CountDownTimer timer;
private int count = 0;
private boolean running;
private Handler handler;
Runnable runnable;
ImageView iv_pauseorresume;
private boolean onclick = true;
private boolean isstop = false;
private String bleAddress;
View view1, view2, view3, view4, view5;
TextView tv_toolbar_title, tv_alarm_setting, tv_battery_percentage;
private int heart_rate;
SamplePagerAdapter samplePagerAdapter;
private FragmentActivity myContext;
ViewPager viewpager;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_measure, container, false);
bleAddress = getArguments().getString("ble_address");
viewpager = (ViewPager) view.findViewById(R.id.viewpager);
CircleIndicator indicator = (CircleIndicator) view.findViewById(R.id.indicator);
btn_start = (TextView) view.findViewById(R.id.btn_start);
linear = (RelativeLayout) view.findViewById(R.id.linear);
linear1 = (RelativeLayout) view.findViewById(R.id.linear1);
linear_pause = (LinearLayout) view.findViewById(R.id.linear_pause);
linear_stop = (LinearLayout) view.findViewById(R.id.linear_stop);
tv_heartrate = (TextView) view.findViewById(R.id.tv_heart_rate);
tv_toolbar_title = (TextView) view.findViewById(R.id.tv_toolbar_title);
tv_alarm_setting = (TextView) view.findViewById(R.id.tv_alarm_setting);
tv_battery_percentage = (TextView) view.findViewById(R.id.tv_battery_percentage);
view1 = (View) view.findViewById(R.id.view1);
view2 = (View) view.findViewById(R.id.view2);
view3 = (View) view.findViewById(R.id.view3);
view4 = (View) view.findViewById(R.id.view4);
view5 = (View) view.findViewById(R.id.view5);
iv_pauseorresume = (ImageView) view.findViewById(R.id.iv_pauseorresume);
tv_pauseorresume = (TextView) view.findViewById(R.id.btn_pause);
tv_time = (TextView) view.findViewById(R.id.time);
ecgAlgo = new EcgAlgo();
ecgAlgo.setISmctAlgoCallback(this);
handler = new Handler();
samplePagerAdapter = new SamplePagerAdapter(getActivity(), getChildFragmentManager(), heart_rate);
viewpager.setAdapter(samplePagerAdapter);
indicator.setViewPager(viewpager);
viewpager.setCurrentItem(0);
linear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isstop) {
measureSwitch = true;
linear1.setVisibility(View.VISIBLE);
linear.setVisibility(View.GONE);
handler.post(runnable = new Runnable() {
#Override
public void run() {
int hours = count / 3600;
int minutes = (count % 3600) / 60;
int sec = count % 60;
String time = String.format("%02d:%02d:%02d", hours, minutes, sec);
tv_time.setText(time);
if (running) {
count++;
}
handler.postDelayed(this, 1000);
}
});
} else {
connectBle();
running = true;
}
}
});
linear_stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ecgAlgo.clearECGParam();
isstop = true;
measureSwitch = false;
count = 0;
handler.removeCallbacks(runnable);
linear1.setVisibility(View.GONE);
linear.setVisibility(View.VISIBLE);
}
});
linear_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (onclick) {
iv_pauseorresume.setImageResource(R.drawable.resume1);
tv_pauseorresume.setText("Resume");
running = false;
onclick = false;
} else {
onclick = true;
running = true;
iv_pauseorresume.setImageResource(R.drawable.pause);
tv_pauseorresume.setText("Pause");
}
}
});
return view;
}
private void connectBle() {
if (TextUtils.isEmpty(bleAddress)) {// 蓝牙地址为空
showToast(R.string.ble_address_empty);
} else if (mBluetoothLeService != null && !isContecting) {// 蓝牙未连接
showDialog();
mBluetoothLeService.connect(bleAddress);
measureSwitch = true;
} else if (mBluetoothLeService == null) {// 连接服务
connectBleService();
} else {// 其它
disDialog();
showToast(R.string.ble_connect_fail);
}
}
/**
* 连接蓝牙服务
*/
public void connectBleService() {
Intent gattServiceIntent = new Intent(getActivity(), BluetoothLeService.class);
getActivity().bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
}
#Override
public void bleData(short key, short value) {
// TODO Auto-generated method stub
switch (key) {
case SmctConstant.KEY_BLE_CONNECT_STATE:// 连接状态改变
if (SmctConstant.VALUE_BLE_CONNECTED == value) {// 已连接
// hasReConnectCount = 0;
//updateNotification(getString(R.string.notification_nomal));
} else if (SmctConstant.VALUE_BLE_DISCONNECTED == value) {// 连接断开
disDialog();
if (isContecting) {//如果已连接 提示设备以断开连接
showToast(R.string.ble_connect_disconnect);
} else {//没有连接 提示连接失败
//showToast(R.string.ble_connect_fail);
}
isContecting = false;
//changeButtonSate(isContecting);
//changeSwitchView(false);
} else if (SmctConstant.VALUE_BLE_SERVICE_DISCOVERED == value) {// 发现服务
if (mBluetoothLeService != null) {
mBluetoothLeService.setCharacteristic(mBluetoothLeService.getSupportedGattServices(),
SmctConstant.UUID_KEY_DATA_FFE2);
}
disDialog();
isContecting = true;
//changeButtonSate(isContecting);
//changeSwitchView(false);
showToast(R.string.ble_connect_success);
}
break;
case SmctConstant.KEY_DEVICE_POWER_LEVEL:// 电量
//refrashPowerLevel(value);
//Log.d("power leve", "" + value);
break;
case SmctConstant.KEY_DEVICE_ELECTRODE_DROP:// 电极脱落
if (measureSwitch)
showToast("Elctrode Dropout!!!");
break;
case SmctConstant.KEY_ECG_DATA:// ecg数据
// 正在测量中
if (measureSwitch) {
//refrashEcgData(value);
//Log.d("Ecg data", "" + value);
//算法计算
ecgAlgo.addECGParam(value);
}
break;
case SmctConstant.KEY_BODY_POSE:// 姿态
if (value == SmctConstant.VALUE_POSE_WALK) {
//refrashPose("go");
Log.d("pose", "go");
} else if (value == SmctConstant.VALUE_POSE_FALL_DOWN) {
showToast("Falls!!!!!!");
Log.d("pose", "Falls");
} else if (value == SmctConstant.VALUE_POSE_LIE_LOW) {
//refrashPose("Flat lay");
Log.d("pose", "Flat lay");
} else if (value == SmctConstant.VALUE_POSE_STAND) {
//refrashPose("Flat lay");
Log.d("pose", "Standing");
} else if (value == SmctConstant.VALUE_POSE_SIDE_DECUBITUS) {
Log.d("pose", "Standing");
}
break;
}
}
#Override
public void bleData(short key, float[] value) {
if (SmctConstant.KEY_ACC_DATA == key) {
//refreshAccData(value);
}
}
/**
* 算法数据
*/
#Override
public void algoData(final int key, final int value) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
switch (key) {
case SmctConstant.KEY_ALGO_HEART_RATE:// 心率
//tv_heartrate.setText(String.valueOf(value));
//arc_progress.setProgress(value);
//heart_rate=value;
// Bundle bundle = new Bundle();
//bundle.putInt("heart_rate", value);
//fragment.setArguments(bundle);
heart_rate = value;
Bundle bundle=new Bundle();
bundle.putInt("heart_rate",value);
samplePagerAdapter.getItem(0).setArguments(bundle);
//notifyViewPagerDataSetChanged();
break;
case SmctConstant.KEY_ALGO_ARRHYTHMIA:// 心律失常
//tvArr.setText(formatString(R.string.arrhythmia, value));
break;
}
}
});
}
public ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
// LogUtil.e("smctservice", "Unable to initialize Bluetooth");
// mHandler.sendEmptyMessage(MSG_BLE_UNINIT);
} else {
mBluetoothLeService.setBleOperate(MeasureFragment.this);
connectBle();
}
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
// LogUtil.e("smctservice", "onServiceDisconnected");
mBluetoothLeService = null;
}
};
private void notifyViewPagerDataSetChanged() {
Log.d(TAG, "\nnotifyDataSetChanged()");
samplePagerAdapter.notifyDataSetChanged();
}
protected void disDialog() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if (mProgressDialog != null) {
mProgressDialog.dismiss();
linear.setVisibility(View.GONE);
linear1.setVisibility(View.VISIBLE);
//new MyCountDownTimer(System.currentTimeMillis(),1000).start();
}
handler.post(runnable = new Runnable() {
#Override
public void run() {
int hours = count / 3600;
int minutes = (count % 3600) / 60;
int sec = count % 60;
String time = String.format("%02d:%02d:%02d", hours, minutes, sec);
tv_time.setText(time);
if (running) {
count++;
}
handler.postDelayed(this, 1000);
}
});
}
});
}
protected void showToast(String msg) {
ToastUtils.showToast(getActivity(), msg);
}
/**
* 统一显示toast管理
*/
protected void showToast(int id) {
ToastUtils.showToast(getActivity(), getResources().getString(id));
}
/**
* 显示连接蓝牙dialog
*/
protected void showDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
mProgressDialog = null;
}
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setMessage(getResources().getString(R.string.text_conn_ble));
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
}
}
And need to update textview already discuss.in this fragment.
public class MyFragment extends Fragment {
private int heart_rate;
private ArcProgress arc_progress;
private TextView tv_heartrate;
private Handler handler;
private Runnable runnable;
private View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveBundle) {
view = inflater.inflate(R.layout.ecg_layout, container, false);
arc_progress = (ArcProgress) view.findViewById(R.id.arc_progress);
tv_heartrate = (TextView) view.findViewById(R.id.tv_heart_rate);
handler = new Handler();
handler.post(runnable = new Runnable() {
#Override
public void run() {
Log.d("heartrate", "" + heart_rate);
arc_progress.setProgress(heart_rate);
tv_heartrate.setText(String.valueOf(heart_rate));
handler.postDelayed(this, 1000);
}
});
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
Hi all I am now integrating youtube API in my app where I have to parse the list of video id's from API then I have to show the videos in a list view when we click on it the video has to be played Until this works fine
There after when the user selects the full-screen mode that is landscape mode I get some errors
public final class VideoGallery extends Fragment implements OnFullscreenListener {
public static Context context;
public static final int ANIMATION_DURATION_MILLIS = 300;
public static final int LANDSCAPE_VIDEO_PADDING_DP = 5;
public final int RECOVERY_DIALOG_REQUEST = 1;
public static VideoListFragment listFragment;
public static VideoFragment videoFragment;
View videoBox;
View view;
View closeButton;
boolean isFullscreen;
public static YouTubePlayer.OnFullscreenListener onFullscreenListener;
static boolean back = false;
FrameLayout relativeLayout;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getContext();
onFullscreenListener = this;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
relativeLayout = new FrameLayout(getActivity());
inflater.inflate(R.layout.video_list_demo, relativeLayout, true);
MainActivity.headerText.setText("Video Gallery");
listFragment = (VideoGallery.VideoListFragment) getChildFragmentManager().findFragmentById(R.id.list_fragment);
videoFragment = (VideoGallery.VideoFragment) getActivity().getFragmentManager().findFragmentById(R.id.video_fragment_container);
videoBox = relativeLayout.findViewById(R.id.video_box);
closeButton = relativeLayout.findViewById(R.id.close_button);
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listFragment.getListView().clearChoices();
listFragment.getListView().requestLayout();
videoFragment.pause();
ViewPropertyAnimator animator = videoBox.animate()
.translationYBy(videoBox.getHeight())
.setDuration(ANIMATION_DURATION_MILLIS);
runOnAnimationEnd(animator, new Runnable() {
#Override
public void run() {
videoBox.setVisibility(View.INVISIBLE);
}
});
}
});
videoBox.setVisibility(View.INVISIBLE);
layout();
checkYouTubeApi();
return relativeLayout;
}
private void checkYouTubeApi() {
YouTubeInitializationResult errorReason =
YouTubeApiServiceUtil.isYouTubeApiServiceAvailable(context);
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(getActivity(), RECOVERY_DIALOG_REQUEST).show();
} else if (errorReason != YouTubeInitializationResult.SUCCESS) {
String errorMessage =
String.format(getString(R.string.error_player), errorReason.toString());
Toast.makeText(context, errorMessage, Toast.LENGTH_LONG).show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST) {
// Recreate the activity if user performed a recovery action
getActivity().recreate();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
layout();
}
#Override
public void onFullscreen(boolean isFullscreen) {
this.isFullscreen = isFullscreen;
layout();
}
private void layout() {
boolean isPortrait = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
listFragment.getView().setVisibility(isFullscreen ? View.GONE : View.VISIBLE);
listFragment.setLabelVisibility(isPortrait);
closeButton.setVisibility(isPortrait ? View.VISIBLE : View.GONE);
if (isFullscreen) {
videoBox.setTranslationY(0); // Reset any translation that was applied in portrait.
setLayoutSize(videoFragment.getView(), MATCH_PARENT, MATCH_PARENT);
setLayoutSizeAndGravity(videoBox, MATCH_PARENT, MATCH_PARENT, Gravity.TOP | Gravity.LEFT);
} else if (isPortrait) {
setLayoutSize(listFragment.getView(), MATCH_PARENT, MATCH_PARENT);
setLayoutSize(videoFragment.getView(), MATCH_PARENT, WRAP_CONTENT);
setLayoutSizeAndGravity(videoBox, MATCH_PARENT, WRAP_CONTENT, Gravity.BOTTOM);
} else {
videoBox.setTranslationY(0); // Reset any translation that was applied in portrait.
int screenWidth = dpToPx(getResources().getConfiguration().screenWidthDp);
setLayoutSize(listFragment.getView(), screenWidth / 4, MATCH_PARENT);
int videoWidth = screenWidth - screenWidth / 4;
setLayoutSize(videoFragment.getView(), videoWidth, WRAP_CONTENT);
setLayoutSizeAndGravity(videoBox, videoWidth, WRAP_CONTENT,
Gravity.RIGHT | Gravity.CENTER_VERTICAL);
}
}
#TargetApi(16)
private void runOnAnimationEnd(ViewPropertyAnimator animator, final Runnable runnable) {
if (Build.VERSION.SDK_INT >= 16) {
animator.withEndAction(runnable);
} else {
animator.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
runnable.run();
}
});
}
}
public static final class VideoListFragment extends ListFragment {
private static List<VideoEntry> VIDEO_LIST;
private PageAdapter adapter;
private View videoBox;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
callApi();
}
private void callApi() {
new DoGet(this, "videogallery").execute(WebserviceEndpoints.VIDEO_GALLERY);
}
public void handleVideoGalleryResponse(String response) {
try {
List<VideoEntry> list = new ArrayList<VideoEntry>();
if (response.length() > 0) {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.optJSONArray("items");
for (int i = 0; i < array.length(); i++) {
JSONObject data = array.optJSONObject(i);
JSONObject obj = data.optJSONObject("id");
JSONObject obj1 = data.optJSONObject("snippet");
String videoId = obj.optString("videoId");
String videoTitle = obj1.getString("title");
if (!videoId.equals("")) {
list.add(new VideoEntry(videoTitle, videoId));
}
}
VIDEO_LIST = Collections.unmodifiableList(list);
adapter = new PageAdapter(getActivity(), VIDEO_LIST);
setListAdapter(adapter);
}
} catch (Exception e) {
Log.d("", "handleResponse: ", e);
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
videoBox = getActivity().findViewById(R.id.video_box);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
String videoId = VIDEO_LIST.get(position).videoId;
back = false;
VideoFragment videoFragment = (VideoFragment) getActivity().getFragmentManager().findFragmentById(R.id.video_fragment_container);
videoFragment.setVideoId(videoId);
if (videoBox.getVisibility() != View.VISIBLE) {
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
videoBox.setTranslationY(videoBox.getHeight());
}
videoBox.setVisibility(View.VISIBLE);
}
if (videoBox.getTranslationY() > 0) {
videoBox.animate().translationY(0).setDuration(ANIMATION_DURATION_MILLIS);
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
VideoFragment f = (VideoFragment) getActivity().getFragmentManager().findFragmentById(R.id.video_fragment_container);
if (f != null)
getActivity().getFragmentManager().beginTransaction().remove(f).commit();
if (adapter != null)
adapter.releaseLoaders();
}
public void setLabelVisibility(boolean visible) {
if (adapter != null)
adapter.setLabelVisibility(visible);
}
}
private static final class PageAdapter extends BaseAdapter {
private final List<VideoEntry> entries;
private final List<View> entryViews;
private final Map<YouTubeThumbnailView, YouTubeThumbnailLoader> thumbnailViewToLoaderMap;
private final LayoutInflater inflater;
private final ThumbnailListener thumbnailListener;
private boolean labelsVisible;
public PageAdapter(Context context, List<VideoEntry> entries) {
this.entries = entries;
entryViews = new ArrayList<View>();
thumbnailViewToLoaderMap = new HashMap<YouTubeThumbnailView, YouTubeThumbnailLoader>();
inflater = LayoutInflater.from(context);
thumbnailListener = new ThumbnailListener();
labelsVisible = true;
}
public void releaseLoaders() {
for (YouTubeThumbnailLoader loader : thumbnailViewToLoaderMap.values()) {
loader.release();
}
}
public void setLabelVisibility(boolean visible) {
labelsVisible = visible;
for (View view : entryViews) {
view.findViewById(R.id.text).setVisibility(visible ? View.VISIBLE : View.GONE);
}
}
#Override
public int getCount() {
return entries.size();
}
#Override
public VideoEntry getItem(int position) {
return entries.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
VideoEntry entry = entries.get(position);
// There are three cases here
if (view == null) {
// 1) The view has not yet been created - we need to initialize the YouTubeThumbnailView.
view = inflater.inflate(R.layout.video_list_item, parent, false);
YouTubeThumbnailView thumbnail = (YouTubeThumbnailView) view.findViewById(R.id.thumbnail);
thumbnail.setTag(entry.videoId);
thumbnail.initialize("AIzaSyB8BPeIbu5T1-flG4tpEdrHDPI3Rk2VTDY", thumbnailListener);
} else {
YouTubeThumbnailView thumbnail = (YouTubeThumbnailView) view.findViewById(R.id.thumbnail);
YouTubeThumbnailLoader loader = thumbnailViewToLoaderMap.get(thumbnail);
if (loader == null) {
// 2) The view is already created, and is currently being initialized. We store the
// current videoId in the tag.
thumbnail.setTag(entry.videoId);
} else {
// 3) The view is already created and already initialized. Simply set the right videoId
// on the loader.
thumbnail.setImageResource(R.drawable.no_thumbnail);
loader.setVideo(entry.videoId);
}
}
TextView label = ((TextView) view.findViewById(R.id.text));
label.setText(entry.text);
label.setVisibility(labelsVisible ? View.VISIBLE : View.GONE);
return view;
}
private final class ThumbnailListener implements
YouTubeThumbnailView.OnInitializedListener,
YouTubeThumbnailLoader.OnThumbnailLoadedListener {
#Override
public void onInitializationSuccess(
YouTubeThumbnailView view, YouTubeThumbnailLoader loader) {
loader.setOnThumbnailLoadedListener(this);
thumbnailViewToLoaderMap.put(view, loader);
view.setImageResource(R.drawable.no_thumbnail);
String videoId = (String) view.getTag();
loader.setVideo(videoId);
}
#Override
public void onInitializationFailure(
YouTubeThumbnailView view, YouTubeInitializationResult loader) {
view.setImageResource(R.drawable.no_thumbnail);
}
#Override
public void onThumbnailLoaded(YouTubeThumbnailView view, String videoId) {
}
#Override
public void onThumbnailError(YouTubeThumbnailView view, YouTubeThumbnailLoader.ErrorReason errorReason) {
view.setImageResource(R.drawable.no_thumbnail);
}
}
}
public static final class VideoFragment extends YouTubePlayerFragment
implements YouTubePlayer.OnInitializedListener {
private YouTubePlayer player;
private String videoId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initialize("AIzaSyB8BPeIbu5T1-flG4tpEdrHDPI3Rk2VTDY", this);
}
#Override
public void onDestroy() {
if (player != null) {
player.release();
}
super.onDestroy();
}
public void setVideoId(String videoId) {
if (videoId != null && !videoId.equals(this.videoId)) {
this.videoId = videoId;
if (player != null) {
player.cueVideo(videoId);
}
}
}
public void pause() {
if (player != null) {
player.pause();
}
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean restored) {
this.player = player;
player.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_CUSTOM_LAYOUT);
player.setOnFullscreenListener(onFullscreenListener);
if (!restored && videoId != null) {
player.cueVideo(videoId);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult result) {
this.player = null;
}
}
private static final class VideoEntry {
private final String text;
private final String videoId;
public VideoEntry(String text, String videoId) {
this.text = text;
this.videoId = videoId;
}
}
private int dpToPx(int dp) {
return (int) (dp * getResources().getDisplayMetrics().density + 0.5f);
}
private static void setLayoutSize(View view, int width, int height) {
ViewGroup.LayoutParams params = view.getLayoutParams();
params.width = width;
params.height = height;
view.setLayoutParams(params);
}
private static void setLayoutSizeAndGravity(View view, int width, int height, int gravity) {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) view.getLayoutParams();
params.width = width;
params.height = height;
params.gravity = gravity;
view.setLayoutParams(params);
}
}
This is my fragment
The layout file is
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/list_fragment"
class="com.mycristoparish.Fragments.VideoGallery$VideoListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize" />
<LinearLayout
android:id="#+id/video_box"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:orientation="vertical">
<ImageButton
android:id="#+id/close_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:src="#android:drawable/btn_dialog" />
<fragment
android:id="#+id/video_fragment_container"
class="com.mycristoparish.Fragments.VideoGallery$VideoFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</merge>
When I try to play the video in full-screen mode I get the following error
java.lang.IllegalArgumentException: Binary XML file line #42: Duplicate id 0x7f0d0117, tag null, or parent id 0x7f0d0115 with another fragment for com.mycristoparish.Fragments.VideoGallery$VideoFragment
Please guide me how can I move further.
Thanks in advance.
The problem is that you are inflating a layout with a fragment inside a fragment.You cannot do it and so you get the error.However you can dynamically add them.
More details
Note: You cannot inflate a layout into a fragment when that layout includes a . Nested fragments are only supported when added to a fragment dynamically.
I would like to ask how can I detect when I try to back to another fragment.
So I have this code:
fragmentManager.replace(R.id.fragment_searched_data_xml, fragment).addToBackStack(null).commit();
that lets me back on that fragment. Now the question is:
when I press the back button from the current fragment so I can go back to initial fragment can I detect it??
public static class FragmentMainClass extends Fragment {
int i;
public FragmentMainClass() {
}
public FragmentMainClass(int i) {
this.i = i;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(
R.layout.fragment_searched_data, container, false);
TextView sn = (TextView) rootView.findViewById(R.id.stop_name);
TextView sc = (TextView) rootView.findViewById(R.id.stop_code);
String prefix = getArguments().getString("bussStopName");
if (sn != null && sc != null) {
if (prefix.contains("/")) {
if (prefix.contains("/ ")) {
sn.setText(prefix.replace("\"", "").split("/ ")[0] + "\n" + prefix.replace("\"", "").split("/ ")[1]);
sc.setText(getArguments().getString("bussStopCode"));
} else {
sn.setText(prefix.replace("\"", "").split("/")[0] + "\n" + prefix.replace("\"", "").split("/")[1]);
sc.setText(getArguments().getString("bussStopCode"));
}
} else {
sn.setPadding(20, 40, 0, 0);
sn.setText(prefix.replace("\"", ""));
sc.setText(getArguments().getString("bussStopCode"));
}
}
final LinearLayout child = (LinearLayout) rootView
.findViewById(R.id.search_result_data_box);
LayoutParams params = (LayoutParams) child.getLayoutParams();
//child.setVisibility(View.GONE);
// params.height = 0;
widthListView = container.getWidth();
rootView.setTranslationX(-container.getWidth());
rootView.animate().setStartDelay(300).translationX(0)
.withEndAction(new Runnable() {
#Override
public void run() {
conreq = new ConnnectionRequest("97", getArguments().getString("bussStopCode"));
//expand(child);
initializeResultList(rootView);
// rootView.setVisibility(View.INVISIBLE);
}
});
return rootView;
}
public static void expand(final View v) {
final int targtetHeight = v.getMeasuredHeight();
v.getLayoutParams().height = 0;
v.setVisibility(View.VISIBLE);
Animation a = new Animation() {
#Override
protected void applyTransformation(float interpolatedTime,
Transformation t) {
v.getLayoutParams().height = interpolatedTime == 1 ? LayoutParams.WRAP_CONTENT
: (int) (targtetHeight * interpolatedTime);
v.requestLayout();
}
#Override
public boolean willChangeBounds() {
return true;
}
};
// 1dp/ms
a.setDuration((int) (targtetHeight / v.getContext().getResources()
.getDisplayMetrics().density));
v.startAnimation(a);
}
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
}
public void initializeResultList(View v) {
result_list = (ListView) v.findViewById(R.id.list_view_results);
//(PullToRefreshListView) v.findViewById(R.id.list_view_results);;
final ResultDataCustomAdapter customAdapter = new ResultDataCustomAdapter(getActivity(), R.layout.pull_refresh_list_item, conreq.getCollectedData().getBusRouteSetData());
//prlv.prepareForRefresh();
((PullToRefreshListView) result_list).setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh() {
// Do work to refresh the list here.
new GetDataTask().execute();
}
});
result_list.setAdapter(customAdapter);
result_list.setVisibility(View.VISIBLE);
result_list.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> av, final View view,
final int i, long i2) {
view.animate().setDuration(500).translationX(widthListView).alpha(0).
withEndAction(new Runnable() {
#Override
public void run() {
//setResult(Activity.RESULT_OK,new Intent().putExtra("bussStopCode", data.get(i).getStopCode()).putExtra("bussStopName", data.get(i).getStopName()));
////int get 1
//data.remove(i);
int temporaryInteger = i;
//customAdapter.notifyDataSetChanged();
//view.setTranslationX(0);
Log.d("data",conreq.getCollectedData().getBusRouteSetData().get(temporaryInteger - 1).getRouteHeading());
Bundle bundle = new Bundle();
bundle.putString("busdestination", conreq.getCollectedData().getBusRouteSetData().get(temporaryInteger-1).getRouteHeading());
bundle.putString("busnumber", conreq.getCollectedData().getBusRouteSetData().get(temporaryInteger-1).getRouteNo());
Fragment fragment = new FragmentNextTripForStop();
fragment.setArguments(bundle);
FragmentTransaction fragmentManager = getFragmentManager().beginTransaction();
fragmentManager.setCustomAnimations(R.anim.left_right_anim_x_left,R.anim.left_right_anim_x_right);
fragmentManager.replace(R.id.fragment_searched_data_xml, fragment).addToBackStack(null).commit();
result_list.setVisibility(View.GONE);
// finish();
//overridePendingTransition(R.anim.right_left_anim_x_left,R.anim.right_left_anim_x_right);
}
});
}});
}
private class GetDataTask extends AsyncTask<Void, Void, String[]> {
#Override
protected String[] doInBackground(Void... params) {
// Simulates a background job.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
;
}
return null;
}
#Override
protected void onPostExecute(String[] result) {
// Call onRefreshComplete when the list has been refreshed.
((PullToRefreshListView) result_list).onRefreshComplete();
super.onPostExecute(result);
}
}
}
While Adding your fragment into host layout add fragment into stack
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.home_fragment, fragment)
.addToBackStack(fragment.getTag())
.commit();
In your onBackPressed()
if (getSupportFragmentManager().getBackStackEntryCount() >= 0) {
getSupportFragmentManager().popBackStack();
}else{
super.onBackPressed();
}