RecyclerView in fragment through activity get position - android

so here is my problem, i have only one activity from i launch my viewpager fragment, in my viewpager i have 4 fragments containing recyclerViews. Every Fragment contains item populated by data on the net, when i click into one i get a WebView Fragment, but when i click on the backbutton i lost my poisiton, cause it's recreating the whole activity.
I don't know how to not recreate the activity and get back my old position, or recreating it but not changing the item's positions and have my old position back. Here's my code. Where i should put what ?! Some help would be very very well come.
Thank You !!
My Activity Class :
public class LauncherActivity extends AppCompatActivity implements ListFragment.OnNewSelectedInterface{
public static final String VIEWPAGER_FRAGMENT = "view_pager";
private ImageView mImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.activity_launcher);
mImageView = (ImageView) findViewById(R.id.logoImageView);
mImageView.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_indefinitely));
if(!isNetworkAvailable()){
alertUserAboutError();
} else {
relativeLayout.postDelayed(new Runnable() {
#Override
public void run() {
ViewPagerFragment savedFragment = (ViewPagerFragment)
getSupportFragmentManager().findFragmentByTag(VIEWPAGER_FRAGMENT);
if(savedFragment == null) {
ViewPagerFragment viewPagerFragment = new ViewPagerFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.activity_launcher, viewPagerFragment, VIEWPAGER_FRAGMENT);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
}, 2000);
}
}
#Override
public void onListNewSelected(int index, ArrayList<Articles> articles) {
WebViewFragment webViewFragment = new WebViewFragment();
Bundle bundle = new Bundle();
bundle.putInt(ViewPagerFragment.KEY_NEW_INDEX, index);
bundle.putParcelableArrayList(ListFragment.KEY_LIST, articles);
webViewFragment.setArguments(bundle);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.activity_launcher, webViewFragment, WebViewFragment.WEBVIEWFRAGMENT);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment alertDialogFragment = new AlertDialogFragment();
alertDialogFragment.show(getFragmentManager(), "error_dialog");
}
}
My ViewPagerClass :
public class ViewPagerFragment extends Fragment {
public static final String KEY_NEW_INDEX = "key_new_index";
private ViewPager mViewPager;
private TabLayout mTabLayout;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_view_pager, container, false);
final OldFactFragment oldFactFragment = new OldFactFragment();
final SportFragment sportFragment = new SportFragment();
final BuzzFragment buzzFragment = new BuzzFragment();
final NewsFragment newsFragment = new NewsFragment();
mViewPager = (ViewPager) view.findViewById(R.id.viewPager);
mTabLayout = (TabLayout) view.findViewById(R.id.tabLayout);
mViewPager.setOffscreenPageLimit(4);
mViewPager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
#Override
public Fragment getItem(int position) {
if(position == 0){
return oldFactFragment;
} else if (position == 1) {
return newsFragment;
} else if (position == 2){
return sportFragment;
} else return buzzFragment;
}
#Override
public CharSequence getPageTitle(int position) {
if(position == 0){
return "Pastly";
} else if (position == 1) {
return "politic";
} else if (position == 2){
return "sport";
} else return "buzz";
}
#Override
public int getCount() {
return 4;
}
});
mTabLayout.setupWithViewPager(mViewPager);
return view;
}
}
My ListFragment(Parent's class of the 4 Fragments in the ViewPager) :
public abstract class ListFragment extends Fragment {
public static final String KEY_LIST = "key_list";
public interface OnNewSelectedInterface {
void onListNewSelected(int index, ArrayList<Articles> articles);
}
protected static final String TAG = ListFragment.class.getSimpleName();
protected ArrayList<Articles> mArticlesList;
protected ItemAdapter mArticleAdapter;
protected RecyclerView mRecyclerView;
protected OnNewSelectedInterface mListener;
protected RecyclerView.LayoutManager mManager;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mListener = (OnNewSelectedInterface) getActivity();
View view = inflater.inflate(R.layout.fragment_list, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
getInfos(getUrl());
return view;
}
protected abstract String[] getUrl();
private void getInfos(String[] url) {
if (isNetworkAvailable()) {
OkHttpClient client = new OkHttpClient();
for (int i = 0; i < getUrl().length; i++) {
Request request = new Request.Builder().url(url[i]).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
String jsonData = response.body().string();
if (response.isSuccessful()) {
Log.v(TAG, jsonData);
getMultipleUrls(jsonData);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
getCurrentArticles(mArticlesList);
}
});
} else {
alertUserAboutError();
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call call, IOException e) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
alertUserAboutError();
}
});
}
});
}
} else{
alertUserAboutError();
}
}
private void getMultipleUrls(String jsonData) throws JSONException {
if (mArticlesList == null) {
mArticlesList = getArticleForecast(jsonData);
} else {
mArticlesList.addAll(getArticleForecast(jsonData));
}
}
private void getCurrentArticles(ArrayList<Articles> articles) {
mArticleAdapter = new ItemAdapter(getActivity(), articles, mListener);
mRecyclerView.setAdapter(mArticleAdapter);
mManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mManager);
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getActivity().
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment alertDialogFragment = new AlertDialogFragment();
alertDialogFragment.show(getActivity().getFragmentManager(), "error_dialog");
}
private ArrayList<Articles> getArticleForecast(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
JSONArray articles = forecast.getJSONArray("articles");
ArrayList<Articles> listArticles = new ArrayList<>(articles.length());
for (int i = 0; i < articles.length(); i++) {
JSONObject jsonArticle = articles.getJSONObject(i);
Articles article = new Articles();
String urlImage = jsonArticle.getString("urlToImage");
article.setTitle(jsonArticle.getString("title"));
article.setDescription(jsonArticle.getString("description"));
article.setImageView(urlImage);
article.setArticleUrl(jsonArticle.getString("url"));
listArticles.add(i, article);
}
return listArticles;
}
}
And my ItemAdapter (Adapter Class) :
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ArticleViewHolder> {
private final ListFragment.OnNewSelectedInterface mListener;
protected ArrayList<Articles> mArticlesList;
protected Context mContext;
private int mPosition;
private int lastPosition = -1;
public ItemAdapter(Context contexts, ArrayList<Articles> mArticleLi, ListFragment.OnNewSelectedInterface listener){
mContext = contexts;
mArticlesList = mArticleLi;
mListener = listener;
}
#Override
public ArticleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_linear, parent, false);
view.findViewById(R.id.textView).setSelected(true);
ArticleViewHolder articleViewHolder = new ArticleViewHolder(view);
articleViewHolder.setIsRecyclable(false);
return articleViewHolder;
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onBindViewHolder(ArticleViewHolder holder, int position) {
mPosition = position;
holder.bindArticle(mArticlesList.get(position));
setAnimation(holder.itemView, position);
holder.mImageView.setClipToOutline(true);
}
private void setAnimation(View viewToAnimate, int position) {
if (position > lastPosition) {
Animation animation = AnimationUtils.loadAnimation(viewToAnimate.getContext(), android.R.anim.slide_in_left);
viewToAnimate.startAnimation(animation);
lastPosition = position;
}
}
#Override
public int getItemCount() {
return mArticlesList.size();
}
public class ArticleViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener{
private TextView mTitle, mArticle;
private ImageView mImageView;
private ArticleViewHolder(View itemView) {
super(itemView);
mTitle = (TextView) itemView.findViewById(R.id.textView);
mArticle = (TextView) itemView.findViewById(R.id.showTextView);
mImageView = (ImageView) itemView.findViewById(R.id.imageView2);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
}
private void bindArticle(Articles article) {
mTitle.setText(article.getTitle());
mArticle.setText(article.getDescription());
mArticle.setVisibility(View.INVISIBLE);
Glide.with(mContext).load(article.getImageView()).into(mImageView);
}
#Override
public void onClick(View view) {
mListener.onListNewSelected(getLayoutPosition(), mArticlesList);
}
#Override
public boolean onLongClick(View view) {
String desc = mArticlesList.get(getAdapterPosition()).getDescription();
mArticle.setVisibility(View.VISIBLE);
mArticle.setText(desc);
mArticle.postDelayed(new Runnable() {
public void run() {
mArticle.setVisibility(View.INVISIBLE);
}
}, 3000);
return true;
}
}
}

