ImageView Slider horizontally - java

I am trying to create a horizontal slider of images fitted in my imageview in my main layout file. But instead of imageview sliding on touch, the code is moving the whole layout horizontally.
Following is my Java code for sliding:
public class Artprofile extends FragmentActivity {
static final int NUM_ITEMS = 5;
ImageFragmentPagerAdapter imageFragmentPagerAdapter;
ViewPager viewPager;
public static final String[] IMAGE_NAME = {"a", "b", "c", "d", "e",};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_page);
imageFragmentPagerAdapter = new ImageFragmentPagerAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(imageFragmentPagerAdapter);
}
public static class ImageFragmentPagerAdapter extends FragmentPagerAdapter {
public ImageFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public Fragment getItem(int position) {
SwipeFragment fragment = new SwipeFragment();
return SwipeFragment.newInstance(position);
}
}
public static class SwipeFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View swipeView = inflater.inflate(R.layout.layoutart, container, false);
ImageView imageView = (ImageView) swipeView.findViewById(R.id.image_view1);
Bundle bundle = getArguments();
int position = bundle.getInt("position");
String imageFileName = IMAGE_NAME[position];
int imgResId = getResources().getIdentifier(imageFileName, "drawable", "com.example.user.myapplication1");
imageView.setImageResource(imgResId);
return swipeView;
}
static SwipeFragment newInstance(int position) {
SwipeFragment swipeFragment = new SwipeFragment();
Bundle bundle = new Bundle();
bundle.putInt("position", position);
swipeFragment.setArguments(bundle);
return swipeFragment;
}
}
}
Following is my main layout file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#drawable/mobileback"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView android:id="#+id/image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxWidth="150dp"
android:maxHeight="150dp"
android:scaleType="fitCenter"
android:layout_marginRight="50dp"
android:layout_marginTop="30dp"
android:layout_marginLeft="400dp"
android:src="#drawable/profilewindow1"
android:layout_marginEnd="58dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="330dp"
android:layout_alignParentStart="true"
android:maxWidth="150dp"
android:maxHeight="150dp"
android:layout_below="#+id/image_view"
android:id="#+id/layout_mobile1">
<ImageView
android:id="#+id/image_view1"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</FrameLayout>
</RelativeLayout>
And this is the Fragment layout used for sliding:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
I dont understand the problem. Kindly help. Thanks in advance

You can use a layout to wrap imageview and then wrap the layout in horizontal scrollview

Related

Android RecyclerView Adapter in a fragment not working

I am trying to use a androidx.recyclerview.widget.RecyclerView inside a Fragment and having a tough time trying to add basic items to it via an adapter. Following is my Fragment:
public class TimelineFragment extends Fragment {
private DataBoundAdapter timelineAdapter;
private View rootView;
#Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_timeline_home, container, false);
initStuff(container);
return rootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
}
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
private void initStuff(ViewGroup container) {
ArrayList<FernPost> list = {...};
timelineAdapter = new DataBoundAdapter(list);
RecyclerView recyclerView = rootView.findViewById(R.id.scroll_timeline);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(),2));
recyclerView.setAdapter(timelineAdapter);
timelineAdapter.notifyDataSetChanged();
}
}
This is the fragment xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="100dp"
android:text="hi there bullshit!!!"/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scroll_timeline"
android:scrollbars="vertical"
android:visibility="visible">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
The Main activity layout xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:tools="http://schemas.android.com/tools"
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"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</com.google.android.material.appbar.AppBarLayout>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_input_add" />
<fragment
android:id="#+id/timeline_fragment"
android:name="com.blinkfast.fern.TimelineFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
here is the adapter code for the recycler view:
public class DataBoundAdapter extends RecyclerView.Adapter<DataBoundViewHolder> {
private List<FernPost> fernPosts;
public DataBoundAdapter(List<FernPost> fernPosts) {
this.fernPosts = fernPosts;
}
#NonNull
#Override
public DataBoundViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fernpost, null);
return new DataBoundViewHolder(itemLayoutView);
}
#Override
public void onBindViewHolder(#NonNull DataBoundViewHolder holder, int position) {
holder.bind(fernPosts.get(position));
}
#Override
public int getItemCount() {
return fernPosts.size()
}
}
And the view holder:
public class DataBoundViewHolder extends RecyclerView.ViewHolder {
private FernPost post;
private View fernPostView;
public DataBoundViewHolder(#NonNull View itemView) {
super(itemView);
this.fernPostView = itemView;
Log.i(DataBoundViewHolder.class.getName(), "");
}
public void bind(FernPost fernPost){
Log.i(DataBoundViewHolder.class.getName(), "binding");
this.post = fernPost;
}
}
I have spent entire day trying various thing making it work, but nothing has so far. The onCreateViewHolder / onBindViewHolder methods are just not getting called. Not sure what i am doing wrong.
Assuming your fragment (the one holding RecyclerView) is displayed and your list has items before passed to DataBoundAdapter, please use different inflation inside your adapter's onCreateViewHolder:
LayoutInflater.from(parent.getContext()).inflate(viewType, parent, false)

