I followed a tutorial to push facebook info from login into an activity with a navigation, then put the into on top, as shown, which, after days of altering code, I finally got it to work.
But now I cant get the original header to go away. I've tried changing every part of the code, but I always end up with all or nothing. I know two heads are better than one, but this is an exception to the rule.
Also, I guess I cant post images, so, the original header is on top, where it should be.
The new header with my facebook profile picture and info, is underneath that.
And below that, starts the navigation drawer menu.
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
JSONObject response, profile_pic_data, profile_pic_url;
TextView user_name, user_email, tokens;
ImageView user_picture;
NavigationView navigation_view;
String name;
Button button2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
tokens = (TextView)findViewById(R.id.textView17);
button2 = (Button)findViewById(R.id.button2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent = getIntent();
String jsondata = intent.getStringExtra("jsondata");
final String uid = intent.getStringExtra("Uid");
setNavigationHeader(); // call setNavigationHeader Method.
setUserProfile(jsondata, uid);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setVisibility(View.INVISIBLE);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Firebase ref = new Firebase("https://luckycashslots.firebaseio.com/data/users/" + MainActivity.uID + "/");
Tokens token = new Tokens("100");
ref.setValue(token);
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
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.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//Toast.makeText(getApplicationContext(), uid, Toast.LENGTH_LONG).show();
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
updateText();
}
});
Firebase ref = new Firebase("https://luckycashslots.firebaseio.com/data/users/" + MainActivity.uID + "/");
Firebase tokRef = ref.child("tokens");
//tokRef.setValue(mAuthData.getProvider());
//Tokens token = new Tokens(100);
//ref.setValue(token);
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child("tokens").getValue() != null) {
name = (String) dataSnapshot.child("tokens").getValue().toString();
tokens.setText(name);
//tokens.setText(dataSnapshot.getValue().toString());
// Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
// System.out.println(dataSnapshot.getValue());
// String woot = dataSnapshot.getValue().toString();
// tokens.setText(woot);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Toast.makeText(getApplicationContext(), "couldnt update token text", Toast.LENGTH_LONG).show();
}
});
}
public void updateText(){
Firebase ref = new Firebase("https://luckycashslots.firebaseio.com/data/users/" + MainActivity.uID + "/");
Firebase tokRef = ref.child("tokens");
//tokRef.setValue(mAuthData.getProvider());
// Tokens token = new Tokens(100);
// ref.setValue(token);
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot tokenSnapshot: dataSnapshot.getChildren()){
Tokens token = tokenSnapshot.getValue(Tokens.class);
System.out.println(token.toString());
name = token.toString();
// name = (String) dataSnapshot.child("tokens").getValue();
tokens.setText(name);
}
// name = (String) dataSnapshot.child("tokens").getValue().toString();
// tokens.setText(name);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Toast.makeText(getApplicationContext(), "couldnt update token text", Toast.LENGTH_LONG).show();
}
});
}
public void setNavigationHeader(){
navigation_view = (NavigationView) findViewById(R.id.nav_view);
navigation_view.removeHeaderView(null);
View header = LayoutInflater.from(this).inflate(R.layout.nav_header_home, null);
navigation_view.addHeaderView(header);
user_name = (TextView) header.findViewById(R.id.username);
user_picture = (ImageView) header.findViewById(R.id.profile_pic);
user_email = (TextView) header.findViewById(R.id.email);
}
public void setUserProfile(String jsondata, String uid){
try
{
response = new JSONObject(jsondata);
user_email.setText(response.get("email").toString());
// user_email.setText(MainActivity.uEmail);
user_name.setText(response.get("name").toString());
// user_name.setText(MainActivity.uName);
profile_pic_data = new JSONObject(response.get("picture").toString());
profile_pic_url = new JSONObject(profile_pic_data.getString("data"));
Picasso.with(this).load(profile_pic_url.getString("url")).into(user_picture);
}
catch
(Exception e) {
e.printStackTrace();
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} 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.home, 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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_slots) {
// Handle the camera action1
Intent intent2 = new Intent(this, SlotPageView.class);
startActivity(intent2);
} else if (id == R.id.nav_spin) {
Intent intent2 = new Intent(this, DailySpinActivity.class);
startActivity(intent2);
} else if (id == R.id.nav_offers) {
} else if (id == R.id.nav_prizes) {
Intent intent2 = new Intent(this, PrizesActivity.class);
startActivity(intent2);
} else if (id == R.id.nav_winners) {
Intent intent2 = new Intent(this, WinnersActivity.class);
startActivity(intent2);
} else if (id == R.id.nav_stats) {
} else if (id == R.id.nav_account) {
Intent intent2 = new Intent(this, AccountActivity.class);
startActivity(intent2);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
activity_home.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
android:fitsSystemWindows="true" tools:openDrawer="start">
<include layout="#layout/app_bar_home" android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView android:id="#+id/nav_view"
android:layout_width="wrap_content" android:layout_height="match_parent"
android:layout_gravity="start" android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_home" app:menu="#menu/activity_home_drawer" />
App bar home xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:fitsSystemWindows="true"
tools:context="learn2crack.learn2crackfb.HomeActivity">
<android.support.design.widget.AppBarLayout android:layout_height="wrap_content"
android:layout_width="match_parent" android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar android:id="#+id/toolbar"
android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary" app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_home" />
<android.support.design.widget.FloatingActionButton android:id="#+id/fab"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="bottom|end" android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
Nav header home xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="#dimen/nav_header_height"
android:background="#drawable/side_nav_bar"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:theme="#style/ThemeOverlay.AppCompat.Dark" android:orientation="vertical"
android:gravity="bottom">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/profile_pic"
android:layout_width="80dp"
android:layout_height="80dp"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:src="#android:drawable/sym_def_app_icon"
/>
<TextView android:id="#+id/username"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:text="Android Studio"
android:textSize="14dp"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textColor="#000000" />
<TextView
android:id="#+id/email"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="android.studio#android.com" />
</LinearLayout>
u have to pass the header view into
navigation_view.removeHeaderView(navigation_view.getHeaderView(0);
and not null
navigation_view.removeHeaderView(null);
when you add header using app:headerLayout="#layout/nav_header_home" just like below
<android.support.design.widget.NavigationView android:id="#+id/nav_view"
android:layout_width="wrap_content" android:layout_height="match_parent"
android:layout_gravity="start" android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_home" app:menu="#menu/activity_home_drawer" />
then no need to add header again from code
remove below lines from setNavigationHeader() method
navigation_view.removeHeaderView(null);
View header = LayoutInflater.from(this).inflate(R.layout.nav_header_home, null);
navigation_view.addHeaderView(header);
after remove method look like below
Edit /
public void setNavigationHeader(){
navigation_view = (NavigationView) findViewById(R.id.nav_view);
View header = LayoutInflater.from(this).inflate(R.layout.nav_header_home, null);
user_name = (TextView) navigation_view.findViewById(R.id.username);
user_picture = (ImageView) navigation_view.findViewById(R.id.profile_pic);
user_email = (TextView) navigation_view. findViewById(R.id.email);
}
Try this, It's workable and tested.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.removeHeaderView(navigationView.getHeaderView(0));
View headerLayout = navigationView.inflateHeaderView(R.layout.nav_header_main);
ImageView user_dp = headerLayout.findViewById(R.id.user_dp);
TextView user_fullname = headerLayout.findViewById(R.id.user_fullname);
TextView user_email = headerLayout.findViewById(R.id.user_email);
user_dp.setBackgroundResource(R.drawable.user);
user_fullname.setText(fullName);
user_email.setText(uemail);
}
Related
In MainActivity, I've created a DrawerLayout and ActionBar. Is there any way to use that same Drawer and ActionBar in other activities without writing the same code again? Here's the code I'm using:
Main.xml:
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:titleTextColor="#FFF"></androidx.appcompat.widget.Toolbar>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/colorPrimary"
>
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/homepage_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
></androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/main_nav"
android:layout_width="277dp"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/header"
app:menu="#menu/drawer_menu"></com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
Main Java (I've Removed The Extra Code [Non Drawer-Actionbar Code]):
DrawerLayout drawerLayout;
Toolbar toolbar;
TextView json;
RequestQueue requestQueue;
ActionBarDrawerToggle actionBarDrawerToggle;
private RequestQueue mqueue;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mqueue = Volley.newRequestQueue(this);
setuptools();
setUpToolbar();
}
private void setUpToolbar()
{
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.app_name,R.string.app_name) ;
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
toolbar.setNavigationIcon(R.drawable.ic_menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.right_menu,menu);
final MenuItem awesomeMenuItem = menu.findItem(R.id.notification_iconmain);
View awesomeActionView = awesomeMenuItem.getActionView();
awesomeActionView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onOptionsItemSelected(awesomeMenuItem);
}
});
final TextView not_num = (TextView) menu.findItem(R.id.notification_iconmain).getActionView().findViewById(R.id.hotlist_hot);
String username = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
String server_url = "https://google.com/api/notifications.php?username="+username;
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, server_url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject notification_numbers = jsonArray.getJSONObject(i);
String final_num = notification_numbers.getString("notifications");
if(final_num.equals("0")){
}else{
not_num.setVisibility(View.VISIBLE);
not_num.setText(final_num);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
mqueue.add(request);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.notification_iconmain){
Intent intent_noti = new Intent(this, NotificationsPage.class);
this.startActivity(intent_noti);
}
if(id == R.id.user_icon){
Intent intent_user = new Intent(this, Profile_Page.class);
this.startActivity(intent_user);
}
return super.onOptionsItemSelected(item);
}
}
What It Does:
It creates a slider drawer, an action bar with the right side menu, and displays the notification count on Bell Icon, and each item has its custom on-click event.
Now, how I can use the same drawer, action bar without writing the code again and again in each activity.
I have three Fragments that I am trying to display by clicking the appropriate option from a Navigation Drawer. I have the Navigation Drawer displaying and opening/closing fine. But I can't get any of the Fragments to display in the Activity. The main screen just stays blank whenever I click an option. There are no compilation errors. I am new to Android development and also Java dev, and I've been trying to complete this project for a month so it will be finished as soon as I can get this to work. You may see some instances of redundant code, because I just wanted to try anything that could work and I am not sure what to delete, so any clarification on that would help too.
The Fragments should be displayed as results in a RecyclerView.
MainActivity:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nView;
private ActionBarDrawerToggle toggle;
private RequestQueue queue;
private List<ATM> atmList;
private RecyclerView atmView;
private AtmRecyclerViewAdapter atmRecyclerViewAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set a Toolbar to replace the ActionBar.
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Find drawer layout
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// Find drawer view
nView = (NavigationView) findViewById(R.id.nav_view);
// Set up drawer view
setupDrawerContent(nView);
// Not sure what this does
nView.setNavigationItemSelectedListener(this);
toggle = new ActionBarDrawerToggle(
this, mDrawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
// Tie DrawerLayout events to the ActionBarDrawerToggle
mDrawer.addDrawerListener(toggle);
queue = Volley.newRequestQueue(this);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
toggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
toggle.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} 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.main, menu);
return true;
}
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
// The action bar home/up action should open or close the drawer.
switch (item.getItemId()) {
case android.R.id.home:
mDrawer.openDrawer(GravityCompat.START);
return true;
}
if (toggle.onOptionsItemSelected(item)) {
return true;
}
/* int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}*/
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_items_catalog) {
// Handle the items catalog action
} else if (id == R.id.nav_items_search) {
} else if (id == R.id.nav_atms) {
/*
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, Constants.atmURL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject atmObj = response.getJSONObject(i);
ATM atm = new ATM();
atm.setAtmId(atmObj.getString("atmid"));
atm.setTitle(atmObj.getString("title"));
atm.setAddress(atmObj.getString("address"));
atm.setType(atmObj.getString("type"));
atm.setLat(atmObj.getDouble("lat"));
atm.setLon(atmObj.getDouble("lon"));
atm.setOnlineStatus(atmObj.getString("onlineStatus"));
atmList.add(atm);
// Log.d("ATM Statuses", atmList.get(i).getOnlineStatus());
}
// atmView = findViewById(R.id.atmRecyclerView);
// atmView.setHasFixedSize(true);
// atmView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
atmRecyclerViewAdapter = new AtmRecyclerViewAdapter
(MainActivity.this, atmList);
atmView.setAdapter(atmRecyclerViewAdapter);
atmRecyclerViewAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(jsonArrayRequest);
*/
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull 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.nav_items_catalog:
fragmentClass = ShowItems.class;
// TODO: Find out how to show the fragments in these calls
// fragment.listItems(???);
break;
case R.id.nav_items_search:
fragmentClass = SearchItems.class;
break;
case R.id.nav_atms:
fragmentClass = ShowATMs.class;
/*
atmView = findViewById(R.id.atmRecyclerView);
atmView.setHasFixedSize(true);
atmView.setLayoutManager(new LinearLayoutManager(this));
*/
break;
default:
fragmentClass = ShowItems.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
// Highlight the selected item has been done by NavigationView
menuItem.setChecked(true);
// Set action bar title
setTitle(menuItem.getTitle());
// Close the navigation drawer
mDrawer.closeDrawers();
}
}
ShowATMs method - Want to show a list of ATM Objects in a RecyclerView format:
public class ShowATMs extends Fragment {
private RecyclerView atmView;
private AtmRecyclerViewAdapter atmRecyclerViewAdapter;
private RequestQueue queue;
// TODO: NEED TO CREATE A VIEW THAT WILL INFLATE CORRECT LAYOUT HERE
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Is this line needed?
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.atm_view, container, false);
atmView = rootView.findViewById(R.id.atmRecyclerView);
atmView.setHasFixedSize(true);
atmView.setLayoutManager(new LinearLayoutManager(getContext()));
final List<ATM> atmList = new ArrayList<>();
queue = Volley.newRequestQueue(getContext());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, Constants.atmURL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject atmObj = response.getJSONObject(i);
ATM atm = new ATM();
atm.setAtmId(atmObj.getString("atmid"));
atm.setTitle(atmObj.getString("title"));
atm.setAddress(atmObj.getString("address"));
atm.setType(atmObj.getString("type"));
atm.setLat(atmObj.getDouble("lat"));
atm.setLon(atmObj.getDouble("lon"));
atm.setOnlineStatus(atmObj.getString("onlineStatus"));
atmList.add(atm);
// Log.d("ATM Statuses", atmList.get(i).getOnlineStatus());
}
atmRecyclerViewAdapter = new AtmRecyclerViewAdapter
(getContext(), atmList);
atmView.setAdapter(atmRecyclerViewAdapter);
atmRecyclerViewAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(jsonArrayRequest);
return rootView;
}
}
XML Files
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<!-- This LinearLayout represents the contents of the screen -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment android:name="com.camelr.bilal.camelrecommerceproject.Fragments.ShowATMs"
android:id="#+id/ATMs"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="0dp"
tools:layout="#layout/atm_view" />
<!-- The ActionBar displayed at the top -->
<include
layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!-- The main content view where fragments are loaded -->
<FrameLayout
android:id="#+id/flContent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<!--<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />-->
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
android:background="#color/colorPrimary"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/drawer_view" />
</android.support.v4.widget.DrawerLayout>
atm_view.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<!--
tools:context=".MainActivity"
tools:showIn="#layout/activity_main">
-->
<android.support.v7.widget.RecyclerView
android:id="#+id/atmRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
I have two other Fragments that I set up a little differently but just showing the one for ATMs because I feel it is the closest to working.
I have implemented a drawer layout whereby when I click a navigation view item a tab layout opens up. The tablayout comes in fine but the problem is when i click the back button of the tab layout the application crashes with No drawer view found with gravity LEFT. Also I have noticed that there is a bit of a lag when the navigation drawer closes when the tab layout comes in, the drawer does not close smoothly.
Below is my java code and xml:
public class Navigation extends AppCompatActivity implements
ItemFragment.OnHeadlineSelectedListener,
SortFragment.OnHeadlineSelectedListener{
private static final String TAG = Navigation.class.getSimpleName();
Toolbar toolbar;
FragmentManager mFragmentManager;
private TextView mCounter;
private ImageView cart;
FragmentTransaction mFragmentTransaction;
public int id, tabPosition = 0, tabPositionNavigation = 0;
private String drinkToSort = "empty";
SharedPreferences preferences;
private LocalStore localStore;
private String userName, email, location;
private String phone;
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation);
localStore = new LocalStore(this);
id = localStore.getLoggedInUser().getId();
userName = localStore.getLoggedInUser().getUserName();
email = localStore.getLoggedInUser().getEmail();
phone = localStore.getLoggedInUser().getPhone();
Log.i(TAG,"USERDATA" + "[" + id + userName + email + phone + location + "]");
relativeLayout = (RelativeLayout) findViewById(R.id.main_content);
preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
toolbar, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle("hello");
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle("hello");
}
};
Bundle extras = getIntent().getExtras();
if (extras != null) {
this.tabPosition = extras.getInt("tabPosition");
this.tabPositionNavigation = extras.getInt("tabPositionNavigation");
this.drinkToSort = extras.getString("drinkToSort");
Log.d(TAG, tabPosition + tabPositionNavigation + drinkToSort);
}
Bundle bundle = new Bundle();
bundle.putString("drinkToSort", drinkToSort);
LiquorFragment obj = new LiquorFragment();
obj.setArguments(bundle);
int width = getResources().getDisplayMetrics().widthPixels/2;
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.frame_container, new NavigationFragment()).commit();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.details_activity, menu);
RelativeLayout badgeLayout = (RelativeLayout) menu.findItem(R.id.cart_no).getActionView();
mCounter = (TextView) badgeLayout.findViewById(R.id.counter);
Log.d("sameSelectionCount", CartCounter.getCounter()+"");
mCounter.setText(""+CartCounter.getCounter());
cart = (ImageView) badgeLayout.findViewById(R.id.cart);
cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("cart_no","cart_no");
Intent intent = new Intent(getApplicationContext(), ShoppingList.class);
startActivity(intent);
}
});
return true;
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
else {
super.onBackPressed();
}
}
#Override
public void onStart() {
super.onStart();
// analytics
GoogleAnalytics.getInstance(this).reportActivityStart(this);
}
#Override
public void onResume() {
super.onResume();
//TabFragment.viewPager.setCurrentItem(1);
Log.d("landposzq",tabPositionNavigation + "");
if (tabPositionNavigation != 0){
if (tabPositionNavigation == 1){
NavigationFragment.viewPager.setCurrentItem(0);
} else if (tabPositionNavigation == 2){
NavigationFragment.viewPager.setCurrentItem(1);
} else if (tabPositionNavigation == 3){
NavigationFragment.viewPager.setCurrentItem(2);
} else if (tabPositionNavigation == 4){
NavigationFragment.viewPager.setCurrentItem(3);
} else if (tabPositionNavigation == 5){
NavigationFragment.viewPager.setCurrentItem(4);
}
}
}
}
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
tools:openDrawer="start"
android:fitsSystemWindows="true">
<!--Main content-->
<RelativeLayout
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/qb"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar" />
</RelativeLayout>
<!--Navigation Drawer-->
<android.support.design.widget.NavigationView
android:id="#+id/main_drawer"
android:layout_width="290dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
android:background="#color/white"
app:headerLayout="#layout/drawer_header"
app:itemTextColor="#000000"
app:itemIconTint="#color/qb"
app:menu="#menu/menu_drawer" >
<LinearLayout
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginLeft="20dp"
android:src="#drawable/balloon4"
/>
<TextView
android:id="#+id/free_drinks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffff99"
android:gravity="center_vertical"
android:padding="10dp"
android:drawableRight="#drawable/direction"
android:height="60dp"
android:textSize="18sp"
android:text="GET FREE DRINKS"
android:textColor="#000000"
android:layout_gravity="bottom"
/>
</LinearLayout>
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
Change your onBackPressed() method as below :
#Override
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawer(GravityCompat.START);
}
else {
super.onBackPressed();
}
}
Menu Item click not working I tried various things but it won't work.
Here are my code:
Home Activity:
public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
private Button mBtRequest;
private Button mBtContinue;
private ProfileFragment mProfileFragment;
private SetPreferences Setpref;
private SlideUp slideUp;
private View dim;
private View sliderView;
Toast toast;
private TextView mTvDrawerName;
private TextView mTvDrawerMobile;
private TextView mtoolbarTitle;
private String mfullName;
private String mMobile;
private SharedPreferences mSharedPreferences;
private CompositeSubscription mSubscriptions;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Checking for first time launch - before calling setContentView()
Setpref = new SetPreferences(this);
if (!Setpref.IsLoggined()) {
gotoMain();
finish();
}
setContentView(R.layout.activity_home);
ButterKnife.bind(this);
mSubscriptions = new CompositeSubscription();
initSharedPreferences();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar.findViewById(R.id.toolbar_title).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Snackbar.make(v, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
mBtRequest = (Button) findViewById(R.id.btn_request);
mBtContinue = (Button) findViewById(R.id.btn_continue);
mBtRequest.setOnClickListener(view -> slideUp());
mBtContinue.setOnClickListener(view -> checkout());
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
sliderView = findViewById(R.id.slideView);
sliderView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (toast != null){
toast.cancel();
}
toast = Toast.makeText(HomeActivity.this, "click", Toast.LENGTH_SHORT);
toast.show();
}
});
dim = findViewById(R.id.dim);
slideUp = new SlideUpBuilder(sliderView)
.withListeners(new SlideUp.Listener.Events() {
#Override
public void onSlide(float percent) {
dim.setAlpha(1 - (percent / 100));
}
#Override
public void onVisibilityChanged(int visibility) {
if (visibility == View.GONE){
// fab.show();
}
}
})
.withStartGravity(Gravity.BOTTOM)
.withLoggingEnabled(true)
.withGesturesEnabled(true)
.withStartState(SlideUp.State.HIDDEN)
.build();
Typeface myraid_bold = Typeface.createFromAsset(getAssets(),"fonts/MyriadPro-Bold_0.otf");
Typeface myraid_semibold = Typeface.createFromAsset(getAssets(),"fonts/MyriadPro-Semibold_0.otf");
View header = navigationView.getHeaderView(0);
mTvDrawerName = (TextView) header.findViewById(R.id.nav_user_name);
mTvDrawerMobile = (TextView) header.findViewById(R.id.nav_mobile_number);
mtoolbarTitle = (TextView) findViewById(R.id.toolbar_title);
mTvDrawerName.setText(mfullName);
mTvDrawerMobile.setText(mMobile);
mTvDrawerName.setTypeface(myraid_bold);
mTvDrawerMobile.setTypeface(myraid_bold);
mtoolbarTitle.setTypeface(myraid_semibold);
mBtRequest.setTypeface(myraid_bold);
mBtContinue.setTypeface(myraid_bold);
}
private void initSharedPreferences() {
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
mfullName = mSharedPreferences.getString(Constants.FULLNAME,"");
mMobile = mSharedPreferences.getString(Constants.MOBILE,"");
}
private void gotoProfile(){
if (mProfileFragment == null) {
mProfileFragment = new ProfileFragment();
}
getFragmentManager().beginTransaction().replace(R.id.fragmentFrame,mProfileFragment,ProfileFragment.TAG).commit();
}
private void gotoMain(){
Setpref.setIsLoggined(false);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
private void slideUp(){
slideUp.show();
}
private void checkout(){
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} 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.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void logout() {
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString(Constants.MOBILE,"");
editor.putString(Constants.TOKEN,"");
editor.putString(Constants.FULLNAME,"");
editor.apply();
gotoMain();
}
private void showSnackBarMessage(String message) {
Snackbar.make(findViewById(R.id.drawer_layout),message,Snackbar.LENGTH_SHORT).show();
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_my_addresses) {
// Handle the camera action
} else if (id == R.id.nav_my_orders) {
} else if (id == R.id.nav_refer) {
} else if (id == R.id.nav_logout) {
logout();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
activity_home_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_my_addresses"
android:icon="#drawable/ic_location_on_white_24px"
android:title="My Addresses" />
<item
android:id="#+id/nav_my_orders"
android:icon="#drawable/ic_history_white_24px"
android:title="My Orders" />
<item
android:id="#+id/nav_refer"
android:icon="#drawable/ic_record_voice_over_white_24px"
android:title="Refer & Earn" />
</group>
<group
android:id="#+id/menu_bottom"
android:checkableBehavior="none">
<item
android:id="#+id/nav_logout"
android:icon="#drawable/ic_exit_to_app_white_24px"
android:title="Logout" />
</group>
</menu>
nav_header_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="#dimen/nav_header_height"
android:background="#drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:text="Aashish Kaushik"
android:id="#+id/nav_user_name"
android:textColor="#android:color/white"/>
<TextView
android:id="#+id/nav_mobile_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="9910454530"
android:textColor="#android:color/white"/>
</LinearLayout>
activity_home.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<FrameLayout
android:alpha="0"
android:id="#+id/dim"
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/dimBg" />
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_home_drawer" />
<!-- The Fragment -->
<FrameLayout
android:id="#+id/fragmentFrame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.v4.widget.DrawerLayout>
When I try to view activity_home.xml as a design it will not showing left drawer but when I install the app on device it will show the left drawer on click but when I click on any time it will not showing check able box and not working.
Update These lines of code works for me.. after update clean and rebuild Project.
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.bringToFront();
Here is a simple solution to address this issue. You can just link your HomeActivity methods to the menu items (whichever you want to). Now just create your methods and go to the menu layout. In the menu layout just add the android:onClick inside the item tag and put the particular method name inside it. And you are done. Let me know if this was useful.
I was able to make a navigation drawer and google sign in app using firebase tutorials from youtube https://www.youtube.com/playlist?list=PLGCjwl1RrtcR1j6EmpBxJyJYowK2QIsdT
I have activity_navigation.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="rjbc.cpvc.NavigationActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout = "#layout/navigation_action"
android:layout_height="wrap_content"
android:layout_width="match_parent" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginStart="101dp"
android:layout_marginTop="201dp"
android:id="#+id/textView5" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#mipmap/ic_person_black_24dp"
android:layout_below="#+id/textView5"
android:layout_alignEnd="#+id/textView5"
android:layout_marginEnd="42dp"
android:layout_marginTop="53dp"
android:id="#+id/imageView" />
</RelativeLayout>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="#menu/navigation_menu"
android:layout_gravity = "start"
app:headerLayout="#layout/navigation_header" />
</android.support.v4.widget.DrawerLayout>
and navigation_header.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent" android:layout_height="140dp"
android:background="#color/colorPrimary"
android:padding="20dp"
android:id="#+id/pName">
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="13dp"
android:id="#+id/textView"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:textColor="#color/common_google_signin_btn_text_dark_default" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#mipmap/ic_person_black_24dp"
android:id="#+id/pPic"
android:layout_above="#+id/textView"
android:layout_alignEnd="#+id/textView"
android:layout_marginEnd="16dp"
android:layout_marginBottom="18dp" />
</RelativeLayout>
this is my navigation_activity.java
public class NavigationActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private Toolbar mToolbar;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private TextView mName;
private String name;
private Uri photoUrl;
private ImageView mPic;
private NavigationView mNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
mToolbar = findViewById(R.id.nav_action);
setSupportActionBar(mToolbar);
mDrawerLayout = findViewById(R.id.drawerLayout);
mToggle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser() == null) {
startActivity(new Intent(NavigationActivity.this,MainActivity.class));
}
}
};
mName = mNavigationView.getHeaderView(0).findViewById(R.id.textView);
mPic = mNavigationView.getHeaderView(0).findViewById(R.id.pPic);
getCurrentinfo();
mNavigationView = findViewById(R.id.nav_view);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(final MenuItem menuItem) {
int id = menuItem.getItemId();
switch (id) {
case R.id.nav_account:
Toast.makeText(NavigationActivity.this, "Account Selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.nav_settings:
Toast.makeText(NavigationActivity.this, "Setting Selected", Toast.LENGTH_SHORT).show();
default:
return true;
}
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void getCurrentinfo() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
for (UserInfo profile : user.getProviderData()) {
// Id of the provider (ex: google.com)
String providerId = profile.getProviderId();
// UID specific to the provider
String uid = profile.getUid();
// Name, email address, and profile photo Url
name = profile.getDisplayName();
photoUrl = profile.getPhotoUrl();
mName.setText(name);
Picasso.with(getApplicationContext())
.load(photoUrl.toString())
.placeholder(R.drawable.logo)
.resize(100, 100)
.transform(new CircleTransform())
.centerCrop()
.into(mPic);
}
}
}
}
in my getcurrentInfo function I am able to place my name and profile pic in the activity_navigation.xml but I want to place it an navigation_header.xml
I tried changing the id of my ImageView and TextView to match with that in the navigation_header but my app crashes.
Try this after mNavigationView = (NavigationView) findViewById(R.id.nav_view);
TextView userName = (TextView)mNavigationView.getHeaderView(0).findViewById(R.id.username);
It is because you are initializing the textview before the navigationview
get initialized
mName = (TextView)mNavigationView.getHeaderView(0).findViewById(R.id.textView);
mPic = (ImageView) mNavigationView.getHeaderView(0).findViewById(R.id.pPic);
getCurrentinfo();
mNavigationView = (NavigationView) findViewById(R.id.nav_view); //navigation view is initialized here
This is going to work 100% hopefully.
Let me know if it works.
`
//Initializing firebase objects
firebaseAuth = FirebaseAuth.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
//Go to your specific database directory or Child
databaseReference = FirebaseDatabase.getInstance().getReference().child("Students").child(firebaseUser.getUid());
//Connect the views of navigation bar
mNavigationView = (NavigationView) findViewById(R.id.nav_view);
mName = (TextView)mNavigationView.getHeaderView(0).findViewById(R.id.textViewHeaderTitle);
mID = (TextView)mNavigationView.getHeaderView(0).findViewById(R.id.textViewHeaderSID);
mImageView = (CircleImageView) mNavigationView.getHeaderView(0).findViewById(R.id.imageViewHeaderIcon);
//Use you DB reference object and add this method to access realtime data
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Fetch values from you database child and set it to the specific view object.
mName.setText(dataSnapshot.child("name").getValue().toString());
mID.setText(dataSnapshot.child("sid").getValue().toString());
String link =dataSnapshot.child("profile_picture").getValue().toString();
Picasso.with(getBaseContext()).load(link).into(mImageView);
}
//SIMPLE BRO. HAVE FUN IN ANDROID <3 GOOD LUCK
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
`
From NavigationView you will access the textview and imageview with "navigationView.getHeaderView(0)" this line
For Quick Sample
TextView userName = (TextView) navigationView.getHeaderView(0).findViewById(R.id.username);
userName.setText(new UserPreference().getUser(MainActivity.this).userName);
All the Best!!