I am trying to pass the Json data in the view pager, its not showing any errors. But it is also not displaying the images in the view pager, am not able to understand my error
JSON:http://www.souqalkhaleejia.com/webapis/banners.php
Banner.java
public class Banner extends Fragment {
ViewPager bannerpager;
ArrayList<Data> bannerdta = new ArrayList<Data>();
BannerAdapter bannerAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View bannerp = inflater.inflate(R.layout.banner, container, false);
bannerpager = (ViewPager) bannerp.findViewById(R.id.bannerpager);
bannerpager.setAdapter(bannerAdapter);
bannerAdapter = new BannerAdapter(bannerdta, getActivity());
loadbanner();
return bannerp;
}
private void loadbanner() {
String bannerurl = "http://www.souqalkhaleejia.com/webapis/banners.php";
JsonObjectRequest bannerreq = new JsonObjectRequest(Request.Method.GET, bannerurl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray banners = response.getJSONArray("banners");
for (int i = 0; i < banners.length(); i++) {
JSONObject banner1 = banners.getJSONObject(i);
Data banndata = new Data();
banndata.setBannerimages(banner1.getString("image"));
bannerdta.add(banndata);
}
} catch (JSONException e) {
e.printStackTrace();
}
bannerAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "" + error, Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance().addToRequestQueue(bannerreq);
}
}
Adapter.java
public class BannerAdapter extends PagerAdapter {
Context cntx;
private ArrayList<Data> blist;
private LayoutInflater binflater;
public BannerAdapter(ArrayList<Data> blist, Context cntx) {
this.blist = blist;
this.cntx = cntx;
binflater= (LayoutInflater) cntx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return blist.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return object==view;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View view=binflater.inflate(R.layout.banner_layout,container,false);
NetworkImageView bannerimage= (NetworkImageView) view.findViewById(R.id.bannerimage);
Data bannerdata=blist.get(position);
ImageLoader imageLoader=AppController.getInstance().getImageLoader();
bannerimage.setImageUrl(bannerdata.getBannerimages(),imageLoader);
view.setTag(bannerdata);
container.addView(view);
Log.i("Banner", "instantiateItem() [position: " + position + "]" + " childCount:" + container.getChildCount());
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
Log.i("Banner", "destroyItem() [position: " + position + "]" + " childCount:" + container.getChildCount());
}
#Override
public int getItemPosition(Object object) {
Data data= (Data) ((View) object).getTag();
int position=blist.indexOf(data);
if(position>=0){
return position;
}else {
return POSITION_NONE;
}
}
}
i am including the viewpager from another class to the home page
Home.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
android:id="#+id/hmebar"
layout="#layout/toolbar" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="200dp"
>
<include layout="#layout/banner"/>
</FrameLayout>
</LinearLayout>
<ListView
android:id="#+id/nav_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#drawable/hover"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>
banner.xml(i had wrote viewpager xml here and included in the Home layout)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/bannerpager"
android:layout_width="match_parent"
android:layout_height="200dp"/>
</LinearLayout>
banner_layout.xml(Single viewpager is the image)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.android.volley.toolbox.NetworkImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/bannerimage"/>
</LinearLayout>
You not update your bannerdta to bannerAdapter, so bannerAdapter.notifyDataSetChanged() will not work.
you can add method updateData(Data banndata) in BannerAdapter.class
pubilc void updateData(Data banndata) {
blist.add(banndata);
notifyDataSetChanged();
}
and after call network request successfull, usebannerAdapter.updateData(banndata)
Related
I am trying replace fragment first on second in ViewPager. And I have small problem becouse after replace still i see in background fragment first and they are working listner from fragment first. What am i doing wrong ? I replace first_fragment view but it doesn't work. In other project i were done somthing simular and it's working well !
public class FirstFragment extends BaseFragment {
private RecyclerView pathwaysRecyclerView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_pathways, container, false);
initializeViews(view);
initRecyclerView();
return view;
}
private void initializeViews(View view) {
pathwaysRecyclerView = view.findViewById(R.id.pathways_recyclerview);
}
private void initRecyclerView(){
pathwaysRecyclerView.setLayoutManager(new GridLayoutManager(requireContext(), 2));
PathwaysAdapter adapter = new PathwaysAdapter(new OnPathwayClickListner(),requireContext());
pathwaysRecyclerView.setAdapter(adapter);
}
private class OnPathwayClickListner implements View.OnClickListener {
#Override
public void onClick(View view) {
navigateToSecondFragment();
}
}
private void navigateToSecondFragment(){
Fragment fragment = new SecondFragment();
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_pathways_view, fragment)
.addToBackStack(null)
.commit();
}
#Override
public void updateView() {
}
}
fragment_first.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragment_pathways_view">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/greyAccent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/ebpHeader"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/greyAccent"
android:orientation="vertical" >
<TextView
android:id="#+id/pathways_name_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/list_of_all_paths"
android:layout_margin="15sp"
app:fontFamily="sans-serif-light"
android:textSize="25sp"
android:textStyle="bold"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/vertical_margin"
android:layout_marginStart="#dimen/vertical_margin"
android:layout_marginEnd="#dimen/vertical_margin"
android:layout_marginBottom="#dimen/beetwen_content_line_margin"
android:textSize="#dimen/textSizeMedium"
android:text="#string/list_of_all_paths_description"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/evaluation_background">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/pathways_recyclerview"
android:layout_marginTop="#dimen/beetwen_content_line_margin"
android:layout_marginStart="#dimen/vertical_margin"
android:layout_marginEnd="#dimen/vertical_margin"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
second fragment
public class SecondFragment extends BaseFragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_path, container, false);
return view;
}
}
fragment_second.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/mainAppBackgroundColor">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/mainAppBackgroundColor"
android:orientation="vertical">
<TextView
android:id="#+id/path_name_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="15sp"
app:fontFamily="sans-serif-light"
android:textSize="25sp"
android:textStyle="bold"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/list_of_skills"
android:layout_marginTop="15sp"
android:layout_marginStart="15sp"
android:layout_marginEnd="15sp"
app:fontFamily="sans-serif-light"
android:textSize="18sp"
android:textStyle="bold"
/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="#dimen/vertical_margin"
android:layout_marginTop="5sp"
android:layout_marginEnd="#dimen/vertical_margin" />
</LinearLayout>
</RelativeLayout>
ViewPager:
<com.habitcoach.android.activity.util.NonSwipeableViewPager
android:id="#+id/hsFragmentsContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:orientation="vertical"
android:paddingBottom="50dp"
android:layout_alignParentLeft="true" />
PageAdapter:
class MainViewViewPageAdapter extends FragmentStatePagerAdapter {
MainViewViewPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getItemPosition(Object object) {
BaseFragment f = (BaseFragment) object;
if (f != null) {
f.updateView();
}
return super.getItemPosition(object);
}
#Override
public Fragment getItem(int position) {
Fragment f = null;
switch (position) {
case 0:
f = new OneFragment();
break;
case 1:
f = new TwoFragment();
break;
case 2:
f = new ThreeeFragment();
break;
case 3:
f = new FourFragment();
break;
}
return f;
}
#Override
public int getCount() {
return 4;
}
}
I modified your code.check below solution.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.hsFragmentsContainer);
viewPager.setAdapter(new MainViewViewPageAdapter(getSupportFragmentManager()));
}}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<android.support.v4.view.ViewPager
android:id="#+id/hsFragmentsContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
MainViewViewPageAdapter.java
public class MainViewViewPageAdapter extends FragmentStatePagerAdapter {
public MainViewViewPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getItemPosition(#NonNull Object object) {
return super.getItemPosition(object);
}
#Override
public Fragment getItem(int position) {
Fragment f = null;
switch (position) {
case 0:
f = new FirstFragment();
break;
case 1:
f = new SecondFragment();
break;
}
return f;
}
#Override
public int getCount() {
return 2;
}}
FirstFragment.java
public class FirstFragment extends Fragment {
private RecyclerView pathwaysRecyclerView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first, container, false);
initializeViews(view);
initRecyclerView();
return view;
}
private void initializeViews(View view) {
pathwaysRecyclerView = view.findViewById(R.id.pathways_recyclerview);
}
private void initRecyclerView(){
pathwaysRecyclerView.setLayoutManager(new GridLayoutManager(requireContext(), 2));
PathwaysAdapter adapter = new PathwaysAdapter(new OnPathwayClickListner(),requireContext());
pathwaysRecyclerView.setAdapter(adapter);
}
public class OnPathwayClickListner implements View.OnClickListener {
#Override
public void onClick(View view) {
navigateToSecondFragment();
}
}
private void navigateToSecondFragment(){
Fragment fragment = new SecondFragment();
getFragmentManager().beginTransaction().replace(R.id.fragment_pathways_view, fragment).addToBackStack(null).commit();
}}
SecondFragment.java
public class SecondFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_second, container, false);
return view;
}
}
PathwaysAdapter.java
class PathwaysAdapter extends RecyclerView.Adapter<PathwaysAdapter.MyViewHolder>{
FirstFragment.OnPathwayClickListner onPathwayClickListner;
Context requireContext;
ArrayList<String> list;
public PathwaysAdapter(FirstFragment.OnPathwayClickListner onPathwayClickListner, Context requireContext) {
this.onPathwayClickListner=onPathwayClickListner;
this.requireContext=requireContext;
list=new ArrayList<>();
for (int i=1;i<=20;i++){
list.add("Pathway "+i);
}
}
#NonNull
#Override
public PathwaysAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row, viewGroup, false);
return new PathwaysAdapter.MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PathwaysAdapter.MyViewHolder myViewHolder, int i) {
myViewHolder.textview.setText(list.get(i));
}
#Override
public int getItemCount() {
return list.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
RelativeLayout layout;
TextView textview;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
textview = itemView.findViewById(R.id.textview);
layout = itemView.findViewById(R.id.layout);
layout.setOnClickListener(onPathwayClickListner);
}}}
row.xml
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardBackgroundColor="#FF9800"
card_view:cardCornerRadius="5dp"
card_view:cardElevation="5dp"
card_view:cardUseCompatPadding="true">
<RelativeLayout
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="100dp">
<TextView
android:id="#+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="#ffffff" />
</RelativeLayout>
Error Shown:
Attempt to invoke virtual method 'void android.widget.GridView.setAdapter(android.widget.ListAdapter)' on a null object reference.
The error surface at the gridView.setAdapter(adapter); but am able to print response from API only to pass it to the adapter for layout to handle the display.
Am suggesting converting the Model Class into a list of array of which is not actually going my way.
Have tried modelName.toArray() and many others.
Thank you as i await your response.
My Model Class
public class MensWear {
private int id, user_id;
private String first_wear;
public MensWear(int id,int user_id,String first_wear) {
this.id = id;
this.user_id = user_id;
this.first_wear = first_wear;
}
public int getId() {
return id;
}
public int getUser_id() {
return user_id;
}
public String getFirst_wear() {
return first_wear;
}
}
My Base Adapter Class
public class PhoneAdapter extends BaseAdapter {
private Context context;
private List<MensWear> mensWears;
public String imageUrlFromServer = "http:/10.0.2.2:5757/api/public/images/";
public PhoneAdapter(Context context, List<MensWear> mensWears) {
this.context = context;
this.mensWears = mensWears;
}
#Override
public int getCount() {
return mensWears.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i,View view,ViewGroup viewGroup) {
final MensWear mensWear = mensWears.get(i);
if (view == null) {
final LayoutInflater layoutInflater = LayoutInflater.from(context);
view = layoutInflater.inflate(R.layout.phone_list, null);
}
//For text
TextView prdId = view.findViewById(R.id.mensWearIdForHompePage);
prdId.setText(prdId.toString());
//For images
final ImageView imageView = view.findViewById(R.id.phoneImages);
if(!TextUtils.isEmpty(mensWear.getFirst_wear())){
Picasso.with(context).load(imageUrlFromServer+mensWear.getFirst_wear())
.into(imageView);
}
return view;
}
}
My Class extending Fragment
public class Phones extends Fragment {
private GridView gridView;
private List<MensWear> mensWears;
private PhoneAdapter adapter;
public Phones() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_phones,container,false);
}
#Override
public void onViewCreated(#NonNull View view,#Nullable Bundle savedInstanceState) {
super.onViewCreated(view,savedInstanceState);
gridView = view.findViewById(R.id.gridHolder);
gridView = view.findViewById(R.id.gridHolder);
Call<MensWearResponse> wearResponseCall =
Service.getInstance().getApi().getAllMensWears();
wearResponseCall.enqueue(new Callback<MensWearResponse>() {
#Override
public void onResponse(Call<MensWearResponse> call,Response<MensWearResponse> response) {
mensWears = response.body().getMensWears();
for (MensWear mwr : mensWears){
Log.d("Name", mwr.getFirst_wear());
}
adapter = new PhoneAdapter(getActivity(), mensWears);
gridView.setAdapter(adapter);
}
#Override
public void onFailure(Call<MensWearResponse> call,Throwable t) {
}
});
}
}
My Layout Files
The Grid Layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
tools:context="com.nelbuc.nelbuc.goodWears"
>
<Grid
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:columnWidth="100dp"
android:numColumns="2"
android:verticalSpacing="24dp"
android:horizontalSpacing="10dp"
android:stretchMode="spacingWidthUniform"
android:id="#+id/gridHolder"
>
</Grid>
</RelativeLayout>
The List Layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/phoneList"
android:layout_width="190dp"
android:background="#fff"
android:layout_height="180dp"
>
<TextView
android:id="#+id/mensWearIdForHompePage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Apple"
android:textStyle="normal|italic"
android:textSize="25dp" />
<ImageView
android:id="#+id/phoneImages"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
/>
</RelativeLayout>
</RelativeLayout>
Error message clearly says that GridView is null. There is no GridView in your layout, there is only Grid. Change Grid to GridView.
In your layout, You are using only Grid. Change from Grid to GridView
Create ArrayList and add the model i.e MensWear into that list like this following and then pass this list into your adpater:
ArrayList<MensWear > arrayList_mens = new ArrayList<MensWear>();
for (MensWear mwr : mensWears)
{
Log.d("Name", mwr.getFirst_wear());
arrayList_mens.add(mwr);
}
i have an Activity with tabLayout, each tab is represented by a Fragment (i have three fragments : Home, Caegories and my account), so i want to display on the HomeFragment an horizontal RecyclerView,everything works well but the RecyclerView doesn't work, where i get this eroor :
E/RecyclerView: No adapter attached; skipping layout.
I havre already tested this solution but i got nothing.
this what i did:
First: ActivityMain and xml layout:
private ArrayList<OfferItem> dataList;
private RecyclerView myRecycler;
private View fragmentViewLayout;
private LastOffersRecyclerAdapter listAdapter;
//......
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setViewPager();
setTabIcons();
mTabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
int tabPoaition = tab.getPosition();
if(tabPoaition == 0){
View view = tab.getCustomView();
TextView tabTextView = (TextView)view.findViewById(R.id.tabRoot);
tabTextView.setTextColor(Color.parseColor("#ef4437"));
tabTextView.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_home_red, 0, 0);
}
else if(tabPoaition ==1){
View view = tab.getCustomView();
TextView tabTextView = (TextView)view.findViewById(R.id.tabRoot);
tabTextView.setTextColor(Color.parseColor("#ef4437"));
tabTextView.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_category_red, 0, 0);
}
else{
View view = tab.getCustomView();
TextView tabTextView = (TextView)view.findViewById(R.id.tabRoot);
tabTextView.setTextColor(Color.parseColor("#ef4437"));
tabTextView.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_person_red, 0, 0);
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
int tabPoaition = tab.getPosition();
if(tabPoaition == 0){
View view = tab.getCustomView();
TextView tabTextView = (TextView)view.findViewById(R.id.tabRoot);
tabTextView.setTextColor(Color.parseColor("#bdbcbc"));
tabTextView.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_home_gray, 0, 0);
}
else if(tabPoaition ==1){
View view = tab.getCustomView();
TextView tabTextView = (TextView)view.findViewById(R.id.tabRoot);
tabTextView.setTextColor(Color.parseColor("#bdbcbc"));
tabTextView.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_category_gray, 0, 0);
}
else{
View view = tab.getCustomView();
TextView tabTextView = (TextView)view.findViewById(R.id.tabRoot);
tabTextView.setTextColor(Color.parseColor("#bdbcbc"));
tabTextView.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_person_gray, 0, 0);
}
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
fragmentViewLayout = getLayoutInflater().inflate(R.layout.fragment_one, null);
listAdapter = new LastOffersRecyclerAdapter(this,dataList);
myRecycler = (RecyclerView)fragmentViewLayout.findViewById(R.id.my_list_recycler);
myRecycler.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false));
myRecycler.setItemAnimator(new DefaultItemAnimator());
myRecycler.setAdapter(listAdapter);
createSampleData();
}
///...
private void createSampleData(){
dataList = new ArrayList<OfferItem>();
OfferItem itm;
for(int i =0 ;i<10 ; i++){
itm = new OfferItem(i,"business_logo.png","offer_img.png","La Piscope","Fes");
dataList.add(itm);
}
listAdapter.notifyDataSetChanged();
}
activity_main.xml
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.biliki.biliki.bilikiapp.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/my_home_app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.TabLayout
android:id="#+id/tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed"
app:tabBackground="?attr/selectableItemBackground"
/>
</android.support.design.widget.AppBarLayout>
<include
android:layout_height="wrap_content"
android:layout_width="match_parent"
app:layout_constraintTop_toBottomOf="#id/my_home_app_bar"
app:layout_constraintLeft_toLeftOf="parent"
layout="#layout/content_main" />
</android.support.constraint.ConstraintLayout>
Second : my AdapterClass
LastOffersRecylerAdapter.java
public class LastOffersRecyclerAdapter extends RecyclerView.Adapter<LastOffersRecyclerAdapter.OffersItemHolder> {
private Context context;
private ArrayList<OfferItem> dataList;
public LastOffersRecyclerAdapter(Context context, ArrayList<OfferItem> dataList) {
this.context = context;
this.dataList = dataList;
}
#Override
public OffersItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.last_offers_item,parent,false);
OffersItemHolder offHolder = new OffersItemHolder(v);
return offHolder;
}
#Override
public void onBindViewHolder(OffersItemHolder holder, int position) {
OfferItem item = dataList.get(position);
int logoResourceId = context.getResources().getIdentifier(item.getLogoUrl(), "drawable", context.getPackageName());
int offerImgResourceId = context.getResources().getIdentifier(item.getOfferImgUrl(), "drawable", context.getPackageName());
holder.busniessLogo.setImageResource(logoResourceId);
holder.offerImg.setImageResource(offerImgResourceId);
holder.offer_business_city.setText(item.getBusiness_name() + "| "+item.getBusiness_city());
}
#Override
public int getItemCount() {
return dataList.size();
}
public class OffersItemHolder extends RecyclerView.ViewHolder{
public ImageView offerImg;
public ImageView busniessLogo;
public TextView offer_business_city;
public OffersItemHolder(View itemView) {
super(itemView);
this.offerImg = itemView.findViewById(R.id.offer_img);
this.busniessLogo = itemView.findViewById(R.id.business_logo);
this.offer_business_city = itemView.findViewById(R.id.business_name_city);
}
}
and this is the xml layout for HomeFragment
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp">
<RelativeLayout
android:id="#+id/title_layout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_margin="5dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">
<com.biliki.biliki.bilikiapp.uitemplate.font.RobotoTextView
android:id="#+id/itemTitle"
android:paddingLeft="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical"
android:layout_toLeftOf="#+id/btnMore"
android:text="#string/lastoffersTitle" />
<Button
android:id="#+id/btnMore"
style="#style/allButtonsstyle"
android:layout_width="65dp"
android:layout_height="42dp"
android:textAlignment="gravity"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="#string/moreLastOffers" />
</RelativeLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/my_list_recycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="horizontal"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="#id/title_layout" />
</android.support.constraint.ConstraintLayout>
the TextView and the button are displayed but the RecyclerView not.
could you please resolve this? thnak you.
UPDATE:
the content_main xml file contains the tabLayout ViewPager :
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="#layout/activity_main">
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tabs_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.constraint.ConstraintLayout>
As Mr. Mike M mentioned, i have moved the code to the HomeFragment Class, and it works.
this is the HomeFragment class:
public class HomeFragment extends Fragment {
public static final String TITLE = "Accueil";
private RecyclerView myRecycler;
private LastOffersRecyclerAdapter listAdapter;
private ArrayList<OfferItem> dataList;
public static HomeFragment newInstance() {
return new HomeFragment ();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
createSampleData();
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
listAdapter = new LastOffersRecyclerAdapter(getContext(),dataList);
myRecycler = rootView.findViewById(R.id.my_list_recycler);
myRecycler.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
myRecycler.setItemAnimator(new DefaultItemAnimator());
myRecycler.setAdapter(listAdapter);
return rootView;
}
private void createSampleData(){
dataList = new ArrayList<OfferItem>();
OfferItem itm;
for(int i =0 ;i<10 ; i++){
itm = new OfferItem(i,"business_logo.png","offer_img.png","La Piscope","Fes");
dataList.add(itm);
}
}
}
i have made a Master/Detail View which contains a TabHost in the Detailview.
i have to populate a list of tabs, and every tab has a listview as its content.
Now when i change my Item to display, after the third change or so, no more tab content is rendered(The indicators are rendered). But when i change the tab, the content gets rendered.
The onCreate Method of the DetailFragment is invoked when i change my item to display. The tabs are genrated and added to the tabhost. But after a few times i switched the item to display, the onCreateView Method of the OrderGroupTabFragment is not invoked anymore, without any reason to me.
Thankful for any help.
Here is my code:
DetailFragment:
/**
* A fragment representing a single Order detail screen. This fragment is either
* contained in a {#link OrderListActivity} in two-pane mode (on tablets) or a
* {#link OrderDetailActivity} on handsets.
*/
public class OrderDetailFragment extends Fragment implements IASyncMethodCallbacks {
private static Logger _logger = Logger.getLogger(OrderDetailFragment.class.getSimpleName());
/**
* The fragment argument representing the item ID that this fragment
* represents.
*
*/
public static final String ARG_ORDER = "order";
private TrafficSafetyOrder _order;
private TrafficSafetyOrderService _trafficSafetyOrderService;
private boolean _detached;
private FragmentTabHost tabHost;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public OrderDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
_detached = false;
_trafficSafetyOrderService = new TrafficSafetyOrderService();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_order_detail,
container, false);
tabHost = (FragmentTabHost)rootView.findViewById(R.id.order_detail_tab_host);
tabHost.setup(getActivity(), ((FragmentActivity)getActivity()).getSupportFragmentManager() , android.R.id.tabcontent);
OrderListItem order = (OrderListItem)getArguments().getSerializable(ARG_ORDER);
try {
if(order != null)
_order = _trafficSafetyOrderService.getOrderForId(order.getId());
} catch (Exception e) {
_logger.log(Level.WARNING, e.getMessage(), e);
}
if (_order != null) {
OrderId orderId = _order.getOrderIdByOrderIdType(OrderIdTypes.GEB);
((TextView) rootView.findViewById(R.id.order_detail_header))
.setText("Auftrag: " + orderId.getName() + orderId.getId());
for (final Group formGroup : _order.getFormGroups()) {
System.out.println("Adding Tab " + formGroup.getDisplayText());
TabSpec spec = tabHost.newTabSpec(formGroup.getDisplayText());
System.out.println("Spec created " + formGroup.getDisplayText());
spec.setIndicator(formGroup.getDisplayText());
System.out.println("Indicator set " + formGroup.getDisplayText());
Bundle bundle = new Bundle();
System.out.println("Bundle created " + formGroup.getDisplayText());
bundle.putSerializable(OrderGroupTabFragment.ORDER_GROUP_LIST_ARG, formGroup.getItems());
System.out.println("Added items to bundle " + formGroup.getDisplayText());
tabHost.addTab(spec, OrderGroupTabFragment.class, bundle);
System.out.println("Tab added " + formGroup.getDisplayText());
}
}
return rootView;
}
#Override
public void onStart() {
super.onStart();
tabHost.setCurrentTab(0);
}
public TrafficSafetyOrder getOrder() {
return _order;
}
public void setOrder(TrafficSafetyOrder _order) {
this._order = _order;
}
#Override
public void onDestroyView() {
super.onDestroyView();
try {
_trafficSafetyOrderService.updateTrafficServiceOrder(_order);
} catch (Exception e) {
_logger.log(Level.WARNING, e.getMessage(), e);
}
}
#Override
public void onDetach() {
super.onDetach();
_detached = true;
}
#Override
public void onASyncMethodCompleted(Object receiver, Method method) {
if(_detached)// if fragment is already detached from Activity, do not execute callback
return;
Toast.makeText(getActivity(), receiver != null ? receiver.getClass().getSimpleName() : "NULL" + "." + method != null ? method.getName() : "NULL" + " executed succesfully", Toast.LENGTH_LONG).show();
}
}
OrderGroupTabFragment:
public class OrderGroupTabFragment extends android.support.v4.app.Fragment{
public static final String ORDER_GROUP_LIST_ARG = "ORDER_GROUP_ITEMS";
private List<GroupItem> groupItems;
private ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
System.out.println("Creating Order List View");
View view = inflater.inflate(R.layout.fragment_order_group_tab_list, null);
groupItems = (List<GroupItem>)getArguments().getSerializable(ORDER_GROUP_LIST_ARG);
listView = (ListView)view.findViewById(R.id.order_detail_tab_list_view);
listView.setAdapter(new GroupItemAdapter(getActivity(), groupItems));
System.out.println("Order List View Created");
return view;
}
}
GroupItemAdapter:
public class GroupItemAdapter extends ArrayAdapter<GroupItem> {
private Context _context;
public GroupItemAdapter(Context context, List<GroupItem> groupItems) {
super(context, R.layout.lvi_group_item , groupItems);
this._context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null){
LayoutInflater li = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = li.inflate(R.layout.lvi_group_item,
parent, false);
holder = new ViewHolder();
holder.header = (TextView)convertView.findViewById(R.id.tab_header);
holder.isVerified = (CheckBox)convertView.findViewById(R.id.tab_verification_checkbox);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
GroupItem item = getItem(position);
holder.header = (TextView)convertView.findViewById(R.id.tab_header);
holder.isVerified = (CheckBox)convertView.findViewById(R.id.tab_verification_checkbox);
if(item != null)
holder.header.setText(item.getName());
return convertView;
}
private class ViewHolder {
TextView header;
CheckBox isVerified;
}
}
fragment_order_detail.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:id="#+id/order_detail_button_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
style="#android:style/Widget.ActionBar">
<Button android:id="#+id/order_detail_button_undo"
android:layout_width="0dp"
android:layout_height="wrap_content"
style="#android:style/Widget.ActionButton"
android:drawableTop="#drawable/ic_action_undo"
android:text="Undo"
android:layout_weight="1"/>
<Button android:id="#+id/order_detail_button_redo"
android:layout_width="0dp"
android:layout_height="wrap_content"
style="#android:style/Widget.ActionButton"
android:drawableTop="#drawable/ic_action_redo"
android:text="Redo"
android:layout_weight="1"/>
<Button android:id="#+id/order_detail_button_submit"
android:layout_width="0dp"
android:layout_height="wrap_content"
style="#android:style/Widget.ActionButton"
android:drawableTop="#drawable/ic_action_tick"
android:text="Submit"
android:layout_weight="1"/>
</LinearLayout>
<TextView
style="?android:attr/textAppearanceLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="16dp"
android:layout_below="#id/order_detail_button_bar"
android:layout_alignParentStart="true"
android:id="#+id/order_detail_header"/>
<android.support.v4.app.FragmentTabHost android:id="#+id/order_detail_tab_host"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/order_detail_header">
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent">
<TabWidget android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"/>
<FrameLayout android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#android:id/tabs"/>
</RelativeLayout>
</android.support.v4.app.FragmentTabHost>
fragment_order_group_tab_list.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/order_detail_tab_list_view"/>
</RelativeLayout>
lvi_group_item.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView android:id="#+id/tab_header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"/>
<CheckBox android:id="#+id/tab_verification_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#id/tab_header"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_toEndOf="#id/tab_header"
android:text="#string/lvi_group_item_verification_succesfull"
/>
</RelativeLayout>
gr33tz gangfish
Got it working.
I took the wrong fragmentmanager to pass to the tabhost.setup() method in my OnCreateView method in the DetailFragment.
tabHost.setup(getActivity(), getChildFragmentManager() , android.R.id.tabcontent);
i wanted to have a custom listView so I did this:
Created an Activity:
public class PRS_MainList_Act extends ListActivity {
MainListAdapter mladp;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prs__main_list_);
ArrayList<MainMenuItem> menuItems = new ArrayList<MainMenuItem>();
menuItems.add(new MainMenuItem(getResources().getString(R.string.main_list_connectivity), getResources().getString(R.string.main_list_connectivityDesc)));
this.mladp = new MainListAdapter(this, R.layout.man_list_item, R.id.textView1, menuItems);
setListAdapter(mladp);
}
}
Create a class for menu items:
public class MainMenuItem {
private String itemText;
private String itemDescription;
private String itemIMG;
private int itemWeight;
private String itemAssociatedActivity;
public MainMenuItem(String itemText, String itemDescription) {
this.itemText = itemText;
this.itemDescription = itemDescription;
}
public String getItemText() {
return itemText;
}
public void setItemText(String itemText) {
this.itemText = itemText;
}
public String getItemIMG() {
return itemIMG;
}
public void setItemIMG(String itemIMG) {
this.itemIMG = itemIMG;
}
public int getItemWeight() {
return itemWeight;
}
public void setItemWeight(int itemWeight) {
this.itemWeight = itemWeight;
}
public String getItemAssociatedActivity() {
return itemAssociatedActivity;
}
public void setItemAssociatedActivity(String itemAssociatedActivity) {
this.itemAssociatedActivity = itemAssociatedActivity;
}
public String getItemDescription() {
return itemDescription;
}
public void setItemDescription(String itemDescription) {
this.itemDescription = itemDescription;
}
}
Custom array adapter:
public class MainListAdapter extends ArrayAdapter<MainMenuItem> {
ArrayList<MainMenuItem> menuItems;
public MainListAdapter(Context context, int resource,
int textViewResourceId, ArrayList<MainMenuItem> menuItems) {
super(context, resource, textViewResourceId, menuItems);
this.menuItems = menuItems;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.man_list_item, parent);
}
MainMenuItem it = menuItems.get(position);
if (it != null) {
TextView titleTV = (TextView) view.findViewById(R.id.textView1);
TextView descriptionTV = (TextView) view.findViewById(R.id.textView2);
ImageView iconIV = (ImageView)view.findViewById(R.id.imageView1);
if (titleTV != null) {
titleTV.setText(it.getItemText());
}
if(descriptionTV != null){
descriptionTV.setText(it.getItemDescription());
}
if(iconIV != null){
if(it.getItemText().equals(getContext().getResources().getString(R.string.main_list_connectivity)))
iconIV.setImageResource(R.drawable.network_connections);
}
}
return view;
}
}
and here are my activity layout and item layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".PRS_MainList_Act" >
<ListView android:id="#android:id/list"
android:layout_height="match_parent"
android:layout_width="match_parent"/>
</LinearLayout>
Item Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="TextView" />
</LinearLayout>
</LinearLayout>
I got this error saying: java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView
Thanks in advance for your help.
You can't use this version of the inflate method:
view = vi.inflate(R.layout.man_list_item, parent);
because this will add the inflated View to the parent, which isn't allowed in a ListView. Instead use this version:
view = vi.inflate(R.layout.man_list_item, parent, false);
which will inflate the view but will not add it to the parent. This version is important because it will provide the proper LayoutParams for your inflated view.