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.
Related
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.
I've Activity A and B. A contains fragments which can be navigated by clicking items on navigation drawer. Activity B has a custom toolbar view. Navigation drawer is available on activity B also as activity B extends activity A. When i return to any fragment of activity A from B by clicking item on item on drawer, custom view persists. I don't want custom view to be shown on fragments of activity A. How can i do that?
Code for main activity goes:
public class MainActivity extends ActionBarActivity {
protected static int position;
private static boolean isLaunch = true;
protected DrawerLayout mDrawerLayout;
protected ListView mDrawerList;
protected Toolbar mToolbar,mToolbar2;
protected FrameLayout frameLayout;
protected View mCustomView;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private SharedPreferences runPrefs;
Menu menu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frameLayout = (FrameLayout) findViewById(R.id.frame_container);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
mTitle = mDrawerTitle = getTitle();
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
ArrayList<NavDrawerItem> navDrawerItems = new ArrayList<NavDrawerItem>();
for (int i = 0; i < navMenuTitles.length; i++) {
navDrawerItems.add(new NavDrawerItem(navMenuTitles[i], navMenuIcons
.getResourceId(i, -1)));
}
// Garbage collection
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
NavDrawerListAdapter adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
if (isLaunch) {
isLaunch = false;
displayView(0);
}
}
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);
mDrawerList.setItemChecked(position, true);
}
}
private void displayView(int position) {
// update the main content by replacing fragments
mDrawerLayout.closeDrawer(mDrawerList);
MainActivity.position = position;
Fragment fragment = null;
switch (position) {
case 0:
fragment = new FragmentMain();
break;
case 1:
fragment = new FragmentLogin();
break;
case 2:
fragment = new FragmentEmergency();
break;
case 3:
fragment = new FragmentFavourite();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
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");
}
}
}
Code for another activity (with custom toolbar view)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.activity_business_result_list, frameLayout);
mDrawerList.setItemChecked(position, true);
this.businessList = (ListView) findViewById(R.id.lvBusinesslist); // Initialize View Containing Fields of ListView
this.footerView = ((LayoutInflater) this.getSystemService(getApplicationContext().LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer, null, false);
this.businessList.addFooterView(footerView);
this.adapter = new BusinessListDataAdapter(this, this.imgFetcher,
this.layoutInflator, this.businesses); // initialize BusinessListDataAdapter
this.businesses = null;
Intent myIntent = getIntent();
// gets the arguments from previously created intent
this.metroTxt = myIntent.getStringExtra("key");
this.metroLoc = myIntent.getStringExtra("loc");
this.metroId = myIntent.getStringExtra("qt");
showCustomView(metroTxt, metroLoc, metroId);
getBusinesses(metroTxt, metroLoc, metroId); // Get Businesses List from server
}
void showCustomView(String metroTxt, String metroLoc, String metroId) {
LayoutInflater mInflater = LayoutInflater.from(this);
if (mCustomView == null)
mCustomView = mInflater.inflate(R.layout.custom_action_bar, null);
mToolbar.removeView(mCustomView);
mToolbar.addView(mCustomView);
}
I have a MainActivity that has a navigation drawer that calls a fragment to load a ListView. That ListView calls an xml to be the layout of the listitem. I am fetching the data from a webservice and wants to display 4 data on each list item. I created a CustomAdapter as mentioned in some tutorial to display data. My problem is I store the data to a String array and don't know how to put it in the object I created then pass to the Adapter then display
MAIN ACTIVITY
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[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#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);
// 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)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Recycle the typed array
navMenuIcons.recycle();
// 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) {
// on first time display view for first nav item
displayView(0);
}
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
}
#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;
}
// 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);
}
#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);
}
/**
* 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);
}
}
/**
* 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 SearchFragment();
break;
case 2:
fragment = new SignInFragment();
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");
}
}
}
HOME FRAGMENT that calls the xml with the listview
public class HomeFragment extends Fragment {
/*Layout Variables*/
protected ProgressBar mProgressBar;
protected JSONArray blogPostData;
protected TextView mTextView;
/*Variables to be displayed*/
protected String[] blogPostTitle;
protected String[] blogPostDate;
protected String[] blogPostAuthor;
/*System Variables*/
private ListView listView;
private View rootView;
articleListObject object;
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container, false);
listView = (ListView) rootView.findViewById(R.id.article_list);
mProgressBar = (ProgressBar) rootView.findViewById(R.id.progressBarHome);
mTextView = (TextView) rootView.findViewById(R.id.networkCheck);
mTextView.setText("Please Wait while we load the data!");
mProgressBar.setVisibility(View.VISIBLE);
ArticleController articleController = new ArticleController(mListener);
articleController.execute();
return rootView;
}
public MyListener mListener = new MyListener(){
#Override
public void onComplete(JSONArray result)
{
blogPostData = result;
updateArticleList();
mProgressBar.setVisibility(View.INVISIBLE);
mTextView.setVisibility(View.INVISIBLE);
/*List<String> stringList = new ArrayList<String>(Arrays.asList(blogPostTitle));
ArrayAdapter<String> arrayAdapter1 = new ArrayAdapter<String>(getActivity(), R.layout.layout_listview_article, R.id.titleTV, stringList);
listView.setAdapter(arrayAdapter1);*/
ArrayList<articleListObject> objects = new ArrayList<articleListObject>();
articleListAdapter articleAdapter = new articleListAdapter(objects);
listView.setAdapter(articleAdapter);
}
};
protected void updateArticleList()
{
try
{
blogPostTitle = new String[blogPostData.length()];
blogPostDate = new String[blogPostData.length()];
blogPostAuthor = new String[blogPostData.length()];
for (int i = 0; i < blogPostData.length(); i++)
{
JSONObject jsonObject = blogPostData.getJSONObject(i);
String title = jsonObject.getString("title");
title = Html.fromHtml(title).toString();
String date = jsonObject.getString("created_at");
date = Html.fromHtml(date).toString();
String author = jsonObject.getString("author");
author = Html.fromHtml(author).toString();
blogPostTitle[i] = title;
blogPostDate[i] = date;
blogPostAuthor[i] = author;
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
}
This is the background async
public class ArticleController extends AsyncTask<Object, Void, JSONArray> {
MyListener mListener;
public ArticleController(MyListener listenr) {
mListener = listenr;
}
#Override
protected JSONArray doInBackground(Object... arg0)
{
String result = "No data available";
JSONArray jsonResponse = null;
try
{
HttpClient httpclient = new DefaultHttpClient();
//TODO: URL ADDRESS for Articles.
HttpPost httpPost = new HttpPost("http://localhost/****/public/webservices/post");
/*httpPost.setHeader("Content-type", "application/json");*/
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
nameValuePair.add(new BasicNameValuePair("page", "1"));
nameValuePair.add(new BasicNameValuePair("limit","10"));
nameValuePair.add(new BasicNameValuePair("category","0"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
/*InputStream inputStream = null;*/
HttpResponse response = httpclient.execute(httpPost);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
result = sb.toString();
jsonResponse = new JSONArray(result);
Log.d("RESULT: ", result);
}
catch (MalformedURLException e)
{
Log.e("TAG", "exception caught: ", e);
}
catch (IOException e)
{
Log.e("TAG", "exception caught: ", e);
}
catch (Exception e)
{
Log.e("TAG", "exception caught: ", e);
}
return jsonResponse;
}
#Override
protected void onPostExecute(JSONArray result)
{
HomeFragment homeFragment = new HomeFragment();
homeFragment.blogPostData = result;
mListener.onComplete(result);
}
}
MY CustomAdapter
public class articleListAdapter extends BaseAdapter {
private LayoutInflater inflater;
private ArrayList<articleListObject> objects;
private class ViewHolder {
TextView textView1;
TextView textView2;
TextView textView3;
}
public articleListAdapter(Context context, ArrayList<articleListObject> objects) {
inflater = LayoutInflater.from(context);
this.objects = objects;
}
public int getCount() {
return objects.size();
}
public articleListObject getItem(int position) {
return objects.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.layout_listview_article, null);
holder.textView1 = (TextView) convertView.findViewById(R.id.titleTV);
holder.textView2 = (TextView) convertView.findViewById(R.id.dateTV);
holder.textView3 = (TextView) convertView.findViewById(R.id.authorTV);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textView1.setText(objects.get(position).getPostTitle());
holder.textView2.setText(objects.get(position).getPostDate());
holder.textView3.setText(objects.get(position).getPostAuthor());
return convertView;
}
}
my constructor
public class articleListObject {
/*Variables to be displayed*/
protected String postTitle;
protected String postDate;
protected String postAuthor;
public articleListObject(String postTitle, String postDate, String postAuthor) {
this.postTitle = postTitle;
this.postDate = postDate;
this.postAuthor = postAuthor;
}
public String getPostTitle() {
return postTitle;
}
public String getPostDate() {
return postDate;
}
public String getPostAuthor() {
return postAuthor;
}
}
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private 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);
// 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
// Photos
navDrawerItems.add(new NavDrawerItem("\nFirst Year", navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem("\nSecond Year", navMenuIcons.getResourceId(3, -1), true, "22"));
// Pages
navDrawerItems.add(new NavDrawerItem("\nThird Year", navMenuIcons.getResourceId(4, -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) {
// on first time display view for first nav item
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;
}
// 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);
}
/**
* 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 FirstYear();
break;
case 1:
fragment = new SecondYear();
break;
case 2:
fragment = new ThirdYear();
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);
}
}
I want to show slider menu & fragment of clicked in the menu in same activity.for ex: I click first option(first year) of slider menu it shows right side first year fragment.
2.Can I adjust width of slider menu. for showing more space for fragment.
Try this code from Android Hive, Android Sliding Menu using Navigation Drawer, by Ravi Tamada:
NavDrawerItem.java
public class NavDrawerItem {
private String title;
private int icon;
private String count = "0";
// boolean to set visiblity of the counter
private boolean isCounterVisible = false;
public NavDrawerItem(){}
public NavDrawerItem(String title, int icon){
this.title = title;
this.icon = icon;
}
public NavDrawerItem(String title, int icon, boolean isCounterVisible, String count){
this.title = title;
this.icon = icon;
this.isCounterVisible = isCounterVisible;
this.count = count;
}
public String getTitle(){
return this.title;
}
public int getIcon(){
return this.icon;
}
public String getCount(){
return this.count;
}
public boolean getCounterVisibility(){
return this.isCounterVisible;
}
public void setTitle(String title){
this.title = title;
}
public void setIcon(int icon){
this.icon = icon;
}
public void setCount(String count){
this.count = count;
}
public void setCounterVisibility(boolean isCounterVisible){
this.isCounterVisible = isCounterVisible;
}
}
NavDrawerListAdapter.java
import info.androidhive.slidingmenu.R;
import info.androidhive.slidingmenu.model.NavDrawerItem;
import java.util.ArrayList;
import android.app.Activity;
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;
public class NavDrawerListAdapter extends BaseAdapter {
private Context context;
private ArrayList<NavDrawerItem> navDrawerItems;
public NavDrawerListAdapter(Context context, ArrayList<NavDrawerItem> navDrawerItems){
this.context = context;
this.navDrawerItems = navDrawerItems;
}
#Override
public int getCount() {
return navDrawerItems.size();
}
#Override
public Object getItem(int position) {
return navDrawerItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.drawer_list_item, null);
}
ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
TextView txtCount = (TextView) convertView.findViewById(R.id.counter);
imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
txtTitle.setText(navDrawerItems.get(position).getTitle());
// displaying count
// check whether it set visible or not
if(navDrawerItems.get(position).getCounterVisibility()){
txtCount.setText(navDrawerItems.get(position).getCount());
}else{
// hide the counter view
txtCount.setVisibility(View.GONE);
}
return convertView;
}
}
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[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#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);
// 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)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
// Recycle the typed array
navMenuIcons.recycle();
// 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) {
// on first time display view for first nav item
displayView(0);
}
}
#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;
}
// 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);
}
#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
package info.androidhive.slidingmenu;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class HomeFragment extends Fragment {
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
return rootView;
}
}
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