I am extending my NavigationObject class to my other activity classes but the drawer would not come out when I click on the menu.
Here is my NavigationObject:
public class NavigationObject extends ActionBarActivity implements OnClickListener{
private DrawerLayout mDrawerLayout;
private ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
ListView listView;
List<RowItem> rowItems;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Firebase.setAndroidContext(this);
setContentView(R.layout.navdrawer);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setIcon(R.drawable.ic_launcher);
System.out.println("ERROR 1");
addDrawerItems();
setupDrawer();
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu, menu);
return super.onCreateOptionsMenu(menu);
}
//junk
public void addDrawerItems() {
System.out.println("ERROR 2");
String[] drawer_Array = { "User Profile", "Setting", "Contact us", "Help", "Logout" };
String[] desc_Array = { "Private", "Change settings", "Ask us anything", "Simple Guide", "Logs out user" };
Integer[] image_Array = { R.drawable.user, R.drawable.setting, R.drawable.contactme, R.drawable.help, R.drawable.logout };
//mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, drawer_Array);
//mDrawerList.setAdapter(mAdapter);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < drawer_Array.length; i++) {
RowItem item = new RowItem(image_Array[i], drawer_Array[i], desc_Array[i]);
rowItems.add(item);
}
System.out.println("ERROR 3");
listView = (ListView) findViewById(R.id.navList);
CustomDrawerBaseAdapter adapter = new CustomDrawerBaseAdapter(this, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position == 0){
Intent toProfile = new Intent(getApplicationContext(), userprofActivity.class);
startActivity(toProfile);
//Toast.makeText(getMsgActivity.this, "Time for an upgrade!", Toast.LENGTH_SHORT).show();
}
else if(position == 1){
//Toast.makeText(getMsgActivity.this, "Time for an Wake!", Toast.LENGTH_SHORT).show();
}
else if(position == 2){
//Toast.makeText(getMsgActivity.this, "Time for an Eat!", Toast.LENGTH_SHORT).show();
}
else if(position == 3){
//Toast.makeText(getMsgActivity.this, "Time for an Dance!", Toast.LENGTH_SHORT).show();
}
else if(position == 4){
//Toast.makeText(getMsgActivity.this, "Time for an Sleep!", Toast.LENGTH_SHORT).show();
}
}
});
System.out.println("ERROR 4");
}
public void setupDrawer() {
//getActionBar().setDisplayHomeAsUpEnabled(true);
//getActionBar().setHomeButtonEnabled(true);
System.out.println("ERROR 5");
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
// enabling action bar app icon and behaving it as toggle button
public void onDrawerOpened(View drawerView) {
System.out.println("ERROR 5");
super.onDrawerOpened(drawerView);
listView.bringToFront();
mDrawerLayout.requestLayout();
getSupportActionBar().setTitle("User Menu Option");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerClosed(View view) {
System.out.println("ERROR 6");
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
System.out.println("ERROR 6.5");
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
System.out.println("ERROR 7");
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(listView);
menu.findItem(R.id.action_write).setVisible(!drawerOpen);
menu.findItem(R.id.action_grabmsg).setVisible(!drawerOpen);
menu.findItem(R.id.action_mydiary).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
System.out.println("landscape");
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
System.out.println("portrait");
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//bundle = getIntent().getExtras();
//String language_chosen = bundle.getString("lang_pick");
if (id == R.id.action_write) {
Intent writeNewMsg = new Intent(getApplicationContext(), writeMsgActivity.class);
//writeNewMsg.putExtra("lang_pick", language_chosen);
startActivity(writeNewMsg);
}
else if(id == R.id.action_grabmsg){
Intent grabNewMsg = new Intent(getApplicationContext(), getMsgActivity.class);
//grabNewMsg.putExtra("lang_pick", language_chosen);
finish();
startActivity(grabNewMsg);
}
else if(id == R.id.action_mydiary){
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
System.out.println("ERROR 8"); //This is where the error is. It is returned but never used.
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
My problem is here:
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
System.out.println("ERROR 8"); //This is where the error is. It is returned but never used.
return true;
}
and here these methods were never called:
public void onDrawerOpened(View drawerView) {
System.out.println("ERROR 5.5");
super.onDrawerOpened(drawerView);
listView.bringToFront();
mDrawerLayout.requestLayout();
getSupportActionBar().setTitle("User Menu Option");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerClosed(View view) {
System.out.println("ERROR 6");
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
Here is the xml for the drawer called navdrawer.xml of NavigationObject class:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/navList"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_gravity="left|start"
android:background="#ffeeeeee"/>
</android.support.v4.widget.DrawerLayout>
UPDATED - STILL NEED ASSISTANCE
Here is where I use the extend on my other classes (This class do not have the drawer xml within their xml because I am inheriting from NavigationObject which has its own xml called navdrawer):
public class MainActivity extends NavigationObject implements OnClickListener{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Firebase.setAndroidContext(this);
setContentView(R.layout.get_msg);
Problem: Everytime I click the option menu bar on the drawer it prints "8" from the NavigationObject class but it does nothing after that. There was no error in the code because all of the system out print I placed worked except for System.out.println("ERROR 5.5") and System.out.println("ERROR 6") which are used to open and close the drawer. The swipe does not work.
This was working when I shoved all of NavigationObject class inside my MainActivity activity class but now it's not working when I made the drawer as a separate class (NavigationObject class) for inheritance.
The menu bar is working fine. But the optionselected at "ERROR 8" does not return anything but still prints out so it's working but its doing nothing either.
Any help is very much appreciated, this is for my final year project and it's due very soon :) .
You set a different layout (R.layout.get_msg) in your derived class. Does this layout contain the NavigationDrawer? If not -- there's your bug.
Edit
Try this: Move the initialization of the NavigationDrawer to a separate method in your base activity like so:
public class NavigationObject extends ActionBarActivity ...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Firebase.setAndroidContext(this);
}
protected void initNavigationDrawer() {
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setIcon(R.drawable.ic_launcher);
System.out.println("ERROR 1");
addDrawerItems();
setupDrawer();
}
And in your MainActivity call the init method in your onCreate() method, after setting the content view.
public class MainActivity extends NavigationObject ...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_msg); // <-- must contain drawer_layout
initNavigationDrawer();
}
Related
My application crashes when I flip orientation. If the commented out line in onCreate runs I can't flip orientation at all. without it I can flip but can't change my background image but when it flips back it still crashes.
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private DrawerLayout mDrawerLayout;
private ListView mListView;
private ImageView bgimage;
int[] drwables = {R.drawable.cindy, R.drawable.fred, R.drawable.kate, R.drawable.keith, R.drawable.matt, R.drawable.rickey};
private ActionBarDrawerToggle toggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState != null){
Toast.makeText(this, "made it", Toast.LENGTH_SHORT).show();
int n = savedInstanceState.getInt("imageId");
Toast.makeText(this, ""+n, Toast.LENGTH_SHORT).show();
bgimage = (ImageView) findViewById(R.id.imgOne);
int[] drwables = {R.drawable.cindy, R.drawable.fred, R.drawable.kate, R.drawable.keith, R.drawable.matt, R.drawable.rickey};
Toast.makeText(this, ""+drwables.length, Toast.LENGTH_SHORT).show();
//This code here
//bgimage.setImageResource(drwables[n]);
}
else{
bgimage = (ImageView) findViewById(R.id.imgOne);
}
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mListView = (ListView) findViewById(R.id.left_drawer);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
String[] names = getResources().getStringArray(R.array.bandImages);
ArrayAdapter<String> itemsAdapter = new ArrayAdapter<String>(this, R.layout.nav_list_row, R.id.textView, names);
mListView.setAdapter(itemsAdapter);
mListView.setOnItemClickListener(this);
toggle = new ActionBarDrawerToggle(this, mDrawerLayout, (Toolbar) findViewById(R.id.toolbar), R.string.open, R.string.closed) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(getTitle());
invalidateOptionsMenu();
}
public void onDrawerOpened(View view) {
super.onDrawerOpened(view);
getSupportActionBar().setTitle(getTitle());
invalidateOptionsMenu();
}
};
mDrawerLayout.addDrawerListener(toggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toggle.syncState();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
int n = Integer.parseInt(bgimage.getTag().toString());
savedInstanceState.putInt("imageId", n);
super.onSaveInstanceState(savedInstanceState);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mListView);
menu.findItem(R.id.action_about).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bgimage = (ImageView) findViewById(R.id.imgOne);
bgimage.setImageResource(drwables[position]);
bgimage.setTag(position);
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if(R.id.action_about == id){
Toast.makeText(this, "Lab 2 Spring 2016, Zack G Johnson", Toast.LENGTH_SHORT).show();
return true;
}
else{
return super.onOptionsItemSelected(item);
}
}
}
Try to place setContentView method before finding and using layout elements.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//put it here
setContentView(R.layout.activity_main);
if(savedInstanceState != null){
Toast.makeText(this, "made it", Toast.LENGTH_SHORT).show();
int n = savedInstanceState.getInt("imageId");
Toast.makeText(this, ""+n, Toast.LENGTH_SHORT).show();
bgimage = (ImageView) findViewById(R.id.imgOne);
int[] drwables = {R.drawable.cindy, R.drawable.fred, R.drawable.kate, R.drawable.keith, R.drawable.matt, R.drawable.rickey};
Toast.makeText(this, ""+drwables.length, Toast.LENGTH_SHORT).show();
//This code here
//bgimage.setImageResource(drwables[n]);
}
else{
bgimage = (ImageView) findViewById(R.id.imgOne);
}
...
In my Activity I have a drawer list that pops from the right but I'm not able to move the drawer toggle from the left to the right side. Please if somebody can help me solve this issue.I just want to move the toggle to the right of the action bar.
package com.parse.starter;
import com.parse.ParseUser;
public class UserDrawer extends AppCompatActivity {
//Declaring Variables
private ListView DrawerList;
private ArrayAdapter<String> Adapter;
private ActionBarDrawerToggle DrawerToggle;
private DrawerLayout DrawerLayout;
private String ActivityTitle;
final ParseUser currentUser = ParseUser.getCurrentUser();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_drawer);
DrawerList = (ListView) findViewById(R.id.navList);
DrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
Button Sample = (Button) findViewById(R.id.button);
}
//Method To Add Items To The List View
private void addDrawerItems() {
String[] DArray = {"Job List", "Notifications", "Messages", "Log Out"};
Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, DArray);
DrawerList.setAdapter(Adapter);
DrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
Intent i0 = new Intent(UserDrawer.this, Set_Info.class);
startActivity(i0);
} else if (position == 1) {
//Intent i1 = new Intent(Drawer1.this, AddPatient.class);
//startActivity(i1);
} else if (position == 2) {
//Intent i2 = new Intent(Drawer1.this, Notifications.class);
//startActivity(i2);
} else if (position == 3) {
//Intent i3 = new Intent(Drawer1.this, Message_Log.class);
//startActivity(i3);
} else if (position == 4) {
Intent i4 = new Intent(UserDrawer.this, MainActivity.class);
startActivity(i4);
Toast.makeText(getApplicationContext(), "You are Logged Out", Toast.LENGTH_LONG).show();
finish();
}
}
});
}
private void setupDrawer() {
DrawerToggle = new ActionBarDrawerToggle(this, DrawerLayout,
R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Menu");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(ActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
DrawerToggle.setDrawerIndicatorEnabled(true);
DrawerLayout.setDrawerListener(DrawerToggle);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item != null && item.getItemId()==android.R.id.home){
if(DrawerLayout.isDrawerOpen(Gravity.RIGHT)){
//Notice the Gravity.Right
DrawerLayout.closeDrawer(Gravity.RIGHT);
}else{
DrawerLayout.openDrawer(Gravity.RIGHT);
}
}
return false;
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
DrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
DrawerToggle.onConfigurationChanged(newConfig);
}
#SuppressWarnings("ResourceType")
public void SampleClick(View view) {
try {
Intent i = new Intent(UserDrawer.this,Set_Info.class);
startActivity(i);
} catch (Exception e) {
}
}
}
This happens to me when in my app when I rotate my phone after I tap the menu key/button, on the phone, (the button on the left of the home button on the device) to show the small settings dialog.
I've google a lot about this issue and I understand that I need to close/dismiss this dialog when my Activity is destroyed (onDestroy()). The problem is I don't know how I can accomplish this.
The even more weird thing is if I tap on the settings button on the action bar of my app to show the small settings dialog and I rotate the device no exception in generated. The exception only occurs if I used the device's menu button.
Here's the menu key/button I'm talking about:
Here is my app after I tap the menu key and the small settings dialog pops up, here if I rotate the device the exception is generated:
Here is the device after the exception been generated, AKA, after rotating the device from the previous image:
I'm running android 4.4.2 CyanogenMod.
Here is the code I think may be related to this issue:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_menu_settings)
{
SettingsFragment settingsFragment = new SettingsFragment();
// settingsFragment.setHttpService(appService);
getFragmentManager().beginTransaction().replace(R.id.content_frame, settingsFragment).addToBackStack("Settings").commit();
return true;
}
else if(mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the drawer is open, hide action items related to the content view
Log.d(TAG, "Butao do menu");
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_menu_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
Log.d(TAG, "onConfigurationChanged - Activity");
}
And I tried calling the closeOptionsMenu() method on the onDestroy() but to no success.
#Override
protected void onDestroy() {
super.onDestroy();
closeOptionsMenu();
}
Here is this stack trace:
android.view.WindowLeaked: Activity com.my.package.design.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41865120 V.E..... ......I. 0,0-399,84} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:348)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at com.android.internal.policy.impl.PhoneWindow.openPanel(PhoneWindow.java:725)
at com.android.internal.policy.impl.PhoneWindow.openPanelsAfterRestore(PhoneWindow.java:1899)
at com.android.internal.policy.impl.PhoneWindow.access$2200(PhoneWindow.java:128)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onAttachedToWindow(PhoneWindow.java:2939)
at android.view.View.dispatchAttachedToWindow(View.java:12592)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2458)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1217)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:544)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5081)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607)
at dalvik.system.NativeStart.main(Native Method)
Any help would be greatly appreciated.
------------------ EDIT --------------------------
Here's my full MainActivity.class code
public class MainActivity extends Activity {
private String hello = "hello";
private static final String TAG = "MainActivity";
private static final String TAG_TASK_FRAGMENT = "task_fragment";
// private final MainLooperSpy mainLooperSpy = new MainLooperSpy();
private boolean isBound = false;
private RetainedFragment retainedFragment;
private WebService webService;
// Get application context
final Context appContext = ApplicationContextProvider.getContext();
// Menu item tittle
private static final String MENU_TITTLE = "Select an Item";
// Within which the entire activity is enclosed
private DrawerLayout mDrawerLayout;
// ListView represents Navigation Drawer
private ListView mDrawerList;
// ActionBarDrawerToggle indicates the presence of Navigation Drawer in the action bar
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CustomDrawerAdapter adapter;
List<DrawerItem> dataList;
// Title of the action bar
String mTitle="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webService = ApplicationContextProvider.getWebService();
dataList = new ArrayList<DrawerItem>();
mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.drawer_list);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
dataList.add(new DrawerItem(true)); // adding a spinner to the list
dataList.add(new DrawerItem("Contacts")); // adding a header to the list
dataList.add(new DrawerItem("Contact List", R.drawable.ic_action_email));
dataList.add(new DrawerItem("Duplicates", R.drawable.ic_action_good));
dataList.add(new DrawerItem("Similares", R.drawable.ic_action_gamepad));
dataList.add(new DrawerItem("Http Server"));// adding a header to the list
dataList.add(new DrawerItem("Configuration", R.drawable.ic_action_search));
dataList.add(new DrawerItem("Backups")); // adding a header to the list
dataList.add(new DrawerItem("Local Backups", R.drawable.ic_action_import_export));
dataList.add(new DrawerItem("Cloud Backups", R.drawable.ic_action_cloud));
dataList.add(new DrawerItem("Help", R.drawable.ic_action_help));
adapter = new CustomDrawerAdapter(this, R.layout.custom_drawer_item, dataList);
mDrawerList.setAdapter(adapter);
mTitle = getTitle().toString();
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close){
// Called when drawer is closed
public void onDrawerClosed(View view)
{
super.onDrawerClosed(view);
getActionBar().setTitle(mTitle);
}
// Called when a drawer is opened
public void onDrawerOpened(View drawerView)
{
super.onDrawerOpened(drawerView);
getActionBar().setTitle(MENU_TITTLE);
}
};
// Setting DrawerToggle on DrawerLayout
mDrawerLayout.setDrawerListener(mDrawerToggle);
// Creating an ArrayAdapter to add items to the listview mDrawerList
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), R.layout.drawer_list_item, getResources().getStringArray(R.array.menu_list));
// Setting item click listener for the listview mDrawerList
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (dataList.get(position).getTitle() == null)
{
selectItem(position);
}
}
});
// Set the App icon has up button
ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
if (savedInstanceState == null)
{
if (dataList.get(0).isSpinner() & dataList.get(1).getTitle() != null)
{
selectItem(3); // 2
}
else if (dataList.get(0).getTitle() != null)
{
selectItem(1);
}
else
{
selectItem(0);
}
}
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
FragmentManager fm = getFragmentManager();
retainedFragment = (RetainedFragment) fm.findFragmentByTag(TAG_TASK_FRAGMENT);
if (retainedFragment == null)
{
retainedFragment = new RetainedFragment();
fm.beginTransaction().add(retainedFragment, TAG_TASK_FRAGMENT).commit();
}
} // end onCreate()
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void setTitle(CharSequence title) {
getActionBar().setTitle(title);
}
#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;
}
/** Handling the touch event of app icon and settings icon */
#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();
if (id == R.id.action_menu_settings)
{
SettingsFragment settingsFragment = new SettingsFragment();
// settingsFragment.setHttpService(appService);
getFragmentManager().beginTransaction().replace(R.id.content_frame, settingsFragment).addToBackStack("Settings").commit();
return true;
}
else if(mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/** Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the drawer is open, hide action items related to the content view
Log.d(TAG, "Butao do menu");
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_menu_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
Log.d(TAG, "onConfigurationChanged - Activity");
}
public void selectItem(int position) {
Fragment fragment = null;
switch (position) {
case 2:
fragment = new PlaceholderFragment();
break;
case 3:
fragment = new ContactMenuFragment();
break;
case 4:
fragment = new ContactMenuFragment();
break;
case 6:
fragment = new HttpMenuFragment();
break;
case 8:
fragment = new SlidingFragment();
break;
case 9:
fragment = new SlidingFragment();
break;
case 10:
fragment = new SlidingFragment();
break;
default:
break;
}
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
setTitle(dataList.get(position).getItemName());
mDrawerLayout.closeDrawer(mDrawerList);
}
// Bind to the service
#Override
protected void onStart()
{
super.onStart();
if(webService.isStarted() == false)
{
webService.startServer(appContext);
}
}
#Override
protected void onStop()
{
super.onStop();
if(webService.isStarted() == true)
{
webService.stopServer();
}
Log.d(TAG, "onStop - Activity");
// mainLooperSpy.dumpQueue();
}
// Check whether the http server is set to run at startup or not
// From the preferences settings
public boolean isServerSetToRunAtStartUp()
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
if(sharedPreferences.contains(SettingsFragment.HTTP_RUN_AT_STARTUP))
{
Log.d(TAG, "Key found!");
}
else
{
Log.d(TAG, "Key does not exist!");
}
if(sharedPreferences.getBoolean(SettingsFragment.HTTP_RUN_AT_STARTUP, false) == false)
{
return false;
}
if(sharedPreferences.getBoolean(SettingsFragment.HTTP_RUN_AT_STARTUP, false) == true)
{
Log.d(TAG, "isServerSetToRunAtStartUp - deu verdadeiro");
return true;
}
return false;
}
#Override
protected void onUserLeaveHint() {
super.onUserLeaveHint();
Log.d(TAG, "onUserLeaveHint - Activity");
// mainLooperSpy.dumpQueue();
}
#Override
public void onUserInteraction() {
super.onUserInteraction();
Log.d(TAG, "onUserInteraction - Activity");
// mainLooperSpy.dumpQueue();
}
#Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause - Activity");
// mainLooperSpy.dumpQueue();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
closeOptionsMenu();
Log.d(TAG, "onSaveInstanceState - Activity");
// mainLooperSpy.dumpQueue();
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume - Activity");
// mainLooperSpy.dumpQueue();
}
#Override
protected void onDestroy() {
closeOptionsMenu();
super.onDestroy();
// closeOptionsMenu();
Log.d(TAG, "onDestroy - Activity");
webService.stopServer();
// mainLooperSpy.dumpQueue();
}
}
If you look at your stack trace, it states that the window leak occurs at line 725 of your PhoneWindow class. The error is occurring because you are attempting to add a new view to a window that has changed or has been removed or has not been initialized yet. make sure your layouts are established and stable before adding a view or changing a view within that layout.
I'm having lot of problems when implementing ActionBar Sherlock, the last one is this one. I have an Slide Menu whith 3 options in my ActionBar. My problem is that when I choose one item (it load a fragment) that has been previously selected the app crash. The log error is
The specified child already has a parent. You must call removeView()
on the child's parent first.
It mark a line where I add view to a HorizontalScroller.
lls.addView(mviews.get(i));
In my OnCreateView I have
final View v = inflater.inflate(R.layout.activity_landing, container,false);
container.removeAllViews();
I haved tried many different ways posted here, but I don't get thw solution to my problem. Any ideas?
EDIT:
Here is some code of my MainActivity and Fragment.
This is the MainActivity. Ther's a ScreenSplash after and a class that extends from Application that control all WebService communications.
public class MainActivity extends SherlockFragmentActivity {
//Declare Variables
//...
Fragment fragment1 = new Fragment1();
Fragment fragment2 = new Fragment2();
Fragment fragment3 = new Fragment3();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().setIcon(R.drawable.ic_launcher);
getSupportActionBar().setTitle("");
setContentView(R.layout.drawer_main);
// Generate title
title = new String[] { "Item 1", "Item 2", "Item 3", "Item 4" };
// Generate icon
icon = new int[] { R.drawable.item1, R.drawable.item2,
R.drawable.item3, R.drawable.item4};
// Locate DrawerLayout in drawer_main.xml
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// Locate ListView in drawer_main.xml
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// Pass results to MenuListAdapter Class
mMenuAdapter = new MenuListAdapter(this, title, subtitle, icon);
// Set the MenuListAdapter to the ListView
mDrawerList.setAdapter(mMenuAdapter);
// Capture button clicks on side menu
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// Enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
// TODO Auto-generated method stub
super.onDrawerClosed(view);
}
public void onDrawerOpened(View drawerView) {
// TODO Auto-generated method stub
super.onDrawerOpened(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
//FOR ABS y ND
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.activity_main, menu);
//Define ActionBar buttons and actions
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//Sliding lateral Menu
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
}
return super.onOptionsItemSelected(item);
}
// The click listener for ListView in the navigation 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) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Locate Position
switch (position) {
case 0:
ft.replace(R.id.content_frame, fragment1);
break;
case 1:
ft.replace(R.id.content_frame, fragment2);
break;
case 2:
ft.replace(R.id.content_frame, fragment3);
break;
}
ft.commit();
mDrawerList.setItemChecked(position, true);
// Close drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
#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);
}
}
This is the fragment with error. Now the other two are empty.
public class Fragment1 extends SherlockFragment implements
AdapterView.OnItemClickListener {
//DeclareVariables
public Fragment1() {
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//some declaration ad settings (witdhs, typefaces, caches,...)
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.main_activity, null,
false);
container.removeAllViews();
lls = (LinearLayout) v.findViewById(R.id.lscroll_item);
lls.removeAllViews();
//Instantiate some elements of the view such as TextViews and ImageViews
//layoutParams
// Show Scroll
DataStore.sharedInstance().getInfo(
new DataStore.infoReturn() {
#Override
public void call(final ArrayList<User> users, int error) {
if(users != null){
for (i = 0; i < users.size(); i++) {
mviews.add((RelativeLayout) getActivity().getLayoutInflater().inflate(R.layout.item_user, null));
mviews.get(i).setLayoutParams(layoutParams2);
imv = (ImageView) mviews.get(i).findViewById(R.id.user);
imv.getLayoutParams().height=friend_height;
imv_click = (ImageView) mviews.get(i).findViewById(R.id.click);
TextView text2 = (TextView) mviews.get(i).findViewById(R.id.fav);
text2.setTypeface(myTypeFace);
//set widths and layoutParams and sources
mviews.get(i).setId(i);
//NEXT LINE IS THE CRASH POINT, WHERE I TRY TO ADD ITEMS TO THE VIEW
lls.addView(mviews.get(i));
mviews.get(i).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
//Set actins when click
}
});
}
}else{
switch (error) {
case -1: //ERROR OBTENER USERS
break;
default:
break;
}
}
}
});
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// actions when click
}
#Override
public void onResume() {
super.onResume();
refreshInfo();
refreshSelectedUsers();
}
#Override
public void onPause() {
super.onPause();
DataStore.sharedInstance().setSelectedUsers(mSelected);
}
#Override
public void onDestroy() {
super.onDestroy();
//delete cache
}
//Some other methods for other UI items.
}
I have hidden some code to make it easier to read.
Use this
final View v = inflater.inflate(R.layout.activity_landing, null, false);
instead of
final View v = inflater.inflate(R.layout.activity_landing, container,false);
I have one problem, how to implement a merchandising display before starting my navigation drawer. this is my code. Thanks for help guys.
This is my code merchan, but is wrong, I want to call this screen before the application itself, which is basically a navigation drawer.
public class Merchan extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.merchan);
Thread logoTimer = new Thread() {
public void run() {
try {
sleep(3000);
Intent menuIntent = new Intent("com.codehevea.menu.Main");
startActivity(menuIntent);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
finish();
}
}
};
logoTimer.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
And this is my principal class. It should boot screen after merchandising.
public class Main extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mMenuTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mMenuTitles = getResources().getStringArray(R.array.menu_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// 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
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mMenuTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content
// view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch (item.getItemId()) {
case R.id.action_websearch:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available,
Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listner for ListView in the navigation 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 by replacing fragments
Fragment fragment = new MenuFragment();
Bundle args = new Bundle();
args.putInt(MenuFragment.ARG_MENU_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mMenuTitles[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);
}
/**
* Fragment that appears in the "content_frame", shows a planet
*/
public static class MenuFragment extends Fragment {
public static final String ARG_MENU_NUMBER = "planet_number";
public MenuFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet,
container, false);
int i = getArguments().getInt(ARG_MENU_NUMBER);
String planet = getResources().getStringArray(R.array.menu_array)[i];
int imageId = getResources().getIdentifier(
planet.toLowerCase(Locale.getDefault()), "drawable",
getActivity().getPackageName());
((ImageView) rootView.findViewById(R.id.image))
.setImageResource(imageId);
getActivity().setTitle(planet);
return rootView;
}
}
}
You're using the wrong Intent constructor. Change it to something like:
Intent menuIntent = new Intent(this, com.codehevea.menu.Main.class);
Note, if the current and target class are in the same package, you don't need the package name, so:
Intent menuIntent = new Intent(this, Main.class);
For more on this, visit Starting Another Activity.