In Your method onListNewSelected You are Replacing the new fragment with the old one as stated in this line
fragmentTransaction.replace(R.id.activity_launcher, webViewFragment, WebViewFragment.WEBVIEWFRAGMENT);
From Google Documentaion
Replace an existing fragment that was added to a container. This is essentially the same as calling remove(Fragment) for all currently added fragments that were added with the same containerViewId and then add(int, Fragment, String) with the same arguments given here.
So you are removing the old Fragment then adding the new one, When you are back to get the old fragment, It is not already there it will be created from scratch, So the position is already gone with the removed fragment.
While using the add method, Will add the new fragment above the previous one, when you go back the previous one already there with its state "Position"

Related

How to send input from searchview which is in an activity to fragment which is in the view pager of that activity

So i have a searchview placed in an activity which has a tablayout and viewpager.In the viewpager there is a fragment for each tab with a textview.What im trying to do is to get the input from the searchview and set the text of the textview with that input and i cant seem to be able to do it.I tried to put the input from the searchview in a bundle(this being done in the activity),and then get the arguments in the fragment in onCreateView() but the problem is that the activity and the fragment are being created simultaneously wthich means that the input from the searchview would be null.
This is the Activity:
public class SearchActivity extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;
SearchView searchView;
Toolbar toolbar;
ImageButton imageButtonBack;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
bindUI();
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.AddFragment(new NewestFragment(), "Newest"); // this line can cause crashes
viewPagerAdapter.AddFragment(new OldestFragment(), "Oldest"); // this line can cause crashes
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
setSearchView();
setImageButtonBack();
}
private void setSearchView() {
searchView.requestFocus();
View v = searchView.findViewById(R.id.search_plate);
v.setBackgroundColor(Color.parseColor("#ffffff"));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Bundle bundle = new Bundle();
bundle.putString("searchViewText", searchView.getQuery().toString());
NewestFragment newestFragment = new NewestFragment();
OldestFragment oldestFragment = new OldestFragment();
newestFragment.setArguments(bundle);
oldestFragment.setArguments(bundle);
searchView.clearFocus();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
Bundle bundle = new Bundle();
bundle.putString("searchViewText", searchView.getQuery().toString());
NewestFragment newestFragment = new NewestFragment();
OldestFragment oldestFragment = new OldestFragment();
newestFragment.setArguments(bundle);
oldestFragment.setArguments(bundle);
return false;
}
});
}
private void bindUI() {
imageButtonBack = findViewById(R.id.back);
tabLayout = findViewById(R.id.tabs);
viewPager = findViewById(R.id.view_pager);
searchView = findViewById(R.id.search_view_searchactivity);
toolbar = findViewById(R.id.toolbar_selected_category);
}
private void setImageButtonBack() {
imageButtonBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
}
The adapter of the ViewPager:
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragmentList = new ArrayList<>(); // this line can cause crashes
private final List<String> titlesList = new ArrayList<>();
public ViewPagerAdapter(#NonNull FragmentManager fragmentManager) {
super(fragmentManager);
}
#NonNull
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return titlesList.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return titlesList.get(position);
}
public void AddFragment(Fragment fragment, String title) {
fragmentList.add(fragment); // this line can cause crashes
titlesList.add(title);
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
And here is the fragment:
public class NewestFragment extends Fragment {
View view;
TextView textView;
public NewestFragment(){
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view=inflater.inflate(R.layout.fragment_search_newest, container, false);
textView=view.findViewById(R.id.tttttttttttttttttttt);
try {
String searchViewText=getArguments().getString("searchViewText");
textView.setText(searchViewText);
}
catch (Exception e){
//something
}
return view;
}
}
The fragments are attached to activity so first activity is created lets leave that but I think you should use a MVVM pattern and create viewmodel and then you can observe the search view and update the fragment textview using that viewmodel class
https://codelabs.developers.google.com/codelabs/kotlin-android-training-live-data/index.html#0
To change the fragments that are created by a FragmentPagerAdapter, you should use a DynamicFragmentPagerAdapter. Refer to the following code below.
public class DynamicFragmentPagerAdapter extends PagerAdapter {
private static final String TAG = "DynamicFragmentPagerAdapter";
private final FragmentManager fragmentManager;
public static abstract class FragmentIdentifier implements Parcelable {
private final String fragmentTag;
private final Bundle args;
public FragmentIdentifier(#NonNull String fragmentTag, #Nullable Bundle args) {
this.fragmentTag = fragmentTag;
this.args = args;
}
protected FragmentIdentifier(Parcel in) {
fragmentTag = in.readString();
args = in.readBundle(getClass().getClassLoader());
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(fragmentTag);
dest.writeBundle(args);
}
protected final Fragment newFragment() {
Fragment fragment = createFragment();
Bundle oldArgs = fragment.getArguments();
Bundle newArgs = new Bundle();
if(oldArgs != null) {
newArgs.putAll(oldArgs);
}
if(args != null) {
newArgs.putAll(args);
}
fragment.setArguments(newArgs);
return fragment;
}
protected abstract Fragment createFragment();
}
private ArrayList<FragmentIdentifier> fragmentIdentifiers = new ArrayList<>();
private FragmentTransaction currentTransaction = null;
private Fragment currentPrimaryItem = null;
public DynamicFragmentPagerAdapter(FragmentManager fragmentManager) {
this.fragmentManager = fragmentManager;
}
private int findIndexIfAdded(FragmentIdentifier fragmentIdentifier) {
for (int i = 0, size = fragmentIdentifiers.size(); i < size; i++) {
FragmentIdentifier identifier = fragmentIdentifiers.get(i);
if (identifier.fragmentTag.equals(fragmentIdentifier.fragmentTag)) {
return i;
}
}
return -1;
}
public void addFragment(FragmentIdentifier fragmentIdentifier) {
if (findIndexIfAdded(fragmentIdentifier) < 0) {
fragmentIdentifiers.add(fragmentIdentifier);
notifyDataSetChanged();
}
}
public void removeFragment(FragmentIdentifier fragmentIdentifier) {
int index = findIndexIfAdded(fragmentIdentifier);
if (index >= 0) {
fragmentIdentifiers.remove(index);
notifyDataSetChanged();
}
}
#Override
public int getCount() {
return fragmentIdentifiers.size();
}
#Override
public void startUpdate(#NonNull ViewGroup container) {
if (container.getId() == View.NO_ID) {
throw new IllegalStateException("ViewPager with adapter " + this
+ " requires a view id");
}
}
#SuppressWarnings("ReferenceEquality")
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
if (currentTransaction == null) {
currentTransaction = fragmentManager.beginTransaction();
}
final FragmentIdentifier fragmentIdentifier = fragmentIdentifiers.get(position);
// Do we already have this fragment?
final String name = fragmentIdentifier.fragmentTag;
Fragment fragment = fragmentManager.findFragmentByTag(name);
if (fragment != null) {
currentTransaction.attach(fragment);
} else {
fragment = fragmentIdentifier.newFragment();
currentTransaction.add(container.getId(), fragment, fragmentIdentifier.fragmentTag);
}
if (fragment != currentPrimaryItem) {
fragment.setMenuVisibility(false);
fragment.setUserVisibleHint(false);
}
return fragment;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
if (currentTransaction == null) {
currentTransaction = fragmentManager.beginTransaction();
}
currentTransaction.detach((Fragment) object);
}
#SuppressWarnings("ReferenceEquality")
#Override
public void setPrimaryItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
Fragment fragment = (Fragment) object;
if (fragment != currentPrimaryItem) {
if (currentPrimaryItem != null) {
currentPrimaryItem.setMenuVisibility(false);
currentPrimaryItem.setUserVisibleHint(false);
}
fragment.setMenuVisibility(true);
fragment.setUserVisibleHint(true);
currentPrimaryItem = fragment;
}
}
#Override
public void finishUpdate(#NonNull ViewGroup container) {
if (currentTransaction != null) {
currentTransaction.commitNowAllowingStateLoss();
currentTransaction = null;
}
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return ((Fragment) object).getView() == view;
}
#Override
public Parcelable saveState() {
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("fragmentIdentifiers", fragmentIdentifiers);
return bundle;
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
Bundle bundle = ((Bundle)state);
bundle.setClassLoader(loader);
fragmentIdentifiers = bundle.getParcelableArrayList("fragmentIdentifiers");
}
}

