NullPointerException: fav_up_btn1 = null - java

I'm getting an error stating:
NullPointerException at com.idg.omv.ui.phone.MainActivity.onCreate(MainActivity.java:149)
I've done a bit of debugging and found that fav_up_btn1 = null however I'm not sure exactly what is causing it. I have verified fav_up_btn1 exists in my XML and I'm not sure exactly what else it might be.
JAVA SNIPPET:
mainScrollView = (ScrollView) findViewById(R.id.groupScrollView);
fav_up_btn1 = (Button) findViewById(R.id.fav_up_btn1);
fav_up_btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean favIsUp = fav_up_btn1
.getBackground()
.getConstantState()
.equals(getResources().getDrawable(
R.drawable.fav_up_btn1).getConstantState());
// set the background
fav_up_btn1
.setBackgroundResource(favIsUp ? R.drawable.fav_dwn_btn1
: R.drawable.fav_up_btn1);
XML:
<?xml version="1.0" encoding="utf-8"?>
<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" >
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtubeplayerview"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<com.idg.omv.ui.widget.VideosListView
android:id="#+id/videosListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<RelativeLayout
android:id="#+id/footer"
android:layout_width="fill_parent"
android:layout_height="70dip"
android:layout_alignParentBottom="true" >
<ScrollView
android:id="#+id/groupScrollView"
android:layout_width="fill_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/selstation_up_btn"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_gravity="center_horizontal"
android:background="#color/darkgrey"
android:scaleType="fitXY"
android:src="#drawable/selstation_up_btn" />
</ScrollView>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:src="#drawable/scroll_lt_arrow" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:src="#drawable/fav_up_btn1" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:src="#drawable/scroll_rt_arrow" />
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true" />
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
FULL JAVA SOURCE:
public class MainActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener,
YouTubeThumbnailView.OnInitializedListener {
// A reference to our list that will hold the video details
private VideosListView listView;
private ActionBarDrawerToggle actionBarDrawerToggle;
private ActionBarDrawerToggle mDrawerToggle;
public static final String API_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
public static final String VIDEO_ID = "o7VVHhK9zf0";
public static final String VIDEO1_ID = "xVHHJqntuXI";
public static final String VIDEO2_ID = "YWteQj_q3Ro";
public static final String VIDEO3_ID = "83ZgtqTw-mI";
public static final String VIDEO4_ID = "n5wMza29JwI";
private YouTubeThumbnailLoader youTubeThumbnailLoader;
private YouTubeThumbnailView youTubeThumbnailView1;
private YouTubeThumbnailView youTubeThumbnailView2;
private YouTubeThumbnailView youTubeThumbnailView3;
private YouTubeThumbnailView youTubeThumbnailView4;
private DrawerLayout drawerLayout;
private ListView drawerListView;
private String[] drawerListViewItems;
ScrollView mainScrollView;
Button fav_up_btn1;
Button fav_dwn_btn1;
private YouTubePlayerView youTubePlayerView;
String TAG = "DEBUG THIS";
private YouTubePlayer youTubePlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ActionBar actionBar = getActionBar();
// if(actionBar == null) {
// Log.i(TAG, "ActionBar is null");
// } else {
// Log.i(TAG, "ActionBat is not null");
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
//final ActionBar actionBar = getActionBar();
actionBar.setCustomView(R.layout.actionbar_custom_view_home);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
if(actionBar == null) { Log.i(TAG,"ActonBar is null");
} else {
Log.i(TAG,"ActionBar is not null");};
Bitmap d = BitmapFactory.decodeResource(this.getResources(),
R.drawable.selstation_up_btn);
ImageView imgView = (ImageView) findViewById(R.id.selstation_up_btn);
imgView.setImageBitmap(d);
// get list items from strings.xml
drawerListViewItems = getResources().getStringArray(R.array.items);
// get ListView defined in activity_main.xml
drawerListView = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
drawerListView.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_listview_item, drawerListViewItems));
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
drawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtubeplayerview);
youTubePlayerView.initialize(API_KEY, this);
mainScrollView = (ScrollView) findViewById(R.id.groupScrollView);
// youTubeThumbnailView1 = (YouTubeThumbnailView) findViewById(R.id.youtubethumbnailview1);
// youTubeThumbnailView1.initialize(API_KEY, this);
fav_up_btn1 = (Button) findViewById(R.id.fav_up_btn1);
fav_up_btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean favIsUp = fav_up_btn1
.getBackground()
.getConstantState()
.equals(getResources().getDrawable(
R.drawable.fav_up_btn1).getConstantState());
// set the background
fav_up_btn1
.setBackgroundResource(favIsUp ? R.drawable.fav_dwn_btn1
: R.drawable.fav_up_btn1);
}
});
youTubeThumbnailView1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (youTubePlayer != null) {
youTubePlayer.cueVideo(VIDEO1_ID);
youTubePlayer.play();
mainScrollView.smoothScrollTo(0, 0);
}
}
});
youTubeThumbnailView2 = (YouTubeThumbnailView) findViewById(R.id.youtubethumbnailview2);
youTubeThumbnailView2.initialize(API_KEY, this);
youTubeThumbnailView2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg1) {
if (youTubePlayer != null) {
youTubePlayer.cueVideo(VIDEO2_ID);
youTubePlayer.play();
mainScrollView.smoothScrollTo(0, 0);
}
}
});
youTubeThumbnailView3 = (YouTubeThumbnailView) findViewById(R.id.youtubethumbnailview3);
youTubeThumbnailView3.initialize(API_KEY, this);
youTubeThumbnailView3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg1) {
if (youTubePlayer != null) {
youTubePlayer.cueVideo(VIDEO3_ID);
youTubePlayer.play();
mainScrollView.smoothScrollTo(0, 0);
}
}
});
youTubeThumbnailView4 = (YouTubeThumbnailView) findViewById(R.id.youtubethumbnailview4);
youTubeThumbnailView4.initialize(API_KEY, this);
youTubeThumbnailView4.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg1) {
if (youTubePlayer != null) {
youTubePlayer.cueVideo(VIDEO4_ID);
youTubePlayer.play();
mainScrollView.smoothScrollTo(0, 0);
}
}
});}
#Override
public void onInitializationFailure(Provider provider,
YouTubeInitializationResult result) {
}
#Override
public void onInitializationSuccess(Provider provider,
YouTubePlayer player, boolean wasRestored) {
youTubePlayer = player;
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
}
public void onInitializationFailure(YouTubeThumbnailView thumbnailView,
YouTubeInitializationResult error) {
}
public void onInitializationSuccess(YouTubeThumbnailView thumbnailView,
YouTubeThumbnailLoader thumbnailLoader) {
youTubeThumbnailLoader = thumbnailLoader;
thumbnailLoader
.setOnThumbnailLoadedListener(new ThumbnailLoadedListener());
youTubeThumbnailLoader.setVideo(VIDEO_ID);
}
private final class ThumbnailLoadedListener implements
YouTubeThumbnailLoader.OnThumbnailLoadedListener {
#Override
public void onThumbnailError(YouTubeThumbnailView arg0, ErrorReason arg1) {
}
#Override
public void onThumbnailLoaded(YouTubeThumbnailView arg0, String arg1) {
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// call ActionBarDrawerToggle.onOptionsItemSelected(), if it returns
// true
// then it has handled the app icon touch event
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ImagePagerAdapter extends PagerAdapter {
private int[] mImages = new int[] { R.drawable.classical_up_btn,
R.drawable.country_up_btn, R.drawable.dance_up_btn,
R.drawable.hiphop_up_btn };
public int getCount() {
return mImages.length;
}
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
public Object instantiateItem(ViewGroup container, int position) {
Context context = MainActivity.this;
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(
R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(mImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
}

It's because you should add this to your button (look the second line).
<Button
android:id="#+id/fav_up_btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:src="#drawable/fav_up_btn1" />
In your code, you didn't provide any id with fav_up_btn1, so when you tried to get the view with this id, it failed

Related

How can I go from current fragment to another at right way, using Yalantis SlideMenu?

Unfortunately, I am finding the developer of this project doesn't reply at all. So I am posting here. I am trying to implement this UI on my project but developer has used image in sample code. I need to implement here a fragment from one to another. I have already tried this but this doesn't change my fragment. Below is the code how I implemented.
Note: Below codes are a lot. I posted it to make sure where the problem was. As the documentation and sample project I did all well.
activity_home.xml
<?xml version="1.0" encoding="utf-8"?>
<io.codetail.widget.RevealLinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:autofit="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/container1"
android:orientation="vertical"
android:weightSum="2"
android:layout_height="match_parent"
android:layout_width="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/lightbrown"
android:orientation="horizontal"
android:weightSum="2">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1.2">
<me.grantland.widget.AutofitTextView
android:id="#+id/textBoy"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="32dp"
android:maxLines="1"
android:singleLine="true"
android:typeface="monospace"
android:text="#string/boy"
android:gravity="center_vertical|center_horizontal"
android:textSize="180sp"
autofit:minTextSize="20sp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.8">
<ImageView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:scaleType="centerInside"
android:src="#drawable/home_boy_one" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/lightGreen"
android:weightSum="2">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1.2">
<me.grantland.widget.AutofitTextView
android:id="#+id/textGirl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|center_horizontal"
android:layout_margin="32dp"
android:maxLines="1"
android:singleLine="true"
android:typeface="monospace"
android:text="#string/girl"
android:textSize="180sp"
autofit:minTextSize="20sp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.8">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerInside"
android:src="#drawable/home_girl_one" />
</RelativeLayout>
</LinearLayout>
</LinearLayout>
</io.codetail.widget.RevealLinearLayout>
Home.java
public class Home extends Fragment implements ScreenShotable {
private View Fragmentone_view;
private Bitmap bitmap;
private AutofitTextView textBoy, textGirl;
private Typeface typeface;
#Nullable
public static Home newInstance() {
Home home = new Home();
return home;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
textBoy = rootView.findViewById(R.id.textBoy);
textGirl = rootView.findViewById(R.id.textGirl);
typeface = Typeface.createFromAsset(getResources().getAssets(), "fonts/trench.otf");
textBoy.setTypeface(typeface);
textGirl.setTypeface(typeface);
Log.d("reachHera","reachhere");
return rootView;
}
#Override
public void takeScreenShot() {
Thread thread = new Thread() {
#Override
public void run() {
try {
Bitmap bitmap = Bitmap.createBitmap(Fragmentone_view.getWidth(),
Fragmentone_view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Fragmentone_view.draw(canvas);
Home.this.bitmap = bitmap;
} catch (Exception ex) {
}
}
};
thread.start();
}
#Override
public Bitmap getBitmap() {
return bitmap;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.Fragmentone_view = view.findViewById(R.id.container1);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
ContentFragment.java
public class ContentFragment extends Fragment implements ScreenShotable {
public static final String CLOSE = "Close";
public static final String BUILDING = "Building";
public static final String BOOK = "Book";
public static final String PAINT = "Paint";
public static final String CASE = "Case";
public static final String SHOP = "Shop";
public static final String PARTY = "Party";
public static final String MOVIE = "Movie";
private View containerView;
protected ImageView mImageView;
protected int res;
private Bitmap bitmap;
public static ContentFragment newInstance(int resId) {
ContentFragment contentFragment = new ContentFragment();
Bundle bundle = new Bundle();
bundle.putInt(Integer.class.getName(), resId);
contentFragment.setArguments(bundle);
return contentFragment;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.containerView = view.findViewById(R.id.container);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
res = getArguments().getInt(Integer.class.getName());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
mImageView = (ImageView) rootView.findViewById(R.id.image_content);
mImageView.setClickable(true);
mImageView.setFocusable(true);
mImageView.setImageResource(res);
return rootView;
}
#Override
public void takeScreenShot() {
Thread thread = new Thread() {
#Override
public void run() {
Bitmap bitmap = Bitmap.createBitmap(containerView.getWidth(),
containerView.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
containerView.draw(canvas);
ContentFragment.this.bitmap = bitmap;
}
};
thread.start();
}
#Override
public Bitmap getBitmap() {
return bitmap;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity implements ViewAnimator.ViewAnimatorListener {
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
private List<SlideMenuItem> list = new ArrayList<>();
private ContentFragment contentFragment;
private ViewAnimator viewAnimator;
private int res = R.drawable.content_music;
private LinearLayout linearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contentFragment = ContentFragment.newInstance(R.drawable.content_music);
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, contentFragment)
.commit();
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerLayout.setScrimColor(Color.TRANSPARENT);
linearLayout = (LinearLayout) findViewById(R.id.left_drawer);
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawerLayout.closeDrawers();
}
});
setActionBar();
createMenuList();
viewAnimator = new ViewAnimator<>(this, list, contentFragment, drawerLayout, this);
}
private void createMenuList() {
SlideMenuItem menuItem0 = new SlideMenuItem(ContentFragment.CLOSE, R.drawable.icn_close);
list.add(menuItem0);
SlideMenuItem menuItem = new SlideMenuItem(ContentFragment.BUILDING, R.drawable.icn_1);
list.add(menuItem);
SlideMenuItem menuItem2 = new SlideMenuItem(ContentFragment.BOOK, R.drawable.icn_2);
list.add(menuItem2);
SlideMenuItem menuItem3 = new SlideMenuItem(ContentFragment.PAINT, R.drawable.icn_3);
list.add(menuItem3);
SlideMenuItem menuItem4 = new SlideMenuItem(ContentFragment.CASE, R.drawable.icn_4);
list.add(menuItem4);
SlideMenuItem menuItem5 = new SlideMenuItem(ContentFragment.SHOP, R.drawable.icn_5);
list.add(menuItem5);
SlideMenuItem menuItem6 = new SlideMenuItem(ContentFragment.PARTY, R.drawable.icn_6);
list.add(menuItem6);
SlideMenuItem menuItem7 = new SlideMenuItem(ContentFragment.MOVIE, R.drawable.icn_7);
list.add(menuItem7);
}
private void setActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
drawerLayout, /* DrawerLayout object */
toolbar, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
linearLayout.removeAllViews();
linearLayout.invalidate();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
if (slideOffset > 0.6 && linearLayout.getChildCount() == 0)
viewAnimator.showMenuContent();
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawerLayout.setDrawerListener(drawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private ScreenShotable replaceFragment(ScreenShotable screenShotable, int topPosition) {
View view = findViewById(R.id.content_frame);
int finalRadius = Math.max(view.getWidth(), view.getHeight());
SupportAnimator animator = ViewAnimationUtils.createCircularReveal(view, 0, topPosition, 0, finalRadius);
animator.setInterpolator(new AccelerateInterpolator());
animator.setDuration(ViewAnimator.CIRCULAR_REVEAL_ANIMATION_DURATION);
findViewById(R.id.content_overlay).setBackgroundDrawable(new BitmapDrawable(getResources(), screenShotable.getBitmap()));
animator.start();
// ContentFragment contentFragment = ContentFragment.newInstance(this.res);
// getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, contentFragment).commit();
return screenShotable;
}
#Override
public ScreenShotable onSwitch(Resourceble slideMenuItem, ScreenShotable screenShotable, int position) {
switch (slideMenuItem.getName()) {
case ContentFragment.CLOSE:
return screenShotable;
case ContentFragment.BOOK:
Toast.makeText(this, "", Toast.LENGTH_SHORT).show();
Home home=Home.newInstance();
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame,home);
return replaceFragment(home,position);
default:
return replaceFragment(screenShotable, position);
}
}
#Override
public void disableHomeButton() {
getSupportActionBar().setHomeButtonEnabled(false);
}
#Override
public void enableHomeButton() {
getSupportActionBar().setHomeButtonEnabled(true);
drawerLayout.closeDrawers();
}
#Override
public void addViewToContainer(View view) {
linearLayout.addView(view);
}
}

Can't see any entry in RecyclerView

I've created a RecyclerView in Android Studio like in an other fragment. The problem is that all is working for the first look but after creating a row object and stating the app I can't see any entries. I've did this RecyclerView the the same way as my old one which works great.. I've searched a lot but I can find the error.
This is my fragment xml:
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/training_swiperefresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/trainingtTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:layout_marginTop="0dp"
android:layout_marginBottom="16dp"
android:textStyle="bold"
android:textColor="#color/colorPrimary"
android:text="#string/trainingTitle" />
<android.support.v7.widget.RecyclerView
android:id="#+id/training_recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:layout_below="#+id/trainingtTitle" />
</RelativeLayout>
</android.support.v4.widget.SwipeRefreshLayout>
This is the row-layout for the RecyclerView:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:focusable="true"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:clickable="true"
android:background="?android:attr/selectableItemBackground"
android:orientation="vertical">
<!-- Plan icon -->
<ImageView
android:id="#+id/planImage"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_centerVertical="true"
android:layout_alignParentStart="true"
android:layout_marginRight="8dp"
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp"
android:contentDescription="Icon"
android:src="#drawable/ic_menu_train" />
<!-- Plan title -->
<TextView
android:id="#+id/planTitle"
android:textColor="#color/colorBlack"
android:layout_width="match_parent"
android:layout_marginLeft="40dp"
android:layout_marginRight="40dp"
android:layout_marginTop="14dp"
android:textSize="16dp"
android:layout_height="wrap_content" />
<!-- Plan type -->
<TextView
android:id="#+id/planType"
android:layout_below="#id/planTitle"
android:layout_marginLeft="40dp"
android:layout_marginRight="40dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!-- Plan date -->
<TextView
android:id="#+id/planDate"
android:layout_width="match_parent"
android:layout_below="#id/planType"
android:layout_marginLeft="42dp"
android:layout_marginRight="40dp"
android:layout_marginBottom="14dp"
android:layout_height="wrap_content" />
<!-- Plan view -->
<ImageView
android:id="#+id/planView"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp"
android:contentDescription="Icon"
android:src="#drawable/ic_menu_show" />
<View
android:layout_width="fill_parent"
android:layout_height="1dip"
android:layout_below="#id/planDate"
android:layout_marginLeft="42dp"
android:background="#DCDCDC" />
</RelativeLayout>
This is my Fragment where I call the Adapter:
public class TrainingFragment extends Fragment {
private OnFragmentInteractionListener mListener;
// Variables for Recycler View
private List<Plans> planList = new ArrayList<>();
private RecyclerView trainingRecyclerView;
private PlansAdapter pAdapter;
public TrainingFragment() {
// Required empty public constructor
}
//Change the title in action bar
public void onResume() {
super.onResume();
String titleString = getResources().getString(R.string.title_activity_navigation_drawer_training);
// Set title bar
((NavigationDrawerActivity) getActivity())
.setActionBarTitle(titleString);
}
public static TrainingFragment newInstance() {
TrainingFragment fragment = new TrainingFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Menü bekannt geben, dadurch kann Fragment Menü-Events verarbeiten
setHasOptionsMenu(true);
}
//Fragment XML geben, sowie als Menü setzen
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_training, menu);
// Declare ImageView and Animation for rotation animation
MenuItem reloadButton = (MenuItem) menu.findItem(R.id.menu_reloadbutton);
final Animation rotation = AnimationUtils.loadAnimation(getActivity(), R.anim.animation_rotate);
//if (reloadButton != null) {
// //reloadButton.setImageResource(R.drawable.ic_menu_reloadentry);
// reloadButton.getActionView().setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// rotation.setRepeatCount(Animation.INFINITE);
// view.startAnimation(rotation);
// }
// });
//}
}
//AddEntry click abfangen und verarbeiten
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Wir prüfen, ob Menü-Element mit der ID "action_daten_aktualisieren"
// ausgewählt wurde und geben eine Meldung aus
int id = item.getItemId();
if (id == R.id.menu_reloadbutton) {
// Text ausgeben
//Toast.makeText(getActivity(), "Liste aktualisieren gedrückt!", Toast.LENGTH_LONG).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_training, container, false);
// Get Refresh Layout
SwipeRefreshLayout swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.training_swiperefresh);
// Change color for the refresh layout
swipeRefreshLayout.setColorSchemeColors(Color.rgb(99, 195, 195));
trainingRecyclerView = (RecyclerView) view.findViewById(R.id.training_recycler_view);
pAdapter = new PlansAdapter(planList, getContext());
RecyclerView.LayoutManager pLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
trainingRecyclerView.setLayoutManager(pLayoutManager);
trainingRecyclerView.setItemAnimator(new DefaultItemAnimator());
trainingRecyclerView.setAdapter(pAdapter);
preparePlansData();
return view;
}
private void preparePlansData() {
// Set plan data
Plans plan = new Plans("ABC-Bestellung", "Muskelaufbau", "Datum: 21.04.1997");
// Add Object to list
planList.add(plan);
plan = new Plans("test", "tttt", "ttttt");
planList.add(plan);
// Notify data changes
pAdapter.notifyDataSetChanged();
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onStart() {
super.onStart();
try {
mListener = (OnFragmentInteractionListener) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException(getActivity().toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
This is my Adapter:
public class PlansAdapter extends RecyclerView.Adapter<PlansAdapter.MyPlanHolder> {
private List<Plans> planList;
private final Context customContext;
public class MyPlanHolder extends RecyclerView.ViewHolder {
public TextView planTitle, planType, planDate;
public MyPlanHolder(View view) {
super(view);
planTitle = (TextView) view.findViewById(R.id.planTitle);
planType = (TextView) view.findViewById(R.id.planType);
planDate = (TextView) view.findViewById(R.id.planDate);
}
}
public PlansAdapter(List<Plans> planList, Context customContext) {
this.planList = planList;
this.customContext = customContext;
}
#Override
public MyPlanHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.plans_list_row, parent, false);
return new MyPlanHolder(itemView);
}
#Override
public void onBindViewHolder(MyPlanHolder holder, int position) {
final Plans plan = planList.get(position);
holder.planTitle.setText(plan.getPlanTitle());
holder.planType.setText(plan.getPlanType());
holder.planDate.setText(plan.getPlanDate());
}
#Override
public int getItemCount() {
return 0;
}
}
And finaly my object class for the elements:
public class Plans {
private String planTitle, planType, planDate;
public Plans(String planTitle, String planType, String planDate) {
this.planTitle = planTitle;
this.planType = planType;
this.planDate = planDate;
}
public void setPlanTitle(String planTitle) {
this.planTitle = planTitle;
}
public String getPlanTitle() {
return planTitle;
}
public void setPlanType(String planType) {
this.planType = planType;
}
public String getPlanType() {
return planType;
}
public void setPlanDate(String planDate) {
this.planDate = planDate;
}
public String getPlanDate() {
return planDate;
}
}
I hope that you can find the issue.
Inside Adapter's getItemCount() method you are returning 0 as size of list.You should change it as return planList.size()
Your code is fine except in your adapter you are returning 0 in getItemCount() method.
Here's the updated code :
public class PlansAdapter extends RecyclerView.Adapter<PlansAdapter.MyPlanHolder> {
private List<Plans> planList;
private final Context customContext;
public class MyPlanHolder extends RecyclerView.ViewHolder {
public TextView planTitle, planType, planDate;
public MyPlanHolder(View view) {
super(view);
planTitle = (TextView) view.findViewById(R.id.planTitle);
planType = (TextView) view.findViewById(R.id.planType);
planDate = (TextView) view.findViewById(R.id.planDate);
}
}
public PlansAdapter(List<Plans> planList, Context customContext) {
this.planList = planList;
this.customContext = customContext;
}
#Override
public MyPlanHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.plans_list_row, parent, false);
return new MyPlanHolder(itemView);
}
#Override
public void onBindViewHolder(MyPlanHolder holder, int position) {
final Plans plan = planList.get(position);
holder.planTitle.setText(plan.getPlanTitle());
holder.planType.setText(plan.getPlanType());
holder.planDate.setText(plan.getPlanDate());
}
#Override
public int getItemCount() {
return planList.size();
}
}

FrameLayout does not match_parent

I am using fragNav and bottombar plugin. I am trying to make a fullscreen fragment through a FrameLayout. By default, those plugins came with an actionBar which i delete in my theme with "Theme.AppCompat.Light.NoActionBar". But Once i did this there is still a white bar on top on my screen. When i look at hierarchyView it appears that my FrameLayout is not matching the parent but all my xml are setup with match_parent width and height..
MainActivity.java
public class MainActivity extends AppCompatActivity {
private BottomBar mBottomBar;
private FragNavController fragNavController;
private final int TAB_FIRST = FragNavController.TAB1;
private final int TAB_SECOND = FragNavController.TAB2;
private final int TAB_THIRD = FragNavController.TAB3;
private final int TAB_FOURTH = FragNavController.TAB4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<Fragment> fragments = new ArrayList<>(4);
fragments.add(FirstFragment.newInstance(0));
fragments.add(SecondFragment.newInstance(0));
fragments.add(ThirdFragment.newInstance(0));
fragments.add(FourthFragment.newInstance(0));
fragNavController = new FragNavController(getSupportFragmentManager(), R.id.container, fragments);
//BottomBar menu
mBottomBar = BottomBar.attach(this, savedInstanceState);
mBottomBar.setItems(R.menu.bottombar_menu);
mBottomBar.setOnMenuTabClickListener(new OnMenuTabClickListener() {
#Override
public void onMenuTabSelected(#IdRes int menuItemId) {
//switch between tabs
switch (menuItemId) {
case R.id.bottomBarItemOne:
fragNavController.switchTab(TAB_FIRST);
break;
case R.id.bottomBarItemSecond:
fragNavController.switchTab(TAB_SECOND);
break;
case R.id.bottomBarItemThird:
fragNavController.switchTab(TAB_THIRD);
break;
case R.id.bottomBarItemFourth:
fragNavController.switchTab(TAB_FOURTH);
break;
}
}
#Override
public void onMenuTabReSelected(#IdRes int menuItemId) {
if (menuItemId == R.id.bottomBarItemOne) {
fragNavController.clearStack();
}
}
});
}
#Override
public void onBackPressed () {
if (fragNavController.getCurrentStack().size() > 1) {
fragNavController.pop();
} else {
super.onBackPressed();
}
}
#Override
protected void onSaveInstanceState (Bundle outState){
super.onSaveInstanceState(outState);
// Necessary to restore the BottomBar's state, otherwise we would
// lose the current tab on orientation change.
mBottomBar.onSaveInstanceState(outState);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
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=".MainActivity"
android:id="#+id/container"
android:background="#color/black">
</FrameLayout>
FirstFragment.java
public class FirstFragment extends Fragment {
public class SwipeDeckAdapter extends BaseAdapter {
private List<String> data;
private Context context;
public SwipeDeckAdapter(List<String> data, Context context) {
this.data = data;
this.context = context;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null){
LayoutInflater inflater = getActivity().getLayoutInflater();
// normally use a viewholder
v = inflater.inflate(R.layout.card_view, parent, false);
}
((TextView) v.findViewById(R.id.textView2)).setText(data.get(position));
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String item = (String)getItem(position);
Log.i("MainActivity", item);
}
});
return v;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home,container,false);
final SwipeDeck cardStack = (SwipeDeck) view.findViewById(R.id.swipe_deck);
cardStack.setHardwareAccelerationEnabled(true);
Button btn = (Button) view.findViewById(R.id.undobutton);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cardStack.swipeTopCardLeft(180);
}
});
Button btn2 = (Button) view.findViewById(R.id.joinbutton);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cardStack.swipeTopCardRight(180);
}
});
final ArrayList<String> testData = new ArrayList<>();
testData.add("0");
testData.add("1");
testData.add("2");
testData.add("3");
testData.add("4");
final SwipeDeckAdapter adapter = new SwipeDeckAdapter(testData, getActivity() );
cardStack.setAdapter(adapter);
cardStack.setEventCallback(new SwipeDeck.SwipeEventCallback() {
#Override
public void cardSwipedLeft(int position) {
Log.i("MainActivity", "card was swiped left, position in adapter: " + position);
}
#Override
public void cardSwipedRight(int position) {
Log.i("MainActivity", "card was swiped right, position in adapter: " + position);
}
#Override
public void cardsDepleted() {
Log.i("MainActivity", "no more cards");
}
#Override
public void cardActionDown() {
Log.i("MainActivity", "Down");
} ;
#Override
public void cardActionUp() {
Log.i("MainActivity", "Up");
};
});
return view;
}
public static FirstFragment newInstance(int index) {
FirstFragment f = new FirstFragment();
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
}
fragment_first.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:background="#color/black"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="io.MainActivity"
android:fitsSystemWindows="true">
<com.daprlabs.cardstack.SwipeLinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:swipedeck="http://schemas.android.com/apk/res-auto"
android:id="#+id/framelayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="10">
<com.daprlabs.cardstack.SwipeDeck
android:id="#+id/swipe_deck"
android:layout_weight="8"
android:layout_width="match_parent"
android:layout_height="0dp"
swipedeck:card_spacing="0dp"
swipedeck:max_visible="3"
swipedeck:render_above="true"
swipedeck:rotation_degrees="15"
swipedeck:opacity_end="0.33">
</com.daprlabs.cardstack.SwipeDeck>
<RelativeLayout
android:id="#+id/rl"
android:layout_weight="2"
android:layout_width="match_parent"
android:layout_height="0dp">
<RelativeLayout
android:id="#+id/container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true">
<Button
android:id="#+id/undobutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Undo"
android:onClick="onClick"/>
<Button
android:id="#+id/joinbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/undobutton"
android:text="Join"
android:onClick="onClick"/>
</RelativeLayout>
</RelativeLayout>
</com.daprlabs.cardstack.SwipeLinearLayout>
In your parent RelativeLayout in fragment_first can you remove the android:fitsSystemWindows="true", I think that may be the cause of the issue.

