Android Navigation Drawer custom ListView not responding to Click - android

I'm using this tutorial to add sliding menu to my app:
http://www.tutorialsbuzz.com/2014/03/android-sliding-menu-navigation-drawer.html
I went completely as said in the tutorial but it doesn't respond to the click events,
(I put log.d in the onClickListener and see that it even not go inside the on clickListener)
(it shows the list icon and title perfectly(i don't get any error, exception,..) but i could't debug why it doesn't invoke the onClickListener..)
Thanks for your help in advance
public class MainActivity extends ActionBarActivity {
/** slide menu **/
String[] menutitles;
TypedArray menuIcons;
/** nav drawer title **/
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private List<RowItem> rowItems;
private CustomAdapter adapter;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*******
*
* for sliding menu
*
* **************/
mTitle = mDrawerTitle = getTitle();
menutitles = getResources().getStringArray(R.array.titles);
menuIcons = getResources().obtainTypedArray(R.array.icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.slider_list);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < menutitles.length; i++) {
RowItem items = new RowItem(menutitles[i], menuIcons.getResourceId(
i, -1));
rowItems.add(items);
}
menuIcons.recycle();
adapter = new CustomAdapter(getApplicationContext(), rowItems);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new SlideitemListener());
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.app_name, R.string.app_name)
{
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
updateDisplay(0);
}
// *******#for sliding menu*************
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.drawer_layout, new PlaceholderFragment())
.commit();
}
}
class SlideitemListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Log.d("in list listener", Integer.toString(position));
updateDisplay(position);
}
}
#SuppressLint("NewApi")
private void updateDisplay(int position) {
android.app.Fragment fragment = null;
switch (position) {
case 0:
fragment = new FB_Fragment();
break;
case 1:
fragment = new GP_Fragment();
break;
case 2:
fragment = new TB_Fragment();
break;
default:
break;
}
if (fragment != null) {
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
setTitle(menutitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#SuppressLint("NewApi")
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#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.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/***
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
and this is custom adapter:
public class CustomAdapter extends BaseAdapter {
Context context;
List<RowItem> rowItem;
CustomAdapter(Context context, List<RowItem> rowItem) {
this.context = context;
this.rowItem = rowItem;
}
private class ViewHolder {
ImageView icon;
TextView title;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_tem, null);
holder = new ViewHolder();
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
holder.title = (TextView) convertView.findViewById(R.id.title);
RowItem row_pos = rowItem.get(position);
// setting the image resource and title
holder.icon.setImageResource(row_pos.getIcon());
holder.title.setText(row_pos.getTitle());
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
#Override
public int getCount() {
return rowItem.size();
}
#Override
public Object getItem(int position) {
return rowItem.get(position);
}
#Override
public long getItemId(int position) {
return rowItem.indexOf(getItem(position));
}
and this is list_tem.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="48dp"
android:background="#fff"
android:padding="5dp" >
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/icon"
android:gravity="center_vertical"
android:textColor="#color/bgc1"
android:textSize="18sp" />
<ImageView
android:id="#+id/icon"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerVertical="true"
android:contentDescription="imgdesc" />
</RelativeLayout>

Find your navigation layout container and set this after config drawerToggle:
navigationContainer.bringToFront();
drawerLayout.requestLayout();

you need to create fragment for each listitems , still if your are not able to resolve then you can download the code from this Link : http://download.tutorialsbuzz.com/subscribers/index_slidemenu.php

Related

Navigation Drawer Submenu

I have implemented navigation drawer in my project.Everything is fine and the project is all set.I only have a problem with my drawer.On click of every item i have sub items but i do not want to show it in expandable list view,I want to open another sub drawer containing sub items right next to my main navigation drawer. How should i proceed.Please Help.
Code in Context
MainActivity
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
private String[] mTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initToolbar();
mTitles=getResources().getStringArray(R.array.drawer_titles);
mDrawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerList=(ListView)findViewById(R.id.left_drawer);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerToggle = new ActionBarDrawerToggle(
this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
private void initToolbar() {
toolbar=(Toolbar)findViewById(R.id.toolbar);
toolbar.setTitle(R.string.toolbar_title);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_drawer);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:id="#+id/toolbar"
android:background="#efeaea"
android:layout_height="50dp"/>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_below="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<LinearLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" />
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
The drawer is given a fixed width in dp and extends the full height of
the container. A solid background is used for contrast
with the content view. -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:dividerHeight="2dp"
android:background="#ffffff"/>
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
you can implement custom Expandable adapter
list_item.xml //child view inside group
<?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="55dip"
android:orientation="vertical"
android:divider="#color/black">
<TextView
android:id="#+id/lblListItem"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="#dimen/textSize14"
android:typeface="sans"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:layout_marginLeft="80dp"/>
</LinearLayout>
list_group.xml //parent view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:orientation="horizontal"
android:padding="3dp"
android:dividerPadding="10dp">
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:id="#+id/navImage"
android:layout_margin="#dimen/padding_10dp"
android:layout_gravity="center"/>
<TextView
android:id="#+id/lblListHeader"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:gravity="left|center"
android:layout_weight=".5"
android:textSize="#dimen/textSize20"/>
<TextView
android:layout_width="50dp"
android:layout_height="match_parent"
android:id="#+id/Collapser"
android:textSize="#dimen/textSize20"
android:textAllCaps="true"
android:text="+"
android:layout_gravity="center_vertical"
android:gravity="center"
android:layout_weight=".5"
android:textStyle="normal"/>
</LinearLayout>
ExpandableListAdapter
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
private int[] headerIcons;
public ExpandableListAdapter(Context context,int[] headerIcons, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this._context = context;
this.headerIcons = headerIcons;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.lblListItem);
txtListChild.setText(childText);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
ImageView headerImage = (ImageView)convertView.findViewById(R.id.navImage);
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setText(headerTitle);
TextView lvlPlusMinus=(TextView)convertView.findViewById(R.id.Collapser);
if(getChildrenCount(groupPosition)!=0)
{
lvlPlusMinus.setTypeface(null, Typeface.NORMAL);
lvlPlusMinus.setText("+");
if(isExpanded)
{
lvlPlusMinus.setTypeface(null, Typeface.NORMAL);
lvlPlusMinus.setText("-");
}
}
else
{
lvlPlusMinus.setText("");
}
headerImage.setImageResource(headerIcons[groupPosition]);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
In your Navigation drawer
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
// private ListView mDrawerListView;
private View mFragmentContainerView;
ExpandableListAdapter listAdapter;
ExpandableListView mDrawerListView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
private int lastExpandedPosition = -1;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
Map<String, String> params;
HashMap<String, String> userDetails;
public Fragment fragment = null;
String tag,URL ;
android.support.v4.app.FragmentManager fragmentManager;
FragmentTransaction transaction;
Handler handler;
Runnable runnable;
private final Handler mDrawerHandler = new Handler();
/**
* AppointmentRequest ♠♠
*/
ProgressDialog bar ;
public static final NavigationDrawerFragment NavUtils = new NavigationDrawerFragment();
public static NavigationDrawerFragment getInstance() {
return NavUtils;
}
public NavigationDrawerFragment() {
}
View contentView;
SessionManager session;
TextView doctorName;
ImageView docImage;
int[] headerIcons;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragmentManager = getFragmentManager();
transaction = fragmentManager.beginTransaction();
session = new SessionManager(getActivity());
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
headerIcons = new int[]{
R.drawable.home,
R.drawable.profile,
R.drawable.logout
};
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
contentView = inflater.inflate(
R.layout.fragment_navigation_drawer_with_topheader, container, false);
mDrawerListView = (ExpandableListView) contentView.findViewById(R.id.expList);
doctorName = (TextView)contentView.findViewById(R.id.docName);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
selectItem(position);
}
});
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(getActivity(), headerIcons, listDataHeader, listDataChild);
mDrawerListView.setAdapter(listAdapter);
mDrawerListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
if (lastExpandedPosition != -1
&& groupPosition != lastExpandedPosition) {
mDrawerListView.smoothScrollToPosition(groupPosition);
mDrawerListView.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = groupPosition;
}
});
mDrawerListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, final int groupPosition, long id) {
final String selected = (String) listDataHeader.get(groupPosition);
mDrawerListView.smoothScrollToPosition(groupPosition);
mDrawerHandler.removeCallbacksAndMessages(null);
mDrawerHandler.postDelayed(new Runnable() {
#Override
public void run() {
//Toast.makeText(getActivity(), selected, Toast.LENGTH_SHORT).show();
}
}, 250);
if (groupPosition == 0 ||)//close drawer if no child
mDrawerLayout.closeDrawers();
return false;
}
});
/**
* Expandable list child on click listener
*/
mDrawerListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, final int groupPosition, final int childPosition, long id) {
final String selected = (String) listAdapter.getChild(
groupPosition, childPosition);
mDrawerListView.smoothScrollToPosition(groupPosition);
mDrawerHandler.removeCallbacksAndMessages(null);
mDrawerHandler.postDelayed(new Runnable() {
#Override
public void run() {
// Toast.makeText(getActivity(), selected, Toast.LENGTH_SHORT).show();
}
}, 250);
mDrawerLayout.closeDrawers();
return true;
}
});
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return contentView;
}
/*
* Preparing the list data
*/
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding Child in Parent
listDataHeader.add("Home");//0
listDataHeader.add("Profile");//1
listDataHeader.add("Sign out");//2
List<String> Profile = new ArrayList<String>();
Casefile.add("Child 1");
Casefile.add("Child 2");
listDataChild.put(listDataHeader.get(0), new ArrayList<String>());// Header, Child data
listDataChild.put(listDataHeader.get(1), Profile);
listDataChild.put(listDataHeader.get(2), new ArrayList<String>());//if no child
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.dehaze);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.dehaze, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
)
{
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(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 void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("WORKAROUND_FOR_BUG_19917_KEY", "WORKAROUND_FOR_BUG_19917_VALUE");
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
/*if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}*/
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
/**
* Diplaying view for selected nav drawer list item
* */
private void displayView(final int position) {
// update the content by replacing fragments
switch (position) {
case 0:
mDrawerLayout.closeDrawers();
tag = "HomeFragment";
fragment = new HomeFragment();
break;
case 1:
mDrawerLayout.closeDrawers();
tag = "ProfileFragment";
fragment = new ProfileFragment();
break;
case 2:
mDrawerLayout.closeDrawers();
tag = "Signout";
fragment= null;
//Signout
break;
default:
break;
}
if (fragment != null) {
// update selected item and title, then close the drawer
mDrawerListView.setItemChecked(position, true);
mDrawerListView.setSelection(position);
mDrawerListView.smoothScrollToPosition(position);
android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.container, fragment, tag);
transaction.commit();
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}

Android activity crashes when populating the listview with data from external databse in the form of JSON

here is the logcat error in image:
with error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.erp.navigationdrawer/com.erp.navigationdrawer.Notices}: java.lang.NullPointerException
This is my code of main activity which other activity extends to have a navigation drawer now on clicking notices in navigation drawer webservice is called and data comes but activity crashes and shows up:
ERROR AT mDrawerToggle.syncState();
Code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer);
// if (savedInstanceState == null) {
// // on first time display view for first nav item
// // displayView(0);
// }
}
public void set(String[] navMenuTitles, TypedArray navMenuIcons) {
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items
if (navMenuIcons == null) {
for (int i = 0; i < navMenuTitles.length; i++) {
navDrawerItems.add(new NavDrawerItem(navMenuTitles[i]));
}
} else {
for (int i = 0; i < navMenuTitles.length; i++) {
navDrawerItems.add(new NavDrawerItem(navMenuTitles[i],
navMenuIcons.getResourceId(i, -1)));
}
}
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
// getSupportActionBar().setIcon(R.drawable.ic_drawer);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, // nav menu toggle icon
R.string.app_name, // nav drawer open - description for
// accessibility
R.string.app_name // nav drawer close - description for
// accessibility
) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
supportInvalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
}
return super.onOptionsItemSelected(item);
}
/***
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
// boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
// menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
switch (position) {
case 0:
Intent intent = new Intent(this, Courses.class);
startActivity(intent);
finish();// finishes the current activity
break;
case 1:
Intent intent2 = new Intent(this, Notices.class);
startActivity(intent2);
finish();
break;
case 2:
Intent intent3 = new Intent(this, Placements.class);
startActivity(intent3);
finish();
break;
default:
break;
}
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
Below is the code for Notices activity that crashes up **AND ITS IS THE ONLY ACTIVITY AMONG NAVIGATION DRAWER TO CRASH:
private void loadservice(String url) {
// Make RESTful webservice call using AsyncHttpClient object
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, null, new AsyncHttpResponseHandler() {
// When the response returned by REST has Http response
// code '200'
#Override
public void onSuccess(String response) {
try {
JSONArray obj = new JSONArray(response);
for (int i = 0; i < obj.length(); i++) {
JSONObject jsonChild = obj.getJSONObject(i);
heading = jsonChild.optString("heading").toString();
content = jsonChild.optString("content").toString();
date = jsonChild.optString("date".toString());
System.out.println(heading + content + date);
entity = new NoticeEntity();
entity.setNotice_heading(heading);
entity.setNotice_content(content);
entity.setNotice_date(date);
arraylist.add(entity);
}
} catch (JSONException e) {
System.out.println(" Exception raised : " + e.getMessage());
e.printStackTrace();
}
}
});
ListView listView = (ListView) findViewById(R.id.notice_listview);
NoticeAdapter adapter = new NoticeAdapter(this, R.layout.custom_notice,
arraylist);
listView.setAdapter(adapter);
}
Here is my **NOTICE ADAPTER ** code below:
public class NoticeAdapter extends ArrayAdapter<NoticeEntity> {
private Context context;
public NoticeAdapter(Context context, int resourceId,
ArrayList<NoticeEntity> items) {
super(context, resourceId, items);
this.context = context;
}
/* private view holder class */
private class ViewHolder {
TextView heading;
TextView content;
TextView date;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
NoticeEntity entity = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.custom_notice, null);
holder = new ViewHolder();
holder.heading = (TextView) convertView
.findViewById(R.id.txtvw_notice_heading);
holder.content = (TextView) convertView
.findViewById(R.id.txtvw_notice_content);
holder.date = (TextView) convertView
.findViewById(R.id.txtvw_notice_date);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.heading.setText(entity.getNotice_heading());
holder.content.setText(entity.getNotice_content());
holder.date.setText(entity.getNotice_date());
return convertView;
}
}
onPostCreate will be executed immediately after onCreate. You're accessing a member variable called mDrawerToggle in your onPostCreate, but it is not assigned before onPostCreate is called. It is normal convention to assign all your views to member variables during onCreate immedately after you call setContentView. In your case, it's being assigned in a method called "set" where I can't see that it's ever being called.
Try moving all the view-related code from set into onCreate.

