debug issue with fragment layout - java

This is my java code on Main Activity:
package com.jcc.javier.navegacioncajon;
import android.app.Activity;
import android.support.v4.app.Fragment;
import android.app.FragmentTransaction;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements
Cajon.NavegationDrawerCallbacks {
private Cajon mNavigationDrawerFragment;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (Cajon) getSupportFragmentManager().findFragmentById(R.id.navegacionCajon);
mTitle = getTitle();
mNavigationDrawerFragment.setUp(R.id.navegacionCajon, (DrawerLayout) findViewById(R.id.cajon_layout));
}
#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);
restoreActionBar();
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);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER="numero_Seccion";
public PlaceholderFragment() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.seccion);
textView.setText("Este es el contenido de la seccion " + Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
public static PlaceholderFragment newInstance (int numeroseccion){
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, numeroseccion);
fragment.setArguments(args);
return fragment;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity)activity).onSectionAttached(getArguments().getInt(ARG_SECTION_NUMBER));
}
}
#Override
public void onNavigationDrawerItemSelected(int position) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, PlaceholderFragment.newInstance(position+1)).commit();
}
public void onSectionAttached (int number){
switch (number){
case 1:
mTitle = getString(R.string.seccion1);
break;
case 2:
mTitle = getString(R.string.seccion2);
break;
case 3:
mTitle = getString(R.string.seccion3);
break;
}
}
public void restoreActionBar(){
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
}
this is my code java in Cajon.java:
package com.jcc.javier.navegacioncajon;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
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;
import java.util.zip.Inflater;
/**
* Created by JAVIER on 05/05/2017.
*/
public class Cajon extends Fragment {
/**Interface para apuntador **/
public static interface NavegationDrawerCallbacks {
void onNavigationDrawerItemSelected(int position);
}
private static final String STATE_SELECTED_POSITION="selected_navigation_drawer_position";
private static final String PREF_USER_LEARNED_DRAWER="navigation_drawer_learned";
private NavegationDrawerCallbacks mCallbacks;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mfragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
/**Implementación de clase Cajon **/
public Cajon() {
}
/**Metodo onCreate **/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
/**Validar si existe un valor en la instancia salvada **/
if (savedInstanceState != null){
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
//mDrawerLayout=null;
selectedItem(mCurrentSelectedPosition);
}
/**Metodo onActivityCreated **/
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(R.layout.cajon, container,false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
selectedItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
//getActivity(),
getSupportActionBar().getThemedContext(),
android.R.layout.simple_list_item_1,
android.R.id.text1,
new String[]{
getString(R.string.seccion1),
getString(R.string.seccion2),
getString(R.string.seccion3),
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen(){
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mfragmentContainerView);
}
public void setUp(int fragmentId, DrawerLayout drawerLayout){
mfragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
/**Poner sombra **/
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(),
mDrawerLayout,
R.drawable.ic_drawer,
R.string.abrir_cajon_navegacion,
R.string.cerrar_cajon_navegacion
) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if(!isAdded()){
return;
}
if(!mUserLearnedDrawer){
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).commit();
}
getActivity().supportInvalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if(!isAdded()){
return;
}
getActivity().supportInvalidateOptionsMenu();
}
};
if(!mUserLearnedDrawer && !mFromSavedInstanceState){
mDrawerLayout.openDrawer(mfragmentContainerView);
}
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private ActionBar getSupportActionBar() {
return ((AppCompatActivity)getActivity()).getSupportActionBar();
}
/**Metodo selectedItem **/
private void selectedItem(int position) {
mCurrentSelectedPosition = position;
if(mDrawerListView != null){
mDrawerListView.setItemChecked(position, true);
}
if(mDrawerLayout != null){
mDrawerLayout.closeDrawer(mfragmentContainerView);
}
if(mCallbacks != null){
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public String toString() {
return super.toString();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavegationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement Navigation NavigationDrawerCallbacks. ");
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void setArguments(Bundle args) {
super.setArguments(args);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
private void showGlobalContextActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mDrawerToggle.onOptionsItemSelected(item)){
return true;
}
if(item.getItemId()==R.id.action_example){
Toast.makeText(getActivity(), "Navegacion Cajon", Toast.LENGTH_LONG).show();
return true;
}
return super.onOptionsItemSelected(item);
}
}
And these ones are my .xml files:
MainActivity:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/cajon_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.jcc.javier.navegacioncajon.MainActivity"
tools:ignore="MergeRootFrame">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<fragment
android:id="#+id/navegacionCajon"
android:name = "com.jcc.javier.navegacioncajon.Cajon"
android:layout_width="#dimen/navegacionCajon"
android:layout_height="match_parent"
android:layout_gravity="start"
tools:layout="#layout/cajon" />
</android.support.v4.widget.DrawerLayout>
GLobal:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never" />
</menu>
Main:
<menu 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"
tools:context="com.jcc.javier.navegacioncajon.MainActivity">
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never" />
<item
android:id="#+id/action_example"
android:title="#string/action_example"
app:showAsAction="ifRoom|withText"></item>
</menu>
Fragment main:
<?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"
android:background="#81F79F"
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="com.jcc.javier.navegacioncajon.MainActivity$PlaceholderFragment">
<TextView
android:id="#+id/seccion"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:textSize="20sp" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Contenido"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
Cajon:
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#008FFF">
</ListView>
and my logcat display this message:
05-24 21:36:50.374 3881-3881/com.jcc.javier.navegacioncajon
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.jcc.javier.navegacioncajon, PID: 3881
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.jcc.javier.navegacioncajon/com.jcc.javier.navegacioncajon.MainActivity}: android.view.InflateException: Binary XML file line #18: Binary XML file line #18: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: android.view.InflateException: Binary XML file line #18: Binary XML file line #18: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #18: Error inflating class fragment
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.support.v7.app.ActionBar.getThemedContext()' on a null object reference
at com.jcc.javier.navegacioncajon.Cajon.onCreateView(Cajon.java:100)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1255)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1472)
at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1691)
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3440)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:378)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:33)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:79)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:777)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.jcc.javier.navegacioncajon.MainActivity.onCreate(MainActivity.java:32)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
I need for solve this error because i cannot run my aplication.

