Android fragment didn't show using recyclerview - java

I want to create navigation drawer using RecyclerView and use fragment. The menu on navigation drawer are using RecyclerView and when menu is clicked then change to selected fragment.
I have a problem when i click a menu but fragment didn't change
below is my MainActivity.java
package com.ayotong.miranda;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
//First We Declare Titles And Icons For Our Navigation Drawer List View
//This Icons And Titles Are holded in an Array as you can see
String TITLES[] = {"Home","Events","Mail","Shop"};
int ICONS[] = {R.drawable.ic_home,R.drawable.ic_article,R.drawable.ic_stat,R.drawable.ic_about};
//Similarly we Create a String Resource for the name and email in the header view
//And we also create a int resource for profile picture in the header view
String NAME = "Akash Bangad";
String COND = "Healthy";
int PROFILE = R.drawable.teh;
int lastMenu = -1;
private Toolbar toolbar; // Declaring the Toolbar Object
RecyclerView mRecyclerView; // Declaring RecyclerView
RecyclerView.Adapter mAdapter; // Declaring Adapter For Recycler View
RecyclerView.LayoutManager mLayoutManager; // Declaring Layout Manager as a linear layout manager
DrawerLayout Drawer; // Declaring DrawerLayout
ActionBarDrawerToggle mDrawerToggle; // Declaring Action Bar Drawer Toggle
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
/* Assinging the toolbar object ot the view
and setting the the Action bar to our toolbar
*/
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView); // Assigning the RecyclerView Object to the xml View
mRecyclerView.setHasFixedSize(true); // Letting the system know that the list objects are of fixed size
mAdapter = new MyAdapter(TITLES,ICONS,NAME,COND,PROFILE, this);
mRecyclerView.setAdapter(mAdapter); // Setting the adapter to RecyclerView
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();
// Toast.makeText(MainActivity.this, "The Item Clicked is: " + recyclerView.getChildPosition(child), Toast.LENGTH_SHORT).show();
onTouchDrawer(recyclerView.getChildPosition(child));
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
mLayoutManager = new LinearLayoutManager(this); // Creating a layout Manager
mRecyclerView.setLayoutManager(mLayoutManager); // Setting the layout Manager
Drawer = (DrawerLayout) findViewById(R.id.DrawerLayout); // Drawer object Assigned to the view
mDrawerToggle = new ActionBarDrawerToggle(this,Drawer,toolbar,R.string.openDrawer,R.string.closeDrawer){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
// code here will execute once the drawer is opened( As I dont want anything happened whe drawer is
// open I am not going to put anything here)
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
// Code here will execute once drawer is closed
}
}; // Drawer Toggle Object Made
Drawer.setDrawerListener(mDrawerToggle); // Drawer Listener set to the Drawer toggle
mDrawerToggle.syncState(); // Finally we set the drawer toggle sync State
}
private void openFragment(final Fragment fragment) {
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.container,fragment);
ft.commit();
}
public void onTouchDrawer(final int position) {
if (lastMenu == position) return;
switch (lastMenu = position) {
case 1:
openFragment(new Home_fragment());
break;
case 2:
openFragment(new Stat_fragment());
break;
default:
return;
}
}
}
below is Main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/DrawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:elevation="7dp">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<include
android:id="#+id/tool_bar"
layout="#layout/tool_bar"
></include>
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/RecyclerView"
android:layout_width="230dp"
android:layout_height="match_parent"
android:layout_gravity="left"
android:background="#ffffff"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
</android.support.v4.widget.DrawerLayout>
below is fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="HOME MIRANDA"
android:padding="8dp"
android:textColor="#fff"
android:background="#color/colorPrimary"
android:textSize="28sp"
android:id="#+id/textView"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<!--<android.support.v7.widget.RecyclerView-->
<!--android:id="#+id/my_recycler_view"-->
<!--android:scrollbars="vertical"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="match_parent"/>-->
</RelativeLayout>
below is fragment_home.java
package com.ayotong.miranda;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Home_fragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//returning our layout file
//change R.layout.yourlayoutfilename for each of your fragments
return inflater.inflate(R.layout.fragment_home, container, false);
}
}
Please help me to solve this so i can change fragment when menu on navigation drawer is clicked.