Adding an header to a custom navigation drawer

I created this header and i want to add it at the top of my listview in my navigation drawer the problem is that i don't know where to add it
<?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="178dp"
android:background="#android:color/holo_red_dark"
android:orientation="vertical"
android:weightSum="1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="56dp"
android:orientation="vertical"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
>
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:textColor="#ffffff"
android:text="Antoine Dupond"
android:textSize="14sp"
android:textStyle="bold"
/>
<TextView
android:id="#+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:layout_marginLeft="16dp"
android:layout_marginTop="5dp"
android:text="dupond#gmail.com"
android:textSize="14sp"
android:textStyle="normal"
/>
</LinearLayout>
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="70dp"
android:layout_height="70dp"
android:src="#drawable/ic_launcher"
android:layout_marginLeft="16dp"
android:layout_marginTop="38dp"
android:id="#+id/circleView"
/>
</RelativeLayout>
My fragment with custom adapter :
public class NavigationDrawerFragment extends Fragment {
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private NavigationDrawerCallbacks mCallbacks;
private ActionBarDrawerToggle mDrawerToggle;
private MyAdapter myAdapter;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
selectItem(mCurrentSelectedPosition);
}
#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.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
myAdapter=new MyAdapter(getActivity());
mDrawerListView.setAdapter(myAdapter);
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;
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(),
mDrawerLayout,
R.string.app_name,
R.string.app_name
)
{
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(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 void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.action_example) {
Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
public class MyAdapter extends BaseAdapter {
private Context context;
String [] socialSites ;
int [] images ={R.drawable.cafe,R.drawable.com,R.drawable.share,R.drawable.set,R.drawable.help};
public MyAdapter(Context context){
this.context=context;
socialSites = context.getResources().getStringArray(R.array.social);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = null;
if (convertView==null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=inflater.inflate(R.layout.custom_row,parent,false);
}
else{
row=convertView;
}
TextView titletexview = (TextView) row.findViewById(R.id.textView);
ImageView titleimageview =(ImageView) row.findViewById(R.id.imageView2);
titletexview.setText(socialSites[position]);
titleimageview.setImageResource(images[position]);
return row;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public Object getItem(int position) {
return socialSites[position];
}
#Override
public int getCount() {
return socialSites.length;
}
}
}
My mainactivity :
public class Nav extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment obj= null;
ListFragment listfragment = null;
switch (position) {
case 0:
listfragment= new F1_fr();
break;
case 1:
obj= new F6_fr();
break;
case 2:
obj= new F3_fr();
break;
case 3:
obj= new F4_fr();
break;
case 4:
obj= new F5_fr();
break;
}
if (obj != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, obj)
.commit();
}
else if (listfragment != null) {
// do stuff if its a listfragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, listfragment)
.commit();
}
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
case 4:
mTitle = getString(R.string.title_section4);
break;
case 5:
mTitle = getString(R.string.title_section5);
break;
case 6:
mTitle = getString(R.string.title_section6);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
/*#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.nav, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}*/
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_nav, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((Nav) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
and the layout :
<ListView 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:choiceMode="singleChoice"
android:divider="#android:color/transparent" android:dividerHeight="0dp"
android:background="#ffe7e7e7"
tools:context="com.example.gweltaz.coffy3.NavigationDrawerFragment"
/>
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context="com.example.gweltaz.coffy3.Nav">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout android:id="#+id/container" android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead. -->
<!-- The drawer is given a fixed width in dp and extends the full height of
the container. -->
<fragment android:id="#+id/navigation_drawer"
android:layout_width="#dimen/navigation_drawer_width" android:layout_height="match_parent"
android:layout_gravity="start"
android:name="com.example.gweltaz.coffy3.NavigationDrawerFragment"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
Inflate the layout and add it as a header to the ListView.
In onCreateView:
View header = inflater.inflate(R.layout.header, mDrawerListView, false);
mDrawerListView.addHeaderView(header, null);

Adding icon in the default navigation drawer in Android Studio

Hi i just generate a navigation drawer using the sample in android studio and in my navagation drawer fragment (where the listview is) i have this code :
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3),
getString(R.string.title_section4),
getString(R.string.title_section5),
getString(R.string.title_section6),
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(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 void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.action_example) {
Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
I want to add icon in front of each item of the list view but i dont know how to do this because i dont understand the whole code of the navigation drawer
Create a custom ArrayAdapter and use a custom layout inside it which has an ImageView and a TextView
Try this
The xml file(call it whatever you want):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/textViewListItem"
android:layout_marginTop="25dp"
android:layout_marginLeft="10dp"
android:layout_gravity="center_horizontal" />
<ImageView
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="-40dp"
android:id="#+id/imageView"
android:src="#drawable/ic_launcher" />
</LinearLayout>
Create a class that will be your adapter, how your list wants to be(have an imageview, have 3 textviews, etc)
public class ListAdapter extends Activity {
private int imageId;
private String itemName;
public ListaAdapter(int imageId, String itemName) {
super();
this.imageId = imageId;
this.itemName = itemName;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
}
then in your activity that you would like the drawer to be implemented try
//instanciate components
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private ListView mDrawerList;
private List<ListAdapter> drawerList = new ArrayList<ListAdapter>();
//in the onCreate method build 3 methods and organize your code
buildDrawer();
populateDrawerList();
buildListDrawer();
private void populateDrawerList() {
drawerList.add(new ListaAdapter(R.drawable.icon_1, "String 1"));
drawerList.add(new ListaAdapter(R.drawable.icon_2, "String 2"));
}
private void buildDrawer() {
mDrawerLayout = (DrawerLayout)findViewById(R.id.your_drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(YourActivity.this, mDrawerLayout, R.drawable.your_drawer_icon, "Open", "Closed"){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle("Drawer Opened");
invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActionBar().setTitle("Drawer Closed");
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void buildListDrawer() {
mDrawerList = (ListView)findViewById(R.id.listViewDrawer);
ArrayAdapter<ListAdapter> adapter = new MyDrawerArrayAdapter();
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MyActivity.this, "You have chosen " + drawerList.get(position).getItemName(), Toast.LENGTH_SHORT).show();
}
});
}
and then your modified Adapter that extends ArrayAdapter:
private class MyDrawerArrayAdapter extends ArrayAdapter<ListAdapter> {
public MyDrawerArrayAdapter() {
super(MyActivity.this, R.layout.drawer_list_item_layout, drawerList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View drawerView = convertView;
if(drawerView == null){
drawerView = getLayoutInflater().inflate(R.layout.drawer_list_item_layout, parent, false);
}
ListAdapter currentPosition = drawerList.get(position);
ImageView drawerImage = (ImageView)drawerView.findViewById(R.id.your_drawerImage);
drawerImage.setImageResource(currentPosition.getImageId());
TextView drawerText = (TextView)drawerView.findViewById(R.id.your_drawerText);
drawerText.setText(currentPosition.getItemName());
return drawerView;
}
}
Step 01 -
Have your res/drawable folder ready with appropriate icons.
Step 02 -
In your values/string.xml add below
<string-array name="mydrawerList">
<item>item 1</item>
<item>item 2</item>
<item>item 3</item>
</string-array>
<array name="mydrawerList_icons">
<item>#drawable/ic_for_item1</item>
<item>#drawable/ic_for_item2</item>
<item>#drawable/ic_for_item3</item>
</array>
make sure you have icons in the "mydrawerList_icons" ordered as "mydrawerList" order.
Step 03 -
in your NavigationDrawerFragment.java add below lines
private String[] listTitles;
private TypedArray listIcons;
in onCreate()
listTitles = getResources().getStringArray(R.array.mydrawerList);
listIcons = getResources().obtainTypedArray(R.array.mydrawerList_icons);
Step 04 -
instead of this
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3),
getString(R.string.title_section4),
getString(R.string.title_section5),
getString(R.string.title_section6),
}));
type this
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
listTitles)
{
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
int resourceId = listIcons.getResourceId(position, 0);
Drawable drawable = getResources().getDrawable(resourceId);
((TextView) v).setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
return v;
}
});
Let me know the output.

