Adding Class Activity to Navigation Drawer Android - android

Can you tell me how to add class activity into navigation drawer? I am going to create one app where i need to have more than one classes. all of these classes extends activity.I know how to add fragment into navigation drawer but i dont understand how do i add class activity into navigation drawer.

You can add activity for this code....
public class test extends Activity implements View.OnClickListener {
private HeaderBar topActionBar;
private DrawerLayoutAdapter drawerLayoutAdapter;
private DrawerLayout drawerLayout;
private ListView leftDrawer;
private String[] drawerTitle = {"", "Test1", "Test2", "Test3", "Test4", "Test5"};
private int[] drawerIcons = {0,
R.drawable.Test1,
R.drawable.Test2,
R.drawable.Test3,
R.drawable.Test4,
R.drawable.Test5};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawerLayoutAdapter = new DrawerLayoutAdapter(test.this, drawerTitle, drawerIcons);
setContentView(R.layout.activity_test);
setId();
setHeaderBar();
changeStatusBarColor();
DrawerLayout.LayoutParams layoutParams = (DrawerLayout.LayoutParams) leftDrawer.getLayoutParams();
leftDrawer.setLayoutParams(layoutParams);
leftDrawer.setAdapter(drawerLayoutAdapter);
if (drawerLayout.isDrawerOpen(leftDrawer)) {
drawerLayout.closeDrawer(leftDrawer);
}
leftDrawer.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int pos, long id) {
drawerLayout.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
});
drawerLayout.closeDrawer(leftDrawer);
displayView(pos);
}
});
}
private void changeStatusBarColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(getResources().getColor(R.color.blue));
}
}
private void setId() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
leftDrawer = (ListView) findViewById(R.id.left_drawer);
leftDrawer = (ListView) findViewById(R.id.left_drawer);
}
private void setHeaderBar() {
try {
topActionBar.ivLeft.setVisibility(View.VISIBLE);
topActionBar.ivLeft.setBackgroundResource(R.drawable.menu);
topActionBar.ivLeft.setOnClickListener(this);
topActionBar.tvTitle.setText(R.string.tilte);
} catch (Exception e) {
e.printStackTrace();
}
}
public void openDrawer() {
try {
leftDrawer.invalidateViews();
drawerLayout.openDrawer(leftDrawer);
} catch (Exception e) {
e.printStackTrace();
}
}
private void closeDrawer() {
try {
if (drawerLayout.isDrawerOpen(leftDrawer))
drawerLayout.closeDrawer(leftDrawer);
} catch (Exception e) {
e.printStackTrace();
}
}
private void displayView(final int positionTitle) {
closeDrawer();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
switch (positionTitle) {
case 0:
break;
case 1:
Intent a = new Intent(test.this, act1.class);
startActivity(a);
break;
case 2:
Intent b = new Intent(test.this, act2.class);
startActivity(b);
break;
case 3:
Intent c = new Intent(test.this, act3.class);
startActivity(c);
break;
case 4:
Intent d = new Intent(test.this, act4.class);
startActivity(d);
break;
case 5:
Intent e = new Intent(test.this, act5.class);
startActivity(e);
break;
default:
break;
}
}
}, 200);
}
#Override
public void onClick(View v) {
try {
switch (v.getId()) {
case R.id.ivLeft:
openDrawer();
break;
default:
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Related

My application showing blank screen for 2 minutes after login for the first time

In my application for the first time when a user logged in, it is taking 2 min to show the home screen.in that time the screen showing as blank.and it is working fine with oreo version. and application is running fine on emulator also.but when i test with mobile it is showing blank. please help me to resolve it.
public class HomeActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener, TabLayout.OnTabSelectedListener {
public static MyAppDataBase myAppDataBase;
ViewPager mViewPager;
SectionsPagerAdapter mSectionsPagerAdapter;
DrawerLayout drawer;
NavigationView navigationView;
ImageView nav_header_profile;
int job_rows_count, policy_row_count;
ImageView img_view_gov_jobs, img_view_my_servant, img_view_gov_policies;
TextView nav_hedaer_user_name, nav_header_mobile;
FloatingActionButton floatingActionButton;
int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
DatabaseReference contactsRef;
UserInfoTable infoTable;
InternetConnection internetConnection;
ContentObserver observer;
String lastTimeStamp;
String previous_timestamp;
List<String> no_of_contacts;
int contactscount;
static UserDetailsAsycTask userDetailsAsycTask;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*getWindow().setEnterTransition(null);
getWindow().setExitTransition(null);
getWindow().setAllowEnterTransitionOverlap(false);
getWindow().setAllowReturnTransitionOverlap(false);*/
setContentView(R.layout.activity_home);
PreferenceUtils.init(HomeActivity.this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Bharat Next");
floatingActionButton = (FloatingActionButton) findViewById(R.id.fab);
toolbar.setTitleTextColor(getResources().getColor(R.color.white));
myAppDataBase = Room.databaseBuilder(HomeActivity.this, MyAppDataBase.class, "userdb")
.addMigrations(MIGRATION_1_2)
.allowMainThreadQueries()
.build();
internetConnection = new InternetConnection(HomeActivity.this);
contactsRef = FirebaseDatabase.getInstance().getReference().child("Contacts");
img_view_gov_jobs = findViewById(R.id.image_view_gov_jobs_for_you);
img_view_my_servant = findViewById(R.id.image_view_my_servant);
img_view_gov_policies = findViewById(R.id.image_view_gov_policies_for_you);
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.getMenu().getItem(0).setChecked(true);
View header = navigationView.getHeaderView(0);
nav_header_profile = header.findViewById(R.id.nav_header_profile);
nav_hedaer_user_name = header.findViewById(R.id.nav_header_user_name);
nav_header_mobile = header.findViewById(R.id.nav_header_mobile_num);
// userDetailsAsycTask=new UserDetailsAsycTask(HomeActivity.this);
// get();
// infoTable=myAppDataBase.myDao().getUsers();
infoTable=myAppDataBase.myDao().getUsers();
String name = infoTable.getName();
String mobile = infoTable.getMobile_num();
nav_hedaer_user_name.setText(name);
nav_header_mobile.setText(mobile);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
mViewPager = (ViewPager) findViewById(R.id.pager);
// initializeContactUpdatesReceiver();
// getContactTimeStamp(HomeActivity.this);
if (PreferenceUtils.GetLogin()) {
InitializeSession();
}
/* mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager.setAdapter(mSectionsPagerAdapter);*/
setupViewPager(mViewPager);
// Set up the tabs for ViewPager
tabLayout.setupWithViewPager(mViewPager);
tabLayout.setOnTabSelectedListener(HomeActivity.this);
drawer = findViewById(R.id.drawer_layout);
img_view_gov_jobs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//govJobs();
if (internetConnection.checkConnection()) {
govJobs();
} else {
Toast.makeText(HomeActivity.this, "No internet connection", Toast.LENGTH_LONG).show();
}
}
});
img_view_gov_policies.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (internetConnection.checkConnection()) {
govPolicies();
} else {
Toast.makeText(HomeActivity.this, "No internet connection", Toast.LENGTH_LONG).show();
}
}
});
img_view_my_servant.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(HomeActivity.this, WorkForActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
// Toast.makeText(HomeActivity.this, "Coming soon", Toast.LENGTH_LONG).show();
}
});
nav_header_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(HomeActivity.this, UserProfile.class));
}
});
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
toggle.getDrawerArrowDrawable().setColor(getResources().getColor(R.color.white));
drawer.setDrawerListener(toggle);
toggle.syncState();
// DialogManager.showProgress(HomeActivity.this);
/*contactsRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild(infoTable.getMobile_num())){
// DialogManager.hideProgress();
contactsRef.child(infoTable.getMobile_num()).removeValue();
// DialogManager.hideProgress();
CheckContactsFragment();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("test","the error is "+databaseError);
}
});
*/
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogManager.showProgress(HomeActivity.this);
// contactsRef.child(infoTable.getMobile_num()).removeValue();
// CheckContactsFragment();
contactsRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(infoTable.getMobile_num())) {
DialogManager.hideProgress();
CheckContactsFragment();
} else if (dataSnapshot.hasChild(infoTable.getMobile_num())) {
contactsRef.child(infoTable.getMobile_num()).removeValue();
DialogManager.hideProgress();
CheckContactsFragment();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("test", "the error is " + databaseError);
}
});
}
});
floatingActionButton.setVisibility(View.VISIBLE);
}
}
});
}
private void CheckContactsFragment() {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":" + mViewPager.getCurrentItem());
// based on the current position you can then cast the page to the correct Fragment class and call some method inside that fragment to reload the data:
if (1 == mViewPager.getCurrentItem() && null != fragment) {
((ContactsFragment) fragment).getContactList(HomeActivity.this);
}
}
private void InitializeSession() {
// DialogManager.showProgress(HomeActivity.this);
ApiService apiService = ApiClient.getClient().create(ApiService.class);
Call<SessionResponse> call = apiService.checkToken("Bearer " + PreferenceUtils.GetToken());
call.enqueue(new Callback<SessionResponse>() {
#Override
public void onResponse(Call<SessionResponse> call, Response<SessionResponse> response) {
// DialogManager.hideProgress();
if (response.isSuccessful()) {
if (response.body().getCode() == 201) {
ShowAlert(HomeActivity.this);
} else if (response.body().getCode() == 200) {
Toast.makeText(HomeActivity.this, response.body().getMesg(), Toast.LENGTH_SHORT).show();
} else if (response.body().getCode() == 205) {
ShowAlert(HomeActivity.this);
}
}
}
#Override
public void onFailure(Call<SessionResponse> call, Throwable t) {
// DialogManager.hideProgress();
onError(t);
}
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
menuItem.setChecked(true);
// close drawer when item is tapped
switch (menuItem.getItemId()) {
case R.id.nav_item_jobs:
if (internetConnection.checkConnection()) {
govJobs();
} else {
Toast.makeText(HomeActivity.this, "No internet connection", Toast.LENGTH_LONG).show();
}
break;
case R.id.nav_item_policies:
if (internetConnection.checkConnection()) {
govPolicies();
} else {
Toast.makeText(HomeActivity.this, "No internet connection", Toast.LENGTH_LONG).show();
}
break;
case R.id.nav_item_my_servant:
// showAlertForm();
// Toast.makeText(HomeActivity.this, "Coming soon", Toast.LENGTH_LONG).show();
startActivity(new Intent(HomeActivity.this, WorkForActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
break;
case R.id.nav_item_about_us:
// Toast.makeText(HomeActivity.this, "Coming soon", Toast.LENGTH_LONG).show();
startActivity(new Intent(HomeActivity.this, AboutUs.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
break;
/* case R.id.nav_item_my_logout:
PreferenceUtils.SaveLogin(false);
PreferenceUtils.saveUserId("");
PreferenceUtils.savePassword("");
DeletedData();
startActivity(new Intent(HomeActivity.this, LoginActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK));
break;*/
}
drawer.closeDrawers();
return true;
}
public void DeletedData() {
PreferenceUtils.deleteData();
myAppDataBase.myDao().deleteUsers();
myAppDataBase.myDao().deleteUserJobDetails();
myAppDataBase.myDao().deleteUserPolicyDetails();
}
private void govJobs() {
job_rows_count = myAppDataBase.myDao().getNumberOfJobRows();
if (job_rows_count >= 1) {
// getWindow().setExitTransition(null);
Intent intent = new Intent(HomeActivity.this, JobsList.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
overridePendingTransition(0,0);
} else {
// startActivity(new Intent(HomeActivity.this, JobUserForm.class));
Intent intent =new Intent(HomeActivity.this, JobUserForm.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
overridePendingTransition(0,0);
}
}
private void govPolicies() {
policy_row_count = myAppDataBase.myDao().getNumberOfPolicyRows();
if (policy_row_count >= 1) {
Intent intent = new Intent(HomeActivity.this, PoliciesGrid.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
overridePendingTransition(0,0);
} else {
//startActivity(new Intent(HomeActivity.this, PolicyUserForm.class));
Intent intent = new Intent(HomeActivity.this, PolicyUserForm.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
overridePendingTransition(0,0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
/* case R.id.action_sign_out:
PreferenceUtils.SaveLogin(false);
DeletedData();
PreferenceUtils.saveUserId("");
PreferenceUtils.savePassword("");
startActivity(new Intent(HomeActivity.this, LoginActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK));
break;*/
case R.id.action_contact_us:
startActivity(new Intent(HomeActivity.this, AboutUs.class));
/* Intent intent = new Intent(Intent.ACTION_SEND);
// intent.setType("text/plain");
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL , new String[]{"recipient#example.com"});
intent.putExtra(Intent.EXTRA_EMAIL, "bharatnext3444#gmail.com");
intent.putExtra(Intent.EXTRA_SUBJECT, "");
intent.putExtra(Intent.EXTRA_TEXT, "");
intent.putExtra(Intent.EXTRA_EMAIL, "bharatnext3444#gmail.com");
startActivity(Intent.createChooser(intent, "Send Email"));*/
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
/* #Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission is granted
contactsRef = FirebaseDatabase.getInstance().getReference().child("Contacts").child(infoTable.getMobile_num());
contactsRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(!(dataSnapshot.exists()&&dataSnapshot.hasChildren())){
CheckContactsFragment();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
} else {
Toast.makeText(this, "Until you grant the permission, we cannot show contacts of your friends", Toast.LENGTH_SHORT).show();
}
}
}*/
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
/* #Override
public void onResume(){
super.onResume();
getContactTimeStamp(HomeActivity.this);
// put your code here...
}*/
}
You tried with other real devices? It's same issue?
This type of error happen when VM heap is Low and in that secession you should increase your ADB emulator Heap to the minimum required.
Into your AVD Manager :
Click Edit on your Emulator
"Show Advanced Settings" at the bottom
Go to: "Memory and Storage"
Edit the VM heap value to 512 MB
Finished

How to open link in a fragment with webview when a specific item is clicked from listview fragment

I have an Android app with a navigation drawer with menu items.This menu contains entry to multiple fragments. One of the fragments has a listview in it with names of websites. My aim is that whenever a name of website is clicked from that list the link associated with the listview item saved in stringarray in strings.xml file is opened in new fragment with webview which opens the site.
So far I have implemented this code for the fragment with listview
class AtlasListFragment extends android.support.v4.app.ListFragment implements AdapterView.OnItemClickListener {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.atlas_list_fragment, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.tut_titles, android.R.layout.simple_list_item_1);
setListAdapter(adapter);
getListView().setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Toast.makeText(getActivity(), "Item: " + position, Toast.LENGTH_SHORT).show();
}}
And the code which launches the fragment from navigation drawer is below
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
android.support.v4.app.Fragment fragment = null;
if (id == R.id.home) {
fragment = frag;
else if (id == R.id.settings) {
fragment=new Settings();
} else if (id == R.id.about_us) {
fragment=new AboutUc();
}
else if(id == R.id.atlas){
fragment = new AtlasListFragment();
}
else{
}
if (fragment!=null)
{
FragmentManager fragmentManager=getSupportFragmentManager();
FragmentTransaction ft=fragmentManager.beginTransaction();
ft.replace(R.id.fragmentview,fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
By this mehod you can open a webview in where you want use WebView layout and use this method in your activity
public void openWebView(String url){
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
}
Hope it works for you
First of all you will need broadcast so you can send your clicked
URL from adapter to your fragment, and in your main fragment when you
receive the url you can use intent or webview
1- CREATE BroadcastHelper CLASS :
public class BroadcastHelper {
public static final String BROADCAST_EXTRA_METHOD_NAME = "INPUT_METHOD_CHANGED";
public static final String ACTION_NAME = "hassan.hossam";
private static final String UPDATE_LOCATION_METHOD = "updateLocation";
public static void sendInform(Context context, String method) {
Intent intent = new Intent();
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void sendInform(Context context, String method, Intent intent) {
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
2- Send intent from your adapter
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent url = new Intent("url");
url ("url_adapter",item.get(position).getURL());
BroadcastHelper.sendInform(context,"url",url);
}
});
3- in your fragment this use :
Receiver receiver;
boolean isReciverRegistered = false;
#Override
public void onResume() {
super.onResume();
if (receiver == null) {
receiver = new Receiver();
IntentFilter filter = new IntentFilter(BroadcastHelper.ACTION_NAME);
getActivity().registerReceiver(receiver, filter);
isReciverRegistered = true;
}
}
#Override
public void onDestroy() {
if (isReciverRegistered) {
if (receiver != null)
getActivity().unregisterReceiver(receiver);
}
super.onDestroy();
}
private class Receiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
Log.v("r", "receive " + arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME));
String methodName = arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME);
if (methodName != null && methodName.length() > 0) {
Log.v("receive", methodName);
switch (methodName) {
case "url":
String url_adapter = arg1.getStringExtra("url_adapter");
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url_adapter));
startActivity(i);
break;
default:
break;
}
}
}
}
i hope this helped

can the Fragment be backed to previous fragment?

I want to back the default fragment from the other fragment when the back button is clicked but i am not able to back to the previous fragment.How can this be achieved??
EduHunt class main class
public class EduHunt extends AppCompatActivity {
private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nvDrawer;
private ActionBarDrawerToggle drawerToggle;
TextView toolBarTitle;
ImageView toolBarLogo;
private Fragment mTabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edu_hunt);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolBarLogo = (ImageView) findViewById(R.id.toolbarlogo);
toolBarTitle = (TextView) findViewById(R.id.toolbartitle);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
nvDrawer = (NavigationView) findViewById(R.id.nvView);
setupDrawerContent(nvDrawer);
// Find our drawer view
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = setupDrawerToggle();
// Tie DrawerLayout events to the ActionBarToggle
mDrawer.addDrawerListener(drawerToggle);
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.flContent, new Search());
tx.commit();
}
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
Fragment fragment = null;
Class fragmentClass;
switch (menuItem.getItemId()) {
case R.id.search:
fragmentClass = Search.class;
toolBarLogo.setVisibility(View.GONE);
toolBarTitle.setText("Search");
break;
case R.id.settings:
fragmentClass = Settings.class;
toolBarLogo.setVisibility(View.GONE);
toolBarTitle.setText("About");
break;
case R.id.register:
fragmentClass = Register.class;
toolBarLogo.setVisibility(View.GONE);
toolBarTitle.setText("Register Now");
break;
case R.id.nearme:
fragmentClass = NearMe.class;
toolBarLogo.setVisibility(View.GONE);
toolBarTitle.setText("Near Me");
break;
default:
fragmentClass = Search.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawer.closeDrawers();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.our_team:
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.activity_our_team);
dialog.show();
return true;
case R.id.feedback:
startActivity(new Intent(EduHunt.this, SendFeedback.class));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.education_hunt, menu);
return true;
}
#Override
public void onBackPressed() {
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentById(R.id.flContent);
if(!(fragment instanceof Search )){
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.flContent, new Search());
tx.commit();
}
}
}
I want to back to the Search fragment(default fragment) when it is backed from the Any other fragment i.e About
About
public class About extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
LinearLayout collegeAffiliation;
ImageView phoneCalls, sendEmails, weblink;
public TextView aboutName, aboutLocation, aboutNumber, aboutEmail, aboutWebsite, aboutCategory, aboutAffiliation;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_about, container, false);
collegeAffiliation = (LinearLayout) v.findViewById(R.id.collegeAffiliation);
aboutName = (TextView) v.findViewById(R.id.about_school_name);
aboutLocation = (TextView) v.findViewById(R.id.about_school_location);
aboutNumber = (TextView) v.findViewById(R.id.about_school_number);
aboutCategory = (TextView) v.findViewById(R.id.about_school_category);
aboutAffiliation = (TextView) v.findViewById(R.id.about_college_affiliation);
aboutEmail = (TextView) v.findViewById(R.id.about_school_email);
aboutWebsite = (TextView) v.findViewById(R.id.about_school_website);
phoneCalls = (ImageView) v.findViewById(R.id.phonecalls);
sendEmails = (ImageView) v.findViewById(R.id.sendEmails);
weblink = (ImageView) v.findViewById(R.id.weblink);
mMapView = (MapView) v.findViewById(R.id.mapview);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
OurSchool ourSchool = null;
OurCollege ourCollege = null;
OurUniversity ourUniversity = null;
if (getActivity().getIntent().getSerializableExtra("school") != null) {
ourSchool = (OurSchool) getActivity().getIntent().getSerializableExtra("school");
aboutName.setText(ourSchool.getSchoolName());
aboutLocation.setText(ourSchool.getSchoolAddress() + "," + ourSchool.getSchoolDistrict() + "," + ourSchool.getSchoolCountry());
aboutNumber.setText(ourSchool.getSchoolPhone());
aboutNumber.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callPhoneNumber();
}
});
phoneCalls.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
callPhoneNumber();
}
});
aboutCategory.setText(ourSchool.getSchoolType());
aboutEmail.setText(ourSchool.getSchoolEmail());
aboutEmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendEmail();
}
});
sendEmails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendEmail();
}
});
aboutWebsite.setText(ourSchool.getSchoolWebsite());
aboutWebsite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setWeblink();
}
});
weblink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setWeblink();
}
});
LatLng schoollatlng = new LatLng(ourSchool.getLatitude(), ourSchool.getLongitude());
googleMap.addMarker(new MarkerOptions().position(schoollatlng).title(ourSchool.getSchoolName()));
CameraPosition cameraPosition = new CameraPosition.Builder().target(schoollatlng).zoom(15).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
} else if (getActivity().getIntent().getSerializableExtra("college") != null) {
ourCollege = (OurCollege) getActivity().getIntent().getSerializableExtra("college");
collegeAffiliation.setVisibility(View.VISIBLE);
aboutName.setText(ourCollege.getCollegeName());
aboutLocation.setText(ourCollege.getCollegeAddress() + "," + ourCollege.getCollegeDistrict() + "," + ourCollege.getCollegeCountry());
aboutNumber.setText(ourCollege.getCollegePhone());
aboutNumber.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callPhoneNumber();
}
});
phoneCalls.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
callPhoneNumber();
}
});
aboutCategory.setText(ourCollege.getCollegeType());
aboutAffiliation.setText(ourCollege.getCollegeAffiliation());
aboutEmail.setText(ourCollege.getCollegeEmail());
aboutEmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendEmail();
}
});
sendEmails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendEmail();
}
});
aboutWebsite.setText(ourCollege.getCollegeWebsite());
aboutWebsite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setWeblink();
}
});
weblink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setWeblink();
}
});
LatLng collegelatlng = new LatLng(ourCollege.getLatitude(), ourCollege.getLongtitude());
googleMap.addMarker(new MarkerOptions().position(collegelatlng).title(ourCollege.getCollegeName()));
CameraPosition cameraPosition = new CameraPosition.Builder().target(collegelatlng).zoom(15).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
} else {
ourUniversity = (OurUniversity) getActivity().getIntent().getSerializableExtra("university");
aboutName.setText(ourUniversity.getUniversityName());
aboutLocation.setText(ourUniversity.getUniversityAddress() + "," + ourUniversity.getUniversityDistrict() + "," + ourUniversity.getUniverstiyCountry());
aboutNumber.setText(ourUniversity.getUniversityPhone());
aboutNumber.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callPhoneNumber();
}
});
phoneCalls.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
callPhoneNumber();
}
});
aboutCategory.setText(ourUniversity.getUniversityType());
aboutEmail.setText(ourUniversity.getUniversityEmail());
aboutEmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendEmail();
}
});
sendEmails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendEmail();
}
});
aboutWebsite.setText(ourUniversity.getUniversityWebsite());
aboutWebsite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setWeblink();
}
});
weblink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setWeblink();
}
});
LatLng unilatlng = new LatLng(ourUniversity.getUniversityLatitude(), ourUniversity.getUniversityLongitude());
googleMap.addMarker(new MarkerOptions().position(unilatlng).title(ourUniversity.getUniversityName()));
CameraPosition cameraPosition = new CameraPosition.Builder().target(unilatlng).zoom(15).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
});
return v;
}
public void callPhoneNumber() {
try {
if (Build.VERSION.SDK_INT > 22) {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CALL_PHONE}, 101);
return;
}
OurSchool ourSchool = null;
OurCollege ourCollege = null;
OurUniversity ourUniversity = null;
if (getActivity().getIntent().getSerializableExtra("school") != null) {
ourSchool = (OurSchool) getActivity().getIntent().getSerializableExtra("school");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + ourSchool.getSchoolPhone()));
startActivity(callIntent);
} else if (getActivity().getIntent().getSerializableExtra("college") != null) {
ourCollege = (OurCollege) getActivity().getIntent().getSerializableExtra("college");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + ourCollege.getCollegePhone()));
startActivity(callIntent);
} else
ourUniversity = (OurUniversity) getActivity().getIntent().getSerializableExtra("university");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + ourUniversity.getUniversityPhone()));
startActivity(callIntent);
} else {
OurSchool ourSchool = null;
OurCollege ourCollege = null;
OurUniversity ourUniversity = null;
if (getActivity().getIntent().getSerializableExtra("school") != null) {
ourSchool = (OurSchool) getActivity().getIntent().getSerializableExtra("school");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + ourSchool.getSchoolPhone()));
startActivity(callIntent);
} else if (getActivity().getIntent().getSerializableExtra("college") != null) {
ourCollege = (OurCollege) getActivity().getIntent().getSerializableExtra("college");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + ourCollege.getCollegePhone()));
startActivity(callIntent);
} else {
ourUniversity = (OurUniversity) getActivity().getIntent().getSerializableExtra("university");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + ourUniversity.getUniversityPhone()));
startActivity(callIntent);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if (requestCode == 101) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
callPhoneNumber();
} else {
Log.e("Permission not Granted", "");
}
}
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
public void sendEmail() {
OurSchool ourSchool = null;
OurCollege ourCollege = null;
OurUniversity ourUniversity = null;
if (getActivity().getIntent().getSerializableExtra("school") != null) {
ourSchool = (OurSchool) getActivity().getIntent().getSerializableExtra("school");
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto", ourSchool.getSchoolEmail(), null));
try {
startActivity(Intent.createChooser(emailIntent, "Send email..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getContext(), "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
startActivity(Intent.createChooser(emailIntent, "Send email..."));
} else if (getActivity().getIntent().getSerializableExtra("college") != null) {
ourCollege = (OurCollege) getActivity().getIntent().getSerializableExtra("college");
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto", ourCollege.getCollegeEmail(), null));
try {
startActivity(Intent.createChooser(emailIntent, "Send email..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getContext(), "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
startActivity(Intent.createChooser(emailIntent, "Send email..."));
} else {
ourUniversity = (OurUniversity) getActivity().getIntent().getSerializableExtra("university");
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto", ourUniversity.getUniversityEmail(), null));
startActivity(Intent.createChooser(emailIntent, "Send email..."));
}
try {
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getContext(), "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
public void setWeblink() {
OurSchool ourSchool = null;
OurCollege ourCollege = null;
OurUniversity ourUniversity = null;
if (getActivity().getIntent().getSerializableExtra("school") != null) {
ourSchool = (OurSchool) getActivity().getIntent().getSerializableExtra("school");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://" + ourSchool.getSchoolWebsite()));
startActivity(intent);
} else if (getActivity().getIntent().getSerializableExtra("college") != null) {
ourCollege = (OurCollege) getActivity().getIntent().getSerializableExtra("college");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://" + ourCollege.getCollegeWebsite()));
startActivity(intent);
} else {
ourUniversity = (OurUniversity) getActivity().getIntent().getSerializableExtra("university");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://" + ourUniversity.getUniversityWebsite()));
startActivity(intent);
}
try {
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getContext(), "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
}
when i back through the any other fragment .The app closes but i want
to display the default fragment.can this be done???
Check fragment instance in onBackPress event
#Override
public void onBackPressed() {
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentById(R.id.flContent);
if(!(fragment instanceof YourDefaultFragment)){
//Load your default fragment
toolBarLogo.setVisibility(View.GONE);
toolBarTitle.setText("Set Title");
}
else{
super.onBackPressed();
}
}
you can do it using interface, backstack listner and onBackPress following way
Create BaseFragment
public class FlipkartBaseFragment extends Fragment {
private MainFlipkartActivity activity;
private ChangeCurrentFragment changeCurrentFragment;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = (MainFlipkartActivity) getActivity();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if(context instanceof ChangeCurrentFragment)
changeCurrentFragment = (ChangeCurrentFragment) context;
}
#Override
public void onDetach() {
super.onDetach();
changeCurrentFragment=null;
}
public ChangeCurrentFragment onChangeCurrentFragment(){
return changeCurrentFragment;
}
public MainFlipkartActivity getBaseActivity() {
return activity;
}
}
Then extend all fragment using BaseFragment
In fragment you can go one fragment to other like
((MainFlipkartActivity) getBaseActivity()).onFragmentChangeListener(new TwoFKTFragment(),"1"+new Random().nextInt());
Then implement MainActivity like this way
public class MainFlipkartActivity extends AppCompatActivity
implements FragmentManager.OnBackStackChangedListener,ChangeCurrentFragment
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
getSupportFragmentManager().addOnBackStackChangedListener(this);
if (null == savedInstanceState) {
HomeFragment cameraImportFragment = new HomeFragment();
manageFragment(cameraImportFragment, Const.TAG_HOME);
}
}
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
finish();
} else {
super.onBackPressed();
}
}
}
public void manageFragment(Fragment fragment, String tag)
{
FragmentManager fragmentManager=getSupportFragmentManager();
// String f_name=fragment.getClass().getName();
if(!fragmentManager.popBackStackImmediate(tag,0))
{
FragmentTransaction ft=fragmentManager.beginTransaction();
ft.replace(R.id.content_frame, fragment, tag);
ft.addToBackStack(tag);
ft.commit();
}
}
#Override
public void onFragmentChangeListener(Fragment fragment, String tag) {
manageFragment(fragment,tag);
}
#Override
public void onBackStackChanged() {
FragmentManager fragmentManager=getSupportFragmentManager();
Fragment fr = fragmentManager.findFragmentById(R.id.frame_container);
if(fr!=null){
fr.onResume();
}
}
To Replace fragment if you want back to previous fragment pass addToBackStack=true
public void replaceFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.replace(R.id.container_framelayout, fragment);
transaction.commit();
getSupportFragmentManager().executePendingTransactions();
}
public boolean popFragment() {
Log.e("test", "pop fragment: " + getSupportFragmentManager().getBackStackEntryCount());
boolean isPop = false;
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
isPop = true;
getSupportFragmentManager().popBackStack();
}
return isPop;
}
put this code in your main activity for backpress
#Override
public void onBackPressed() {
if(!popFragment()) {
super.onBackPressed();
}
}

getArguments() returns null when retrieving data from activity

I have two different activities :
1.Login.java
2.Dashboard.java
In dashboard activity i have added navigation drawer by making navigation drawer fragment appearing in dashboard activity.
Now i want to pass data to that navigation drawer fragment through login.java
Here is my code :
Login.java- All things are imported
public class Login extends AppCompatActivity implements View.OnClickListener, OnItemSelectedListener{
private EditText loginid;
private EditText password;
private Spinner type;
private Button loginbtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginid=(EditText) findViewById(R.id.editText_loginid);
password=(EditText) findViewById(R.id.editText_password);
loginbtn=(Button) findViewById(R.id.btn_login);
type=(Spinner) findViewById(R.id.spinner_type);
loginbtn.setOnClickListener(this);
type.setOnItemSelectedListener(this);
List<String> types = new ArrayList<String>();
types.add("Student");
types.add("Faculty");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, types);
type.setAdapter(adapter);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String id= loginid.getText().toString().trim();
String pass= password.getText().toString().trim();
String type_passed = type.getSelectedItem().toString().toLowerCase();
LoginRequest(type_passed,id,pass);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
public void LoginRequest(final String type_selected,String id,String pass)
{
VolleySingleton volleySingleton = VolleySingleton.getInstance();
RequestQueue requestQueue= volleySingleton.getRequestQueue();
JsonObjectRequest jsonobject= new JsonObjectRequest(Request.Method.GET,
"http://10.0.2.2:80/noticeboardapi/loginrequest.php/?type="+type_selected+"&enrollid="+id+"&password="+pass+"",
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Bundle bundle = new Bundle();
bundle.putString("type", type_selected);
NavigationDrawerFragment navfrag = new NavigationDrawerFragment();
// TODO Auto-generated method stub
if(type_selected.equals("student"))
{
try {
String enrollid = response.getString("enrollid");
String name = response.getString("name");
String section = response.getString("section");
String rollno = response.getString("rollno");
int status = Integer.parseInt(response.getString("status"));
switch(status)
{
case 0:
{
Toast.makeText(getApplicationContext(), "Incorrect password", Toast.LENGTH_SHORT).show();
break;
}
case 1:
{
navfrag.setArguments(bundle);
Intent sloggedin= new Intent(getApplicationContext(),Dashboard.class);
startActivity(sloggedin);
finish();
break;
}
case 2:
{
Toast.makeText(getApplicationContext(), "User does not exist", Toast.LENGTH_SHORT).show();
break;
}
default:
{
Toast.makeText(getApplicationContext(), "Request Not Accepted", Toast.LENGTH_SHORT).show();
break;
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if(type_selected.equals("faculty"))
{
try {
String enrollid = response.getString("enrollid");
String name = response.getString("name");
String cc = response.getString("cc");
String hod = response.getString("hod");
int status = Integer.parseInt(response.getString("status"));
switch(status)
{
case 0:
{
Toast.makeText(getApplicationContext(), "Incorrect password Faculty", Toast.LENGTH_SHORT).show();
break;
}
case 1:
{
navfrag.setArguments(bundle);
Intent floggedin= new Intent(getApplicationContext(),Dashboard.class);
startActivity(floggedin);
finish();
break;
}
case 2:
{
Toast.makeText(getApplicationContext(), "Faculty does not exist", Toast.LENGTH_SHORT).show();
break;
}
default:
{
Toast.makeText(getApplicationContext(), "Request Not Accepted", Toast.LENGTH_SHORT).show();
break;
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} , new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Response \n" + error.getMessage(), Toast.LENGTH_LONG).show();
}
});
requestQueue.add(jsonobject);
}
}
My Navigation Drawer Fragment.java:
public class NavigationDrawerFragment extends Fragment implements NavigationListAdapter.ClickedListener{
public static final String PREF_FILE_NAME="testpref";
public static final String KEY_USER_LEARNED_DRAWER="user_learned_drawer";
private RecyclerView recyclerView;
private NavigationListAdapter adapter;
private View containerView;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
//Inflate the layout for this fragment
String type = getArguments().getString("type");
View layout = inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
recyclerView= (RecyclerView) layout.findViewById(R.id.drawerList);
adapter= new NavigationListAdapter(getActivity(), getNavData("student"));
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return layout;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
HomeFragment home = new HomeFragment();
transaction.replace(R.id.layout_dashboard, home, "Home");
transaction.addToBackStack("home");
transaction.commit();
}
public static List<NavigationListContent> getNavData(String type){
List<NavigationListContent> data = new ArrayList<NavigationListContent>();
if(type.equals("student")){
int[] icons= {R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher};
String[] titles= {"Home","Profile","Contact Us"};
for(int i =0;i<titles.length && i<icons.length;i++)
{
NavigationListContent current = new NavigationListContent();
current.title=titles[i];
current.iconId=icons[i];
data.add(current);
}
}else if(type.equals("faculty"))
{
int[] icons= {R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher};
String[] titles= {"Home","Profile","Add Notice","Contact Us"};
for(int i =0;i<titles.length && i<icons.length;i++)
{
NavigationListContent current = new NavigationListContent();
current.title=titles[i];
current.iconId=icons[i];
data.add(current);
}
}
return data;
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
mUserLearnedDrawer = Boolean.valueOf(readFromPreferences(getActivity(),KEY_USER_LEARNED_DRAWER , "false"));
if(savedInstanceState!=null)
{
mFromSavedInstanceState=true;
}
}
public void setUp(int fragmentID,DrawerLayout drawerLayout,Toolbar toolbar) {
// TODO Auto-generated method stub
containerView= getActivity().findViewById(fragmentID);
mDrawerLayout=drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close){
#Override
public void onDrawerClosed(View drawerView) {
// TODO Auto-generated method stub
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
// TODO Auto-generated method stub
super.onDrawerOpened(drawerView);
if(!mUserLearnedDrawer)
{
mUserLearnedDrawer=true;
saveToPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, mUserLearnedDrawer+"");
}
getActivity().invalidateOptionsMenu();
}
};
if(mUserLearnedDrawer &&mFromSavedInstanceState)
{
mDrawerLayout.openDrawer(containerView);
}
mDrawerLayout.addDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
mDrawerToggle.syncState();
}
});
}
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 preferenceValue){
SharedPreferences sharedPreferences=context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(preferenceName, preferenceValue);
}
#Override
public void itemClicked(View view, int position) {
// TODO Auto-generated method stub
//startActivity(new Intent(getActivity(), SubActivity.class));
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
switch(position)
{
case 0:
{
HomeFragment home = new HomeFragment();
transaction.replace(R.id.layout_dashboard, home, "Home");
transaction.addToBackStack("home");
break;
}
case 1:
{
ProfileFragment profile = new ProfileFragment();
transaction.replace(R.id.layout_dashboard, profile, "Profile");
transaction.addToBackStack("profile");
break;
}
case 2:
{
AddNoticeFragment addnotice = new AddNoticeFragment();
transaction.replace(R.id.layout_dashboard, addnotice, "AddNotice");
transaction.addToBackStack("addnotice");
break;
}
case 3:
{
ContactUsFragment contactus = new ContactUsFragment();
transaction.replace(R.id.layout_dashboard, contactus, "ContactUs");
transaction.addToBackStack("contactus");
break;
}
default:
{
Toast.makeText(getActivity(), "No such Option", Toast.LENGTH_SHORT).show();
transaction.addToBackStack("home");
break;
}
}
mDrawerLayout.closeDrawers();
transaction.commit();
}
}
My Dashboard.java
public class Dashboard extends AppCompatActivity {
private Toolbar toolbar;
private DrawerLayout drawer_layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
toolbar=(Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawer_layout=(DrawerLayout) findViewById(R.id.drawer_layout);
NavigationDrawerFragment drawerfragment= (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerfragment.setUp(R.id.fragment_navigation_drawer,drawer_layout,toolbar);
}
#Override
public void onBackPressed() {
if (drawer_layout.isDrawerOpen(Gravity.START)) { // replace this with
// actual function
// which returns if
// the drawer is
// open
drawer_layout.closeDrawer(Gravity.START); // replace this with
// actual function which
// closes drawer
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.dashboard, 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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Error received:
04-29 19:11:06.009: E/AndroidRuntime(3641): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
I have tried many stackoverflow solution but no one works for me.
Please tell me what to do as i am stucked here for too much of time and thanks in advance!

NavigationDrawer and Up Navigation

I implemented a BaseActivity which extends the ActionBarActivity and implements a NavigationDrawer. All my Activities are inheriting from this BaseActivity.
Im now wondering if i can implement a NavigationDrawer and still have the proper up navigation using the toolbar or is the device back button supposed to work as the up navigation button when i implemented a NavigationDrawer?
EDIT:
Custom NavigationDrawer with Toolbar
public abstract class NavigationActivity extends ActionBarActivity {
private Toolbar toolbar = null;
private DrawerLayout drawerLayout = null;
private ActionBarDrawerToggle drawerToggle = null;;
private ListView listView = null;
private CharSequence drawerTitle = null;
private CharSequence title = null;
private NavigationDrawerConfiguration navigationConfig = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.navigationConfig = this.getNavigationDrawerConfiguration();
this.setContentView(this.navigationConfig.getMainLayout());
this.toolbar = (Toolbar) this.findViewById(R.id.app_bar);
this.drawerLayout = (DrawerLayout) this.findViewById(navigationConfig.getDrawerLayoutId());
this.listView = (ListView) this.findViewById(navigationConfig.getLeftDrawerId());
this.listView.setAdapter(navigationConfig.getBaseAdapter());
this.listView.setOnItemClickListener(new DrawerItemClickListener());
this.drawerTitle = this.getTitle();
this.title = this.getTitle();
this.setSupportActionBar(this.toolbar);
this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
this.getSupportActionBar().setHomeButtonEnabled(true);
this.drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, this.toolbar, this.navigationConfig.getDrawerOpenDesc(), this.navigationConfig.getDrawerCloseDesc()) {
#Override
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(title);
invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(drawerTitle);
invalidateOptionsMenu();
}
};
this.drawerLayout.setDrawerListener(this.drawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
this.drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
this.drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (this.navigationConfig.getActionMenuItemsToHideWhenDrawerOpen() != null) {
boolean drawerOpen = this.drawerLayout.isDrawerOpen(listView);
for (int item : this.navigationConfig.getActionMenuItemsToHideWhenDrawerOpen()) {
menu.findItem(item).setVisible(!drawerOpen);
}
}
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (this.drawerToggle.onOptionsItemSelected(item)) {
return true;
} else {
return false;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
if (this.drawerLayout.isDrawerOpen(this.listView)) {
this.drawerLayout.closeDrawer(this.listView);
} else {
this.drawerLayout.openDrawer(this.listView);
}
return true;
}
return super.onKeyDown(keyCode, event);
}
protected NavigationDrawerConfiguration getNavigationDrawerConfiguration() {
NavigationDrawerItem[] menu = new NavigationDrawerItem[] {
// NavigationMenuSection.create(100, "Demos"),
NavigationMenuItem.create(100, "Item 1", "ic_measure", false, this),
NavigationMenuItem.create(200, "Item 2", "ic_list", false, this),
// NavigationMenuSection.create(200, "General"),
NavigationMenuItem.create(300, "Item 3", "ic_diagrams", false, this),
NavigationMenuItem.create(400, "Item 4", "ic_calculator", false, this),
NavigationMenuItem.create(500, "Item 5", "ic_scanner", false, this),
NavigationMenuItem.create(600, "Item 6", "ic_profile", false, this),
NavigationMenuItem.create(700, "Item 7", "ic_follower", false, this),
NavigationMenuItem.create(800, "Item 8", "ic_settings", false, this)
};
NavigationDrawerConfiguration navigationDrawerConfiguration = new NavigationDrawerConfiguration();
navigationDrawerConfiguration.setMainLayout(R.layout.activity_menu_slide);
navigationDrawerConfiguration.setDrawerLayoutId(R.id.menu_slide_layout);
navigationDrawerConfiguration.setLeftDrawerId(R.id.menu_slide_list);
navigationDrawerConfiguration.setNavigationItems(menu);
navigationDrawerConfiguration.setDrawerOpenDesc(R.string.open_navigation_drawer);
navigationDrawerConfiguration.setDrawerCloseDesc(R.string.close_navigation_drawer);
navigationDrawerConfiguration.setBaseAdapter(new NavigationDrawerAdapter(this, R.layout.activity_menu_slide_item_row, menu));
return navigationDrawerConfiguration;
}
public void selectItem(int position) {
NavigationDrawerItem selectedItem = this.navigationConfig.getNavigationItems()[position];
this.onNavigationItemSelected(selectedItem.getId());
this.listView.setItemChecked(position, true);
if (selectedItem.updateActionBarTitle()) {
this.setTitle(selectedItem.getLabel());
}
if (this.drawerLayout.isDrawerOpen(this.listView)) {
this.drawerLayout.closeDrawer(this.listView);
}
}
protected void onNavigationItemSelected(int id) {
Intent intent = null;
switch ((int) id) {
case 100:
intent = new Intent(this, MeasureDataActivity.class);
break;
case 200:
intent = new Intent(this, MeasureDataListActivity.class);
break;
case 300:
intent = new Intent(this, DiagramsActivity.class);
break;
case 400:
intent = new Intent(this, CalcActivity.class);
break;
case 500:
intent = new Intent(this, RecipeActivity.class);
break;
case 600:
intent = new Intent(this, ProfileActivity.class);
break;
case 700:
intent = new Intent(this, FollowerActivity.class);
break;
case 800:
intent = new Intent(this, SettingsActivity.class);
break;
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(intent);
}
protected int getDrawerIcon() {
return R.drawable.ic_navigation_drawer;
}
protected DrawerLayout getDrawerLayout() {
return this.drawerLayout;
}
protected ActionBarDrawerToggle getDrawerToggle() {
return this.drawerToggle;
}
#Override
public void setTitle(CharSequence title) {
this.title = title;
this.getSupportActionBar().setTitle(title);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
/**
*
*/
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
}
I think in the onCreate after the super() call you can do this:
mDrawerToggle.setDrawerIndicatorEnabled(false);
If this alone doesn't work (or just doesn't work) try this:
getActionBar().setDisplayHomeAsUpEnabled(true);
Follow this link: Missing Up navigation icon after switching from ICS ActionBar to Lollipop Toolbar
Original poster found this link

Categories

Resources