Try to call the openFragment() in the onItemTouchListener of the recycler view. Before loading the fragment try to close the drawer and then call the openFragment(). I think it should work. Also check whether the container id is correct.

Related

Bottom Navigation Bar not working inside fragment

I am trying to show a Bottom Navigation Bar with 3 items inside a fragment, and it shows correctly without errors in my code. But the thing is that when I click on one of the options, the code supposed to be run doesn't work, it doesn't even log anything on the console.
TransporteFragment.Java:
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class TransporteFragment extends Fragment {
public TransporteFragment() {
// Required empty public constructor
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_busC1:
return true;
case R.id.action_busC2:
BusC2Fragment busC2Fragment = new BusC2Fragment();
FragmentManager fragmentManager = getChildFragmentManager();
fragmentManager.beginTransaction().replace(R.id.espacioLineas, busC2Fragment).commit();
return true;
case R.id.action_busC3:
return true;
}
return false;
}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_transporte, container, false);
BottomNavigationView navegacion = (BottomNavigationView) v.findViewById(R.id.navbartransporte);
navegacion.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_transporte, container, false);
}
}
fragment_transporte.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.gberti.smarthuesca.TransporteFragment">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/espacioLineas">
</FrameLayout>
<android.support.design.widget.BottomNavigationView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/navbartransporte"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_alignParentBottom="true"
android:background="#color/white"
app:menu="#menu/navbar_transporte_items" />
</RelativeLayout>
Thank you.
In your onCreateView method instead of return inflater.inflate(R.layout.fragment_transporte, container, false); try return v;

'boolean android.support.v7.widget.RecyclerView$LayoutManager.canScrollVertically()'