update listview when i remove item on it

I'm very newly into this programming language can somebody help me what to do.
Here is my screenshot# http://imgur.com/hGQCHpk
the listview is not updating if i click the home fragment where listview contains
MainActivity.Java
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navLogout;
String[] navMenuTitles;
TypedArray navMenuIcons;
ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(
R.array.nav_drawer_items_not_login);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons
.getResourceId(0, -1)));
// login
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons
.getResourceId(1, -1)));
// register
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons
.getResourceId(2, -1)));
// classic brownies
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons
.getResourceId(3, -1)));
// cupcakes
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons
.getResourceId(3, -1)));
// cookies
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons
.getResourceId(3, -1)));
// feedback
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons
.getResourceId(4, -1)));
// about
navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuIcons
.getResourceId(5, -1)));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, // nav menu toggle icon
R.string.app_name, // nav drawer open - description for
// accessibility
R.string.app_name // nav drawer close - description for
// accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
displayView(0);
}
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
Fragment fragment = null;
Fragment newFragment = new AboutFragment();
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_search:
Toast.makeText(this, "search selected", Toast.LENGTH_SHORT).show();
break;
case R.id.action_shoppingcart:
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
transaction.replace(R.id.frame_container, newFragment,
"AboutFragment");
transaction.commit();
getActionBar().setTitle("Shopping cart");
return true;
default:
break;
}
return true;
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_search).setVisible(!drawerOpen);
menu.findItem(R.id.action_shoppingcart).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new LoginFragment();
break;
case 2:
fragment = new RegisterFragment();
break;
case 3:
fragment = new ClassicBrowniesFragment();
break;
case 4:
fragment = new CupcakesFragment();
break;
case 5:
fragment = new CookiesFragment();
break;
case 6:
fragment = new FeedbackFragment();
break;
case 7:
fragment = new AboutFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
HomeFragment.java
public class HomeFragment extends Fragment implements OnItemClickListener {
String[] member_names;
TypedArray product_icons;
String[] statues;
String[] contactType;
List<RowItem> rowItems;
ListView mylistview;
CustomAdapter myadapter;
CustomAdapter newadapter;
EditText editsearch;
public HomeFragment() {
}
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container, false);
rowItems = new ArrayList<RowItem>();
member_names = getResources().getStringArray(R.array.Member_names);
product_icons = getResources().obtainTypedArray(R.array.product_icons);
statues = getResources().getStringArray(R.array.statues);
for (int i = 0; i < member_names.length; i++) {
RowItem item = new RowItem(member_names[i],
product_icons.getResourceId(i, -1), statues[i]);
rowItems.add(item);
}
mylistview = (ListView) rootView.findViewById(R.id.list);
mylistview.setItemsCanFocus(true);
//
final CustomAdapter adapter = new CustomAdapter(getActivity(), rowItems);
mylistview.setAdapter(adapter);
product_icons.recycle();
mylistview.setOnItemClickListener(this);
mylistview.setScrollingCacheEnabled(false);
mylistview.invalidateViews();
adapter.notifyDataSetChanged();
this.setRetainInstance(true);
return rootView;
}
public void updateList(List adapter) {
mylistview = (ListView) rootView.findViewById(R.id.list);
mylistview.setAdapter((ListAdapter) adapter);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String member_name = rowItems.get(position).getMember_name();
int product_icons = rowItems.get(position).getProfile_pic_id();
String status = rowItems.get(position).getStatus();
RowItem item = rowItems.get(position);
Intent intent = new Intent(getActivity(), HomeFragment.class);
intent.putExtra("member_name", member_name);
intent.putExtra("product_icons", product_icons);
intent.putExtra("status", status);
rowItems.remove(item);
newadapter = new CustomAdapter(getActivity(), rowItems);
mylistview.setAdapter(newadapter);
newadapter.notifyDataSetChanged();
Toast.makeText(getActivity().getApplicationContext(),
"Added to Cart: " + member_name, Toast.LENGTH_SHORT).show();
}
}
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
HomeFragment home = new HomeFragment();
Context context;
List<RowItem> rowItems;
public CustomAdapter(Context context, List<RowItem> rowItems) {
this.context = context;
this.rowItems = rowItems;
}
public CustomAdapter() {
// TODO Auto-generated constructor stub
}
#Override
public int getCount() {
return rowItems.size();
}
#Override
public Object getItem(int position) {
return rowItems.get(position);
}
#Override
public long getItemId(int position) {
return rowItems.indexOf(getItem(position));
}
/* private view holder class */
private class ViewHolder {
ImageView product_icons;
TextView member_name;
TextView status;
Button addtocart;
}
ViewHolder holder = null;
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.member_name = (TextView) convertView
.findViewById(R.id.member_name);
holder.product_icons = (ImageView) convertView
.findViewById(R.id.product_icons);
holder.status = (TextView) convertView.findViewById(R.id.status);
holder.addtocart = (Button) convertView
.findViewById(R.id.btnaddtocart);
RowItem row_pos = rowItems.get(position);
holder.product_icons.setImageResource(row_pos.getProfile_pic_id());
holder.member_name.setText(row_pos.getMember_name());
holder.status.setText(row_pos.getStatus());
holder.addtocart.setText(" add to cart");
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
}
RowItem.java
public class RowItem {
private String member_name;
private int profile_pic_id;
private String status;
public RowItem(String member_name, int profile_pic_id, String status) {
this.member_name = member_name;
this.profile_pic_id = profile_pic_id;
this.status = status;
}
public String getMember_name() {
return member_name;
}
public void setMember_name(String member_name) {
this.member_name = member_name;
}
public int getProfile_pic_id() {
return profile_pic_id;
}
public void setProfile_pic_id(int profile_pic_id) {
this.profile_pic_id = profile_pic_id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
Please help me with this thing for my software engineering subject i hope anyone can help me.
It seems like you are just removing the view that holds the data and not actually changing the underlying data set. You call rowItems.remove() when you want the item removed but remember when the fragment is reloaded like when you click on the Home navigation option that the code in HomeFragment.createView() is run.
In that code you can see that the rowItems is initialized here
member_names = getResources().getStringArray(R.array.Member_names);
for (int i = 0; i < member_names.length; i++) {
RowItem item = new RowItem(member_names[i],
product_icons.getResourceId(i, -1), statues[i]);
rowItems.add(item);
}
So unless you are removing the item from the Member_names array resource when it is deleted then it will appear every time you recreate the fragment.

Categories

Resources