Update the row item data of recyclerview

The fragment consists of View Pager which shows the product count that
needs to be updated when the product is deleted or added .
public class SubCategoryFragment extends BaseFragment implements OnItemClickListener
{
private View rootView;
private MasterCategory subCategory;
private RecyclerView subCategoryRecyclerView;
private SubCategoryListAdapter subCategoryListAdapter;
private ArrayList<MasterCategory> superSubCategories;
private String iconImageURL;
private ArrayList<MerchantOrder> merchantorder;
/*private IRequestComplete iRequestComplete;*/
private int categoryId;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
return rootView = inflater.inflate(R.layout.fragment_category_list, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
initialiseUI();
}
initialise fragment
protected void initialiseUI()
{
categoryId = getArguments().getInt("categoryId");
iconImageURL = (String) getArguments().getSerializable("iconImageURL");
subCategory = (MasterCategory) getArguments().getSerializable("data");
subCategoryRecyclerView = (RecyclerView) rootView.findViewById(R.id.category_list_rc_view);
rootView.findViewById(R.id.dashboard_progressbar_newlyadded).setVisibility(View.GONE);
subCategoryRecyclerView.setHasFixedSize(true);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(context);
subCategoryRecyclerView.setLayoutManager(mLayoutManager);
superSubCategories = subCategory.getCategories();
rootView.findViewById(R.id.dashboard_progressbar_newlyadded).setVisibility(View.GONE);
if (superSubCategories != null && !superSubCategories.isEmpty())
{
subCategoryListAdapter = new SubCategoryListAdapter(superSubCategories, iconImageURL);
subCategoryRecyclerView.setAdapter(subCategoryListAdapter);
subCategoryListAdapter.setmOnItemClickListener(this);
updateListView();
}
else
{
rootView.findViewById(R.id.text_no_order_error).setVisibility(View.VISIBLE);
((TextView) rootView.findViewById(R.id.text_no_order_error)).setText("No Category found!");
}
}
Update the listview
private void updateListView()
{
if (subCategoryListAdapter == null)
{
subCategoryListAdapter = new SubCategoryListAdapter(superSubCategories,iconImageURL);
subCategoryRecyclerView.setAdapter(subCategoryListAdapter);
}
else
{
subCategoryListAdapter.notifyDataSetChanged();
}
subCategoryListAdapter.notifyDataSetChanged();
}
the itemclick opens up a fragment which displays the product details
#Override
public void onItemClick(View view, int position)
{
/*MasterCategory superSubCategories = subCategoryListAdapter.getSuperSubCategory(position);
Bundle bundle = new Bundle();
bundle.putSerializable("data", superSubCategories);
SuperSubCategoryProductsFragment superSubCategoryProductsFragment = new SuperSubCategoryProductsFragment();
superSubCategoryProductsFragment.setArguments(bundle);
manageFragment(superSubCategoryProductsFragment, SuperSubCategoryProductsFragment.class.getName(), CategoryDetailsFragment.class.getName(), bundle);*/
/*ArrayList<MasterCategory> superSubCategories = subCategoryListAdapter.getSuperSubCategory(position).getCategories();
if (null != superSubCategories){
Bundle bundle = new Bundle();
bundle.putSerializable("data", superSubCategories);
SuperSubCategoryListFragment categoryDetailsFragment = new SuperSubCategoryListFragment();
categoryDetailsFragment.setArguments(bundle);
manageFragment(categoryDetailsFragment, SuperSubCategoryListFragment.class.getName(), SubCategoryFragment.class.getName(), null);
}*/
MasterCategory superSubCategories = subCategoryListAdapter.getSuperSubCategory(position);
superSubCategories.getSubCategoryCount();
superSubCategories.getProductCount();
subCategoryListAdapter.notifyDataSetChanged();
if (superSubCategories.isHasChildCategory())
{
Bundle bundle = new Bundle();
bundle.putSerializable("data", superSubCategories);
Intent intent = new Intent(context, BaseFragmentActivity.class);
intent.putExtra("toolbarTitle", superSubCategories.getName());
intent.putExtra("FragmentClassName", SuperSubCategoryFragment.class.getName());
intent.putExtra("data", bundle);
startActivity(intent);
}
else
{
Intent intent = new Intent(context, BaseFragmentActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("categoryId", superSubCategories.getCategoryId());
bundle.putString("categoryName", superSubCategories.getName());
bundle.putBoolean("isSubCatProducts", !superSubCategories.isHasChildCategory());
bundle.putInt("ProductCount", superSubCategories.getProductCount());
intent.putExtra("toolbarTitle", superSubCategories.getName());
intent.putExtra("FragmentClassName", SubCategoryProductsFragment.class.getName());
intent.putExtra("data", bundle);
startActivity(intent);
}
}
#Override
public void onPause()
{
super.onPause();
}
#Override
public void onResume()
{
super.onResume();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView)
{
super.onAttachedToRecyclerView(subCategoryRecyclerView);
subCategoryRecyclerView.getAdapter().notifyDataSetChanged();
}
}
This is my Adapter attached to the fragment
public class SubCategoryListAdapter extends RecyclerView.Adapter<SubCategoryListAdapter.ViewHolder> implements View.OnClickListener {
private static final String TAG = SubCategoryListAdapter.class.getSimpleName();
private ArrayList<MasterCategory> superSubCategories;
private ImageLoader imageloader;
private com.amoda.androidlib.intf.OnItemClickListener mOnItemClickListener;
private String iconImageURL;
#Override
public void onClick(View view)
{
if (mOnItemClickListener != null)
mOnItemClickListener.onItemClick(view, (Integer) view.getTag());
}
public class ViewHolder extends RecyclerView.ViewHolder
{
public TextView name;
public TextView productCount;
public NetworkImageView image;
public ViewHolder(View itemLayoutView)
{
super(itemLayoutView);
productCount = (TextView) itemLayoutView.findViewById(R.id.product_count);
name = (TextView) itemLayoutView.findViewById(R.id.name);
image = (NetworkImageView) itemLayoutView.findViewById(R.id.image);
}
}
public SubCategoryListAdapter(ArrayList<MasterCategory> superSubCategories, String iconImageURL)
{
this.superSubCategories = superSubCategories;
imageloader = Global.getInstance().getImageLoader();
this.iconImageURL = iconImageURL;
}
#Override
public SubCategoryListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.super_category_list_row, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position)
{
holder.name.setText("" + superSubCategories.get(position).getName());
holder.image.setDefaultImageResId(R.drawable.logo_amoda);
holder.image.setImageUrl(iconImageURL, imageloader);
if(!superSubCategories.get(position).isHasChildCategory())
{
holder.productCount.setText("" + superSubCategories.get(position).getProductCount());
}
else
{
holder.productCount.setText("");
holder.productCount.setBackgroundResource(R.drawable.icn_right_arrow);
}
holder.itemView.setTag(position);
holder.itemView.setOnClickListener(this);
}
public void setmOnItemClickListener(com.amoda.androidlib.intf.OnItemClickListener mOnItemClickListener)
{
this.mOnItemClickListener = mOnItemClickListener;
}
#Override
public int getItemCount()
{
if (superSubCategories != null)
return superSubCategories.size();
else
return 0;
}
public MasterCategory getSuperSubCategory(int position)
{
return superSubCategories.get(position);
}
}
This is my View pager in my activity
private void showSubCategoryTabs()
{
setToolbarTitle(category != null ? category.getName() : "");
try
{
mPromotionalImage.setDefaultImageResId(R.drawable.nodeals_img);
mPromotionalImage.setImageUrl(category.getImageUrl(), imageLoader);
}
catch (Exception e)
{
e.printStackTrace();
}
tabContent = new ArrayList<String>();
for (MasterCategory subCategories : category.getCategories())
{
/*Check if the sub-sub category has super-sub category or not.*/
if (null != subCategories.getCategories())
tabContent.add(subCategories.getName());
}
mViewPager.setAdapter(mSectionsPagerAdapter);
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
}
#Override
public void onPageSelected(int position)
{
Fragment fragment = ((SectionsPagerAdapter) mViewPager.getAdapter()).getFragment(position);
if (fragment != null)
{
fragment.onResume();
}
}
#Override
public void onPageScrollStateChanged(int state)
{
}
});
}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter
{
private SectionsPagerAdapter sectionspageradapter;
private FragmentManager fragmentManager=null;
private Bundle bundle=new Bundle();
public SectionsPagerAdapter(FragmentManager fm)
{
super(fm);
fragmentManager=fm;
}
#Override
public Object instantiateItem(ViewGroup container,int position)
{
Object obj=super.instantiateItem(container,position);
if(obj instanceof Fragment)
{
Fragment f=(Fragment)obj;
String tag=f.getTag();
f.onResume();
}
return obj;
}
#Override
public Fragment getItem(int position)
{
MasterCategory subCategories = category.getCategories().get(position);
if (subCategories.isHasChildCategory())
{
SubCategoryFragment subCategoryFragment = new SubCategoryFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("iconImageURL", category.getIconImageUrl());
bundle.putSerializable("data", category.getCategories().get(position));
subCategoryFragment.setArguments(bundle);
return subCategoryFragment;
}
else
{
SubCategoryProductsFragment subCategoryProductsFragment = new SubCategoryProductsFragment();
Bundle bundle = new Bundle();
bundle.putInt("categoryId", subCategories.getCategoryId());
bundle.putString("categoryName", subCategories.getName());
bundle.putBoolean("isSubCatProducts", true);
subCategoryProductsFragment.setArguments(bundle);
return subCategoryProductsFragment;
}
}
#Override
public int getCount()
{
return tabContent.size();
}
#Override
public CharSequence getPageTitle(int position)
{
Locale l = Locale.getDefault();
return tabContent.get(position);
}
public Fragment getFragment(int position)
{
String tag = String.valueOf(mMerchantSubCategories.get(position));
return fragmentManager.findFragmentByTag(tag);
}
}
#Override
public void onResume()
{
if (!EventBus.getDefault().isRegistered(this))
EventBus.getDefault().register(this);
super.onResume();
}
#Override
protected void onPause()
{
super.onPause();
}
#Override
public void onStop()
{
super.onStop();
//*Unregister event bus when the app goes in background*//*
if (EventBus.getDefault().isRegistered(this))
EventBus.getDefault().unregister(this);
}
#Override
public void onDestroy()
{
super.onDestroy();
if (EventBus.getDefault().isRegistered(this))
EventBus.getDefault().unregister(this);
}
public void onError(VolleyError volleyError)
{
UIHelper.stopProgressDialog(mProgressDialog);
Functions.Application.VolleyErrorCheck(this, volleyError);
}
just add this method to your viewPager adapter and your problem is solved.
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
this is override method of viewPager.
when you swipe one fragment to another it will automatically refresh page.
try this approach.. maybe its work for you..
put this code in your SubCategoryListAdepter
public void delete(int position) { //removes the row
superSubCategories.remove(position);
notifyItemRemoved(position);
}
make onClickListener to your ViewHolder:
suppose you click on your text and this row will be deleted.
#Override
public void onClick(View v) {
if(v.getId() == R.id.name){
//calls the method above to delete
delete(getAdapterPosition());
}
now you can also add data like this way.. thats working fine at runtime.. no need to refresh your page.

ViewPagerAdapter update fragment when starting again

I have the following ViewPagerAdapter:
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(((AppCompatActivity)getActivity()).getSupportFragmentManager());
adapter.addFrag(new OwnerPendingBookingsFragment(), "Pendientes");
adapter.addFrag(new OwnerConfirmedBookingsFragment(), "Confirmados");
adapter.addFrag(new OwnerFinishedBookingsFragment(), "Finalizados");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
And one of the fragments that I use is like that:
public class OwnerConfirmedBookingsFragment extends Fragment {
private View myView;
private ListView booking_list;
private ArrayAdapter adapter;
private SharedPreferences preferences;
private Toast toast;
private ProgressDialog progressDialog;
private BookingList bookings;
private boolean isFirstTime;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (isFirstTime) {
myView = inflater.inflate(R.layout.owner_confirmed_bookings_layout, container, false);
isFirstTime = false;
}
return myView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isFirstTime = true;
//Getting out sharedpreferences
preferences = getActivity().getSharedPreferences(Config.SHARED_PREF_LOGIN, Context.MODE_PRIVATE);
new FindBookings().execute("");
}
private void setUpAdapter(){
booking_list = (ListView) myView.findViewById(R.id.owner_confirmed_bookings);
getActivity().setTitle("Nuevas solicitudes");
if(bookings.getBookings().size() == 0){
booking_list.setVisibility(View.GONE);
LinearLayout no_vehicles = (LinearLayout) myView.findViewById(R.id.no_confirmed_bookings_layout);
no_vehicles.setVisibility(View.VISIBLE);
}else {
for (int i = 0; i < bookings.getBookings().size(); i++){
try {
new setImageTask(i).execute(bookings.getBookings().get(i).getDriver_image()).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
adapter = new OwnerFinishedBookingsAdapter(myView.getContext(), bookings.getBookings());
booking_list.setAdapter(adapter);
booking_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int booking_line = bookings.getBookings().get(position).getBooking_line_id();
Fragment booking_info = new OwnerPendingBookingInfoFragment();
Bundle args = new Bundle();
args.putInt("bookingLine", booking_line);
booking_info.setArguments(args);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame, booking_info);
transaction.addToBackStack(null);
transaction.commit();
}
});
}
}
private class FindBookings extends AsyncTask<String, Void, String> {
String token = preferences.getString(Config.TOKEN, "");
#Override
protected void onPreExecute() {
toast = Toast.makeText(getActivity().getApplicationContext(), "", Toast.LENGTH_LONG);
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage(getActivity().getString(R.string.finding_bookings));
progressDialog.show();
}
#Override
protected void onPostExecute(String s){
if(bookings.getError() != 0){
if(bookings.getError() == Config.JWT_EXPIRED){
logout();
Toast.makeText(getActivity().getApplicationContext(),
getActivity().getString(R.string.session_expired),
Toast.LENGTH_LONG).show();
}else {
toast.setText(getActivity().getString(R.string.find_pendings_errror));
toast.show();
}
}else {
setUpAdapter();
}
progressDialog.dismiss();
}
#Override
protected String doInBackground(String... params) {
bookings = DBConnect.getPendingBookingList(preferences.getInt(Config.IDUSER, 0), token);
return "done";
}
}
The first time I use it, all the fragments loads without any problem. But when I go to another activity and then return it doesn't update the data. I debug it and onCreate and onCreateView are not firing?
I tried to remove the fragment when going to another activity but nothing worked for me.