How to fix my issue when I try to use RecyclerView. When I add 2 line of code
recyclerView = (RecyclerView) findViewById(R.id.movies_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
My code always show error
06-22 19:52:25.801 19743-19743/com.transvision.bertho.transvisiondashboardapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.transvision.bertho.transvisiondashboardapp, PID: 19743
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.transvision.bertho.transvisiondashboardapp/com.transvision.bertho.transvisiondashboardapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
at com.transvision.bertho.transvisiondashboardapp.MainActivity.onCreate(MainActivity.java:53)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
How to fix my issue? It looks like RecyclerView.setLayoutManager but I cant resolve my issue alone.
This is my code (ChannelAdapter.java)
package adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.transvision.bertho.transvisiondashboardapp.R;
import java.util.List;
import model.Channel;
public class ChannelAdapter extends RecyclerView.Adapter<ChannelAdapter.ChannelViewHolder> {
private List<Channel> channels;
private int rowLayout;
private Context context;
public static class ChannelViewHolder extends RecyclerView.ViewHolder {
LinearLayout moviesLayout;
TextView movieTitle;
TextView data;
TextView movieDescription;
TextView rating;
TextView name;
TextView code;
TextView description;
TextView number;
TextView definition;
TextView paket;
ImageView logo;
public ChannelViewHolder(View v) {
super(v);
moviesLayout = (LinearLayout) v.findViewById(R.id.movies_layout);
name = (TextView) v.findViewById(R.id.title);
definition = (TextView) v.findViewById(R.id.subtitle);
description = (TextView) v.findViewById(R.id.description);
// rating = (TextView) v.findViewById(R.id.rating);
}
}
public ChannelAdapter(List<Channel> channels, int rowLayout, Context context) {
this.channels = channels;
this.rowLayout = rowLayout;
this.context = context;
}
#Override
public ChannelAdapter.ChannelViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
return new ChannelViewHolder(view);
}
#Override
public void onBindViewHolder(ChannelViewHolder holder, final int position) {
holder.name.setText(channels.get(position).getName());
holder.definition.setText(channels.get(position).getDefinition());
holder.description.setText(channels.get(position).getDescription());
// holder.rating.setText(channels.get(position).getVoteAverage().toString());
}
#Override
public int getItemCount() {
return channels.size();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
app_bar_main.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:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.transvision.bertho.transvisiondashboardapp.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
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:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/main" />
<android.support.design.widget.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"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
main.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">
<FrameLayout
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
fragment_home.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.transvision.bertho.transvisiondashboardapp.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/movies_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
</RelativeLayout>
and My MainActivity.java
package com.transvision.bertho.transvisiondashboardapp;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import java.util.List;
import adapter.ChannelAdapter;
import model.Channel;
import model.ChannelResponse;
import model.Movie;
import model.MoviesResponse;
import page.DefaultFragment;
import page.HomeFragment;
import page.ProfileFragment;
import rest.ApiClient;
import rest.ApiInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = MainActivity.class.getSimpleName();
private final static String API_KEY = "7e8f60e325cd06e164799af1e317d7a7";
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.movies_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
Fragment fragment = null;
fragment = new DefaultFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.root, fragment);
fragmentTransaction.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment = null;
String title = getString(R.string.app_name);
if (id == R.id.nav_camera) {
fragment = new HomeFragment();
title = "Home";
getChannelData();
} else if (id == R.id.nav_gallery) {
fragment = new ProfileFragment();
title = "Profile";
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.root, fragment);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void getChannelData() {
ApiInterface apiService = ApiClient.getChannel().create(ApiInterface.class);
Call<ChannelResponse> call = apiService.getItems();
call.enqueue(new Callback<ChannelResponse>() {
#Override
public void onResponse(Call<ChannelResponse> call, Response<ChannelResponse> response) {
int statusCode = response.code();
List<Channel> channel = response.body().getItems();
Log.d(TAG, "NUMBER OF MOVIES RECEIVED : " + channel.size());
recyclerView.setAdapter(new ChannelAdapter(channel, R.layout.list_channel, getApplicationContext()));
}
#Override
public void onFailure(Call<ChannelResponse> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
}
public void showToast(String output){
Toast.makeText(this.getBaseContext(), output, Toast.LENGTH_SHORT).show();
}
}
Maybe I forgot to change something, please help...
Thanks
Your recyclerView is null.
Because the RecyclerView is only added when fragment_home.xml is loaded to your activity.
That mean it is ready after (assuming your DefaultFragment is inflate fragment_home.xml)
Fragment fragment = null;
fragment = new DefaultFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.root, fragment);
fragmentTransaction.commit();
You should do the findViewById after that.
However, fragmentTransaction.commit(); is an async process. The fragment content may not be available immediately after that.
So, you will need to call fragmentTransaction.commitNow() to make sure the fragment is added to activity.
recyclerView = (RecyclerView) findViewById(R.id.movies_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
It is not a very good idea to find fragment's view from the activity level. One of the reason is to avoid the situation like you are facing now as fragment content cannot be guaranteed in activity.
The better way is to find and set view content inside the fragment onViewCreated
If your data is get from activity, you can still pass the data to fragment from activity.
See, topics like "communication between fragment and activity"
https://developer.android.com/training/basics/fragments/communicating.html
recyclerView = (RecyclerView) findViewById(R.id.movies_recycler_view);
// The above line doesnot throw null pointer exception, since you can cast null to any object. Refer this post - http://stackoverflow.com/questions/18723596/no-exception-while-type-casting-with-a-null-in-java
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// The above line will throw null pointer exception, since here we are accessing the null object and invoking a method on that null object.
Try like this to avoid the null pointer exception
recyclerView = (RecyclerView) findViewById(R.id.movies_recycler_view);
if(recyclerView != null) {
recyclerView.setLayoutManager(new LinearLayoutManager(this));
.....
.....
.....
}
Either move fragment_home.xml code inside your main.xml file, If you want recyclerView inside your activity. i.e.
main.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">
<FrameLayout
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v7.widget.RecyclerView
android:id="#+id/movies_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
</FrameLayout>
</LinearLayout>
OR
add a Fragment to your activity which inflates fragment_home.xml and move recyclerView initialization code to your fragment. i.e. Below code in your fragment:
recyclerView = (RecyclerView) rootview.findViewById(R.id.movies_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));

onActivityCreated remove layout of Fragment

I'm trying to create an application which deals with fragments.
First, build an application login without using fragments and it worked perfectly, but I tried to be more constructive and create a menu done for me.
I was trying to migrate all that created the Activity Log for Fragments but I'm having trouble trying to pass everything from a place to another.
What happens to me now is that I have actions that were being created in the OnCreate (Activity) and tried to pass all the functions for onCreateView (Fragments) but when I return from view, is not shown me in app layout that was supposed to.
MainActivity:
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nvDrawer;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set tolbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Find our drawer view
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = setupDrawerContent();
// Tie DrawerLayout events to the ActionBarToggle
mDrawer.setDrawerListener(drawerToggle);
// Find our drawer view
nvDrawer = (NavigationView) findViewById(R.id.nvView);
// Setup drawer view
setupDrawerContent(nvDrawer);
}
private ActionBarDrawerToggle setupDrawerContent() {
return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the planet to show based on
// position
Fragment fragment = null;
Class fragmentClass = null;
switch(menuItem.getItemId()) {
case R.id.nav_first_fragment:
fragmentClass = FirstFragment.class;
break;
case R.id.nav_second_fragment:
fragmentClass = SecondFragment.class;
break;
case R.id.nav_third_fragment:
fragmentClass = ThirdFragment.class;
break;
case R.id.nav_status_fragment:
fragmentClass = LoginStatusFragment.class;
break;
case R.id.nav_login_fragment:
fragmentClass = LoginFragment.class;
break;
case R.id.nav_register_fragment:
fragmentClass = ThirdFragment.class;
break;
default:
fragmentClass = FirstFragment.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.flContent, fragment);
fragmentTransaction.commit();
//fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
// Highlight the selected item, update the title, and close the drawer
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawer.closeDrawers();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
else if (item.getItemId() == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// Make sure this is the method with just `Bundle` as the signature
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);
}
}
LoginStatusFragment:
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import java.util.HashMap;
import helper.SQLiteHandler;
import helper.SessionManager;
/**
* Created by NB21094 on 24/11/2015.
*/
public class LoginStatusFragment extends Fragment {
private TextView txtName;
private TextView txtEmail;
private Button btnLogout;
private Context context;
private SQLiteHandler db;
private SessionManager session;
private View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.activity_loginstatus, container, false);
context = getActivity().getApplicationContext();
txtName = (TextView) view.findViewById(R.id.name);
txtEmail = (TextView) view.findViewById(R.id.email);
btnLogout = (Button) view.findViewById(R.id.btnLogout);
// SqLite database handler
db = new SQLiteHandler(context);
// session manager
session = new SessionManager(context);
if (!session.isLoggedIn()) {
logoutUser();
}
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
String name = user.get("name");
String email = user.get("email");
// Displaying the user details on the screen
txtName.setText(name);
txtEmail.setText(email);
// Logout button click event
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logoutUser();
}
});
return view;
//return inflater.inflate(R.layout.activity_loginstatus, container, false);
}
/**
* Logging out the user. Will set isLoggedIn flag to false in shared
* preferences Clears the user data from sqlite users table
* */
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
// Launching the login activity
/*Intent intent = new Intent(LoginStatusActivity.this, MainActivity.class);
startActivity(intent);
finish();*/
changeFragment("main");
}
private void changeFragment(String option){
Fragment fragment = null;
Class fragmentClass = null;
if(option.contains("loginstatus")){
fragmentClass = LoginStatusFragment.class;
} else if (option.contains("register")){
//fragmentClass = LogoutFragment.class;
} else if (option.contains("main")) {
fragmentClass = FirstFragment.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}
}
activity_loginstatus.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" > -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/welcome"
android:textSize="20dp" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:textColor="#color/lbl_name"
android:textSize="24dp" />
<TextView
android:id="#+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="13dp" />
<Button
android:id="#+id/btnLogout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dip"
android:background="#color/btn_logut_bg"
android:text="#string/btn_logout"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="15dp" />
</LinearLayout>
</LinearLayout>
<!-- </RelativeLayout> -->
Can you please help me?
The layout never appear and i dont know why.