RecyclerView not replacing detail pane with fragment on item click

Everytime I click a recycler view item on a tablet, it opens an activity rather than replacing the detail pane with a fragment.
The following line of code is what I use to detect wheter the detail pane is present:
mTwoPane = Objects.requireNonNull(getActivity()).findViewById(R.id.detail_container) != null;
Any ideas on the correct location to put this line of code?
activity 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="match_parent">
<android.widget.Toolbar
android:id="#+id/masterToolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
>
<LinearLayout
android:id="#+id/singleline_text_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="vertical">
<TextView
android:id="#+id/md_toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#android:style/TextAppearance.Material.Widget.ActionBar.Title"/>
</LinearLayout>
</android.widget.Toolbar>
<RelativeLayout
android:id="#+id/master_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
sw600dp activity XML
<?xml version="1.0" encoding="utf-8"?>
<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="match_parent">
<android.widget.Toolbar
android:id="#+id/masterToolbar"
android:layout_width="0dp"
android:layout_height="?actionBarSize"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toStartOf="#+id/detailBackgroundToolbar"
app:layout_constraintHorizontal_weight="2"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:id="#+id/singleline_text_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="vertical">
<TextView
android:id="#+id/md_toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#android:style/TextAppearance.Material.Widget.ActionBar.Title"/>
</LinearLayout>
</android.widget.Toolbar>
<RelativeLayout
android:id="#+id/master_container"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintHorizontal_weight="2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toStartOf="#+id/divider"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#+id/masterToolbar" />
<View
android:id="#+id/divider"
android:layout_width="1dp"
android:layout_height="0dp"
android:background="?attr/dividerColor"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="#+id/masterToolbar"
app:layout_constraintTop_toBottomOf="#+id/masterToolbar" />
<android.widget.Toolbar
android:id="#+id/detailBackgroundToolbar"
android:layout_width="0dp"
android:layout_height="?actionBarSize"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_weight="3"
app:layout_constraintStart_toEndOf="#+id/masterToolbar"
app:layout_constraintTop_toTopOf="parent" />
<android.support.v7.widget.CardView
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_margin="4dp"
app:cardCornerRadius="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/divider"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintWidth_percent="0.5">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar_dualline"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<FrameLayout
android:id="#+id/detail_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</android.support.v7.widget.CardView>
<View
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/divider"
app:layout_constraintTop_toBottomOf="#+id/detailBackgroundToolbar" />
</android.support.constraint.ConstraintLayout>
Fragment class
public class MyFragment extends Fragment {
public MyFragment() {}
List<Product> wcList;
RecyclerView mRecyclerView;
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet device.
*/
public boolean mTwoPane;
public static MyFragment newInstance() {
return new MyFragment();
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
mTwoPane = Objects.requireNonNull(getActivity()).findViewById(R.id.detail_container) != null;
mRecyclerView = view.findViewById(R.id.recyclerView_list);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
mRecyclerView.addItemDecoration(new DividerItemDecoration(Objects.requireNonNull(getContext()), LinearLayout.VERTICAL));
myList = new ArrayList<>();
String[] items = getResources().getStringArray(R.array.product_names);
String[] itemDescriptions = getResources().getStringArray(R.array.product_descriptions);
for (int n = 0; n < items.length; n++){
Product desserts = new Product();
desserts.setProductName(items[n]);
wdessertsc.setProductDescriptions(itemDescriptions[n]);
myList.add(desserts);
}
MyListAdapter listAdapter = new MyListAdapter(getActivity(), myList);
mRecyclerView.setAdapter(listAdapter);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
mTwoPane = Objects.requireNonNull(getActivity()).findViewById(R.id.detail_container) != null;
super.onActivityCreated(savedInstanceState);
}
}
Adapter class
public class MyListAdapter extends RecyclerView.Adapter<MyListAdapter.MyViewHolder> {
public boolean mTwoPane;
private Context mCtx;
private List<Product> myList;
public MyListAdapter(Context mCtx, List<Product> myList) {
this.mCtx = mCtx;
this.myList = myList;
}
#NonNull
#Override
public MyListAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.listitem_dualline, parent,false);
return new MyListAdapter.MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MyListAdapter.MyViewHolder holder, final int position) {
Log.d(TAG, "onBindViewHolder: called.");
final Product product = myList.get(holder.getAdapterPosition());
holder.textviewTitle.setText(product.getProductName());
holder.textviewSubtitle.setText(product.getPRoductDescription());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Fragment newFragment;
if (product.getStationName().equals(v.getResources().getString(R.string.product_1))) {
newFragment = new FragmentProduct1();
} else {
newFragment = new FragmentProdcut2();
}
MyActivity activity = (MyActivity) v.getContext();
FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.detail_container, newFragment);
transaction.commit();
} else {
Intent intent;
if (product.getStationName().equals(v.getResources().getString(R.string.product_1))) {
intent = new Intent(v.getContext(), Product1Activity.class);
} else {
intent = new Intent(v.getContext(), Product2Activity.class);
}
mCtx.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return myList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
RelativeLayout relativeLayout;
TextView textviewTitle, textviewSubtitle;
StationViewHolder(View itemView) {
super(itemView);
mTwoPane = itemView.findViewById(R.id.detail_container) != null;
relativeLayout = itemView.findViewById(R.id.listitem_relativelayout);
textviewTitle = itemView.findViewById(R.id.listitem_title);
textviewSubtitle = itemView.findViewById(R.id.listitem_subtitle);
}
}
}
This line mTwoPane = itemView.findViewById(R.id.detail_container) != null; from your view holder will always be false.
Why?
Because, your detail_container is not part of your view holder's item container, so itemView will always return null for your view. instead pass your boolean flag from your fragment to your adapter !
I think you are checking item two pan with recyclerview item xml
mTwoPane = itemView.findViewById(R.id.detail_container) != null;
That you can check while constructing recyclerview adapter and save it from the activity content view itself.

