I created a new fragment which is ProfileFragment.java and also created fragment_profile.xml.
The program does not give any error but my layout doesnt show. What is wrong?
My ProfileFragment.java :
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
public class ProfileFragment extends Fragment {
//firebase auth
FirebaseAuth firebaseAuth;
FirebaseUser user;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
//layout views
ImageView avatar;
TextView nameTxt, emailTxt, phoneTxt;
public ProfileFragment() {
//boş public constructor gerekli
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_profile, container, false);
//init firebase
firebaseAuth = FirebaseAuth.getInstance();
user = firebaseAuth.getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Users");
//init layout views
avatar = view.findViewById(R.id.avatar);
nameTxt = view.findViewById(R.id.nameTxt);
emailTxt = view.findViewById(R.id.emailTxt);
phoneTxt = view.findViewById(R.id.phoneTxt);
/* giriş yapan kullanıcıların bilgilerini email yada uid kullanarak çekmek zorundayız
Kullanıcı detaylarını email adreslerini kullanarak çekicez
orderbyChild query kullanarak giriş yapılan email ile email key ini eşleştirerek kullanıcı detaylarına ulaşılıyor
*/
Query query = databaseReference.orderByChild("email").equalTo(user.getEmail());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
//gerekli veriler gelene kadar kontrol et
for (DataSnapshot ds: snapshot.getChildren()){
//verileri almak için
String name = ""+ ds.child("name").getValue();
String email = ""+ ds.child("email").getValue();
String phone = ""+ ds.child("phone").getValue();
String image = ""+ ds.child("image").getValue();
//set data
nameTxt.setText(name);
emailTxt.setText(email);
phoneTxt.setText(phone);
try {
// resim alınırsa ayarla
Picasso.get().load(image).into(avatar);
} catch (Exception e){
// resim alınırken herangi bir sıkıntı varsa varsayılan olarak ayarla
Picasso.get().load(R.drawable.add_photo_foreground).into(avatar);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
return view;
}
}
and my fragment_profile.xml :
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F1EDED"
tools:context=".ProfileFragment">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="180dp"
android:background="#2ECC71">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="120dp"
android:orientation="horizontal"
android:layout_marginTop="100dp">
<ImageView
android:id="#+id/avatar"
android:layout_width="120dp"
android:layout_height="120dp"
android:src="#drawable/add_photo_foreground"
android:layout_marginStart="20dp"
android:background="#6AE493"
android:padding="5dp">
</ImageView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/nameTxt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:textSize="25dp"
android:textColor="#FFFFFF"></TextView>
<TextView
android:id="#+id/emailTxt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:textColor="#FFFFFF"></TextView>
<TextView
android:id="#+id/phoneTxt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:textColor="#FFFFFF"></TextView>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
</ScrollView>
I want to create a user profile page using firebase realtime database. The user details come from using email for current signed user. But my profile layout file does not work. How can I fix this problem? Whats wrong in my code?
My DasboardAvtivity.java -> For fragment transaction.
package com.gamze.pawsbook;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class DashboardActivity extends AppCompatActivity {
//FirebaseAuth
FirebaseAuth firebaseAuth;
//Actionbar
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
//ActionBar ve başlığı
actionBar = getSupportActionBar();
actionBar.setTitle("Profile");
//profileTxt = findViewById(R.id.profileTxt);
firebaseAuth = FirebaseAuth.getInstance();
//Bottom navigation
BottomNavigationView navigationView = findViewById(R.id.navigation);
navigationView.setOnNavigationItemSelectedListener(selectedListener);
//Home Fragment'ı boş default fragment olarak ayarlanması
actionBar.setTitle("Home"); //ActionBar başlığını değiştirme
HomeFragment homeFragment = new HomeFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content, homeFragment, "");
ft.commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener selectedListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
//itemlere tıklanma özelliği ekleme
switch (item.getItemId()){
case R.id.action_home:
//home fragment değişimi
actionBar.setTitle("Home"); //ActionBar başlığını değiştirme
HomeFragment homeFragment = new HomeFragment();
FragmentTransaction ftHome = getSupportFragmentManager().beginTransaction();
ftHome.replace(R.id.content, homeFragment, "");
ftHome.commit();
return true;
case R.id.action_map:
//map fragment değişimi
actionBar.setTitle("Map"); //ActionBar başlığını değiştirme
MapFragment mapFragment = new MapFragment();
FragmentTransaction ftMap = getSupportFragmentManager().beginTransaction();
ftMap.replace(R.id.content, mapFragment, "");
ftMap.commit();
return true;
case R.id.action_users:
//users fragment değişimi
actionBar.setTitle("Users"); //ActionBar başlığını değiştirme
UsersFragment usersFragment = new UsersFragment();
FragmentTransaction ftUsers = getSupportFragmentManager().beginTransaction();
ftUsers.replace(R.id.content, usersFragment, "");
ftUsers.commit();
return true;
case R.id.action_profile:
//profile fragment değişimi
actionBar.setTitle("Profile"); //ActionBar başlığını değiştirme
ProfileFragment profileFragment = new ProfileFragment();
FragmentTransaction ftProfile = getSupportFragmentManager().beginTransaction();
ftProfile.replace(R.id.content, profileFragment, "");
ftProfile.commit();
return true;
}
return false;
}
};
private void checkUserStatus() {
//mevcut kullanıcıyı al
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null){
//kullanıcı giriş yapmışsa burada kal
//giriş yapan kullanıcının email i
//profileTxt.setText(user.getEmail());
}
else{
//kullanıcı giriş yapmamışsa main activity'e git
Intent intent = new Intent(DashboardActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
protected void onStart() {
//uygulamanın başlangıcını konrtol et
checkUserStatus();
super.onStart();
}
//options menu dahil etme
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//menuyu dahil etme
getMenuInflater().inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
//menu itemlerine onClick özelliği aktifleştirme
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
//itemlerin id'lerini al
int id = item.getItemId();
if (id == R.id.action_logout){
//hesaptan çıkış yap
firebaseAuth.signOut();
checkUserStatus();
}
return super.onOptionsItemSelected(item);
}
}
activity_dashboard.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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DashboardActivity">
//FrameLayout fragmentlerin üstüste gelebilmesi için daha kullanışlıdır
<FrameLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="0dp">
</FrameLayout>
//BottomNavigationBar
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentEnd="false"
android:layout_alignParentBottom="true"
android:background="?android:attr/windowBackground"
app:menu="#menu/bottombar_menu">
</com.google.android.material.bottomnavigation.BottomNavigationView>
</RelativeLayout>
This is what is showing from fragment_profile.xml.
Your question doesn't give information whether you are getting an empty view like above or you are not getting any view. I will try to answer on two ansumption.
Empty View
No View at all
Empty View
If you are getting empty view then you must put some Logs statement in your database responce, check if that database is returning some value.
public class ProfileFragment extends Fragment {
//Log Statment
private static final String TAG = "ProfileFragment";
......
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
//gerekli veriler gelene kadar kontrol et
for (DataSnapshot ds: snapshot.getChildren()){
//verileri almak için
String name = ""+ ds.child("name").getValue();
String email = ""+ ds.child("email").getValue();
String phone = ""+ ds.child("phone").getValue();
String image = ""+ ds.child("image").getValue();
//set data
nameTxt.setText(name);
emailTxt.setText(email);
phoneTxt.setText(phone);
Log.d(TAG, "onDataChange: \nName: "+name+" email: "+ email);
try {
// resim alınırsa ayarla
Picasso.get().load(image).into(avatar);
} catch (Exception e){
// resim alınırken herangi bir sıkıntı varsa varsayılan olarak ayarla
Picasso.get().load(R.drawable.add_photo_foreground).into(avatar);
}
}
Log.d(TAG, "onDataChange: Data is empty");
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.d(TAG, "onCancelled: "+error);
}
}
}
.........
You can use breakpoints as well to further investigation.
No View at all
If view is not changing on ProileFragment then you must check how you are starting ProfileFragment.
getSupportFragmentManager().beginTransaction().replace(R.id.frgment_container, new ProfileFragment()).commit();
If you are using Navigation Component then make sure you are navigating to correct destination.
I will also suggest you to strcture the code in following format under Profile Fragment -
public class ProfileFragment extends Fragment {
//firebase auth
............
//layout views
..............
public ProfileFragment() {
//boş public constructor gerekli
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_profile, container, false);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//init firebase
.................
//init layout views
.......................
/* giriş yapan kullanıcıların bilgilerini email yada uid kullanarak çekmek zorundayız
Kullanıcı detaylarını email adreslerini kullanarak çekicez
orderbyChild query kullanarak giriş yapılan email ile email key ini eşleştirerek kullanıcı detaylarına ulaşılıyor
*/
Query query = databaseReference.orderByChild("email").equalTo(user.getEmail());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
.................
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
...............
}
});
}
}
Edit (activity_dashboard.xml)
Try following layout file for activity_dashboard.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="match_parent"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".DashboardActivity">
<FrameLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="?attr/actionBarSize"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_alignParentEnd="false"
android:layout_alignParentBottom="true"
android:background="?android:attr/windowBackground"
app:menu="#menu/bottombar_menu"/>
</RelativeLayout>
I am using ?attr/actionBarSize, which is the standard action bar size for android.
Happy Coding !
Related
I'm new for Android Project. I create project with Firebase. In this project I want to add Logged User name's to textview in nav header. I use for login or registration Model options. But I can't.
Does anyone have any experience with this? My firebase database datas shown like this.
I want make like this
My Home Activity is this
package com.cavad.firebaseproject;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView)
findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
Fragment category = new CategoryFragment();
this.setDefaultFragment(category);
}
private void setDefaultFragment(Fragment defaultFragment)
{
this.replaceFragment(defaultFragment);
}
public void replaceFragment(Fragment destFragment)
{
FragmentManager fragmentManager = this.getSupportFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.category, destFragment);
fragmentTransaction.commit();
}
#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_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
My nav_header xml file is this nav_header_home.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="wrap_content"
android:background="#color/colorPrimaryDark"
android:gravity="bottom"
android:orientation="vertical"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<TextView
android:id="#+id/userName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="userName"
android:textColor="#color/white"
android:textSize="20sp"
android:layout_marginTop="15dp"
android:layout_marginBottom="10dp"
android:textStyle="bold"/>
</LinearLayout>
My Model class is this
package com.cavad.firebaseproject.Model;
public class User {
private String userName;
private String password;
private String email;
public User(){
}
public User(String userName, String password, String email) {
this.userName = userName;
this.password = password;
this.email = email;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
My Firebase database rules is this
{
"rules": {
".read": true,
".write": true
}
}
My Login activity is this
package com.cavad.firebaseproject;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.cavad.firebaseproject.Model.User;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class Login extends Fragment {
EditText user, password;
ImageView signin;
FirebaseDatabase database;
DatabaseReference users;
public Login() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_login, container,
false);
database = FirebaseDatabase.getInstance();
users = database.getReference("Users");
user = view.findViewById(R.id.name);
password = view.findViewById(R.id.password);
signin = view.findViewById(R.id.submit);
signin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
signin(user.getText().toString(),password.getText().toString());
}
});
return view;
}
private void signin(final String user, final String pwd){
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(user).exists())
{
if (!user.isEmpty())
{
User login =
dataSnapshot.child(user).getValue(User.class);
if (login.getPassword().equals(pwd))
{
Toast.makeText(getActivity(), "Uğurla daxil
oldunuz", Toast.LENGTH_SHORT).show();
startActivity(new
Intent(getActivity().getApplication(), Home.class));
}
else
Toast.makeText(getActivity(), "Zəhmət olmasa
Şifrəni düzgün daxil edin", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getActivity(), "Zəhmət olmasa
İstifadəçi adınızı daxil edin", Toast.LENGTH_SHORT).show();
}
}
else
Toast.makeText(getActivity(), "Belə bir istifadəçi adı
tapılmadı !!!", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
My Login acticity xml is this
<LinearLayout
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="wrap_content"
tools:context=".Login"
android:background="#color/colorPrimaryDark"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2"
android:layout_marginTop="7dp"
android:layout_marginBottom="7dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="7dp"
android:layout_marginBottom="7dp"
app:hintEnabled="false"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp">
<EditText
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="48dp"
android:hint="#string/name"
android:inputType="text"
android:textSize="20sp"
android:drawableStart="#drawable/ic_user"
android:drawableLeft="#drawable/ic_user"
android:drawablePadding="10dp"
android:background="#drawable/edttext_background"
android:paddingRight="10dp"
android:paddingLeft="10dp"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="7dp"
android:layout_marginBottom="7dp"
app:hintEnabled="false"
app:passwordToggleDrawable="#drawable/visibility"
app:passwordToggleEnabled="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp">
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="48dp"
android:textSize="20sp"
android:inputType="textPassword"
android:hint="#string/password"
android:drawableStart="#drawable/ic_lock"
android:drawableLeft="#drawable/ic_lock"
android:background="#drawable/edttext_background"
android:drawablePadding="10dp"
android:paddingRight="10dp"
android:paddingLeft="10dp" />
</android.support.design.widget.TextInputLayout>
<ImageView
android:id="#+id/submit"
android:layout_width="48dp"
android:layout_height="48dp"
android:gravity="center"
android:layout_gravity="center"
android:src="#drawable/ic_check"
android:background="#drawable/check_background"
android:layout_marginTop="15dp"
android:layout_marginBottom="15dp"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
Step 1. Get the current signed in user:-
The recommended way to get the current user is by calling the getCurrentUser method. If no user is signed in, getCurrentUser returns null.Example :-
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// Name, email address, and profile photo Url
String name = user.getDisplayName();
String email = user.getEmail();
Uri photoUrl = user.getPhotoUrl();
// Check if user's email is verified
boolean emailVerified = user.isEmailVerified();
// The user's ID, unique to the Firebase project. Do NOT use this value to
// authenticate with your backend server, if you have one. Use
// FirebaseUser.getIdToken() instead.
String uid = user.getUid();
}
For More check the link
Manage Users in Firebase
Step 2. Set it to the navigation view header:-
You can get the textview like:-
NavigationView navigationView = (NavigationView) findViewById(R.id.your_nav_view_id);
View header = navigationView.getHeaderView(0)
TextView text = (TextView) header.findViewById(R.id.textView);
If you want to retrieve logged user email, username and pictures stored in the real-time database and show them in the navigation header then you can simply follow this:
NavigationView navigationView = findViewById(R.id.nav_view);
database = FirebaseDatabase.getInstance();
auth = FirebaseAuth.getInstance();
database.getReference().child("Users").child(auth.getUid())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
//we have Users class which contain user properties and methods.
User user = snapshot.getValue(User.class);
View header = navigationView.getHeaderView(0);
nav_email = header.findViewById(R.id.nav_email);
nav_username = header.findViewById(R.id.nav_username);
nav_profile = header.findViewById(R.id.nav_profilePic);
Picasso.get().load(user.getProfilePic()).placeholder(R.drawable.avatar).into(nav_profile);
nav_email.setText(user.getMail());
nav_username.setText(user.getUserName());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
If you want to use Picasso to retrieve an image from the real time database and then set it on the nav header imageview then add the following dependency in your bundle Gradle module file :
implementation 'com.squareup.picasso:picasso:2.71828'
Then you can use Picasso in your project.
retrive logged user data from firebase realtime database in navigation header
// xml file
<TextView
android:id="#+id/your_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/gotham_bold"
android:text="User Name"
android:textColor="#color/brown"
android:textSize="18sp"
/>
<TextView
android:id="#+id/user_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/gotham_book"
android:text="User Name"
android:textColor="#color/brown"
android:textSize="15sp"
android:layout_gravity="center"
/>
// java code
firebaseDatabase.getReference().child("Users").child(auth.getUid())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
View header = navigationView.getHeaderView(0);
name = header.findViewById(R.id.your_name);
username = header.findViewById(R.id.user_name);
name.setText(user.getName1());
username.setText("#" + user.getUsername1());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
I'm trying to add fragment with Navigation drawer to the main activity, where are two buttons. However, when Navigation drawer is opened, buttons are above it. Moreover, Navigation drawer is not clickable, but buttons are.
Screenshot of opened Navigation drawer
Here is my code.
XML File implementing Navigation Drawer - MainActivity.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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:theme="#style/Theme.AppCompat.Light.NoActionBar"
tools:context=".MainActivity">
<Button
android:id="#+id/mainTestsButton"
android:layout_width="112dp"
android:layout_height="105dp"
android:layout_alignParentEnd="true"
android:layout_marginTop="334dp"
android:layout_marginEnd="167dp"
android:onClick="goTest"
android:text="Button2"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/mainLearningButton"
android:layout_width="114dp"
android:layout_height="102dp"
android:layout_alignParentEnd="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="108dp"
android:layout_marginEnd="175dp"
android:layout_marginBottom="118dp"
android:onClick="goLearn"
android:text="Button1"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<fragment
android:id="#+id/fragmentList"
android:name="com.chemistryApps.NavigationDrawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout="#layout/fragment_navigation_drawer" />
</RelativeLayout>
Navigation Drawer 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"
android:theme="#style/Theme.AppCompat.Light.NoActionBar"
tools:context=".NavigationDrawer">
<android.support.constraint.ConstraintLayout
android:id="#+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0">
</android.support.constraint.ConstraintLayout>
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<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"
app:menu="#menu/menu_layout" />
</android.support.v4.widget.DrawerLayout>
Navigation Drawer Fragment Java class
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
public class NavigationDrawer extends Fragment {
private DrawerLayout mDrawerLayout;
NavigationView navigationView;
private OnFragmentInteractionListener mListener;
public NavigationDrawer() {
// Required empty public constructor
}
public static NavigationDrawer newInstance(String param1, String param2) {
NavigationDrawer fragment = new NavigationDrawer();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.i("buttonClicked", "onCreateView");
View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
mDrawerLayout = view.findViewById(R.id.drawer_layout);
navigationView = view.findViewById(R.id.nav_view);
mDrawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(#NonNull View view, float v) {
Log.i("buttonClicked", "onDrawerOpened");
}
#Override
public void onDrawerOpened(#NonNull View view) {
Log.i("buttonClicked", "onDrawerOpened");
navigationView.bringToFront();
mDrawerLayout.requestLayout();
}
#Override
public void onDrawerClosed(#NonNull View view) {
Log.i("buttonClicked", "onDrawerOpened");
}
#Override
public void onDrawerStateChanged(int i) {
Log.i("buttonClicked", "onDrawerOpened");
}
});
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
// set item as selected to persist highlight
Log.i("buttonClicked", "onNavigationItemSelected()" + menuItem.toString());
menuItem.setChecked(true);
// close drawer when item is tapped
mDrawerLayout.closeDrawers();
// Add code here to update the UI based on the item selected
switch (menuItem.getItemId()){
case R.id.learning:
Intent intent = new Intent(getActivity(), LearningActivity.class);
startActivity(intent);
return true;
case R.id.test:
Intent intent2 = new Intent(getActivity(), TestActivity.class);
startActivity(intent2);
return true;
case R.id.settings:
return true;
case R.id.help:
return true;
default:
return false;
}
}
});
return inflater.inflate(R.layout.fragment_navigation_drawer, container,
false);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
Thank you in advance for an answer.
EDIT:
I am attaching the main activity code
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MainActivity extends AppCompatActivity implements
NavigationDrawer.OnFragmentInteractionListener {
public void goLearn (View view){
Log.i("buttonClicked", "goLearn");
final Intent intent = new Intent(this, LearningActivity.class);
startActivity(intent);
}
public void goTest (View view){
Log.i("buttonClicked", "goTest");
final Intent intent = new Intent(this, TestActivity.class);
startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onFragmentInteraction(Uri uri) {
return;
}
}
So my problem, let's say we are in SignInFragment (To navigate in SignInFragment, the launcher is the MainActivity inside that it will open the HomeFragment then inside of HomeFragment there is code if there is no user signed in it will navigate to SignInFragment) then in SignInFragment there is a TextView "Do not have account yet? Register here." So whenever I press that nothings happen. Hope you understand.
I will add the other Fragments to easily understand the flow of my App.
Here are the codes for: MainActivity
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HomeActivity fragment = new HomeActivity();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, fragment, fragment.getTag());
ft.commit();
}
Here are the codes for: HomeActivity
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class HomeActivity extends Fragment {
private static final String TAG = "HomeActivity";
TextView mWelcome;
Button btnSignout;
//Firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.home_activity, container, false);
mWelcome = view.findViewById(R.id.welcome);
btnSignout = view.findViewById(R.id.btnSignOut);
setupFirebaseAuth();
//Firebase
mAuth = FirebaseAuth.getInstance();
btnSignout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.container, new SignOutFragment());
ft.commit();
}
});
return view;
}
/*
-------------------------------Firebase--------------------------------
*/
/*
check if the user is logged in
*/
private void checkCurrentUser(FirebaseUser user){
Log.d(TAG, "checkCurrentUser: checking if user is logged in.");
if (user == null){
SignInFragment fragment = new SignInFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.remove(HomeActivity.this);
ft.replace(R.id.container, fragment);
ft.commit();
}
}
private void setupFirebaseAuth(){
Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
//checking if the user is logged in or not remove
// checkCurrentUser(user);
if (user != null){
//User is signed in
Log.d(TAG, "onAuthStateChanged: signed_in: " + user.getUid());
}else {
// User is signed out
Log.d(TAG, "onAuthStateChanged: signed_out");
}
}
};
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
checkCurrentUser(mAuth.getCurrentUser());
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null){
mAuth.removeAuthStateListener(mAuthListener);
}
}
Here are the codes for: SignInFragment
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class SignInFragment extends Fragment {
private static final String TAG = "SignInFragment";
private TextView mEmail, mPassword, mHeading, mToRegister, mFckyou;
private EditText eEmail, ePassword;
private Button btnSignin;
private ProgressBar mProgressBar;
//Firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.signin_fragment, container, false);
//TextView
mEmail = view.findViewById(R.id.tvEmail);
mPassword = view.findViewById(R.id.tvPassword);
mHeading = view.findViewById(R.id.heading);
mToRegister = view.findViewById(R.id.tvToRegister);
mFckyou = view.findViewById(R.id.fckyou);
//EditText
mEmail = view.findViewById(R.id.etEmail);
ePassword = view.findViewById(R.id.etPassword);
//Button
btnSignin = view.findViewById(R.id.btnSignin);
//ProgressBar
mProgressBar = view.findViewById(R.id.progressBar);
//Progress Bar and Text view = GONE
mProgressBar.setVisibility(View.GONE);
mFckyou.setVisibility(View.GONE);
navigateToReigster();
setupFirebaseAuth();
signInUser();
return view;
}
public void navigateToReigster(){
mToRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RegisterFragment fragment = new RegisterFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.container, fragment, fragment.getTag());
ft.commit();
}
});
}
private boolean isStringNull(String string){
if (string.equals("")){
return true;
}
return false;
}
/*
---------------------------------Firebase-----------------------------------
*/
private void signInUser(){
// Button = to sign in the user.
btnSignin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = eEmail.getText().toString();
String password = ePassword.getText().toString();
if (isStringNull(email) && isStringNull(password)){
Toast.makeText(getActivity(), "You must field out all the fields.", Toast.LENGTH_SHORT).show();
}else {
//Progress Bar and TextView be visible
mProgressBar.setVisibility(View.VISIBLE);
mFckyou.setVisibility(View.VISIBLE);
//To sign in users
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Toast.makeText(getActivity(), "Sign in Successful!", Toast.LENGTH_SHORT).show();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.container, new HomeActivity());
ft.commit();
}else {
//Progress bar and Text View will be GONE. So the users can try again.
mProgressBar.setVisibility(View.GONE);
mFckyou.setVisibility(View.GONE);
Toast.makeText(getActivity(), "Could not sign in. Please try again.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
}
Here are my codes for: RegisterFragment
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class RegisterFragment extends Fragment {
private static final String TAG = "RegisterFragment";
private TextView mEmail, mPassword, mHeading, mToSignin, mFckyou;
private EditText eEmail, ePassword;
private Button btnRegister;
private ProgressBar mProgressBar;
//Firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private String userID;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.register_fragment, container, false);
//TextView
mEmail = view.findViewById(R.id.tvEmail);
mPassword = view.findViewById(R.id.tvPassword);
mHeading = view.findViewById(R.id.heading);
mToSignin = view.findViewById(R.id.tvToSignin);
mFckyou = view.findViewById(R.id.fckyou);
//EditText
mEmail = view.findViewById(R.id.etEmail);
ePassword = view.findViewById(R.id.etPassword);
//Button
btnRegister = view.findViewById(R.id.btnRegister);
//ProgressBar
mProgressBar = view.findViewById(R.id.progressBar);
//Progress Bar and Text View = GONE
mProgressBar.setVisibility(View.GONE);
mFckyou.setVisibility(View.GONE);
navigateToSignIn();
registerNewUser();
setupFirebaseAuth();
return view;
}
public void navigateToSignIn(){
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.container, new SignInFragment());
ft.commit();
}
private boolean isStringNull(String string){
if (string.equals("")){
return true;
}
return false;
}
/*
To check if the user is creating a same email.
*/
public void checkUserId(){
if (mAuth.getCurrentUser() != null){
userID = mAuth.getCurrentUser().getUid();
}
}
/*
---------------------------------Firebase-----------------------------------
*/
public void registerNewUser(){
// To register new user
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = eEmail.getText().toString();
String password = ePassword.getText().toString();
if (isStringNull(email) && isStringNull(password)){
Toast.makeText(getContext(), "You must field out all the fields.", Toast.LENGTH_SHORT).show();
}else {
//Progress Bar and TextView be visible
mProgressBar.setVisibility(View.VISIBLE);
mFckyou.setVisibility(View.VISIBLE);
//To create/register new user
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
//user is succesfully registered and logged in
checkUserId(); //Checking if the user is create same email
Log.d(TAG, "onComplete: AuthstateChange: " + userID);
Toast.makeText(getActivity(), "Registered Successfully", Toast.LENGTH_SHORT).show();
//AFter Registering account it will navigate to the Login Fragment
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.container, new SignInFragment());
fr.commit();
}else {
//If can't register the Progresss bar and Text view will be gone, so users can sign in again.
//Progress Bar and Text View = GONE. So users can try again.
mProgressBar.setVisibility(View.GONE);
mFckyou.setVisibility(View.GONE);
Toast.makeText(getActivity(), "Please check your internet. Or maybe you registered same email.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
}
Here are my codes for: register_fragment.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/heading"
android:text="Register"
android:textColor="#000"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:textSize="50sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvEmail"
android:text="Email"
android:layout_below="#+id/heading"
android:layout_marginLeft="10dp"
android:layout_marginTop="100dp"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/etEmail"
android:textColor="#000"
android:hint="Type your email here..."
android:layout_below="#+id/tvEmail"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvPassword"
android:text="Password"
android:layout_below="#+id/etEmail"
android:layout_marginTop="20dp"
android:layout_marginLeft="10dp"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/etPassword"
android:inputType="textPassword"
android:layout_below="#+id/tvPassword"
android:hint="Type your password here..."
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnRegister"
android:text="Register"
android:layout_below="#+id/etPassword"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvToSignin"
android:text="Already have an account? Sign in here."
android:textColor="#color/colorPrimary"
android:textSize="10sp"
android:layout_below="#+id/btnRegister"
android:layout_marginTop="10dp"
android:layout_centerHorizontal="true"/>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar"
android:layout_below="#+id/tvEmail"
android:layout_marginTop="35dp"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fckyou"
android:text="That's bad"
android:textColor="#color/colorAccent"
android:textStyle="bold"
android:layout_below="#+id/progressBar"
android:layout_centerHorizontal="true"/>
Here are my codes for: signin_fragment.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/heading"
android:text="Sign In"
android:textColor="#000"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:textSize="50sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvEmail"
android:text="Email"
android:layout_below="#+id/heading"
android:layout_marginLeft="10dp"
android:layout_marginTop="100dp"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/etEmail"
android:textColor="#000"
android:hint="Type your email here..."
android:layout_below="#+id/tvEmail"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvPassword"
android:text="Password"
android:layout_below="#+id/etEmail"
android:layout_marginTop="20dp"
android:layout_marginLeft="10dp"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/etPassword"
android:inputType="textPassword"
android:layout_below="#+id/tvPassword"
android:hint="Type your password here..."
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnSignin"
android:text="Sign in"
android:layout_below="#+id/etPassword"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvToRegister"
android:text="Do not have a account yet? Register here."
android:textColor="#color/colorPrimary"
android:textSize="10sp"
android:layout_below="#+id/btnSignin"
android:layout_marginTop="10dp"
android:layout_centerHorizontal="true"/>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar"
android:layout_below="#+id/tvEmail"
android:layout_marginTop="35dp"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fckyou"
android:text="Fuck you..."
android:textColor="#color/colorAccent"
android:textStyle="bold"
android:layout_below="#+id/progressBar"
android:layout_centerHorizontal="true"/>
//Home Activity
//implemet View.OnClickListener , it is working
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class SignInFragment extends Fragment implements View.OnClickListener {
private static final String TAG = "SignInFragment";
private TextView mEmail, mPassword, mHeading, mToRegister, mFckyou;
private EditText eEmail, ePassword;
private Button btnSignin;
private ProgressBar mProgressBar;
//Firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.signin_fragment, container, false);
//TextView
mEmail = view.findViewById(R.id.tvEmail);
mPassword = view.findViewById(R.id.tvPassword);
mHeading = view.findViewById(R.id.heading);
mToRegister = view.findViewById(R.id.tvToRegister);
mFckyou = view.findViewById(R.id.fckyou);
//EditText
mEmail = view.findViewById(R.id.etEmail);
ePassword = view.findViewById(R.id.etPassword);
//Button
btnSignin = view.findViewById(R.id.btnSignin);
//ProgressBar
mProgressBar = view.findViewById(R.id.progressBar);
//Progress Bar and Text view = GONE
mProgressBar.setVisibility(View.GONE);
mFckyou.setVisibility(View.GONE);
mToRegister.setOnClickListener(this);
setupFirebaseAuth();
signInUser();
return view;
}
public void navigateToReigster(){
Fragment fragment = new RegisterFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, fragment).commit();
});
}
#Override
public void onClick(View vv) {
if (vv == mToRegister) {
navigateToReigster();
}
}
private boolean isStringNull(String string){
if (string.equals("")){
return true;
}
return false;
}
/*
---------------------------------Firebase-----------------------------------
*/
private void signInUser(){
// Button = to sign in the user.
btnSignin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = eEmail.getText().toString();
String password = ePassword.getText().toString();
if (isStringNull(email) && isStringNull(password)){
Toast.makeText(getActivity(), "You must field out all the fields.", Toast.LENGTH_SHORT).show();
}else {
//Progress Bar and TextView be visible
mProgressBar.setVisibility(View.VISIBLE);
mFckyou.setVisibility(View.VISIBLE);
//To sign in users
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Toast.makeText(getActivity(), "Sign in Successful!", Toast.LENGTH_SHORT).show();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.container, new HomeActivity());
ft.commit();
}else {
//Progress bar and Text View will be GONE. So the users can try again.
mProgressBar.setVisibility(View.GONE);
mFckyou.setVisibility(View.GONE);
Toast.makeText(getActivity(), "Could not sign in. Please try again.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
}
I think the problem is with getFragmentManager(),
when using fragments from v4.app.Fragment you need to use getSupportFragmentManager()
Update:
I just realized you are starting new fragment from a fragment. Though this is not a good practice and you should always let your parent activity make fragment transactions.You can learn more here and here
But for now you can get a reference to getSupportFragmentManager() like this:
mToRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RegisterFragment fragment = new RegisterFragment();
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, fragment, fragment.getTag());
ft.commit();
}
});
Did you set your TextView to be clickable
I want to pass some List from fragment into 2 other fragment. When i pass data to fragment two it is going well. But it is error when pass to the fragment three
Error code
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.yehezkiel.eclassapp, PID: 15267
java.lang.IllegalArgumentException: No view found for id 0x7f0d00c4 (com.example.yehezkiel.eclassapp:id/fragment3) for
fragment ThreeFragment{e045027 #3 id=0x7f0d00c4}
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1415)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1752)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1821)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:797)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2595)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2382)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2337)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2244)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:702)
at android.os.Handler.handleCallback(Handler.java:742)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5555)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:745)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:635)
Pass Code in OneFragment.java
Bundle bundle=new Bundle();
bundle.putStringArrayList("keys", keys);
//set Fragmentclass Arguments
Fragment fragobj=new TwoFragment();
fragobj.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frag2, fragobj).commitAllowingStateLoss();
Bundle bundle2=new Bundle();
bundle2.putStringArrayList("keys", keys);
//set Fragmentclass Arguments
Fragment fragobj2=new ThreeFragment();
fragobj2.setArguments(bundle2);
FragmentManager fragmentManager2 = getFragmentManager();
fragmentManager2.beginTransaction().replace(R.id.fragment3, fragobj2).commitAllowingStateLoss();
the first pass into TwoFragment did well. But the second pass gave me error like that. Please help me. I have been check all of the id in the ThreeFragment.xml and all correct.
ThreeFragment.java
package com.example.yehezkiel.eclassapp;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
public class ThreeFragment extends Fragment {
View v;
private List<DaftarPengumuman> listPengumuman = new ArrayList<>();
private ArrayList<String> obj3 = new ArrayList<>();
public ThreeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_three, container, false);
Bundle bundle = this.getArguments();
if(getArguments()!=null)
{
obj3 = bundle.getStringArrayList("keys");
Log.e("nba",obj3.toString());
}
// Inflate the layout for this fragment
return v;
}
}
fragment_three.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment3"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.yehezkiel.eclassapp.ThreeFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Three"
android:textSize="40dp"
android:textStyle="bold"
android:layout_centerInParent="true"/>
</FrameLayout>
This is my MainActivity.java that is stored the viewpager
package com.example.yehezkiel.eclassapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private List<MataKuliah> listMatkul = new ArrayList<>();
private ArrayList<String> keys = new ArrayList<>();
private myAdapter myAdapter;
private Button logoutBtn;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener authListener;
private RecyclerView mRecycleView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private Toolbar mToolbar;
private NavigationView mNavigationView;
private TextView mTextName;
private TextView mTextNim;
private ProgressBar mProgressBar;
static {
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
}
DatabaseReference userRef = FirebaseDatabase.getInstance().getReference("users");
FirebaseUser users = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference mataKuliahRef = FirebaseDatabase.getInstance().getReference("courses");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mAuth = FirebaseAuth.getInstance();
//Navbar menu
mToolbar = (Toolbar) findViewById(R.id.navbaraction);
setSupportActionBar(mToolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawabel_main);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mNavigationView = (NavigationView) findViewById(R.id.nav_menu);
View header = mNavigationView.getHeaderView(0);
mTextName = (TextView) header.findViewById(R.id.header_name);
mTextNim = (TextView) header.findViewById(R.id.header_nim);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar2);
mProgressBar.setVisibility(View.VISIBLE);
//Tab Layout
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case (R.id.tugas):
break;
case (R.id.logout_menu):
signOut();
break;
}
return true;
}
});
userRef.child(users.getUid()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = (String) dataSnapshot.child("name").getValue().toString();
String nim = (String) dataSnapshot.child("nim").getValue().toString();
mTextNim.setText(nim);
mTextName.setText(name);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user == null) {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}
};
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "Beranda");
adapter.addFragment(new TwoFragment(), "Tugas");
adapter.addFragment(new ThreeFragment(), "Pengumuman");
viewPager.setAdapter(adapter);
}
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 boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
private void signOut() {
mAuth.signOut();
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(authListener);
}
}
MainActivity.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:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawabel_main"
tools:context="com.example.yehezkiel.eclassapp.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<include
layout="#layout/navbar_action"
android:layout_width="match_parent"
android:layout_height="wrap_content"></include>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:tabGravity="fill"
app:tabMode="fixed" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<ProgressBar
android:id="#+id/progressBar2"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:visibility="visible"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="304dp" />
<android.support.v7.widget.RecyclerView
android:id="#+id/MainRView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="2dp"
android:layout_marginEnd="6dp"
android:layout_marginStart="6dp"
android:layout_marginTop="2dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</android.support.v7.widget.RecyclerView>
<Button
android:id="#+id/logoutBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="444dp"
android:background="#color/colorPrimary"
android:text="LOGOUT"
android:textColor="#color/white"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.945"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="#menu/navbar_main"
android:layout_gravity="start"
app:headerLayout="#layout/navbar_header"
android:id="#+id/nav_menu">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
I have problem with ActionBar in my fragment. It's invisible in it, so I can't execute getActionBar().setDisplayHomeAsUpEnabled(true); in my SignUpActivity.java. In every other Activity (not Fragment) it's visible.
Could You tell me what I am doing wrong? Probably something is missing.
fragment_sign_up.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="fill_parent"
xmlns:tools="http://schemas.android.com/tools"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
tools:context="com.msh.organizer.SignUpActivity">
<EditText
android:layout_below="#id/toolbar"
android:id="#+id/nickname_et"
android:hint="#string/nickname"
android:layout_marginTop="40dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/email_et"
android:hint="#string/mail"
android:layout_marginTop="5dp"
android:layout_below="#id/nickname_et"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/password_et"
android:hint="#string/password"
android:inputType="textPassword"
android:layout_marginTop="5dp"
android:layout_below="#id/email_et"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/sign_up_btn"
android:layout_marginTop="15dp"
android:layout_below="#id/password_et"
android:text="#string/sign_up"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
activity_sign_up.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.msh.organizer.SignUpActivity"
tools:ignore="MergeRootFrame" />
SignUpActivity.java
package com.msh.organizer;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class SignUpActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
//getActionBar().setDisplayHomeAsUpEnabled(true);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new SignUpFragment())
.commit();
}
//Toast.makeText(this,"Sign Up", Toast.LENGTH_LONG).show();
}
#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);
}
}
SignUpFragment.java
package com.msh.organizer;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.parse.SignUpCallback;
public class SignUpFragment extends Fragment implements View.OnClickListener {
private Button mSignUpButton;
private EditText mNickNameEditText;
private EditText mEmailEditText;
private EditText mPasswordEditText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_sign_up, container, false);
mSignUpButton = (Button) rootView.findViewById(R.id.sign_up_btn);
mNickNameEditText = (EditText) rootView.findViewById(R.id.nickname_et);
mEmailEditText = (EditText) rootView.findViewById(R.id.email_et);
mPasswordEditText = (EditText) rootView.findViewById(R.id.password_et);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mSignUpButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_up_btn:
trySignUp();
break;
}
}
private void trySignUp() {
String nickname = mNickNameEditText.getText().toString();
String email = mEmailEditText.getText().toString();
String password = mPasswordEditText.getText().toString();
boolean failed = false;
if (TextUtils.isEmpty(nickname)){
mNickNameEditText.setError("Nickname cannnot be empty!");
failed = true;
}
if (TextUtils.isEmpty(password)){
mPasswordEditText.setError("Password cannnot be empty!");
failed = true;
}
if (TextUtils.isEmpty(email)){
mEmailEditText.setError("Email cannnot be empty!");
failed = true;
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
mEmailEditText.setError("Inwalid E-mail address!");
failed = true;
}
if (!failed){
signUp(nickname, email, password);
}
}
private void signUp(String nickname, String email, String password) {
ParseUser user = new ParseUser();
user.setUsername(email);
user.setPassword(password);
user.setEmail(email);
// other fields can be set just like with ParseObject
user.put("nickname", nickname);
user.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
if (getActivity() != null){
getActivity().setResult(Activity.RESULT_OK);
getActivity().finish();
}
} else {
if (getActivity() != null) {
Toast.makeText(getActivity(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
}
}
});
}
}
You can use Toolbar inside an AppBarLayout in your activity:
SignUpActivity.java
...
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
...
activity_sign_up.xml
<android.support.design.widget.AppBarLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<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/ThemeOverlay.AppCompat.Light"
app:layout_scrollFlags="scroll|enterAlways|snap" />
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.msh.organizer.SignUpActivity"
tools:ignore="MergeRootFrame" />