Can't get swipe working for swipeable tabs

I am following http://www.android4devs.com/2015/01/how-to-make-material-design-sliding-tabs.html and I have the same code. I can't get the tabs to swipe to each other and I can't view any content in the tabs. My code is below. Thanks for the help!
activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:fab="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="activity.MainActivity">
<include
android:id="#+id/toolbar"
layout="#layout/tool_bar" />
<slidingModel.SlidingTabLayout
android:layout_below="#+id/toolbar"
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="4dp"
android:background="#color/primary_color"
/>
<android.support.v4.view.ViewPager
android:layout_below="#id/tabs"
android:id="#+id/pager"
android:layout_height="0dp"
android:layout_width="match_parent"
/>
<com.melnykov.fab.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
fab:fab_colorNormal="#color/fab_normal"
fab:fab_colorPressed="#color/fab_pressed"
fab:fab_colorRipple="#color/fab_ripple"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
MainActivity.java
package activity;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.gursimran.bei.forte.R;
import adapter.ViewPagerAdapter;
import slidingModel.SlidingTabLayout;
public class MainActivity extends AppCompatActivity {
Toolbar mToolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[] = {"Factorial", "Permutation", "Random"};
int Numboftabs = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.fab_pressed);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
ViewPagerAdapter.java
package adapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import fragment.FactorialTab;
import fragment.PermutationTab;
import fragment.RandomTab;
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
// Build a Constructor and assign the passed Values to appropriate values in the class
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
//This method return the fragment for the every position in the View Pager
#Override
public Fragment getItem(int position) {
if(position == 0) // if the position is 0 we are returning the First tab
{
FactorialTab factorialTab = new FactorialTab();
return factorialTab;
} else if(position == 1) // As we are having 2 tabs if the position is now 0 it must be 1 so we are returning second tab
{
PermutationTab permutationTab = new PermutationTab();
return permutationTab;
}
else {
RandomTab randomTab = new RandomTab();
return randomTab;
}
}
// This method return the titles for the Tabs in the Tab Strip
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
// This method return the Number of tabs for the tabs Strip
#Override
public int getCount() {
return NumbOfTabs;
}
}
Swipe Function control by ViewPager .Your Viewpager layout_height is 0dp in here That's why have problem .
So basically set this way
android:layout_width="match_parent"
android:layout_height="wrap_content"