Adding GridView for TabAcitivty fragments

I am trying to add gridview for my layout.
The MainActivity contains 5 number of tabs , where first tab is AlbumsActivity.
AlbumsActivity
public class AlbumsActivity extends Fragment{
public AlbumsActivity() {
// 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.activity_albums, container, false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_layout);
GridView gridView = (GridView) findViewById(R.id.grid_view);
// Instance of ImageAdapter Class
gridView.setAdapter(new ImageAdapter(this));
}
}
ImageAdapter.java
I am using this class adapter to populate the grids in AlbumsActivity.
public class ImageAdapter extends BaseAdapter {
private Context mContext;
// Keep all Images in array
public Integer[] mThumbIds = {
R.drawable.splas,
R.drawable.abc,
};
// Constructor
public ImageAdapter(Context c){
mContext = c;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(150, 150));
return imageView;
}
}
grid_layout.xml
<GridView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/grid_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="3"
android:columnWidth="90dp"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:gravity="center"
android:stretchMode="columnWidth" >
</GridView>
activity_albums.xml
This is layout file for AlbumsActivity , where i want to show grids in page.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:orientation="vertical"
tools:context="com.example.android.musiclist.AlbumsActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/ald"
android:textSize="20sp"
android:textColor="#color/colorPrimaryDark"
android:textStyle="bold"/>
</LinearLayout>
I think you are doing it wrong.
MainActivity - 5 Tabs and one framelayout
AlbumsActivity (Fragment) - Activity_Albums.xml (TextView, GridView)
ImageAdapter (BaseAdapter) - Custom Layout (ImageView)
3 -> 2 (Gridview) -> 1
if not you have to create, set parameters and inject gridview with custom layout to main layout programatically
//Try this
activity_albums.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:orientation="vertical"
tools:context="com.example.android.musiclist.AlbumsActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/ald"
android:textSize="20sp"
android:textColor="#color/colorPrimaryDark"
android:textStyle="bold"/>
<FrameLayout
android:id="#+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
AlbumsActivity
public class AlbumsActivity extends Fragment{
private View view;
private FrameLayout fl;
private GridView gv;
public AlbumsActivity() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.activity_albums,container,false);
fl = view.findViewById(R.id.frameLayout);
gv = findViewById(R.id.grid_view);
gv.setAdapter(new ImageAdapter(this));
fl.addView(gv);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
Or Something similar, I am too lazy to type everything now. just google search "android custom arrayadapter" and you will find tons of examples. It's really simple