How does findFragmentByTag work in a parent Fragment to know which child fragment is currently showing with ViewPagerAdapter?

My MainFragment is like
public class MainTabFragment extends Fragment {
public static int position_child_tab = 0, three_childs_tab_position = 0;
static int count = -1;
int position_tab = 0;
Bundle args;
public static MyTabLayout myTabLayout;
private static MainTabFragment sMainTabFragment;
public static NonSiwpablePager pager;
private Fragment mFragment;
public MainTabFragment() {
// Required empty public constructor
}
public static MainTabFragment getInstance() {
return sMainTabFragment;
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment MainTabFragment.
*/
// TODO: Rename and change types and number of parameters
public static MainTabFragment newInstance(String param1, String param2) {
return new MainTabFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
args = getArguments();
if (args != null && args.containsKey("pos_next"))
position_tab = args.getInt("pos_next");
if (args != null && args.containsKey("pos_end"))
position_child_tab = args.getInt("pos_end");
if (position_child_tab != 3) {
three_childs_tab_position = position_child_tab;
} else {
three_childs_tab_position = 0;
}
args = new Bundle();
args.putInt("pos_end", position_child_tab);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_tab_fragment, container, false);
myTabLayout = (MyTabLayout) view.findViewById(R.id.mainTabLayout);
pager = (NonSiwpablePager) view.findViewById(R.id.pager);
ViewPagerAdapter mAdapter = getViewPagerAdapter();
pager.setAdapter(mAdapter);
pager.setOffscreenPageLimit(4);
myTabLayout.setupWithViewPager(pager);
for (int i = 0; i < mAdapter.getCount(); i++) {
View customView = mAdapter.getCustomeView(getActivity(), i);
myTabLayout.getTabAt(i).setCustomView(customView);
}
pager.setCurrentItem(position_tab);
pager.setOffscreenPageLimit(3);
// changeTab();
myTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
Fragment fragment = getFragmentManager().findFragmentByTag("TOP");
if (fragment != null){
pager.setCurrentItem(position_tab);
}
Log.e("Fragment", fragment + "" +pager.getCurrentItem());
//
return view;
}
public void changeTab(){
pager.getCurrentItem();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
myTabLayout.getTabAt(position_tab).getCustomView().setSelected(true);
}
public void setCurrentItem(int item) {
pager.setCurrentItem(item);
}
private ViewPagerAdapter getViewPagerAdapter() {
ViewPagerAdapter mAdapter = new ViewPagerAdapter(getChildFragmentManager());
String title_arr[] = {"ADVISORY", "TOP ADVISORS", "EXPERT VIEW"};
for (int i = 0; i < title_arr.length; i++) {
Map<String, Object> map = new Hashtable<>();
map.put(ViewPagerAdapter.KEY_TITLE, title_arr[i]);
if (i == 0) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, AdvisoryPagerFragment.newInstance());
AdvisoryPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
} else if (i == 1) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, TopAdvisoryPagerFragment.newInstance());
TopAdvisoryPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
} else if (i == 2) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, ExperViewPagerFragment.newInstance());
ExperViewPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
}
mAdapter.addFragmentAndTitle(map);
}
return mAdapter;
}
public static class ViewPagerAdapter extends FragmentStatePagerAdapter {
private static final String KEY_TITLE = "fragment_title";
private static final String KEY_FRAGMENT = "fragment";
boolean abc = false;
private int[] drawables = new int[]{R.drawable.advisory_selector, R.drawable.top_advisors_selector, R.drawable.expertview_selector};
private List<Map<String, Object>> maps = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public View getCustomeView(Context context, int pos) {
View mView = LayoutInflater.from(context).inflate(R.layout.custom_tab_view, null);
TextView mTextView = (TextView) mView.findViewById(R.id.textView);
mTextView.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/ufonts.com_cambria.ttf"));
ImageView mImageView = (ImageView) mView.findViewById(R.id.imageView2);
mImageView.setTag(pos);
/*if(count >0)
{
Toast.makeText(context,"Count Is "+count,Toast.LENGTH_SHORT).show();
mImageView = (ImageView) mImageView.getTag(0);
mImageView.setSelected(false);
}
*/
mImageView.setImageResource(drawables[pos]);
mTextView.setText(getPageTitle(pos));
return mView;
}
public void addFragmentAndTitle(Map<String, Object> map) {
maps.add(map);
}
#Override
public CharSequence getPageTitle(int position) {
return (CharSequence) maps.get(position).get(KEY_TITLE);
}
#Override
public Fragment getItem(int position) {
Log.e("Fragmentss" ,(Fragment) maps.get(position).get(KEY_FRAGMENT) +"");
return (Fragment) maps.get(position).get(KEY_FRAGMENT);
}
#Override
public int getCount() {
return maps.size();
}
}
}
Here I can get that this fragment is visible by using findFragmentByTag. I wanna know how I can use same thing for the child of this Fragment which are added using FragmentPagerAdapter.
Fragment fragment = getFragmentManager().findFragmentByTag("TOP");
if (fragment != null){
Log.e("Fragment", fragment + "" +pager.getCurrentItem()); }
So now I wanna do same thing and get name of current selected Fragment out of 3 which are mentioned above in FragmentPagerAdapter as AdvisoryPagerFragment,TopAdvisoryPagerFragment and ExperViewPagerFragment.
Try this
Fragment fragment = getFragmentManager().findFragmentByTag("TOP");
if(fragment instanceOf Fragment1){
// Do something
}else if(fragment instanceOf Fragment2){
// Do something
}else{
// Do something
}