Adding Multiple Header in drawer list

I want to add multiple header in drawerlist. Right now I am able to add just one header. How to I add header (like categories) in my drawer list?
MainActivity.java
package com.pixalstudio.javaclasses;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements AdapterView.OnItemClickListener {
private Toolbar toolbar;
ListView mDrawerList;
DrawerLayout mDrawerLayout;
ActionBarDrawerToggle mDrawerToggle;
String[] mDrawerListItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConnectivityManager cManager = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
NetworkInfo nInfo = cManager.getActiveNetworkInfo();
if (nInfo != null && nInfo.isConnected()) {
Toast.makeText(this, "Newtwrok Available", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Network Not Available", Toast.LENGTH_LONG).show();
}
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
LayoutInflater inflater = getLayoutInflater();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mDrawerList = (ListView) findViewById(R.id.drawerList);
mDrawerListItems = getResources().getStringArray(R.array.drawer_list);
ViewGroup header_news = (ViewGroup) inflater.inflate(R.layout.nav_header, mDrawerList, false);
mDrawerList.addHeaderView(header_news, null, false);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mDrawerListItems));
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int editPosition = position + 1;
Toast.makeText(MainActivity.this, "You Have Selected " + editPosition, Toast.LENGTH_SHORT).show();
mDrawerLayout.closeDrawer(mDrawerList);
}
});
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout,
toolbar,
R.string.drawer_open,
R.string.drawer_close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
invalidateOptionsMenu();
syncState();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
syncState();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle.syncState();
}
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int editPosition = position + 1;
Toast.makeText(MainActivity.this, "You Have Selected " + editPosition, Toast.LENGTH_SHORT).show();
mDrawerLayout.closeDrawer(mDrawerList);
}
}
activity_main.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:orientation="vertical">
<include
android:id="#+id/app_bar"
layout="#layout/app_bar">
</include>
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<ListView
android:id="#+id/drawerList"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#CE93D8">
</ListView>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
nav_header.xml
android:id="#+id/head1"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimaryDark"
android:padding="16dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
android:orientation="vertical"
android:gravity="bottom">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Header 1"
android:textColor="#android:color/white"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"/>
</LinearLayout>
I tried searching for the solution but every time I mess up with the code. Can someone give me perfect solution for this with code? Thank you in advance. :)
This is how I want like Title 1 and Title 2

Categories

Resources