Android: NullPointerException when adding an Adapter to a ListView [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am creating a ViewPager in activity_table.xml.
This ViewPager has two pages which both share the same layout: list.xml.
This layout contains a ListView which I am trying to create an Adapter for.
The app compiles correctly but crashes when it tries to add the said Adapter to the ListView with a
NullPointerException when attempting to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference.
I have heard that I have to "load" a layout before I can use the Views it contains, but I how do I do that?
I have tried setContentView(R.layout.list), but it throws the same error...
Table.java
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
ViewPager viewPager = (ViewPager) findViewById(R.id.container);
viewPager.setAdapter(sectionsPagerAdapter);
String[] tmp = new String[mainTable.length-2];
ListView listView = (ListView)findViewById(R.id.listView);
ListAdapter listAdapter = new ListAdapter(this,R.layout.list_item,tmp);
listView.setAdapter(listAdapter);
public static class TableFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section number";
public TableFragment() {
}
public static TableFragment newInstance(int sectionNumber) {
TableFragment fragment = new TableFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER,sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.list,container,false);
TextView title = (TextView) rootView.findViewById(R.id.title);
if(getArguments().getInt(ARG_SECTION_NUMBER) == 1)
title.setText("Heute");
else if(getArguments().getInt(ARG_SECTION_NUMBER) == 2)
title.setText("Morgen");
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return TableFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "today";
case 1:
return "tomorrow";
}
return null;
}
}
public class ListAdapter extends ArrayAdapter<String> {
public ListAdapter(Context context, int textViewResourceId) {
super(context,textViewResourceId);
}
public ListAdapter(Context context, int resource, String[] items) {
super(context,resource,items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.list_item, null);
}
String p = getItem(position);
if(p!=null) {
TextView grade = (TextView) v.findViewById(R.id.grade);
TextView hour = (TextView) v.findViewById(R.id.hour);
TextView course = (TextView) v.findViewById(R.id.course);
TextView teacher = (TextView) v.findViewById(R.id.teacher);
TextView room = (TextView) v.findViewById(R.id.room);
TextView description = (TextView) v.findViewById(R.id.description);
try {
grade.setText(tableData[position][1]);
hour.setText(tableData[position][2]);
course.setText(tableData[position][3]);
teacher.setText(tableData[position][4]);
room.setText(tableData[position][5]);
description.setText(tableData[position][6]);
} catch (ArrayIndexOutOfBoundsException e) {
return v;
}
}
return v;
}
}
activity_table.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:fitsSystemWindows="true"
tools:context="de.fuchstim.vertretungsplan.Table">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/fab_margin"
android:layout_gravity="bottom|right"
app:srcCompat="#drawable/reload_arrow_white" />
</android.support.design.widget.CoordinatorLayout>
list.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="match_parent">
<TextView
android:text="Heute (25.10.16)"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/title"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.DialogWindowTitle"
android:textAlignment="center" />
<GridLayout android:layout_gravity="start"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/grade"
android:layout_height="wrap_content"
android:text="Klasse"
android:layout_row="0"
android:layout_column="0"
android:layout_width="0dp"
android:textSize="14sp"
android:layout_columnWeight="40"
android:paddingStart="10dp" />
<TextView
android:text="Stunde"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/hour"
android:layout_row="0"
android:layout_column="1"
android:layout_columnWeight="15"/>
<TextView
android:text="Lehrer"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/teacher"
android:layout_row="0"
android:layout_column="3"
android:layout_columnWeight="15"/>
<TextView
android:text="Kurs"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/course"
android:layout_row="0"
android:layout_column="2"
android:layout_columnWeight="15"/>
<TextView
android:text="Raum"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/room"
android:layout_row="0"
android:layout_column="4"
android:layout_columnWeight="15"/>
</GridLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:id="#+id/listView" />
</LinearLayout>
I have tried setContentView(R.layout.list), but it throws the same error...
First, you need to use setContentView(R.layout.activity_table) instead.
Second, you cannot find the ListView from the Activity, since it is contained within the Fragment layout.
See here? Your ListView is in the same layout as this title element, so you need to find the ListView here...
View rootView = inflater.inflate(R.layout.list,container,false);
TextView title = (TextView) rootView.findViewById(R.id.title);
Move that ListView code from the Activity to the Fragment. And use getActivity() for the Adapter within the Fragment instead of this to get the Context.
That is where the #+id/listView value exists. That layout is searched with rootView.findViewById.
Since, you did not get null pointer at this location :
ViewPager viewPager = (ViewPager) findViewById(R.id.container);
viewPager.setAdapter(sectionsPagerAdapter);
So, this means you are using :
setContentView(R.layout.activity_table);
Because viewpager is only in above layout, and since listview is not in this layout xml file, you get null pointer on :
ListView listView = (ListView)findViewById(R.id.listView);
ListAdapter listAdapter = new ListAdapter(this,R.layout.list_item,tmp);
listView.setAdapter(listAdapter);
because listview in null, not present in activity_table xml file.
You need to set adapter in OnCreateView() :
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.list,container,false);
TextView title = (TextView) rootView.findViewById(R.id.title);
// Add below ...
String[] tmp = new String[mainTable.length-2];
ListView listView = (ListView)rootView.findViewById(R.id.listView);
ListAdapter listAdapter = new ListAdapter(getActivity(),R.layout.list_item,tmp);
listView.setAdapter(listAdapter);
// ends here ...
if(getArguments().getInt(ARG_SECTION_NUMBER) == 1)
title.setText("Heute");
else if(getArguments().getInt(ARG_SECTION_NUMBER) == 2)
title.setText("Morgen");
return rootView;
}
Hope this helps !

