I have silder layout.xml in rss fragment. I do not know how to call them in fragment. I need to put some rss feed one link and get the data. Let me know if you know anyone
EnchantedViewPager
<com.Tamillive.newspaper.EnchantedViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="210dp" />
Rss feed layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="#+id/swipeRefreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="210dp"
android:layout_marginEnd="5dp"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp">
<com.Tamillive.newspaper.EnchantedViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="210dp" />
<me.relex.circleindicator.CircleIndicator
android:id="#+id/indicator_unselected_background"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="5dp"
android:layout_marginEnd="10dp"
app:ci_drawable="#drawable/selecteditem_dot"
app:ci_drawable_unselected="#drawable/nonselecteditem_dot"
app:ci_height="6dp"
app:ci_width="6dp"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp" />
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#color/background_white"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/list"
style="#style/listStyleNoPadding"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#null"
android:focusable="false" />
</LinearLayout>
</LinearLayout>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
<com.facebook.shimmer.ShimmerFrameLayout
android:id="#+id/shimmer_view_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:shimmer_duration="1000">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include
android:id="#+id/lyt_shimmer_recipes_list_big"
layout="#layout/include_shimmer_recipes_list_big" />
</RelativeLayout>
</com.facebook.shimmer.ShimmerFrameLayout>
</RelativeLayout>
RssFragment
public class RssFragment extends Fragment {
// Added argument key for URL
private static final String ARG_URL = "url_string";
public static final int RECIPES_LIST_SMALL = 0;
public static final int RECIPES_LIST_BIG = 1;
public static final int RECIPES_GRID_2_COLUMN = 2;
public static final int RECIPES_GRID_3_COLUMN = 3;
private RSSFeed rssFeed = null;
private ArrayList<RSSItem> postsList;
private RssAdapter listAdapter;
private ViewModeUtils viewModeUtils;
private SwipeRefreshLayout swipeRefreshLayout;
SharedPref sharedPref;
private Activity mAct;
private RelativeLayout ll;
private String url;
private AdView mAdView;
private View rootView;
private ShimmerFrameLayout lyt_shimmer;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ll = (RelativeLayout) inflater.inflate(R.layout.fragment_list_refresh, container, false);
return ll;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
lyt_shimmer = ll.findViewById(R.id.shimmer_view_container);
RecyclerView listView = ll.findViewById(R.id.list);
postsList = new ArrayList<>();
listAdapter = new RssAdapter(getContext(), postsList);
listAdapter.setModeAndNotify(InfiniteRecyclerViewAdapter.MODE_PROGRESS);
listView.setAdapter(listAdapter);
listView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
swipeRefreshLayout = ll.findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
refreshItems();
initShimmerLayout();
}
private void initShimmerLayout() {
View lyt_shimmer_recipes_list_big = ll.findViewById(R.id.lyt_shimmer_recipes_list_big);
if (sharedPref.getRecipesViewType() == RECIPES_LIST_SMALL) {
lyt_shimmer_recipes_list_big.setVisibility(View.GONE);
} else if (sharedPref.getRecipesViewType() == RECIPES_LIST_BIG) {
lyt_shimmer_recipes_list_big.setVisibility(View.VISIBLE);
} else if (sharedPref.getRecipesViewType() == RECIPES_GRID_2_COLUMN) {
;
lyt_shimmer_recipes_list_big.setVisibility(View.GONE);
} else if (sharedPref.getRecipesViewType() == RECIPES_GRID_3_COLUMN) {
lyt_shimmer_recipes_list_big.setVisibility(View.GONE);
}
}
});
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mAct = getActivity();
// get URL from arguments
url = RssFragment.this.getArguments().getString(ARG_URL);
refreshItems();
}
private class RssTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
try {
// Pass the URL string as parameter to URL class
URL rssUrl = new URL(url);
SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
XMLReader myXMLReader = mySAXParser.getXMLReader();
RSSHandler myRSSHandler = new RSSHandler();
myXMLReader.setContentHandler(myRSSHandler);
InputSource myInputSource = new InputSource(rssUrl.openStream());
myXMLReader.parse(myInputSource);
rssFeed = myRSSHandler.getFeed();
} catch (ParserConfigurationException | IOException | SAXException e) {
Log.printStackTrace(e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (rssFeed != null) {
if (rssFeed.getList().size() > 0) {
postsList.addAll(rssFeed.getList());
}
listAdapter.setHasMore(false);
listAdapter.setModeAndNotify(InfiniteRecyclerViewAdapter.MODE_LIST);
swipeRefreshLayout.setRefreshing(false);
} else {
String message = null;
if (!url.startsWith("http"))
message = "Debug info: '" + url + "' is most likely not a valid RSS url. Make sure the url entered in your configuration starts with 'http' and verify if it's valid XML using validator.w3.org/feed";
Helper.noConnection(mAct, message);
listAdapter.setModeAndNotify(InfiniteRecyclerViewAdapter.MODE_EMPTY);
swipeRefreshLayout.setRefreshing(false);
}
super.onPostExecute(result);
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.rss_menu, menu);
viewModeUtils = new ViewModeUtils(getContext(), getClass());
viewModeUtils.inflateOptionsMenu(menu, inflater);
ThemeUtils.tintAllIcons(menu, mAct);
}
private void refreshItems() {
postsList.clear();
lyt_shimmer.setVisibility(View.GONE);
lyt_shimmer.stopShimmer();
listAdapter.setModeAndNotify(InfiniteRecyclerViewAdapter.MODE_PROGRESS);
new RssTask().execute(
);
}
private void swipeProgress(final boolean show) {
if (!show) {
swipeRefreshLayout.setRefreshing(show);
lyt_shimmer.setVisibility(View.GONE);
lyt_shimmer.stopShimmer();
return;
}
swipeRefreshLayout.post(() -> {
swipeRefreshLayout.setRefreshing(show);
lyt_shimmer.setVisibility(View.VISIBLE);
lyt_shimmer.startShimmer();
});
}
#Override
public void onDestroy() {
super.onDestroy();
swipeProgress(false);
lyt_shimmer.stopShimmer();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
viewModeUtils.handleSelection(item, new ViewModeUtils.ChangeListener() {
#Override
public void modeChanged() {
listAdapter.notifyDataSetChanged();
}
});
switch (item.getItemId()) {
case R.id.info:
//show information about the feed in general in a dialog
if (rssFeed != null) {
String FeedTitle = (rssFeed.getTitle());
String FeedDescription = (rssFeed.getDescription());
//String FeedPubdate = (myRssFeed.getPubdate()); most times not present
String FeedLink = (rssFeed.getLink());
AlertDialog.Builder builder = new AlertDialog.Builder(mAct);
String titlevalue = getResources().getString(R.string.feed_title_value);
String descriptionvalue = getResources().getString(R.string.feed_description_value);
String linkvalue = getResources().getString(R.string.feed_link_value);
if (FeedLink.equals("")) {
builder.setMessage(titlevalue + ": \n" + FeedTitle +
"\n\n" + descriptionvalue + ": \n" + FeedDescription);
} else {
builder.setMessage(titlevalue + ": \n" + FeedTitle +
"\n\n" + descriptionvalue + ": \n" + FeedDescription +
"\n\n" + linkvalue + ": \n" + FeedLink);
}
builder.setNegativeButton(getResources().getString(R.string.ok), null)
.setCancelable(true);
builder.create();
builder.show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}}
// This is the factory to instantiate the RssFragment instance with the url string as arguments
public static RssFragment newInstance(String url) {
RssFragment newInstance = new RssFragment();
Bundle bundle = new Bundle();
bundle.putString(ARG_URL, url);
newInstance.setArguments(bundle);
return newInstance;
}
}
ScrollableTabsActivity
public class ScrollableTabsActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrollable_tabs);
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
toolbar = (Toolbar) findViewById(R.id.toolbar2);
setSupportActionBar(toolbar);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(RssFragment.newInstance("http://www.rssmix.com/u/12847959/rss.xml"), "உலகம்");
adapter.addFrag(RssFragment.newInstance("http://www.rssmix.com/u/12847980/rss.xml"), "சினிமா");
adapter.addFrag(RssFragment.newInstance("http://www.rssmix.com/u/12850122/rss.xml"), "வேலை வாய்ப்பு");
adapter.addFrag(RssFragment.newInstance("http://www.rssmix.com/u/12850077/rss.xml"), "டெக்னாலஜி");
adapter.addFrag(RssFragment.newInstance("http://www.rssmix.com/u/12850128/rss.xml"), "சமையலறை");
adapter.addFrag(RssFragment.newInstance("http://www.rssmix.com/u/12850092/rss.xml"), "விவசாயம்");
adapter.addFrag(RssFragment.newInstance("http://www.rssmix.com/u/12850103/rss.xml"), "கல்வி-வேலைவாய்ப்பு");
adapter.addFrag(RssFragment.newInstance("http://www.rssmix.com/u/12850110/rss.xml"), "விளையாட்டு");
viewPager.setAdapter(adapter);
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
}).setNegativeButton("No", null).show();
}
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 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);
}
}
}
I need to put an rss feed link to something and get the data.
Related
I need a help. I am developing dynamic tabs with dynamic data in viewpager fragment's list. Somehow i got the dynamic tabs and hit API in placeholder fragment to get the recyclerview list.
there are two issue. 1. design is overlapping the tabs and 2. its loading 3rd id data first.
here is the code.
here is main class
public class NewsFeed extends Fragment {
private static RecyclerView listView;
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
private TabLayout tabLayout;
private ViewPager viewPager;
private RecyclerView recyclerView;
private ApiInterface apiInterface;
private List<BlogCatData> list = new ArrayList<BlogCatData>();
private BlogCatListAdaptor adapter;
private String item;
private ArrayList<BlogCatData> dataModelList = new ArrayList<BlogCatData>();
private ArrayList<String> CatTitleList = new ArrayList<>();
private static ArrayList<String> CatIdList = new ArrayList<>();
private View view1;
private View v;
// private ArrayAdapter<BlogCatData> adapter;
public NewsFeed() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_news_feed, container, false);
getAllBlogCat();
return v;
}
private void setViewIDs() {
tabLayout = v.findViewById(R.id.tabs);
viewPager = v.findViewById(R.id.container);
setUpViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
}
private void getAllBlogCat() {
// avi.show();
apiInterface = APIClient.getClient().create(ApiInterface.class);
Call<BlogCatModel> call = apiInterface.GETBlogCategory();
call.enqueue(new Callback<BlogCatModel>() {
#Override
public void onResponse(Call<BlogCatModel> call, retrofit2.Response<BlogCatModel> response) {
if (response.isSuccessful()) {
CatIdList.clear();
list = response.body().getDATA();
for (int i = 0; i < list.size(); i++) {
CatTitleList.add(list.get(i).getTITLE());
CatIdList.add(list.get(i).getID());
}
Log.v("CatTitle", CatTitleList.toString());
Log.v("CatId", CatIdList.toString());
setViewIDs();
// adapter.setPostList(list)
} else {
try {
JSONObject jObjError = new JSONObject(response.errorBody().string());
Toast.makeText(getApplicationContext(), jObjError.getString("message"), Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onFailure(Call<BlogCatModel> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.toString(), Toast.LENGTH_SHORT).show();
call.cancel();
}
});
}
private void setUpViewPager(ViewPager viewPager) {
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
for (int i = 0; i < CatTitleList.size(); i++) {
Bundle bundle = new Bundle();
bundle.putString("id", CatIdList.get(i));
PlaceholderFragment categoryList = new PlaceholderFragment();
categoryList.setArguments(bundle);
sectionsPagerAdapter.addFragment(categoryList, CatTitleList.get(i));
}
sectionsPagerAdapter.notifyDataSetChanged();
viewPager.setAdapter(sectionsPagerAdapter);
}
public static class PlaceholderFragment extends Fragment {
private final static String TAG = PlaceholderFragment.class.getSimpleName();
private static String item;
private static ArrayList<String> dataModelList = new ArrayList<String>();
// private ArrayAdapter<Model> adapter;
private RecyclerView listView;
private List<BlogData> dataList = new ArrayList<>();
private BlogListAdaptor blogListAdaptor;
private static String id;
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
id = CatIdList.get(sectionNumber);
Bundle args = new Bundle();
args.putString("ID", id);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment__newsfeed_placeholder, container, false);
listView = view.findViewById(R.id.recycler_view);
getBlog(Id);
setBlog();
return view;
}
private void getBlog(String id) {
ApiInterface apiInterface = APIClient.getClient().create(ApiInterface.class);
Call<BlogModel> call = apiInterface.getNewsByCategory(id);
call.enqueue(new Callback<BlogModel>() {
#Override
public void onResponse(Call<BlogModel> call, retrofit2.Response<BlogModel> response) {
if (response.isSuccessful()) {
dataList = response.body().getDATA();
blogListAdaptor.setPostList(dataList);
} else {
try {
JSONObject jObjError = new JSONObject(response.errorBody().string());
Toast.makeText(getApplicationContext(), jObjError.getString("message"), Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onFailure(Call<BlogModel> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.toString(), Toast.LENGTH_SHORT).show();
call.cancel();
}
});
}
private void setBlog() {
blogListAdaptor = new BlogListAdaptor(getActivity(), dataList);
listView.setAdapter(blogListAdaptor);
listView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
listView.setLayoutManager(linearLayoutManager);
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 0);
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public int getCount() {
return mFragmentTitleList.size();
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
}
return mFragmentTitleList.get(position);
}
#Override
public int getItemPosition(Object object) {
return super.getItemPosition(object);
}
}
}
and here is the adapter class for recyclerview
public class BlogListAdaptor extends RecyclerView.Adapter<BlogListAdaptor.MyViewHlder> {
private Activity activity;
private List<BlogData> list;
private boolean valid;
private EditText name, email, phone, date, noOfGuest, msg;
private Spinner partyMode, timeSlot;
private AlertDialog alertDialog;
final Calendar myCalendar = Calendar.getInstance();
private String PartyModeStr, TimeSlotStr;
private String Id;
private String title;
public BlogListAdaptor(Activity activity, List<BlogData> list) {
this.activity = activity;
this.list = list;
}
public void setPostList(List<BlogData> dataList) {
list = dataList;
notifyDataSetChanged();
}
#NonNull
#Override
public MyViewHlder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.blog_list_layout, viewGroup, false);
MyViewHlder my = new MyViewHlder(view);
return my;
}
#Override
public void onBindViewHolder(#NonNull MyViewHlder myViewHlder, int i) {
myViewHlder.Title.setText(list.get(i).getTITLE());
myViewHlder.Author.setText(list.get(i).getAUTHOR());
if (list.get(i).getIMGSRC() != null)
Glide.with(activity).load(Constant.ImgRoot + list.get(i).getIMGSRC())
.into(myViewHlder.Image);
myViewHlder.cardview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(activity, DetailActivity.class);
intent.putExtra("Id", list.get(i).getID());
intent.putExtra("Title", list.get(i).getTITLE());
intent.putExtra("Author", list.get(i).getAUTHOR());
intent.putExtra("Content", list.get(i).getCONTENT());
activity.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return list.size();
}
class MyViewHlder extends RecyclerView.ViewHolder {
private TextView Title, Author;
private ImageView Image;
private CardView cardview;
public MyViewHlder(#NonNull View itemView) {
super(itemView);
Image = itemView.findViewById(R.id.image);
Title = itemView.findViewById(R.id.title);
Author = itemView.findViewById(R.id.author);
cardview = itemView.findViewById(R.id.cardview);
}
}
}
Please help me out, to call api...
fragment_newsfeed_placeholder
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
fragment_news_feed
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
app:tabGravity="center"
app:tabMode="scrollable"
app:tabTextColor="#ffffff" />
<androidx.viewpager.widget.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/tabs" />
I have a gallery of images that shows the images in a recyclerviewusing glide and by clicking on each image in the recyclerview that image open in a view pager. every thing is ok in the beginning the recyclerview is fine, the images open in a viewpager and sliding in viewpager are all fine. but when i press back to close the viewpager and goback to recyclerview suddenly the allocated memory raises to about 400 MB!!!
there are 8 images that are about 490*420 pixel and 72 KB size.
MainGallery.xml
<android.support.v7.widget.RecyclerView
android:id="#+id/recView_Gallery1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
>
</android.support.v7.widget.RecyclerView>
<Button
android:id="#+id/btn_retry_Gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="تلاش مجدد"
android:textSize="16sp"
android:visibility="gone"
android:layout_gravity="center"
android:gravity="center"/>
</android.support.design.widget.CoordinatorLayout>
GalleryEnter.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent">
<ImageView
android:id="#+id/iv_photoGallety"
android:adjustViewBounds="true"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:layout_margin="2dp"
android:layout_width="match_parent"
android:background="#android:color/white"/>
</LinearLayout>
ImageDetail.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorAccent"
tools:context="com.parsroyan.restaurant.imageDetailActivity">
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.design.widget.CoordinatorLayout>
MainGalleryActivity.java
public class GalleryMain_Activity extends AppCompatActivity {
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
public static RecyclerView recListMenuTypes;
public static ImageAdapter mta;
ArrayList<ImageGallery> data = new ArrayList<>();
Button btn_retry;
TextView tv_message;
ImageView imv_message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery_main_);
btn_retry = (Button) findViewById(R.id.btn_retry_Gallery);
recListMenuTypes = (RecyclerView) findViewById(R.id.recView_Gallery1)
;
recListMenuTypes.setHasFixedSize(true);
GridLayoutManager mLayoutManager = new
GridLayoutManager(GalleryMain_Activity.this, 2);
recListMenuTypes.setLayoutManager(mLayoutManager);
//LinearLayoutManager llm = new
LinearLayoutManager(GalleryMain_Activity.this);
//llm.setOrientation(LinearLayoutManager.VERTICAL);
//recListMenuTypes.setLayoutManager(llm);
recListMenuTypes.setItemAnimator(new DefaultItemAnimator());
mta = new ImageAdapter(GalleryMain_Activity.this, data);
recListMenuTypes.setAdapter(mta);
Check_Connection_Retrive();
btn_retry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Check_Connection_Retrive();
}
});
}
private void alertView1(String message,boolean success) {
final TypedArray styledAttributes =
GalleryMain_Activity.this.getTheme().obtainStyledAttributes(new int[] {
android.R.attr.actionBarSize });
int Y = (int) styledAttributes.getDimension(0, 0);
styledAttributes.recycle();
LayoutInflater inflater = getLayoutInflater();
View toastLayout = inflater.inflate(R.layout.custom_toast,
(ViewGroup)
findViewById(R.id.custom_toast_layout));
tv_message = (TextView)
toastLayout.findViewById(R.id.custom_toast_message);
tv_message.setText(message);
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP | Gravity.START |
Gravity.FILL_HORIZONTAL,0,Y);
toast.setView(toastLayout);
imv_message = (ImageView)
toastLayout.findViewById(R.id.custom_toast_image);
if(!success){
toastLayout.setBackgroundColor(Color.parseColor("#cc0000"));
imv_message.setBackgroundResource(android.R.drawable.ic_dialog_alert);
}
else {
imv_message.setBackgroundResource(android.R.drawable.ic_dialog_info);
}
toastLayout.setAlpha(.8f);
toast.show();
}
public void Check_Connection_Retrive()
{
if(InternetConnection.checkConnection(getApplicationContext(),this))
{
btn_retry.setVisibility(View.GONE);
new FetchGallery().execute();
}
else
{
btn_retry.setVisibility(View.VISIBLE);
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
private class FetchGallery extends AsyncTask<String, String, String> {
TransparentProgressDialog pdLoading = new
TransparentProgressDialog
(GalleryMain_Activity.this,R.drawable.progress_circle);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {`enter code here`
super.onPreExecute();
//pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
//pdLoading.setProgress(10);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
url = new URL("My_URL");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "1";
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return "2";
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return "3";
}
} catch (IOException e) {
return "4";
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
switch(result) {
case "1":
break;
case "2":
break;
case "3":
break;
case "4":
break;
default:
try {
btn_retry.setVisibility(View.GONE);
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
//JSONObject json_data = jArray.getJSONObject(i);
ImageGallery image = new ImageGallery();
//image.name = json_data.getString("name");
image.title = jArray.get(i).toString();
image.url = "MY_URL" + image.title;
data.add(image);
}
// Setup and Handover data to recyclerview
mta.notifyDataSetChanged();
recListMenuTypes.addOnItemTouchListener(new
RecyclerViewTouchListener(getApplicationContext(), recListMenuTypes, new
RecyclerViewClickListener() {
#Override
public void onClick(View view, int position) {
Intent intent = new Intent(GalleryMain_Activity.this,
imageDetailActivity.class);
intent.putParcelableArrayListExtra("data", data);
intent.putExtra("pos", position);
startActivity(intent);
}
#Override
public void onLongClick(View view, int position){
}
}));
} catch (JSONException e) {
Toast.makeText(GalleryMain_Activity.this,
e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
}
ImageAdapter.java
public class ImageAdapter extends
RecyclerView.Adapter<ImageAdapter.MenuViewHolder> {
private List<ImageGallery> imageGalleryList;
private Context context;
protected int lastPosition = -1;
public ImageAdapter(Context Context,List<ImageGallery> contactList)
{
this.imageGalleryList = contactList;
this.context = Context;
}
#Override
public int getItemCount() {
return imageGalleryList.size();
}
#Override
public void onBindViewHolder(ImageAdapter.MenuViewHolder menuViewHolder,
int i) {
final ImageGallery m = imageGalleryList.get(i);
Glide.with(context).load("MyURL"+m.title)
.thumbnail(.1f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.override(200,200).placeholder(R.drawable.logoback)
.into(menuViewHolder.vImage);
setFadeAnimation(menuViewHolder,i);
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
public ImageAdapter.MenuViewHolder onCreateViewHolder(ViewGroup
viewGroup, int i) {
final View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.activity_gallery_enter, viewGroup, false);
return new ImageAdapter.MenuViewHolder(itemView);
}
#Override
public void onViewDetachedFromWindow(ImageAdapter.MenuViewHolder holder)
{
((ImageAdapter.MenuViewHolder)holder).itemView.clearAnimation();
}
public class MenuViewHolder extends RecyclerView.ViewHolder{
protected ImageView vImage;
public MenuViewHolder(View v) {
super(v);
vImage = (ImageView) v.findViewById(R.id.iv_photoGallety);
}
}
private void setFadeAnimation(ImageAdapter.MenuViewHolder view, int
position) {
if (position > lastPosition) {
AlphaAnimation anim = new AlphaAnimation(0.0f, 2.0f);
anim.setDuration(1000);
view.itemView.startAnimation(anim);
lastPosition = position;
}
}
}
ImageDetailActivity.java
public class imageDetailActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
public ArrayList<ImageGallery> data = new ArrayList<>();
int pos;
Toolbar aboveToolbar;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_detail);
//aboveToolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.detail_toolbar);
//setSupportActionBar(aboveToolbar);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
data = getIntent().getParcelableArrayListExtra("data");
pos = getIntent().getIntExtra("pos", 0);
setTitle(data.get(pos).getName());
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), data);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setPageTransformer(true, new DepthPageTransformer());
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setCurrentItem(pos);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
//noinspection ConstantConditions
setTitle(data.get(position).getName());
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public ArrayList<ImageGallery> data = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager fm, ArrayList<ImageGallery> data) {
super(fm);
this.data = data;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position, data.get(position).getName(), data.get(position).getUrl());
}
#Override
public int getCount() {
// Show 3 total pages.
return data.size();
}
// #Override
//public CharSequence getPageTitle(int position) {
//return data.get(position).getName();
// }
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
String name, url;
ImageView ImageView;
int pos;
private static final String ARG_SECTION_NUMBER = "section_number";
//private static final String ARG_IMG_TITLE = "image_title";
private static final String ARG_IMG_URL = "image_url";
#Override
public void setArguments(Bundle args) {
super.setArguments(args);
this.pos = args.getInt(ARG_SECTION_NUMBER);
//this.name = args.getString(ARG_IMG_TITLE);
this.url = args.getString(ARG_IMG_URL);
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber, String name, String url) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
//args.putString(ARG_IMG_TITLE, name);
args.putString(ARG_IMG_URL, url);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_image_detail, container, false);
this.ImageView = (ImageView) rootView.findViewById(R.id.detail_image);
Glide.with(getActivity()).load(url).thumbnail(0.1f).crossFade()
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.override(200,200).placeholder(R.drawable.tiara3)
.into(this.ImageView);
return rootView;
}
}
}
error log:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.OutOfMemoryError
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:501)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:354)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:785)
at android.content.res.Resources.loadDrawable(Resources.java:1970)
at android.content.res.Resources.getDrawable(Resources.java:660)
at com.bumptech.glide.request.GenericRequest.getPlaceholderDrawable(GenericRequest.java:416)
at com.bumptech.glide.request.GenericRequest.clear(GenericRequest.java:323)
at com.bumptech.glide.request.ThumbnailRequestCoordinator.clear(ThumbnailRequestCoordinator.java:106)
at com.bumptech.glide.manager.RequestTracker.clearRequests(RequestTracker.java:94)
at com.bumptech.glide.RequestManager.onDestroy(RequestManager.java:221)
at com.bumptech.glide.manager.ActivityFragmentLifecycle.onDestroy(ActivityFragmentLifecycle.java:64)
at com.bumptech.glide.manager.SupportRequestManagerFragment.onDestroy(SupportRequestManagerFragment.java:147)
at android.support.v4.app.Fragment.performDestroy(Fragment.java:2322)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1240)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1290)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1272)
at android.support.v4.app.FragmentManagerImpl.dispatchDestroy(FragmentManager.java:2186)
at android.support.v4.app.FragmentController.dispatchDestroy(FragmentController.java:271)
at android.support.v4.app.FragmentActivity.onDestroy(FragmentActivity.java:388)
at android.support.v7.app.AppCompatActivity.onDestroy(AppCompatActivity.java:209)
at android.app.Activity.performDestroy(Activity.java:5273)
at android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1110)
at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3438)
at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3469)
at android.app.ActivityThread.access$1200(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1287)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
real device result:
enter image description here
smulator result:
enter image description here
Add below line in Application tag in Menifest file:
android:largeHeap="true"
I am building a order receiving app for waiter in which half page is activity layout which contains listview and half is viewpager which contains json arraylist in fragment. I want to add the menu data from fragment when clicked on + button with number of quantity to be add on root activity's listview
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/My_Container_1_ID"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="140dp"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="#string/app_name"
app:layout_collapseMode="parallax"
android:background="#mipmap/bgactionbar">
<ImageView
android:id="#+id/logo"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_marginLeft="30dp"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:background="#mipmap/logoapp"
/>
<ImageView
android:id="#+id/triangle"
android:layout_width="280dp"
android:layout_height="100dp"
android:layout_toRightOf="#+id/logo"
android:background="#mipmap/caley"
/>
<RelativeLayout
android:id="#+id/searchLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/triangle"
android:background="#F3EEE8"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:src="#android:drawable/ic_menu_search"
android:layout_toRightOf="#+id/search_menu"
/>
<EditText
android:id="#+id/search_menu"
android:layout_width="350dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:hint="Search Menu..."
android:textColorHint="#color/tab_text"
android:textColor="#color/tab_text"
android:background="#android:color/transparent"
android:layout_alignParentLeft="true"
android:inputType="textVisiblePassword"/>
</RelativeLayout>
<ImageView
android:id="#+id/coffee"
android:layout_width="110dp"
android:layout_height="140dp"
android:layout_toRightOf="#+id/searchLayout"
android:background="#mipmap/coffee"
android:layout_alignParentRight="true"
/>
</RelativeLayout>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.CollapsingToolbarLayout>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
style="#style/MyCustomTabLayout"
android:background="#mipmap/background"
app:tabMode="fixed" />
</android.support.design.widget.AppBarLayout>
</FrameLayout>
<RelativeLayout
android:id="#+id/content"
android:layout_width="360dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentBottom="true"
android:background="#mipmap/background"
android:layout_below="#id/My_Container_1_ID">
<TextView
android:id="#+id/txtorder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Order"
android:textStyle="bold"
android:textColor="#color/tab_text"
android:textSize="20sp" />
<android.support.v7.widget.RecyclerView
android:id="#+id/orderlist"
android:layout_width="340dp"
android:layout_height="match_parent"
android:layout_above="#+id/submit_order"
android:layout_below="#+id/txtorder"
android:background="#mipmap/background"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<Button
android:id="#+id/submit_order"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/orderlist"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/orderlist"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:background="#EE6426"
android:textColor="#android:color/white"
android:text="Submit" />
</RelativeLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_below="#+id/My_Container_1_ID"
android:layout_toRightOf="#+id/content"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</RelativeLayout>
public class Menu extends AppCompatActivity implements Coffee.OnMenuInteractionListener {
// private ArrayList<MenuDataModel> allOrders;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
ListView listView;
RecyclerView recyclerView;
RecyclerAdapter adapter;
// MenuTabAdapter adapter;
// ArrayList<MenuDataModel> allOrders;
private List<MenuDataModel> allOrders = new ArrayList<MenuDataModel>();
// private List<String> orderList = new ArrayList<>();
private String Quantity, Name;
EditText count, inputSearch;
TextView order;
String searchValue;
private ArrayList<String> stringArrayList;
CollapsingToolbarLayout collapsingToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
collapsingToolbar= (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
// collapsingToolbar.setTitle(getString(R.string.app_name));
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
// listView = (ListView) findViewById(R.id.orderlist);
// adapter = new MenuTabAdapter(this, allOrders);
// listView.setAdapter(adapter);
TextView orddd = (TextView) findViewById(R.id.txtorder);
inputSearch = (EditText) findViewById(R.id.search_menu);
// inputSearch.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
//
// collapsingToolbar.setVisibility(View.GONE);
//
// }
// });
// recyclerView = (RecyclerView) findViewById(R.id.orderlist);
// recyclerView.setHasFixedSize(true);
// LinearLayoutManager layoutManager = new LinearLayoutManager(this);
// recyclerView.setLayoutManager(layoutManager);
//
// adapter = new RecyclerAdapter(this, allOrders);
// recyclerView.setAdapter(adapter);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new Coffee(), "Coffee");
adapter.addFragment(new Coffee(), "BreakFast");
adapter.addFragment(new Coffee(), "Beverage");
viewPager.setAdapter(adapter);
}
#Override
public void onFragmentSetOrders(ArrayList<MenuDataModel> menuList) {
allOrders = menuList;
}
#Override
public void onMenuListItemClick(int position) {
//musicService.setSong(position);
MenuDataModel menuorder = allOrders.get(position);
// menuorder.setName(menuorder.getName());
// menuorder.setName(allOrders);
allOrders.add(menuorder);
}
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 Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
public class Coffee extends Fragment {
ListView listView;
MenusAdapter adapter;
// Movies json url
private static final String url = "url";
private ProgressDialog pDialog;
private List<MenuDataModel> menuList = new ArrayList<MenuDataModel>();
OnMenuInteractionListener menuItemClick;
private String searchData;
private EditText inputSearch;
// Activity activity;
//OnMenuInteractionListener mCallback;
public Coffee() {
// Required empty public constructor
}
public interface OnMenuInteractionListener {
public void onFragmentSetOrders(ArrayList<MenuDataModel> menuList);
public void onMenuListItemClick(int position);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
menuItemClick = (OnMenuInteractionListener) getActivity();
}
#Override
public void onDetach() {
super.onDetach();
menuItemClick = null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// searchData = getArguments().getString("search");
inputSearch = (EditText) getActivity().findViewById(R.id.search_menu);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// When user changed the Text
//adapter.getFilter().filter(cs.toString());
if (count < before) {
// We're deleting char so we need to reset the adapter data
adapter.resetData();
}
Coffee.this.adapter.getFilter().filter(s);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
View view = inflater.inflate(R.layout.fragment_coffee, container, false);
listView = (ListView) view.findViewById(R.id.list);
adapter = new MenusAdapter(getActivity(), menuList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
showpDialog();
// Creating volley request obj
JsonObjectRequest bookingReq = new JsonObjectRequest(Request.Method.GET, "" + url + "?", null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("bsd", response.toString());
// Parsing json
try {
JSONArray menu = response.getJSONArray("menus");
int length = menu.length();
for (int i = 0; i < menu.length(); i++) {
JSONObject obj = menu.getJSONObject(i);
MenuDataModel dm = new MenuDataModel();
// Log.d("vdata", String.valueOf(menu.length()));
dm.setID(obj.getString("id"));
dm.setName(obj.getString("name"));
dm.setThumbnailUrl(obj.getString("photo"));
Log.d("image", String.valueOf(obj.getString("photo")));
dm.setDescription(obj.getString("description"));
dm.setRate(obj.getString("price"));
dm.setStatus(obj.getString("status"));
// adding movie to movies array
menuList.add(dm);
// Log.d("nth", String.valueOf(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
hidepDialog();
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#SuppressWarnings("deprecation")
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("b", "Error: " + error.getMessage());
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(bookingReq);
return view;
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.setMessage("Please wait...");
pDialog.show();
}
private void hidepDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
public class MenusAdapter extends BaseAdapter implements Filterable {
private static final String TAG = MenusAdapter.class.getSimpleName();
List<MenuDataModel> MenuItems;
List<MenuDataModel> mSearchValues;
private android.widget.Filter menufilter;
Coffee.OnMenuInteractionListener mCallback;
//private Activity activity;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public MenusAdapter(Activity activity, List<MenuDataModel> MenuItems) {
//this.activity = activity;
this.MenuItems = MenuItems;
this.mSearchValues = MenuItems;
}
#Override
public int getCount() {
return MenuItems.size(); // total number of elements in the list
}
#Override
public Object getItem(int i) {
return MenuItems.get(i); // single item in the list
}
#Override
public long getItemId(int i) {
return i; // index number
}
#Override
public View getView(final int index, View view, final ViewGroup parent) {
if (view == null) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.menu_item, parent, false);
}
// if (imageLoader == null)
// imageLoader = AppController.getInstance().getImageLoader();
final ImageView increase = (ImageView) view.findViewById(R.id.icon_increase);
ImageView decrease = (ImageView) view.findViewById(R.id.icon_decrease);
final EditText count = (EditText) view.findViewById(R.id.count_menu);
NetworkImageView thumbnailUrl = (NetworkImageView) view.findViewById(R.id.menu_image);
TextView name = (TextView) view.findViewById(R.id.menu_items);
// TextView description = (TextView) view.findViewById(R.id.description);
// TextView rate = (TextView) view.findViewById(R.id.price);
final MenuDataModel data = MenuItems.get(index);
name.setText(String.valueOf(data.getName()));
thumbnailUrl.setImageUrl(data.getThumbnailUrl(), imageLoader);
thumbnailUrl.setDefaultImageResId(R.mipmap.logoapp);
thumbnailUrl.setErrorImageResId(R.mipmap.logoapp);
// description.setText(String.valueOf(data.getDescription()));
// title.setText(data.getTitle());
// rate.setText(String.valueOf(data.getRate()));
// final double dis = Double.valueOf(data.getRate());
final int[] quantity = {MenuItems.get(index).getAnInt()};
increase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(parent.getContext(), "Button Clicked"+ dataModel.getName(),Toast.LENGTH_LONG).show();
//Intent yes= new Intent(parent.getContext(), yes(dataModel.getName().class));
quantity[0]++;
count.setText(quantity[0] + "");
count.setTag(quantity[0] + "");
// mCallback.onFragmentSetOrders(all);
mCallback.onMenuListItemClick(MenuItems.get(index).getAnInt());
// Coffee.OnMenuInteractionListener listener = (Coffee.OnMenuInteractionListener) activit;
// mCallback.onFragmentSetOrders(menu);
// Bundle bundle = new Bundle();
// bundle.putString("quantity", quantity[0] + "");
// bundle.putString("name", String.valueOf(data.getName()));
// q.putExtra("bookingid", dataModel.getbkid());
// parent.getContext().startActivity(q);
}
});
decrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
count.getTag();
count.setTag(quantity[0] + "");
quantity[0]--;
count.setText(quantity[0] + "");
}
});
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
return view;
}
#Override
public Filter getFilter() {
if (menufilter == null)
menufilter = new MenuFilter();
return menufilter;
}
public void resetData() {
MenuItems = mSearchValues;
}
private class MenuFilter extends android.widget.Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
// We implement here the filter logic
if (constraint == null || constraint.length() == 0) {
// No filter implemented we return all the list
results.values = mSearchValues;
results.count = mSearchValues.size();
} else {
// We perform filtering operation
List<MenuDataModel> nDriverList = new ArrayList<MenuDataModel>();
for (MenuDataModel p : MenuItems) {
if (p.getName().toUpperCase().startsWith(constraint.toString().toUpperCase()))
nDriverList.add(p);
}
results.values = nDriverList;
results.count = nDriverList.size();
}
return results;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
// Now we have to inform the adapter about the new list filtered
if (results.count == 0)
notifyDataSetInvalidated();
else {
MenuItems = (List<MenuDataModel>) results.values;
notifyDataSetChanged();
}
}
}
;
}
i am getting null pointer exception on mCallback.onMenuListItemClick(MenuItems.get(index).getAnInt());
Step 1: Create Interface
public interface ActivityCommunicator{
public void passDataToActivity(ArrayList<string> arrayList);
}
Step 2:Initialize interface object in fragment class
private ActivityCommunicator activityCommunicator;;
public void onAttach(Activity activity)
{
super.onAttach(activity);
context = getActivity();
activityCommunicator =(ActivityCommunicator)context;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
init();
}
public void init() {
activityButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
activityCommunicator.passDataToActivity("Your Array List");
}
});
}
step 3: Access Your arraylist from fragment in your activity class.
public class MainActivity extends FragmentActivity implements ActivityCommunicator{
public static ArrayList<String> aList;
#Override
public void passDataToActivity(ArrayList<String> arrayList){
aList = arrayList;
}
}
I have an app which loads feeds from a webservice. Uuntil the feed is loaded I show a Dialog saying "please wait...".
I want to show a Circle ProgressBar instead.
What I am showing
What I want to show
public class M {
static ProgressDialog pDialog;
private static SharedPreferences mSharedPreferences;
public static void showLoadingDialog(Context mContext) {
pDialog = new ProgressDialog(mContext);
pDialog.setMessage(mContext.getString(R.string.please_wait));
pDialog.setIndeterminate(true);
pDialog.setCancelable(true);
pDialog.show();
}
}
Activity that shows that Progress Dialog
public class HomeFragment extends Fragment implements OnClickListener {
public RecyclerView postsList;
public View mView;
public FloatingActionButton mFabButton;
public Toolbar toolbar;
public Intent mIntent;
public LinearLayoutManager layoutManager;
int currentPage = 1;
private HomeListAdapter mHomeListAdapter;
private SwipeRefreshLayout mSwipeRefreshLayout;
private CacheManager mCacheManager;
private Gson mGson;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mCacheManager = CacheManager.getInstance(getActivity().getApplicationContext());
mGson = new Gson();
mView = inflater.inflate(R.layout.fragment_home, container, false);
initializeView();
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(R.string.title_home);
((AppCompatActivity) getActivity()).getSupportActionBar().setShowHideAnimationEnabled(true);
getPosts(true);
return mView;
}
private void initializeView() {
postsList = (RecyclerView) mView.findViewById(R.id.postsList);
mFabButton = (FloatingActionButton) mView.findViewById(R.id.fabButton);
mFabButton.setOnClickListener(this);
mFabButton.setRippleColor(getActivity().getResources().getColor(R.color.accentColor));
//layout manager
layoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
postsList.setLayoutManager(layoutManager);
mHomeListAdapter = new HomeListAdapter(getActivity(), new ArrayList<PostsItem>());
postsList.setAdapter(mHomeListAdapter);
mSwipeRefreshLayout = (SwipeRefreshLayout) mView.findViewById(R.id.swipeHome);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
setCurrentPage(1);
getPosts(false);
}
});
//setting up our OnScrollListener
postsList.addOnScrollListener(new HidingScrollListener(layoutManager) {
#Override
public void onHide() {
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mFabButton.getLayoutParams();
int fabBottomMargin = lp.bottomMargin;
mFabButton.animate().translationY(mFabButton.getHeight() + fabBottomMargin).setInterpolator(new AccelerateInterpolator(2)).start();
}
#Override
public void onShow() {
mFabButton.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)).start();
}
#Override
public void onLoadMore(int currentPage) {
setCurrentPage(currentPage);
getPosts(false);
}
});
}
#Override
public void onDestroy() {
super.onResume();
M.hideLoadingDialog();
}
public void getPosts(boolean isMain) {
if (M.isNetworkAvailable(getActivity().getApplicationContext())) {
if (isMain) {
M.showLoadingDialog(getActivity());
}
PostsAPI mPostsAPI = APIService.createService(PostsAPI.class, M.getToken(getActivity()));
mPostsAPI.getPosts(getCurrentPage(), new Callback<List<PostsItem>>() {
#Override
public void success(List<PostsItem> postsItems, retrofit.client.Response response) {
if (postsItems.size() == 0) {
} else {
try {
mCacheManager.write(mGson.toJson(postsItems), "Posts-" + getCurrentPage() + ".json");
} catch (Exception e) {
e.printStackTrace();
}
}
updateView(postsItems);
}
#Override
public void failure(RetrofitError error) {
M.T(getActivity(), getString(R.string.ServerError));
M.hideLoadingDialog();
}
});
} else {
try {
String Posts = mCacheManager.readString("Posts-" + getCurrentPage() + ".json");
Gson mgson = new Gson();
updateView((List<PostsItem>) mgson.fromJson(Posts, new TypeToken<List<PostsItem>>() {
}.getType()));
} catch (Exception e) {
// M.L(e.getMessage());
}
}
}
private void showWelcomeMessage() {
mView.findViewById(R.id.welcomePanel).setVisibility(View.VISIBLE);
postsList.setVisibility(View.GONE);
}
private void updateView(List<PostsItem> postsItems) {
if (getCurrentPage() != 1) {
List<PostsItem> oldItems = mHomeListAdapter.getPosts();
if (oldItems.size() == 0 && postsItems.size() == 0) {
showWelcomeMessage();
}
oldItems.addAll(postsItems);
mHomeListAdapter.setPosts(oldItems);
} else {
if (postsItems.size() == 0) {
showWelcomeMessage();
}
mHomeListAdapter.setPosts(postsItems);
}
if (mSwipeRefreshLayout.isRefreshing()) {
mSwipeRefreshLayout.setRefreshing(false);
}
M.hideLoadingDialog();
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.fabButton) {
mIntent = new Intent(getActivity(), PublishActivity.class);
startActivity(mIntent);
}
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
}
the one you are showing is a ProgressDialog and one you want to show is a ProgressBar.
you need to include a progressbar in your layout something like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ProgressBar
android:id="#+id/progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<!-- your entire layout here -->
</LinearLayout>
</RelativeLayout>
then you can show or hide the progress bar and/or rest of your layout from java like this:
show:
findViewById(R.id.progressbar).setVisibility(View.VISIBLE);
hide:
findViewById(R.id.progressbar).setVisibility(View.GONE);
I am using TabLayout to show three tabs and on selection of each am calling FragmentTransaction.replace method. Now my problem is that the first two fragments are correctly replaced but the third fragment in particular is not getting replaced though I debugged and found that all corresponding methods of the 3rd fragments are called and there is no error. Now am out of my wits, please help!!.
This is the code in my onCreate() method of my main activity from where i am showing the three tabs.
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Home"));
tabLayout.addTab(tabLayout.newTab().setText("Explore"));
tabLayout.addTab(tabLayout.newTab().setText("Me"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
HomeTabFragment htf = new HomeTabFragment();
transaction.replace(R.id.tab_content_fragment, htf);
transaction.commit();
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
int position = tab.getPosition();
if (position == 0) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
HomeTabFragment htf = new HomeTabFragment();
transaction.replace(R.id.tab_content_fragment, htf);
//transaction.commitAllowingStateLoss();
transaction.addToBackStack(null);
transaction.commit();
} else if (position == 1) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
ItemListFragment ilf = new ItemListFragment();
transaction.replace(R.id.tab_content_fragment, ilf);
//transaction.commitAllowingStateLoss();
transaction.addToBackStack(null);
transaction.commit();
} else if (position == 2) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
MeTabFragment meTabFragment = new MeTabFragment();
transaction.replace(R.id.tab_content_fragment, meTabFragment);
transaction.addToBackStack(null);
transaction.commit();
//transaction.commitAllowingStateLoss();
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
And this is my MeTabFragment...
public class MeTabFragment extends Fragment implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
private DisplayDensity display;
private int profilePicSizeInPx;
private final float percentageOfScreenHeightOfProfilePic = 0.15f;
private CheckInternetConnection connection;
private ImageView userProfilePic;
private TextView userName;
private ProgressBar profilePicPB;
private String personPhotoUrl;
private String PROFILE_PIC_SIZE = "400";
private SharedPreferences sPrefs;
private SharedPreferences.Editor editor;
ListView m_homeOfferLV = null;
MeTabAdapter m_meTabAdapter = null;
ArrayList<MeData> m_ArrayList;
private GoogleApiClient mGoogleApiClient;
// Creating a listener interface to communicate back to the calling activity
//OnLogOutButtonClickListener mCallback;
private Analytics analytics;
private Tracker t;
// Container Activity must implement this interface
public static MeTabFragment newInstance() {
MeTabFragment fragment = new MeTabFragment();
//fragment.setArguments(bundle);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
analytics = new Analytics(getActivity(),getActivity().getString(R.string.MeTabFragment));
t = analytics.getTrackerInstance();
}
#Override
public void onResume() {
super.onResume();
if(Analytics.analytics_enabled && Analytics.lastTabStripPositionValue==2)
t.send(new HitBuilders.ScreenViewBuilder().build());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
sPrefs = getActivity().getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
editor = sPrefs.edit();
mGoogleApiClient = ApiClientGoogle.mApiClientGoogle;
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
connection = new CheckInternetConnection(getActivity());
display = new DisplayDensity(getActivity());
profilePicSizeInPx = (int) (percentageOfScreenHeightOfProfilePic * (float) display.getScreenHeightInPixels());
//mAnalytics = new Analytics(getActivity(),"Me");
return inflater.inflate(R.layout.fragment_me_tab, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
m_homeOfferLV = (ListView) view.findViewById(R.id.me_tab_list_view);
userProfilePic = (ImageView) view.findViewById(R.id.profile_pic);
userName = (TextView) view.findViewById(R.id.user_name_tv);
userProfilePic.getLayoutParams().height = profilePicSizeInPx;
userProfilePic.getLayoutParams().width = profilePicSizeInPx;
tracker.send(new HitBuilders.EventBuilder()
.setCategory("MeScreen")
.setAction("click")
.setLabel("Me")
.build());*/
userName.setText(sPrefs.getString(getString(R.string.user_name), "User Name"));
personPhotoUrl = sPrefs.getString(getString(R.string.user_profile_pic_url), null);
if (sPrefs.getBoolean(getString(R.string.is_google_logged_in), false) && personPhotoUrl != null) {
personPhotoUrl = personPhotoUrl.substring(0, personPhotoUrl.length() - 2) + PROFILE_PIC_SIZE;
}
//if user is connected to internet and has profile pic url then fetch the url and show his profile pic.
if (personPhotoUrl != null && connection.isConnectedToInternet()) {
//show progress bar till the image is fetched and don't show the profile pic for now.
profilePicPB.setVisibility(View.VISIBLE);
new LoadProfileImage(userProfilePic).execute(personPhotoUrl);
} else {
//show default pic only and set progress bar visiblity to null.
Log.v("Debug", "Profile pic url is null");
profilePicPB.setVisibility(View.INVISIBLE);
}
m_ArrayList = new ArrayList<MeData>();
MeData meData = new MeData();
meData.mPageRank = 1;
meData.mTitle = "My Collections";
meData.mDetail = "";
m_ArrayList.add(meData);
meData = new MeData();
meData.mPageRank = 2;
meData.mTitle = "My Offers";
meData.mDetail = "";
m_ArrayList.add(meData);
meData = new MeData();
meData.mPageRank = 3;
meData.mTitle = "My Store List";
meData.mDetail = "";
m_ArrayList.add(meData);
meData = new MeData();
meData.mPageRank = 4;
meData.mTitle = "Settings";
meData.mDetail="";
m_ArrayList.add(meData);
//adding an empty item in the list to draw the bottom border.
meData = new MeData();
meData.mPageRank = 5;
meData.mTitle = "";
meData.mDetail="";
m_ArrayList.add(meData);
m_meTabAdapter = new MeTabAdapter(getActivity(), R.layout.fragment_me_tab_template, m_ArrayList);
m_homeOfferLV.setAdapter(m_meTabAdapter);
m_homeOfferLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (m_ArrayList.get(position).mPageRank == 1) {
Intent i = new Intent(getActivity(), MyProductsActivity.class);
getActivity().startActivity(i);
} else if (m_ArrayList.get(position).mPageRank == 2) {
Intent i = new Intent(getActivity(), MyOffersActivity.class);
getActivity().startActivity(i);
} else if (m_ArrayList.get(position).mPageRank == 3) {
if (connection.isConnectedToInternet()) {
Intent i = new Intent(getActivity(), MyStoresActivity.class);
getActivity().startActivity(i);
} else {
Toast.makeText(getActivity(), getActivity().getString(R.string.check_internet_connection_try_again), Toast.LENGTH_SHORT).show();
}
}else if (m_ArrayList.get(position).mPageRank ==4){
Intent i = new Intent(getActivity(),SettingsActivity.class);
getActivity().startActivity(i);
}
}
});
m_homeOfferLV.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.getParent().requestDisallowInterceptTouchEvent(true);
return false;
}
});
setListViewHeightBasedOnChildren(m_homeOfferLV);
}
//***************************************
// GOOGLE CONNECTION METHODS
//***********************************
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public LoadProfileImage(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
profilePicPB.setVisibility(View.GONE);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
}
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null)
return;
int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.UNSPECIFIED);
int totalHeight = 0;
View view = null;
for (int i = 0; i < listAdapter.getCount(); i++) {
view = listAdapter.getView(i, view, listView);
if (i == 0)
view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, listView.getLayoutParams().WRAP_CONTENT));
view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
totalHeight += view.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
listView.requestLayout();
}
Edit: Included the 3rd fragment's layout
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="0dp"
android:fillViewport="true"
android:gravity="top">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="#drawable/customborder">
<ImageView
android:id="#+id/profile_pic"
android:layout_width="400px"
android:layout_height="400px"
android:layout_marginBottom="3dp"
android:background="#drawable/com_facebook_profile_picture_blank_square" />
<ProgressBar
android:id="#+id/profile_pic_progress_bar"
style="#android:style/Widget.ProgressBar.Small"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</FrameLayout>
<TextView
android:id="#+id/user_name_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="5dp"
android:textSize="15sp"
android:textStyle="bold" />
<ListView
android:id="#+id/me_tab_list_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:divider="#null"
android:dividerHeight="0dp" />
</LinearLayout>
Since your code is identical for every fragment look for the reason in the third fragment's layout.
First of all change root ScrollView parameters like this:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scroll_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true" >
I suppose original android:layout_height="0dp" isn't processed as you expect, so fragment is actually inflated and added but you just don't see it.