my app has no error yet it is showing an error "unfortunately zine has stopped"
main activity.java
package piestudio.zine;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
public class MainActivity extends ActionBarActivity{
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUP((DrawerLayout) findViewById(R.id.drawer_layout),toolbar);
}
}
`
navigation drawer activity
package piestudio.zine;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class NavigationDrawerFragment extends Fragment {
public static final String PREF_FILE_NAME = "testpref";
public static final String KEY_USER_LEARNED_DRAWER="user_learned_drawer";
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
public NavigationDrawerFragment() {
// Required empty public constructor
}
#Override
public void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUserLearnedDrawer=Boolean.valueOf(readFromPreferences(getActivity(),KEY_USER_LEARNED_DRAWER,"false"));
if(savedInstanceState!=null){
mFromSavedInstanceState=true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
}
public void setUP(DrawerLayout drawerLayout, Toolbar toolbar) {
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
public static void saveToPreferences(Context context, String preferenceName, String preferenceValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(preferenceName, preferenceValue);
editor.apply();
}
public static String readFromPreferences(Context context, String preferenceName, String defaultValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(preferenceName,defaultValue);
}
}
now as you can see the code , now whenever i try to run this on my phone (as my emulator is not working ) it stops by saying ## unfortunatley,zine has stopped
Try changing this code
private Toolbar toolbar;
to this
android.support.v7.widget.Toolbar
and see whether the crash is happening or not. Please logcat output so that we can debug the crash in a better manner.
Related
I've successfully build this app but the app keep on crashing in my emulator/phone. It seen like it can't read my MainActivity
MainActivity.java
package com.example.remotelab;
private NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;
public static Socket clientSocket = null;
public static ObjectInputStream objectInputStream = null;
public static ObjectOutputStream objectOutputStream = null;
private static ActionBarActivity thisActivity;
private boolean doubleBackToExitPressedOnce = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
thisActivity = this;
mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
.findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//checkForPermission();
}
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager
.beginTransaction()
.replace(R.id.container,
returnAppropriateFragment(position + 1)).commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
}
my app crash and send me this bug report on my phone
main_activity.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.remotelab.MainActivity" >
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<fragment
android:id="#+id/navigation_drawer"
android:name="com.example.remotecontrolpc.NavigationDrawerFragment"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
NavigationDrawerFragnent.java
package com.example.remotelab;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class NavigationDrawerFragment extends Fragment {
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private NavigationDrawerCallbacks mCallbacks;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState
.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
selectItem(position);
}
});
NavigationDrawerItem navigationDrawerItems[] = new NavigationDrawerItem[] {
new NavigationDrawerItem(R.drawable.connect, getString(R.string.connect)),
new NavigationDrawerItem(R.drawable.touchpad, getString(R.string.touchpad)),
new NavigationDrawerItem(R.drawable.keyboard, getString(R.string.keyboard)),
new NavigationDrawerItem(R.drawable.file_transfer, getString(R.string.file_transfer)),
new NavigationDrawerItem(R.drawable.presentation, getString(R.string.presentation)),
new NavigationDrawerItem(R.drawable.power_off, getString(R.string.power_off))
};
mDrawerListView.setAdapter(new NavigationDrawerItemAdapter(getActionBar().getThemedContext(),
R.layout.listview_item_navigation_drawer, navigationDrawerItems));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null
&& mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(getActivity(),
mDrawerLayout,
R.drawable.ic_drawer,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true)
.apply();
}
getActivity().supportInvalidateOptionsMenu();
}
};
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException(
"Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
public static interface NavigationDrawerCallbacks {
void onNavigationDrawerItemSelected(int position);
}
}
Got The Bug
You Have To Remove All Unwanted Code From Android's Default Fragment Creation's.
Take Backup Of NavigationDrawerFragment File and Replace Below NavigationDrawerFragment with your NavigationDrawerFragment File.
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class NavigationDrawerFragment extends Fragment {
private Context mContext;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
mContext = view.getContext();
initialiseView(view);
return view;
}
private void initialiseView(View view) {
//DO ANY INSTANCE VARIABLE INITIALISATION
}
}
I'm trying to use an unique activity that contain navigation view and their option will open another fragment. Everything is ok, unless the MainFragment is being recreated when back from another fragment (that was opened from the navigation view). I'd like to know how to avoid this because it's loading the list again.
MainActivity:
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(R.string.home);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getSupportFragmentManager().beginTransaction()
.add(R.id.layout, new MainFragment())
.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.getMenu().findItem(R.id.nav_home).setChecked(true);
getSupportFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
}
switch (item.getItemId()) {
case R.id.nav_history:
getSupportFragmentManager().beginTransaction()
.replace(R.id.layout, new Fragment2())
.addToBackStack(null)
.commit();
break;
case R.id.nav_settings:
break;
case R.id.nav_logout:
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Main Fragment:
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import br.com.example.adapters.ScheduledServicesAdapter;
import br.com.example.entities.ScheduledService;
public class MainFragment extends Fragment {
private final class ScheduleServiceTask extends AsyncTask<Void, Void, List<ScheduledService>> {
#Override
protected List<ScheduledService> doInBackground(Void... params) {
mList = new ArrayList<>();
mList.add(new ScheduledService(new Date(), 250.50, 0));
mList.add(new ScheduledService(new Date(), 50.75, 0));
return mList;
}
#Override
protected void onPostExecute(List<ScheduledService> scheduledServices) {
super.onPostExecute(scheduledServices);
setData(scheduledServices);
}
}
private RecyclerView mRecyclerView;
private ScheduledServicesAdapter mAdapter;
private List<ScheduledService> mList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
super.onCreateView(inflater, parent, savedInstanceState);
return inflater.inflate(R.layout.content_main, parent, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getActivity(),
linearLayoutManager.getOrientation());
mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.addItemDecoration(dividerItemDecoration);
new ScheduleServiceTask().execute();
}
private void setData(List<ScheduledService> list) {
ProgressBar progressBar = (ProgressBar) getActivity().findViewById(R.id.progress_bar);
progressBar.setVisibility(View.GONE);
if (!list.isEmpty()) {
mAdapter = new ScheduledServicesAdapter(list);
mRecyclerView.setAdapter(mAdapter);
} else {
TextView emptyText = (TextView) getActivity().findViewById(R.id.empty_text);
emptyText.setVisibility(View.VISIBLE);
}
}
}
Fragment 2 has a hello world text view for test purpose.
When you put your MainFragment to BackStack (means that the view
of this fragment is not visible because Fragment2 take the
screen), all the views which belong to it will be destroyed.
Then when you back to MainFragment from another fragment, view of
MainFragment will be re-created. That mean onCreateView and onViewCreated will be
called again.
In your case, I suggest:
Move new ScheduleServiceTask().execute(); to onCreate or to
another method (example: requestGetData())
Init mAdapter and set adapter for mRecyclerView in onViewCreated()
On setData() method, all you need is re-set data for mAdapter and call notifyDatasetChanged() function.
#Douglas Fomaro, Better you can move your data(mList) outside fragment. Maintain DataManager Class that hold all your list data value.
I have a MainActivity that has a NavigationDrawer in it.In the menu of the drawer each item starts a new activity.Now when i press the Back button from any of these activities i end up in a blank page,when i press it again it goes to main activity.What i want is to go directly to the main activity.
my MainActivity.java:
package com.defcomm.invento;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.defcomm.invento.NavigationDrawerActivity;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class INVENTO extends AppCompatActivity {
private Toolbar toolbar;
private CoordinatorLayout mCoordinator;
private CollapsingToolbarLayout mCollapsableLayout;
private NestedScrollView nestedScrollView;
private ViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
mCoordinator= (CoordinatorLayout) findViewById(R.id.coordinator_layout);
mCollapsableLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
toolbar= (Toolbar) findViewById(R.id.appbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
mCollapsableLayout.setTitle(getResources().getString(R.string.app_name));
nestedScrollView= (NestedScrollView) findViewById(R.id.rvToDoList);
mCollapsableLayout.setExpandedTitleTextAppearance(R.style.ExpandedTitleTextAppearence);
mCollapsableLayout.setCollapsedTitleTextColor(getResources().getColor(R.color.textColor));
NavigationDrawerActivity drawerFragment= (NavigationDrawerActivity) getSupportFragmentManager().
findFragmentById(R.id.navigation_drawer);
drawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawerlayout), toolbar);
}
#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_invento, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
my NavigationDrawer.java1:
package com.defcomm.invento;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.support.design.widget.CollapsingToolbarLayout;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import java.util.ArrayList;
import java.util.List;
public class NavigationDrawerActivity extends Fragment implements MyAdapter.clickListener {
private ActionBarDrawerToggle mdrawerToggle;
private DrawerLayout mdrawerLayout;
private boolean mUserLearnedState;
private MyAdapter adapter;
private CoordinatorLayout mcoordinator;
private RecyclerView recyclerView;
private CollapsingToolbarLayout collapsingToolbarLayout;
View containerId;
public static final String file_pref_name = "Testpef";
public static final String KEY_USER_VALUE = "user_learned_drawer";
private boolean mfromSavedInstanceState;
public NavigationDrawerActivity() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUserLearnedState = Boolean.valueOf(readPreference(getActivity(), KEY_USER_VALUE, "false"));
if (savedInstanceState != null) {
mfromSavedInstanceState = true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout=inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView= (RecyclerView) layout.findViewById(R.id.recycler);
adapter=new MyAdapter(getActivity(),getdata());
adapter.setClicklistener(this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return layout;
}
public static List<ListItems> getdata(){
List<ListItems> nav_data=new ArrayList<>();
int[] icons={R.drawable.variable,R.drawable.ignore};
String[] texts={"Coding","Hacking"};
for(int i=0;i<icons.length&&i<icons.length;i++){
ListItems current=new ListItems();
current.iconId=icons[i];
current.IconName=texts[i];
nav_data.add(current);
}
return nav_data;
}
public void setUp(final int fragmentId, DrawerLayout drawerlayout, final Toolbar toolbar) {
mdrawerLayout = drawerlayout;
containerId = getActivity().findViewById(fragmentId);
mdrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerlayout, toolbar,
R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!mUserLearnedState) {
mUserLearnedState = true;
saveToPreference(getActivity(), KEY_USER_VALUE, mUserLearnedState + "");
}
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
if (slideOffset < 0.5f) {
toolbar.setAlpha(1 - slideOffset);
}
}
};
if (!mUserLearnedState && !mfromSavedInstanceState) {
mdrawerLayout.openDrawer(containerId);
}
mdrawerLayout.setDrawerListener(mdrawerToggle);
mdrawerLayout.post(new Runnable() {
#Override
public void run() {
mdrawerToggle.syncState();
}
});
}
public static void saveToPreference(Context context, String preferenceName, String preferenceValue) {
SharedPreferences shared = context.getSharedPreferences(file_pref_name, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString(preferenceName, preferenceValue);
editor.apply();
}
public static String readPreference(Context context, String preferenceName, String defaultValue) {
SharedPreferences share = context.getSharedPreferences(file_pref_name, Context.MODE_PRIVATE);
return share.getString(preferenceName, defaultValue);
}
#Override
public void ItemCLick(View view, int position) {
if(position==0){
startActivity(new Intent(getActivity(),Coding.class));
}
if(position==1){
startActivity(new Intent(getActivity(),Hacking.class));
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.defcomm.invento" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".INVENTO"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Coding"
android:label="#string/title_activity_coding" >
</activity>
<activity
android:name=".Hacking"
android:label="#string/title_activity_hacking" >
</activity>
</application>
you can try this.
#Override
public void onBackPressed() {
startActivity(new Intent(this,MainActivity.class));
this.finish();
}
Try this
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
This will close all other activities and start MainActivity
This will close the drawer when it's open and back is pressed rather than taking you back to the previous activity (or exiting).
DrawerLayout drawer...
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if(drawer.isDrawerOpen(Gravity.LEFT)){
drawer.closeDrawer(Gravity.LEFT);
startActivity(new Intent(CurrentActivity.this , MainActivity.class))
finish();
}else{
super.onBackPressed();
}
}
I'm trying to implement a navigation bar within my android application. However, my compilers complains with following errors:
Error:(39, 25) error: cannot find symbol variable drawer_open
Error:(39, 47) error: cannot find symbol variable drawer_close
My code:
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends ActionBarActivity {
/***********************************************************
MEMBERS
**********************************************************/
private Toolbar m_toolbar;
private String m_navTitles[] = {"Nr. 1", "Nr. 2", "Nr. 3", "Nr. 4" };
private int m_icons[] = {R.drawable.ic_action, R.drawable.ic_action, R.drawable.ic_action, R.drawable.ic_action};
private DrawerLayout m_drawer;
private ActionBarDrawerToggle m_drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Set toolbar */
m_toolbar = (Toolbar) findViewById(R.id.tool_bar); //find toolbar from layout
setSupportActionBar(m_toolbar); //call to set toolbar as the ActionBar
/* Set navigation drawer */
m_drawer = (DrawerLayout) findViewById(R.id.DrawerLayout); //assign drawer object to view
m_drawerToggle = new ActionBarDrawerToggle(this, m_drawer, m_toolbar, R.string.drawer_open, R.string.drawer_close){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
// code here will execute once the drawer is opened
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
// Code here will execute once drawer is closed
}
}; // made drawer toggle object
m_drawer.setDrawerListener(m_drawerToggle);
m_drawerToggle.syncState();
}
Please note that my code for the navigation drawer is not finished yet. I wanted to fix the drawer_open/drawer_close errors first.
Many thanks in advance!
Did you have drawer_open and drawer_close in your strings.xml?
I think you didn't add these two strings in your strings.
Try this Your pbm is solved here copy this code and replace yours :
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends ActionBarActivity {
/***********************************************************
MEMBERS
**********************************************************/
private Toolbar m_toolbar;
private String m_navTitles[] = {"Nr. 1", "Nr. 2", "Nr. 3", "Nr. 4" };
private int m_icons[] = {R.drawable.ic_action, R.drawable.ic_action, R.drawable.ic_action, R.drawable.ic_action};
private DrawerLayout m_drawer;
private ActionBarDrawerToggle m_drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Set toolbar */
m_toolbar = (Toolbar) findViewById(R.id.tool_bar); //find toolbar from layout
setSupportActionBar(m_toolbar); //call to set toolbar as the ActionBar
/* Set navigation drawer */
m_drawer = (DrawerLayout) findViewById(R.id.DrawerLayout); //assign drawer object to view
m_drawerToggle = new ActionBarDrawerToggle(this, m_drawer, m_toolbar, "drawer_open", "drawer_close"){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
// code here will execute once the drawer is opened
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
// Code here will execute once drawer is closed
}
}; // made drawer toggle object
m_drawer.setDrawerListener(m_drawerToggle);
m_drawerToggle.syncState();
}
so what i am trying is if the DrawerLayout is open and than i rotated the screen the DrawerLayout should close , but it does not
here is the code
package com.moammedx.learingmaterial;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.widget.Toast;
public class NavigationDrwaerFragment extends Fragment {
public static final String PREF_FILE_NAME = "testpref";
public static final String KEY_USER_LEARNED_DRAWER = "user_learnd_drawer";
private View contenerView;
private ActionBarDrawerToggle mDrawerTolggle;
private DrawerLayout mDrawerLayout;
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
public NavigationDrwaerFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUserLearnedDrawer = Boolean.valueOf(readFromPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, "false"));
if (savedInstanceState != null) {
mFromSavedInstanceState = true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_navigation_drwaer, container, false);
}
public void SetUp(int fragmenID, DrawerLayout drawerlayout, Toolbar toolbar) {
contenerView = getActivity().findViewById(fragmenID);
mDrawerLayout = drawerlayout;
mDrawerTolggle = new ActionBarDrawerToggle(getActivity(), drawerlayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
if (!mUserLearnedDrawer) {
super.onDrawerOpened(drawerView);
mUserLearnedDrawer = true;
saveToPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, mUserLearnedDrawer + "");
}
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
Toast.makeText(getActivity(), "onDrawerClosed", Toast.LENGTH_SHORT).show();
}
};
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(contenerView);
}
if (mFromSavedInstanceState) {
Toast.makeText(getActivity(), "close now", Toast.LENGTH_SHORT).show();
mDrawerLayout.closeDrawer(contenerView);
}
mDrawerLayout.setDrawerListener(mDrawerTolggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerTolggle.syncState();
}
});
}
public static void saveToPreferences(Context context, String preferencesName, String preferencesValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(preferencesName, preferencesValue);
editor.apply();
}
public static String readFromPreferences(Context context, String preferencesName, String defaultValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(preferencesName, defaultValue);
}
}
the SetUp method is called from the main activity
In the onCreat i checked of savedInstanceState is exist
and later inside the SetUp i used .colseDrawer to close the DrawerLayout , but it does not close , and i added for toast just for test and it show up when i rotate the screen
The reason is because the inner workings of the DrawerLayout close command is not wrapped in a post runnable. Meaning, your close command will fire, but before it's state saving kicks in and returns it to it's previous state (in this case open). To fix from your code, simply wrap the contents of your close command in a post runnable. It'll execute after the onCreate() and onRestoreState() are called, closing your drawer on rotation.
Will i solve it by adding .closeDrawer in onResume
public void onResume() {
super.onResume();
mDrawerLayout.closeDrawer(contenerView);
}
It is better to close it on onRestoreInstanceState
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
mDrawerLayout.closeDrawer(GravityCompat.START, false)
}