Why is my RecyclerView not showing anything? / What happend if Recycler Adapter is set again after notifyDataSetChanged() called?

I am new to Android Programming and I've been trying to make a fragment which displays a list of items using RecyclerView. Everything seems fine and there is no error when I run the app.
Here is my code:
FriendsFragment.java
public class FriendsFragment extends android.support.v4.app.Fragment {
#Bind(R.id.friendList)
RecyclerView friendList;
RecyclerView.LayoutManager friendsManager;
FriendListAdapter friendListAdapter;
public FriendsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_friends, container, false);
ButterKnife.bind(this, view);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
friendList.setHasFixedSize(true);
friendsManager = new LinearLayoutManager(view.getContext());
friendList.setLayoutManager(friendsManager);
friendListAdapter = new FriendListAdapter(new ArrayList<Friends>());
friendList.setAdapter(friendListAdapter);
test();
friendListAdapter.notifyDataSetChanged();
friendList.setAdapter(friendListAdapter);
super.onViewCreated(view, savedInstanceState);
}
private void test() {
Friends friend = new Friends();
friend.setName("Junjie Saitamaria");
friendListAdapter.addNewFriend(friend);
}
}
FriendListAdapter.java
public class FriendListAdapter extends RecyclerView.Adapter<FriendListAdapter.ViewHolderFriend> {
private List<Friends> friendList;
public FriendListAdapter(List<Friends> friends) {
if(friends != null) {
friendList = friends;
}
}
public void addNewFriend(Friends friend) {
friendList.add(0, friend);
}
#Override
public ViewHolderFriend onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_friend, parent, false);
ViewHolderFriend viewHolder = new ViewHolderFriend(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolderFriend holder, int position) {
Friends currentFriend = friendList.get(position);
holder.friendName.setText(currentFriend.getName());
}
#Override
public int getItemCount() {
return friendList.size();
}
static class ViewHolderFriend extends RecyclerView.ViewHolder {
#Bind(R.id.friend_avatar)
public ImageView friendThumbnail;
#Bind(R.id.friend_name)
public TextView friendName;
Context currentContext = null;
public ViewHolderFriend(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
this.currentContext = itemView.getContext();
}
}
}
fragment_friends.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
tools:context="com.cebuinstituteoftechnology_university.citumessenger.FriendsFragment">
<android.support.v7.widget.RecyclerView
android:id="#+id/friendList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true" >
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
list_item_friend.xml
<?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="vertical">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="80dp"
android:id="#+id/friends_card"
android:elevation="2dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- icon -->
<ImageView
android:id="#+id/friend_avatar"
android:layout_width="64dp"
android:layout_height="64dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp"
android:contentDescription="icon"
android:src="#drawable/avatar"
/>
<!-- title -->
<TextView
android:id="#+id/friend_name"
android:layout_width= "wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_toRightOf="#+id/friend_avatar"
android:layout_alignBaseline="#+id/friend_avatar"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:text="Name" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Looks everything fine except this extra line friendList.setAdapter(friendListAdapter); in below code:
friendList.setAdapter(friendListAdapter);
test();
friendListAdapter.notifyDataSetChanged();
friendList.setAdapter(friendListAdapter);
Replace above 3 lines with this and see :
friendList.setAdapter(friendListAdapter);
test();
friendListAdapter.notifyDataSetChanged();
Remove following line from onViewCreated() Method
friendList.setAdapter(friendListAdapter);
other code is fine.

Categories