I am facing a problem as I try to implement a login screen in my Android app. The user has to fill out the login and password field with the string \"user\". Whenever I run thi
Try this..
Because Button
,EditText
's all belongs to fragment_main.xml
so you have to do that in PlaceholderFragment.java
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
Button ok = null;
EditText login = null;
EditText pass = null;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
ok = (Button) rootView.findViewById(R.id.ok);
login = (EditText) rootView.findViewById(R.id.login_text);
pass = (EditText) rootView.findViewById(R.id.pass_text);
ok.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String loginStr = login.getText().toString();
String passStr = pass.getText().toString();
if (loginStr != null && loginStr.equals("user")) {
if (passStr != null && passStr.equals("user")) {
Toast.makeText(getActivity(), "Redirecting...",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "Wrong Credentials",
Toast.LENGTH_SHORT).show();
}
}
}
});
return rootView;
}
}
add method
myMethod() {
//Code hear
}
To Activity and on your xml add
android:onClick="myMethod"
To your button
You are initializing views that is in fragment_main.xml
in Activity. Instead you should initialize it in Fragment onCreateView
using rootView.findViewById
.
findViewById
looks for a view in the current view hierarchy. You have set activity_main.xml
to Activity. So if you initializing views in Activity fails leading to NUllPointerException
.
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
Button ok = null;
EditText login = null;
EditText pass = null;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
ok = (Button) rootView.findViewById(R.id.ok);
login = (EditText) rootView.findViewById(R.id.login_text);
pass = (EditText) rootView.findViewById(R.id.pass_text);
ok.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String loginStr = login.getText().toString();
String passStr = pass.getText().toString();
if (loginStr != null && loginStr.equals("user")) {
if (passStr != null && passStr.equals("user")) {
Toast.makeText(getActivity(), "Redirecting...",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "Wrong Credentials",
Toast.LENGTH_SHORT).show();
}
}
}
});
return rootView;
}
}