getSupportActionBar() returned null. Make sure your activity is using a theme which provides an ActionBar (an AppCompat theme) or use setSupportActionBar(toolbar) in your MainActivity.onCreate().

Change this:
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext()
To:
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActivity(),

Related

cannot set tab layout inside fragment

I am trying to set a tab layout inside a fragment and call it by an option inside navigation drawer but I am getting a null object reference error.
I am setting my navigation drawer inside Main2Activity
Main2Activity
import android.content.Intent;
import android.os.Bundle;
import com.bumptech.glide.Glide;
import com.example.fireapp.model.Users;
import com.firebase.ui.auth.AuthUI;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.tabs.TabLayout;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.text.Layout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import com.example.fireapp.ui.main.SectionsPagerAdapter;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import de.hdodenhof.circleimageview.CircleImageView;
public class Main2Activity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private View headerView;
private TextView usernameText;
private TextView emailText;
private CircleImageView userImage;
private FirebaseUser firebaseUser;
private DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
//toolbar
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("fireApp");
//navigation drawer
drawerLayout = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
//user details
navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
headerView = navigationView.getHeaderView(0);
usernameText = headerView.findViewById(R.id.usernameText);
userImage = headerView.findViewById(R.id.userImage);
emailText = headerView.findViewById(R.id.userEmail);
setUserDetails();
// if(savedInstanceState==null) {
// getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
// new chatFragment()).commit();
// navigationView.setCheckedItem(R.id.nav_chat);
// }
}
private void setUserDetails() {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("User").child(firebaseUser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Users user = dataSnapshot.getValue(Users.class);
usernameText.setText(user.getUsername());
emailText.setText(firebaseUser.getEmail());
if (user.getImageUrl().equals("default")) {
userImage.setImageResource(R.mipmap.ic_launcher);
} else {
Glide.with(getApplicationContext()).load(user.getImageUrl()).into(userImage);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch(menuItem.getItemId()){
case R.id.nav_chat:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new chatFragment()).commit();
break;
case R.id.nav_share:
Toast.makeText(this, "Share!", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_feedback:
Toast.makeText(this, "Feedback!", Toast.LENGTH_SHORT).show();
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
//3 dots menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.logout) {
AuthUI.getInstance()
.signOut(Main2Activity.this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
startActivity(new Intent(Main2Activity.this, MainActivity.class));
finish();
}
});
return true;
} else
return false;
}
}
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.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:context=".Main2Activity"
tools:openDrawer="end">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<com.google.android.material.navigation.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:id="#+id/nav_view"
app:headerLayout="#layout/drawer_header"
app:menu="#menu/drawer_menu"></com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
chatFragment
package com.example.fireapp;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.fireapp.ui.main.SectionsPagerAdapter;
import com.google.android.material.tabs.TabLayout;
public class chatFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_chat,container,false);
tabLayout=view.findViewById(R.id.tabs);
viewPager=view.findViewById(R.id.view_pager);
viewPager.setAdapter(new SectionsPagerAdapter(getChildFragmentManager()));
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return view;
}
}
fragment_chat.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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".chatFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary" />
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</FrameLayout>
SectionPagerAdapter
package com.example.fireapp.ui.main;
import android.content.Context;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import com.example.fireapp.R;
import com.example.fireapp.tab1;
import com.example.fireapp.tab2;
import com.example.fireapp.tab3;
import java.util.List;
/**
* A [FragmentPagerAdapter] that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
#StringRes
private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2,R.string.tab_text_3};
private Context mContext ;
public SectionsPagerAdapter(Context context, FragmentManager fm) {
super(fm);
mContext = context;
}
public SectionsPagerAdapter(FragmentManager childFragmentManager) {
super(childFragmentManager);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0 :
tab1 tab1 = new tab1();
return tab1;
case 1:
tab2 tab2 = new tab2();
return tab2;
case 2:
tab3 tab3 = new tab3();
return tab3;
}
return null;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return mContext.getResources().getString(TAB_TITLES[position]);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
I am getting the following error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.fireapp, PID: 6785
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at com.example.fireapp.ui.main.SectionsPagerAdapter.getPageTitle(SectionsPagerAdapter.java:61)
at com.google.android.material.tabs.TabLayout.populateFromPagerAdapter(TabLayout.java:1323)
at com.google.android.material.tabs.TabLayout.setPagerAdapter(TabLayout.java:1314)
at com.google.android.material.tabs.TabLayout.setupWithViewPager(TabLayout.java:1227)
at com.google.android.material.tabs.TabLayout.setupWithViewPager(TabLayout.java:1188)
at com.google.android.material.tabs.TabLayout.setupWithViewPager(TabLayout.java:1168)
at com.example.fireapp.chatFragment$1.run(chatFragment.java:32)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
I am new to android development please help.
java.lang.NullPointerException: Attempt to invoke virtual method
'android.content.res.Resources android.content.Context.getResources()'
on a null object reference
NullPointerException is thrown when an application attempts to use an object reference that has the null value.
You can try with this
private String TAB_TITLES[] = new String[]{"Tab1", "Tab2", "Tab3"};
Then
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return TAB_TITLES[position];
}
getPageTitle() - This method may be called by the ViewPager to obtain a title string to describe the specified page.

Unable to start activity ComponentInfo | E/AndroidRuntime: FATAL EXCEPTION

Greeting everyone, I'm trying to make an app with a navigational drawer and capable of having selectable contacts in one of the drawers but it keeps crashing.The app I built worked great for displaying the contact. When I started trying to implement the clicking on the contacts to navigate to another Fragment which would have the contact info, The App Wouldn't launch. Any help, even to point me in the right direction is greatly appreciated.
Project File
Main Activity Java Fragment
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
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.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.example.v1z0.assignments.Utils.*;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Log.d(TAG, "onCreate: started");
initImageLoader();
init();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
private void initImageLoader()
{
UniversalImageLoader universalImageLoader = new UniversalImageLoader(MainActivity.this);
ImageLoader.getInstance().init(universalImageLoader.getConfig());
}
#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();
if (id == R.id.nav_activity_faculty) {
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame,
new ViewContactsFragment()).commit();
} else if (id == R.id.nav_second_layout) {
getFragmentManager().beginTransaction().replace(R.id.content_frame,
new SecondFragment()).commit();
} else if (id == R.id.nav_third_layout) {
getFragmentManager().beginTransaction().replace(R.id.content_frame,
new ThirdFragment()).commit();
} else if (id == R.id.nav_fourth_layout) {
getFragmentManager().beginTransaction().replace(R.id.content_frame,
new FourthFragment()).commit();
} else if (id == R.id.nav_fifth_layout) {
getFragmentManager().beginTransaction().replace(R.id.content_frame,
new FifthFragment()).commit();
} else if (id == R.id.nav_sixth_layout) {
getFragmentManager().beginTransaction().replace(R.id.content_frame,
new SixthFragment()).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void init()
{
{
ViewContactsFragment fragment = new ViewContactsFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
}
My Contact Fragment
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ContactFragment extends Fragment {
private static final String TAG = "ContactFragment";
public ContactFragment(){
super();
setArguments(new Bundle());
}
private Toolbar toolbar;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_contact, container, false);
toolbar = (Toolbar) view.findViewById(R.id.contactToolbar);
Log.d(TAG, "onCreateView: started");
//Toolbar Pre-req//
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
setHasOptionsMenu(true);
//Go Back//
ImageView ivBackArrow = (ImageView) view.findViewById(R.id.ivBackArrow);
ivBackArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: clicked back arrow");
getActivity().getSupportFragmentManager().popBackStack();
}
});
//Go To Edit//
ImageView ivEdit = (ImageView) view.findViewById(R.id.ivEdit);
ivEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: clicked edit");
EditContactFragment fragment = new EditContactFragment();
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.addToBackStack(getString(R.string.edit_contact_fragment));
Log.d(TAG, "onClick: fragment" + getString(R.string.edit_contact_fragment));
transaction.commit();
}
});
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.contact_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.menuitem_delete:
Log.d(TAG, "onOptionsItemSelected: deleting contact");
}
return super.onOptionsItemSelected(item);
}
}
Also the View Contact Fragment holding the contact information
import android.content.Context;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import java.util.ArrayList;
import com.example.v1z0.assignments.Models.Contact;
import com.example.v1z0.assignments.Utils.CustomListAdapter;
public class ViewContactsFragment extends Fragment {
private static final String TAG = "FirstFragment";
//images
private String testImageURL = "cis.ncu.edu.jm/images/faculty/man.jpg";
private String hgraham = "cis.ncu.edu.jm/images/faculty/hgraham.jpg";
private String dmitchell = "cis.ncu.edu.jm/images/faculty/dmitchell.png";
private String mnarayana = "cis.ncu.edu.jm/images/faculty/mnarayana.jpg";
private String hosborne = "cis.ncu.edu.jm/images/faculty/hosborne.jpg";
private String mreid = "cis.ncu.edu.jm/images/faculty/mreid.jpg";
private String esmall = "cis.ncu.edu.jm/images/faculty/esmall.jpg";
private String hsmith = "cis.ncu.edu.jm/images/faculty/hsmith.jpg";
private String ktooma = "cis.ncu.edu.jm/images/faculty/ktooma.jpg";
//widgets etc
private static final int STANDARD_APPBAR = 0;
private static final int SEARCH_APPBAR = 1;
private int mAppBarState;
private AppBarLayout viewContactsBar, searchBar;
private CustomListAdapter adapter;
private ListView contactsList;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_viewcontacts, container, false);
viewContactsBar = (AppBarLayout) view.findViewById(R.id.viewContactsToolbar);
searchBar = (AppBarLayout) view.findViewById(R.id.searchtoolbar);
contactsList = (ListView) view.findViewById(R.id.contactsList);
Log.d(TAG, "onCreate: started");
setAppBarState(STANDARD_APPBAR);
setupContactsList();
//add contact navigation//
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fabAddContact);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: clicked fab");
}
});
//search contact navigation//
ImageView ivSearchContact = (ImageView) view.findViewById(R.id.ivSearchIcon);
ivSearchContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: clicked search");
toggleToolBarState();
}
});
ImageView ivBackArrow = (ImageView) view.findViewById(R.id.ivBackArrow);
ivBackArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: clicked back arrow");
toggleToolBarState();
}
});
return view;
}
private void setupContactsList()
{
final ArrayList<Contact> contacts = new ArrayList<>();
contacts.add(new Contact("Mr. Sheldon Glenn ", "(876) 963-7281", "work", "sheldon.glenn#ncu.edu.jm ", testImageURL));
contacts.add(new Contact("Mr. Hamlet Graham ", "(876) 963-7278", "work", "hamlet.graham#ncu.edu.jm ", hgraham));
contacts.add(new Contact("Mr. Oche Magbegor ", "(876) 963-7280", "work", "oche.magbegor#ncu.edu.jm ", testImageURL));
contacts.add(new Contact("Mr. Damion Mitchell ", "(876) 963-7285", "work", "damion.mitchell AT ncu.edu.jm ", dmitchell));
contacts.add(new Contact("Mr. Melvin Narayana ", "(876) 963-7279", "work", "melvin.narayana#ncu.edu.jm", mnarayana));
contacts.add(new Contact("Mr. Henry Osborne ", "(876) 963-7282", "work", "Henry.Osborne#ncu.edu.jm ", hosborne));
contacts.add(new Contact("Mr. Marlon Richards ", " (876) 963-7276", "work", "marlon.richards#ncu.edu.jm", testImageURL));
contacts.add(new Contact("Mrs. E. Beverley Small ", "(876) 963-7276", "work", "esmall#ncu.edu.jm ", esmall));
contacts.add(new Contact("Mr. Halzen Smith ", "(876) 963-7284", "work", "hsmith#ncu.edu.jm ", hsmith));
contacts.add(new Contact("Mr. Keron Tooma ", " (876) 963-7283", "work", "keron.tooma#ncu.edu.jm ", ktooma));
adapter = new CustomListAdapter(getActivity(), R.layout.layout_contactslistitem, contacts, "http://");
contactsList.setAdapter(adapter);
contactsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
{
Log.d(TAG, "onClick: navigating to contact" + (R.string.contact_fragment));
ContactFragment fragment = new ContactFragment();
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.addToBackStack(getString(R.string.edit_contact_fragment));
Log.d(TAG, "onClick: fragment" + getString(R.string.contact_fragment));
transaction.commit();
}
});
}
private void toggleToolBarState()
{
Log.d(TAG, "toggleToolBarState: toggling AppBatState");
if (mAppBarState == STANDARD_APPBAR)
{
setAppBarState(SEARCH_APPBAR);
}
else
{
setAppBarState(STANDARD_APPBAR);
}
}
#Override
public void onResume() {
super.onResume();
setAppBarState(STANDARD_APPBAR);
}
private void setAppBarState(int state)
{
Log.d(TAG, "setAppBarState: changing app bar state to" + state);
mAppBarState = state;
if (mAppBarState == STANDARD_APPBAR)
{
searchBar.setVisibility(View.GONE);
viewContactsBar.setVisibility(View.VISIBLE);
//keyboard hide//
View view = getView();
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
try
{
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}catch (NullPointerException e)
{
Log.d(TAG, "setAppBarState: NullPointerException" + e.getMessage());
}
}
else if (mAppBarState == SEARCH_APPBAR)
{
viewContactsBar.setVisibility(View.GONE);
searchBar.setVisibility(View.VISIBLE);
//keyboard show//
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
}
LogCat Error
--------- beginning of crash
2018-10-14 01:48:19.869 7041-7041/com.example.v1z0.assignments E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.v1z0.assignments, PID: 7041
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.v1z0.assignments/com.example.v1z0.assignments.MainActivity}: java.lang.IllegalArgumentException: No view found for id 0x7f080055 (com.example.v1z0.assignments:id/fragment_container) for fragment ViewContactsFragment{dcf4537 #0 id=0x7f080055}
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f080055 (com.example.v1z0.assignments:id/fragment_container) for fragment ViewContactsFragment{dcf4537 #0 id=0x7f080055}
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1422)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1759)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1827)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:797)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2596)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2383)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2338)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2245)
at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3248)
at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3200)
at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:195)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:597)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1334)
at android.app.Activity.performStart(Activity.java:7029)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2741)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6494) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 
XML Fragments
Solo Contact Page
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/relLayout1">
<include layout="#layout/snippet_contacttoolbar"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/relLayout1"
android:id="#+id/relLayout2">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
app:civ_border_color="#color/black"
app:civ_border_width="1dp"
android:id="#+id/contactImage" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/contactImage"
android:layout_marginTop="30dp"
android:textSize="30sp"
android:textColor="#color/black"
android:layout_marginStart="30dp"
android:id="#+id/tvName" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/tvName"
android:id="#+id/lvContactProperties">
</ListView>
</RelativeLayout>
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
View Contact List Fragment
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#drawable/first">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/relLayout1">
<include layout="#layout/snippet_searchtoolbar"/>
<include layout="#layout/snippet_viewcontactstoolbar"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/relLayout1">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/contactsList"></ListView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="25sp"
android:id="#+id/textNoContacts"
android:textColor="#color/black"
/>
</RelativeLayout>
</RelativeLayout>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:elevation="10dp"
app:fabSize="normal"
app:rippleColor="#color/colorAccent"
android:src="#drawable/ic_person_add"
android:id="#+id/fabAddContact"/>
</android.support.design.widget.CoordinatorLayout>
Edit Page
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.constraint.ConstraintLayout>
I apologize for the lengthy question
In your init() methond of MainActivity class file, you reference incorrect resource id.
private void init()
{
{
ViewContactsFragment fragment = new ViewContactsFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame, fragment);//not R.id.fragment_container
transaction.addToBackStack(null);
transaction.commit();
}
}
In addition to navylover answer. I also changed Fragment_container in my ViewContactFragment and it worked
contactsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id)
{
Log.d(TAG, "onClick: navigating to contact" + (R.string.contact_fragment));
ContactFragment fragment = new ContactFragment();
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame, fragment);
transaction.addToBackStack(getString(R.string.edit_contact_fragment));
Log.d(TAG, "onClick: fragment contentFrame" );
transaction.commit();
}
});

use navigation drawer in all activities in my project

I have created a navigation drawer in my AbstractActivity.class and i want to use that drawer in all my activities , so i created another drawer class and extending that class in another activity but it isnt working , can anyonetell me whats wrong in my code ?
Abstractactivity.class
package com.astro.famouspandit.Activities.Abstract;
import android.content.Intent;
import android.content.res.Configuration;
import android.media.Image;
import android.os.Bundle;
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;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.astro.famouspandit.Activities.Activity.ChartStyle;
import com.astro.famouspandit.Activities.Activity.Contact;
import com.astro.famouspandit.Activities.Activity.Settings;
import com.astro.famouspandit.Activities.Activity.Welcome;
import com.astro.famouspandit.R;
public class AbstractActivity extends AppCompatActivity {
private String[] mPlanetTitles;
private LinearLayout mDrawerList;
protected DrawerLayout mDrawerLayout;
protected ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
protected Toolbar toolbar;
protected FrameLayout framelayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_abstract);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (LinearLayout) findViewById(R.id.left_drawer);
framelayout = (FrameLayout)findViewById(R.id.content_frame);
mTitle = mDrawerTitle = getTitle().toString();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
toolbar, R.string.drawer_open, R.string.drawer_close){
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_Aboutus).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
private void selectItem(int position) {
switch(position) {
case 1:
Intent a = new Intent(this, Welcome.class);
startActivity(a);
break;
case 2:
Intent b = new Intent(this, Welcome.class);
startActivity(b);
break;
default:
}
}
public boolean onOptionsItemSelected(MenuItem item){
int items = item.getItemId();
switch(items){
case R.id.action_Settings:{
Intent intent = new Intent(this,Settings.class);
startActivity(intent);
}break;
case R.id.action_Contact_us:{
Intent intent = new Intent(this,Contact.class);
startActivity(intent);
}break;
case R.id.action_Aboutus:{
Intent intent = new Intent(this,ChartStyle.class);
startActivity(intent);
}break;
case R.id.action_Profile:{
Intent intent = new Intent(this,ChartStyle.class);
startActivity(intent);
}break;
}
return super.onOptionsItemSelected(item);
}
}
activity_abstract.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="#layout/toolbar"/>
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<LinearLayout android:id="#+id/left_drawer"
android:layout_width="280dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:orientation="vertical"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#0F6177">
<LinearLayout android:id="#+id/view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<include layout="#layout/navigation_drawer"></include>
</LinearLayout>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
NavigationActivity.class
package com.astro.famouspandit.Activities.Abstract;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
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.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import com.astro.famouspandit.R;
public abstract class NavigationActivity extends AppCompatActivity implements View.OnClickListener{
protected DrawerLayout mDrawerLayout;
private LinearLayout mFrameLayout_HeaderView;
protected FrameLayout mFrameLayout_ContentFrame;
protected ActionBarDrawerToggle mActionBarDrawerToggle;
protected Toolbar mToolbar;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
mFrameLayout_ContentFrame = (FrameLayout) findViewById(R.id.main_activity_content_frame);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
mFrameLayout_HeaderView = (LinearLayout) findViewById(R.id.mainLayout);
mFrameLayout_HeaderView.setOnClickListener(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.main_activity_DrawerLayout);
mDrawerLayout.closeDrawers();
mDrawerLayout.setStatusBarBackground(R.color.colorPrimary);
mActionBarDrawerToggle = new ActionBarDrawerToggle
(
this,
mDrawerLayout,
mToolbar,
R.string.drawer_open,
R.string.drawer_close
) {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
// Disables the burger/arrow animation by default
super.onDrawerSlide(drawerView, 0);
}
};
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
mActionBarDrawerToggle.syncState();
}
}
activity_navigationactivity.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_activity_DrawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<!-- The main content view -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar" />
<FrameLayout
android:id="#+id/main_activity_content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<!-- The navigation drawer -->
<include layout="#layout/navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
class where i am extending NavigationActivity Class
public class Welcome extends NavigationActivity implements View.OnClickListener{
private CardView mAstro,mMatch,mPanch,mAsk,mContact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.activity_welcome,mFrameLayout_ContentFrame);
This is a fairly common question has been blogged about. Essentially, you want to create a BaseActivity with a layout that contains the Navigation Drawer and then have your other Activities extend the BaseActivity and inflate their layouts within the BaseActivity's layout. This way you have the Navigation Drawer in all your activity and reuse the code for setting up the Drawer (since that code lives in the BaseActivity).
You can find an example implementation along with a more detailed explanation here: http://lucas-dev.com/blog/entry/base-activities-sliding-menu.html

how can i add an image header to my navigation drawer layout

how can i add an image header to my navigation drawer layout like this one. the problem i now have is that every listitem has it's own icon but the header image is also printed on every item.
this is what i want
What i now have is this:
this is what i have now
mainactivity.java
main activity.java
package be.yvandamme.ginlovers.activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.google.android.gms.analytics.GoogleAnalytics;
import be.yvandamme.ginlovers.R;
import be.yvandamme.ginlovers.WebViewAppApplication;
import be.yvandamme.ginlovers.adapter.DrawerAdapter;
import be.yvandamme.ginlovers.fragment.MainFragment;
public class MainActivity extends ActionBarActivity
{
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private ListView mDrawerListView;
private CharSequence mTitle;
private CharSequence mDrawerTitle;
private String[] mTitles;
public static Intent newIntent(Context context)
{
Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
return intent;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupActionBar();
setupDrawer(savedInstanceState);
// init analytics tracker
((WebViewAppApplication) getApplication()).getTracker();
}
#Override
public void onStart()
{
super.onStart();
// analytics
GoogleAnalytics.getInstance(this).reportActivityStart(this);
}
#Override
public void onResume()
{
super.onResume();
}
#Override
public void onPause()
{
super.onPause();
}
#Override
public void onStop()
{
super.onStop();
// analytics
GoogleAnalytics.getInstance(this).reportActivityStop(this);
}
#Override
public void onDestroy()
{
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// action bar menu
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// open or close the drawer if home button is pressed
if(mDrawerToggle.onOptionsItemSelected(item))
{
return true;
}
// action bar menu behaviour
switch(item.getItemId())
{
case android.R.id.home:
Intent intent = MainActivity.newIntent(this);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfiguration)
{
super.onConfigurationChanged(newConfiguration);
mDrawerToggle.onConfigurationChanged(newConfiguration);
}
#Override
public void setTitle(CharSequence title)
{
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
private void setupActionBar()
{
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar bar = getSupportActionBar();
bar.setDisplayUseLogoEnabled(false);
bar.setDisplayShowTitleEnabled(true);
bar.setDisplayShowHomeEnabled(true);
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
}
private void setupDrawer(Bundle savedInstanceState)
{
mTitle = getTitle();
mDrawerTitle = getTitle();
// title list
mTitles = getResources().getStringArray(R.array.navigation_title_list);
// icon list
TypedArray iconTypedArray = getResources().obtainTypedArray(R.array.navigation_icon_list);
Integer[] icons = new Integer[iconTypedArray.length()];
for(int i=0; i<iconTypedArray.length(); i++)
{
icons[i] = iconTypedArray.getResourceId(i, -1);
}
iconTypedArray.recycle();
// reference
mDrawerLayout = (DrawerLayout) findViewById(R.id.activity_main_layout);
mDrawerListView = (ListView) findViewById(R.id.activity_main_drawer);
// set drawer
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerListView.setAdapter(new DrawerAdapter(this, mTitles, icons));
mDrawerListView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View clickedView, int position, long id)
{
selectDrawerItem(position, false);
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close)
{
#Override
public void onDrawerClosed(View view)
{
getSupportActionBar().setTitle(mTitle);
supportInvalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView)
{
getSupportActionBar().setTitle(mDrawerTitle);
supportInvalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
// show initial fragment
if(savedInstanceState == null)
{
selectDrawerItem(0, true);
}
}
private void selectDrawerItem(int position, boolean init)
{
String[] urlList = getResources().getStringArray(R.array.navigation_url_list);
String[] shareList = getResources().getStringArray(R.array.navigation_share_list);
Fragment fragment = MainFragment.newInstance(urlList[position], shareList[position]);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.activity_main_container, fragment).commitAllowingStateLoss();
mDrawerListView.setItemChecked(position, true);
if(!init) setTitle(mTitles[position]);
mDrawerLayout.closeDrawer(mDrawerListView);
}
}
drawer adapter.java
package be.yvandamme.ginlovers.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import be.yvandamme.ginlovers.R;
public class DrawerAdapter extends BaseAdapter
{
private Context mContext;
private String[] mTitleList;
private Integer[] mIconList;
public DrawerAdapter(Context context, String[] titleList, Integer[] iconList)
{
mContext = context;
mTitleList = titleList;
mIconList = iconList;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
// inflate view
View view = convertView;
if(view == null)
{
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.drawer_item, parent, false);
// view holder
ViewHolder holder = new ViewHolder();
holder.titleTextView = (TextView) view.findViewById(R.id.drawer_item_title);
holder.iconImageView = (ImageView) view.findViewById(R.id.drawer_item_icon);
view.setTag(holder);
}
// entity
String title = mTitleList[position];
Integer icon = mIconList[position];
if(title!=null && icon!=null )
{
// view holder
ViewHolder holder = (ViewHolder) view.getTag();
// content
holder.titleTextView.setText(title);
holder.iconImageView.setImageResource(icon);
}
return view;
}
#Override
public int getCount()
{
if(mTitleList!=null) return mTitleList.length;
else return 0;
}
#Override
public Object getItem(int position)
{
if(mTitleList!=null) return mTitleList[position];
else return null;
}
#Override
public long getItemId(int position)
{
return position;
}
public void refill(Context context, String[] titleList, Integer[] iconList)
{
mContext = context;
mTitleList = titleList;
mIconList = iconList;
notifyDataSetChanged();
}
static class ViewHolder
{
TextView titleTextView;
ImageView iconImageView;
}
}
this is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/activity_main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/activity_main_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
<ListView
android:id="#+id/activity_main_drawer"
android:layout_width="#dimen/drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:drawSelectorOnTop="true"
android:fastScrollEnabled="false"
android:listSelector="#drawable/selector_clickable_item_bg"
android:background="#color/global_bg_front"
/>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
and this my drawer_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="#dimen/global_spacing_l"
android:gravity="center_vertical"
android:orientation="horizontal"
android:background="?attr/drawerItemBackground">
<ImageView
android:id="#+id/drawer_image"
android:layout_width="280dp"
android:layout_height="140dp"
android:src="#drawable/loading" />
<ImageView
android:id="#+id/drawer_item_icon"
android:layout_width="#dimen/global_spacing_m"
android:layout_height="#dimen/global_spacing_m"
android:layout_marginLeft="#dimen/global_keyline_s"
android:layout_marginRight="#dimen/global_spacing_xs"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:layout_below="#+id/drawer_image"/>
<TextView
android:id="#+id/drawer_item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="#dimen/global_keyline_s"
android:textAppearance="#style/TextAppearance.WebViewApp.Body1"
android:layout_below="#+id/drawer_image"/>
</RelativeLayout>
Try by add header view to your listview (header will also scroll in this case), You need to do like this in your MainActivity :
View header = (View) getLayoutInflater().inflate(
R.layout.header_layout, null);
ImageView img=(ImageView)header.findViewById(R.id.imgView);
img.setBackgroundResource(R.drawable.icon);
mainListView.addHeaderView(header);
Or you can use DesignLibrary like here or here.
Add another view in your XML and position it above activity_main_drawer inside your DrawerLayout. The header is probably not supposed to scroll so it shouldn't be in your listview. Also, remove drawer_image from the listview item layout. Since it's not supposed to be in all the items.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/activity_main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/activity_main_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
<LinearLayout
android:layout_width="#dimen/drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:orientation="vertical">
<ImageView
android:id="#+id/drawer_image"
android:layout_width="280dp"
android:layout_height="140dp"
android:src="#drawable/loading" />
<ListView
android:id="#+id/activity_main_drawer"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:choiceMode="singleChoice"
android:drawSelectorOnTop="true"
android:fastScrollEnabled="false"
android:listSelector="#drawable/selector_clickable_item_bg"
android:background="#color/global_bg_front"
/>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
Or use http://developer.android.com/reference/android/support/design/widget/NavigationView.html and add your image as header view.
navView = (NavigationView) findViewById(R.id.navView);
navView.inflateHeaderView(R.layout.myheader)
or in XML
app:headerLayout="#layout/myheader"

What is best example for Navigation Drawer in Material Design in low API

I trying find more info how create best Navigation Drawer panel with Material Desing's guidelines.
Google recommended page Creating a Navigation Drawer. This example based on Support Library v4.
Also link about v7 AppCompat v21 — Material Design for Pre-Lollipop Devices!. This work fine only on Android API 21+. I can't use this Material Desing in lower OS's vesion, because If I set target=android-20 (or less) in project.properties I get errors in Eclipse (several hundred):
C:\<workspace>\android-support-v7-appcompat\res\values-v21\styles_base.xml:75: error: Error retrieving parent for item: No resource found that matches the given name 'android:Widget.Material.ActionButton'
....
:( several hundred error in 'values-v21' directory
....
I use features of low Android API, that was deprecated or undefined in Android API 21+. But I need support Material Design in low API (14+).
Please give examples of creating Navigation Drawer on low Android API 14+.
Use this as a dependency :
compile "com.android.support:appcompat-v7:21.0.2" (or use newer)
Layout :
<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">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="#layout/toolbar"
android:id="#+id/mytoolbardrawer"
/>
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_below="#id/mytoolbardrawer"
android:layout_height="match_parent"
/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/rel_drawer"
android:layout_width="304dp"
android:layout_height="match_parent"
android:layout_gravity="start"
>
<ImageView
android:layout_width="match_parent"
android:layout_height="171dp"
android:id="#+id/img_drawer"
android:scaleType="centerCrop"
android:src="#drawable/photo_4"/>
<ListView
android:id="#+id/list_slidermenu"
android:layout_below="#id/img_drawer"
android:layout_width="304dp"
android:listSelector="#drawable/list_selector"
android:checkable="true"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:paddingStart="16dp"
android:paddingEnd="16dp"
android:dividerHeight="1dp"
android:theme="#style/ThemeOverlay.AppCompat.Light"
android:background="#android:color/white" />
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
Drawer Activity :
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
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.text.Html;
import android.text.SpannableString;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
public class DrawerActivity extends ActionBarActivity {
Toolbar t;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private RelativeLayout mRelativeLayout;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle,mTitle;
private String[] navMenuItems;
private SpannableString[] navmenuItems;
private ArrayAdapter<SpannableString> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer);
t=(Toolbar)findViewById(R.id.mytoolbardrawer);
setSupportActionBar(t);
initStuffs();
if (savedInstanceState == null) {
new SliderMenuClickListener().displayView(0);
}
}
private void initStuffs() {
mTitle=mDrawerTitle=getTitle();
navMenuItems=getResources().getStringArray(R.array.Titles);
mDrawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerList=(ListView)findViewById(R.id.list_slidermenu);
mRelativeLayout=(RelativeLayout)findViewById(R.id.rel_drawer);
navmenuItems=new SpannableString[navMenuItems.length];
for(int i=0;i<navMenuItems.length;i++) {
navmenuItems[i] = new SpannableString(Html.fromHtml("<font color='#000000'>" + navMenuItems[i] + "</font>"));
}
adapter=new ArrayAdapter<SpannableString>(DrawerActivity.this,android.R.layout.simple_list_item_1,navmenuItems);
mDrawerList.setAdapter(adapter);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle=new ActionBarDrawerToggle(DrawerActivity.this,mDrawerLayout,t,R.string.app_name,R.string.app_name){
public void onDrawerClosed(View view){
getSupportActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View view){
getSupportActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerList.setOnItemClickListener(new SliderMenuClickListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.drawer, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean drawerOpen=mDrawerLayout.isDrawerOpen(mRelativeLayout);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void setTitle(CharSequence title) {
super.setTitle(title);
mTitle=title;
getSupportActionBar().setTitle(mTitle);
}
#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.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class SliderMenuClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
displayView(position);
}
private void displayView(int position) {
Fragment fragment=null;
switch (position){
case 0:
fragment=new HomeFragment();
break;
case 1:
fragment=new HomeFragment();
break;
case 2:
fragment=new HomeFragment();
break;
case 3:
fragment=new HomeFragment();
break;
default:break;
}
if(fragment!=null){
FragmentManager fm=getSupportFragmentManager();
fm.beginTransaction().replace(R.id.frame_container,fragment).commit();
mDrawerList.setItemChecked(position,true);
mDrawerList.setSelection(position);
setTitle(navMenuItems[position]);
mDrawerLayout.closeDrawer(mRelativeLayout);
}else{
Log.e("DrawerActivity","Error creating fragment");
}
}
}
}

Categories