Strange behavior of ViewPager

I am using for my Android app PagerSlidingTabStrip and Material Navigation Drawer libraries. I am watching strange behavior of ViewPager - when I am opening it first time, it works normally, but I am opening it again, ViewPager is empty, as without adapter.
MainActivity:
public class MainActivity extends AppCompatActivity {
private Drawer drawer;
private int lastSelection;
private BroadcastReceiver mRegistrationBroadcastReceiver;
private boolean isClickedByUser = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = new DrawerBuilder().withActivity(MainActivity.this)
.withToolbar(toolbar).addDrawerItems(
new PrimaryDrawerItem().withName(R.string.name1)
.withIcon(R.drawable.icon1),
new PrimaryDrawerItem()
.withName(R.string.name2)
.withIcon(R.drawable.icon2))
.withOnDrawerItemClickListener(
new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(AdapterView<?> adapterView, View view,
int position, long id,
IDrawerItem iDrawerItem) {
switch (position) {
case 0:
setTitle(R.string.title1);
break;
case 1:
setTitle(R.string.title2);
break;
}
FragmentManager fManager = getSupportFragmentManager();
FragmentTransaction transaction = fManager.beginTransaction();
transaction.replace(R.id.container, PlaceholderFragment.newInstance(
position)).commitAllowingStateLoss();
lastSelection = position;
return false;
}
})
.build();
drawer.setSelection(0);
}
#Override
public void onBackPressed() {
if (drawer != null && drawer.isDrawerOpen()) {
drawer.closeDrawer();
} else {
super.onBackPressed();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
drawer.setSelection(lastSelection);
}
}
PlaceholderFragment, in that ViewPager is done:
public class PlaceholderFragment extends Fragment {
private static final String ID = "id";
private int id;
public static PlaceholderFragment newInstance(int id) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ID, id);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
id = getArguments().getInt(ID);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = null;
switch (id) {
case 0:
rootView = inflater.inflate(R.layout.view1, container, false);
break;
case 1:
rootView = inflater.inflate(R.layout.tabs, container, false);
ViewPager pager = (ViewPager) rootView.findViewById(R.id.viewPager);
pager.setAdapter(new PagerAdapter(getActivity().getSupportFragmentManager()));
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) rootView.findViewById(R.id.tabs);
tabs.setViewPager(pager);
tabs.setShouldExpand(true);
tabs.setIndicatorColorResource(R.color.tab_indicator_color);
tabs.setTextColorResource(R.color.tab_text_color);
break;
default:
break;
}
return rootView;
}
private class PagerAdapter extends FragmentPagerAdapter {
private int[] titlesResIds = { R.string.title1, R.string.title2 };
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return getString(titlesResIds[position]);
}
#Override
public int getCount() {
return titlesResIds.length;
}
#Override
public Fragment getItem(int position) {
return TabFragment.newInstance(position);
}
}
}
TabFragment:
public class TabFragment extends ListFragment {
private static final String ID = "id";
private int id;
public static TabFragment newInstance(int id) {
TabFragment fragment = new TabFragment();
Bundle args = new Bundle();
args.putInt(ID, id);
fragment.setArguments(args);
return fragment;
}
public TabFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
id = getArguments().getInt(ID);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
AsyncTask<String, String, String> asyncTask = new AsyncTask<String, String, String>() {
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://host/")
.build();
String result = null;
try {
Response response = client.newCall(request).execute();
result = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
Gson gson = new Gson();
JsonReader reader = new JsonReader(new StringReader(response));
reader.setLenient(true);
ArrayList<Message> messages = gson.fromJson(reader,
new TypeToken<ArrayList<Message>>(){}.getType());
int i = messages.size() - 1;
while (i != -1) {
if (messages.get(i).getType() != id)
messages.remove(i);
i--;
}
ArrayAdapter adapter = new MyListAdapter(messages);
setListAdapter(adapter);
}
};
asyncTask.execute();
return inflater.inflate(R.layout.fragment, container, false);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent messageIntent = new Intent(getActivity(), MessageActivity.class);
startActivity(messageIntent);
}
private class MyListAdapter extends ArrayAdapter {
private Context context = getActivity();
private ArrayList<Message> messages;
public MyListAdapter(ArrayList<Message> messages) {
super(getActivity(), R.layout.list_adapter);
this.messages = messages;
}
#Override
public int getCount() {
return messages.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.list_adapter, parent, false);
holder = new ViewHolder();
holder.imageIcon = (ImageView) convertView.findViewById(R.id.list_icon);
holder.textDatetime = (TextView) convertView.findViewById(R.id.list_text_datetime);
holder.textPrimary = (TextView) convertView.findViewById(R.id.list_text_primary);
holder.textSecondary = (TextView) convertView.findViewById(R.id.list_text_secondary);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Message message = messages.get(position);
long timestamp = message.getTimestamp() * 1000;
Date date = new Date(timestamp);
String datetime = new SimpleDateFormat("dd.MM.yyyy hh:mm", Locale.US).format(date);
holder.imageIcon.setImageResource(message.getIcon() == 0 ?
R.drawable.icon1 :
R.drawable.icon2);
holder.textDatetime.setText(datetime);
holder.textPrimary.setText(message.getTitle());
holder.textSecondary.setText(message.getMessage());
return convertView;
}
private class ViewHolder {
ImageView imageIcon;
TextView textDatetime;
TextView textPrimary;
TextView textSecondary;
}
}
}
I already decided my problem. I'm insert method getChildFragmentManager() in my PlaceholderFragment as in this answer - How set ViewPager inside a Fragment.

Categories

Resources