Android ViewPager child fragments load but tabs don't

I'm using a ViewPager in a fragment that loads a child fragment per tab, and that is working fine the child fragments are loaded, but the issue is that the tabs themselves, where the tab click-able names go, is not showing, nor is it responding to click events. I reach this screen by selecting an element in a recyclerview in a previous fragment.
The expected layout structure is the following:
But the problem is that, although everything else loads fine and I can side swipe to switch child fragments, the tab bar doesn't load at all and I just get this:
I'm not sure what is causing this, but when I rotate the screen and back, then they appear.
MainActivity class
public class MainActivity extends AppCompatActivity {
private final static int PROFILE_FRAGMENT = 1;
private final static int PRIZES_FRAGMENT = 2;
private final static int STORES_FRAGMENT = 3;
private final static int ABOUT = 4;
private int currentFragment = 3;
private String currentFragmentName = "StoresListFragment";
public int HEADER_IMAGE = R.drawable.avatar;
private DrawerLayout drawer;
private List<DrawerItem> dataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
FragmentManager fm = getSupportFragmentManager();
if (getIntent().getStringExtra("STORE_DETAILS") != null) {
openFragment(new StoreDetailsFragment());
setTitle(getString(R.string.title_store_details));
}
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
}
RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView);
mRecyclerView.setHasFixedSize(true);
dataList = new ArrayList<>();
addItemsToDataList();
NavDrawerAdapter mAdapter = new NavDrawerAdapter(dataList, this, db.getClientName(), db.getPoints(), HEADER_IMAGE);
mRecyclerView.setAdapter(mAdapter);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
drawer = (DrawerLayout) findViewById(R.id.DrawerLayout);
drawer.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(
this, drawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};
drawer.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
onTouchDrawer(currentFragment);
final GestureDetector mGestureDetector =
new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
View child = recyclerView.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if (child != null && mGestureDetector.onTouchEvent(motionEvent)) {
drawer.closeDrawers();
onTouchDrawer(recyclerView.getChildLayoutPosition(child));
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
}
private void addItemsToDataList() {
dataList.add(new DrawerItem(getString(R.string.title_profile), R.mipmap.ic_action_profile));
dataList.add(new DrawerItem(getString(R.string.title_prizes), R.mipmap.ic_action_prizes));
dataList.add(new DrawerItem(getString(R.string.title_stores), R.mipmap.ic_action_sales));
dataList.add(new DrawerItem(getString(R.string.title_about), R.mipmap.ic_action_about));
}
public void openFragment(final Fragment fragment) {
if (!fragment.toString().equalsIgnoreCase(currentFragmentName)) {
// update the transfer content by replacing fragments
currentFragmentName = fragment.toString();
switchContent(fragment);
}
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commitAllowingStateLoss();
}
private void onTouchDrawer(final int position) {
currentFragment = position;
switch (position) {
case PROFILE_FRAGMENT:
openFragment(new ProfileFragment());
setTitle(getString(R.string.title_profile));
break;
case PRIZES_FRAGMENT:
openFragment(new PrizesListFragment());
setTitle(getString(R.string.title_prizes));
break;
case STORES_FRAGMENT:
openFragment(new StoresListFragment());
setTitle(getString(R.string.title_stores));
break;
case ABOUT:
openFragment(new AboutFragment());
setTitle(getString(R.string.title_about));
break;
default:
}
}
/*
* helper to switch content with backstack
*/
public void switchContent(Fragment fragment) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragment)
// add to backstack
.addToBackStack(fragment.getClass().getSimpleName())
.commitAllowingStateLoss();
}
#Override
protected void onResume() {
if (getIntent().getStringExtra("SALES_LIST") != null) {
openFragment(new StoreDetailsFragment());
setTitle(getString(R.string.title_store_details));
} else if (getSupportFragmentManager().getBackStackEntryCount() <= 0) {
openFragment(new StoresListFragment());
setTitle(getString(R.string.title_stores));
}
super.onResume();
}
}
The fragment in question:
public class StoreDetailsFragment extends Fragment {
private ViewPager viewPager;
private Store storeSelected = null;
private TextView storeName;
private ImageView bannerImage;
private TextView storesubtitle;
public StoreDetailsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_store_details, container, false);
viewPager = (ViewPager) rootView.findViewById(R.id.tabanim_viewpager);
TabLayout storeTabLayout = (TabLayout) rootView.findViewById(R.id.tabanim_tabs);
setupViewPager(viewPager);
storeTabLayout.setupWithViewPager(viewPager);
storeTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
switch (tab.getPosition()) {
case 0:
Toast.makeText(getActivity(), "Sales List", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(getActivity(), "Store Description", Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(getActivity(), "Store Ratings", Toast.LENGTH_SHORT).show();
break;
case 3:
Toast.makeText(getActivity(), "Images", Toast.LENGTH_SHORT).show();
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
bannerImage = (ImageView) rootView.findViewById(R.id.store_details_banner_image);
storeName = (TextView) rootView.findViewById(R.id.text_store_details_name);
storesubtitle = (TextView) rootView.findViewById(R.id.text_store_details_subtitle);
return rootView;
}
#Override
public void onResume() {
super.onResume();
// Set title
getMainActivity().setTitle(R.string.title_store_details);
}
protected MainActivity getMainActivity() {
return (MainActivity) getActivity();
}
}
Fragment in question's layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
android:id="#+id/main_content"
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.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="300dp"
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="match_parent"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:id="#+id/store_details_banner_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="?attr/actionBarSize"
android:background="#drawable/white_placeholder"
android:contentDescription=""
android:fitsSystemWindows="true"/>
<LinearLayout
android:id="#+id/smth"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginBottom="?attr/actionBarSize"
android:background="#ffffff"
android:orientation="vertical">
<TextView
android:id="#+id/text_store_details_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="18dp"
android:layout_marginTop="40dp"
android:textColor="#333"
android:textSize="15sp"
android:textStyle="bold"/>
<TextView
android:id="#+id/text_store_details_subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginStart="13dp"
android:layout_marginTop="3dp"
android:drawableLeft="#mipmap/ic_action_store_house"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#333"/>
</LinearLayout>
<android.support.v7.widget.Toolbar
android:id="#+id/anim_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/transparent"
app:layout_collapseMode="parallax"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<android.support.design.widget.TabLayout
android:id="#+id/tabanim_tabs"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_gravity="bottom"
android:visibility="visible"
app:tabGravity="center"
app:tabIndicatorColor="#F1514A"
app:tabMode="scrollable"
app:tabSelectedTextColor="#android:color/white"
app:tabTextColor="#99ffffff"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/tabanim_viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
</android.support.design.widget.CoordinatorLayout>
And the ViewPagerAdaper:
public class StoreDetailsViewPagerTabAdaper extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public StoreDetailsViewPagerTabAdaper(FragmentManager manager) {
super(manager);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(android.support.v4.app.Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}}
Any help and suggestions are appreciated.
In the end I couldn't find a solution to this and even after consulting some more experienced developers we could only find a workaround, which was just have this be inside an activity instead of a fragment and then the viewpager behaves as expected. I couldn't figure out why it doesn't inside a fragment.
If anyone finds a more suitable answer, go ahead, but until then I'll set this to be the accepted answer.
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
Try this one and initiate your adapter with getChildFragmentManager
I would try to log inside getPageTitle, because I think when you rotate the screen everything is destroyed an the mFragmentTitleList is empty when you redraw the titles, so try to find out what's going on by doing something like:
#Override
public CharSequence getPageTitle(int position) {
Log.d("ViewPagerAdapter", "Displaying title: "+ mFragmentTitleList.get(position));
return mFragmentTitleList.get(position);
}
Your TabLayout might not be showing because you set height to it. Try setting android:layout_height="wrap_content".
You don't have to handle tab clicks manually – if you bind the TabLayout with ViewPager
tabLayout.setupWithViewPager(viewPager);
the listener is created automatically. I would suggest to remove the custom listener.

SherlockfragmentActivity and sherlockListFragment

I'm trying to make a drobdown navigation menu so i can move between my pages using SherlockFragmentActivity and SerlockListFragment
but every time i'm starting my app it's give this following error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.download.manager/com.download.manager.Main}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is android.R.id.list
this is SherlockFragmentActivity class
public class Main extends SherlockFragmentActivity implements OnNavigationListener{
private static final String KEY_MODELS="models";
private static final String KEY_POSITION="position";
private static final String[] labels= { "All", "Downloads","Completed","Later" };
private CharSequence[] models=new CharSequence[4];
private DownloadList frag=null;
private int lastPosition=-1;
ActionBar act;
ViewPager myviewpager;
int mSelectedPageIndex=1;
DownloadService downloadservice;
Intent serviceIntent ;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
frag=(DownloadList)getSupportFragmentManager().findFragmentById(android.R.id.content);
if (frag==null) {
frag=new DownloadList();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, frag).commit();
}
if (state != null) {
models=state.getCharSequenceArray(KEY_MODELS);
}
if (downloadservice==null)
downloadservice= new DownloadService();
ArrayAdapter<String> nav=null;
act=getSupportActionBar();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
{
nav= new ArrayAdapter<String>( act.getThemedContext(),android.R.layout.simple_spinner_item,labels);
}
else
{
nav=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,labels);
}
nav.setDropDownViewResource(android.R.layout.simple_list_item_1);
act.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
act.setDisplayShowTitleEnabled(false);
act.setHomeButtonEnabled(false);
act.setListNavigationCallbacks(nav, this);
if (state != null) {
act.setSelectedNavigationItem(state.getInt(KEY_POSITION));
}
serviceIntent= new Intent(Main.this,downloadservice.getClass());
if (startService(serviceIntent)==null)
startService(serviceIntent);
act.setTitle("");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater infalter = getSupportMenuInflater();
infalter.inflate(R.menu.mymenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==R.id.sub1)
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Downlaod New File");
alert.setMessage("Enter URL");
final EditText input = new EditText(this);
alert.setView(input);
input.setText("http://205.196.123.184/ddpha7c5b8lg/616c36j0d1xbztf /Lecture+ppt+Ch2.ppt");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
Log.d("value",value);
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.show();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
lastPosition=itemPosition;
return false;
}
this is SherlockListFragment class
public class DownloadList extends SherlockListFragment {
int index=0;
Button downloadButton;
Button pauseButton;
Button resumeButton;
TextView textLink;
TextView progressbar;
DownloadService downloadservice= new DownloadService();
MyAdapter listadapter;
Intent serviceIntent ;
String state;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getActivity().setContentView(R.layout.downloadlist);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,BundlesavedInstanceState) {
View rootView = inflater.inflate(R.layout.downloadlist, container, false);
return rootView;
}
int getIndex()
{
return index;
}
public class MyAdapter extends ArrayAdapter<NewDownload>
{
private final List<NewDownload> list;
private final Activity context;
Thread t;
public MyAdapter(Context context,List<NewDownload> list) {
super(context, R.layout.list_item, list);
this.context = (Activity) context;
this.list = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getActivity().
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list_item, null);
pauseButton = (Button) row.findViewById(R.id.btn1);
resumeButton = (Button) row.findViewById(R.id.btn2);
textLink = (TextView) row.findViewById(R.id.tv1);
progressbar = (TextView) row.findViewById(R.id.progressBar1);
textLink.setText(downloadservice.
downloads.get(position).getName());
progressbar.setBottom(downloadservice.
downloads.get(position).getDownloadedSize());
progressbar.setTop(downloadservice.
downloads.get(position).getTotalSize());
final int p = position;
final NewDownload r = list.get(p);
if (r.state=="downloading")
{
progressbar.setText("DownLoading...");
pauseButton.setEnabled(true);
resumeButton.setEnabled(false);
}
else if (r.state=="pause")
{
pauseButton.setEnabled(false);
resumeButton.setEnabled(true);
progressbar.setText(r.state);
}
pauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
downloadservice.pause(p);
setListAdapter(listadapter );
}
});
resumeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (getActivity().startService(serviceIntent)==null)
getActivity().startService(serviceIntent);
downloadservice.resume(p);
setListAdapter(listadapter );
}
});
return row;
}
}
this is downloadlist.xml
<ListView
android:id="#+id/list" xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
this is list_item.XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="File Name" />
<TextView
android:id="#+id/progressBar1"
android:layout_width="306dp"
android:layout_height="wrap_content"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/btn1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="34dp"
android:layout_gravity="center_horizontal"
android:text="Pause" />
<Button
android:id="#+id/btn2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="34dp"
android:layout_gravity="right"
android:text="Resume" />
</LinearLayout>
</LinearLayout>
So any one can tell me where is my mistake ?
This error:
Your content must have a ListView whose id attribute is android.R.id.list
means you must use:
<ListView
android:id="#android:id/list"
...
in download.xml.

Categories