Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class LoginFragment extends Fragment {
- private static final String TAG = "LoginFragment";
- EditText mUsername, mPassword;
- Button mLogin;
- String url = "abc";
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_login, container, false);
- mUsername = (EditText) rootView.findViewById(R.id.login_name_edit_text);
- mPassword = (EditText) rootView.findViewById(R.id.login_password_edit_text);
- mLogin = (Button) rootView.findViewById(R.id.login_button);
- mLogin.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- String username = mUsername.toString();
- String password = mPassword.toString();
- if (username.trim().length() > 0 && password.trim().length() > 0) {
- checkLogin(username, password);
- } else {
- Toast.makeText(getContext(), "Please enter the credentials!", Toast.LENGTH_SHORT).show();
- }
- }
- });
- return rootView;
- }
- private void checkLogin(final String username, final String password) {
- // Tag used to cancel the request
- StringRequest strReq = new StringRequest(Request.Method.POST,
- url, new Response.Listener<String>() {
- @Override
- public void onResponse(String response) {
- Log.d(TAG, "Login Response: " + response.toString());
- try {
- JSONObject jObj = new JSONObject(response);
- boolean error = jObj.getBoolean("error");
- // Check for error node in json
- if (!error) {
- // user successfully logged in
- // Launch main activity
- Intent intent = new Intent(getActivity(),
- MainActivity.class);
- startActivity(intent);
- getActivity().finish();
- } else {
- // Error in login. Get the error message
- String errorMsg = jObj.getString("message");
- Toast.makeText(getContext(),
- errorMsg, Toast.LENGTH_LONG).show();
- }
- } catch (JSONException e) {
- // JSON error
- e.printStackTrace();
- }
- }
- }, new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- Log.e(TAG, "Login Error: " + error.getMessage());
- Toast.makeText(getContext(),
- error.getMessage(), Toast.LENGTH_LONG).show();
- }
- }) {
- @Override
- public String getBodyContentType() {
- return "application/x-www-form-urlencoded; charset=UTF-8";
- }
- @Override
- protected Map<String, String> getParams() throws AuthFailureError {
- // Posting parameters to login url
- Map<String, String> params = new HashMap<String, String>();
- params.put("username", username);
- params.put("password", password);
- return params;
- }
- };
- // Adding request to request queue
- MySingleton.getInstance(getContext()).addToRequestQueue(strReq);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement