samedi 25 avril 2015

Authenticate method is NULL when automatic login


After a user has already logged into the app, I have their username and password saved to shared preferences, therefore when they login again, they should be able to authenticate automatically and subsequently bypass the login activity.

I have started and binded the service, and sent the authenticate methods to the server, yet the section:

                             result = imService.authenticateUser(
                                     userName.trim(),
                                     password.trim());

always returns NULL and does not allow automatic logging in.

Why would this be the case?

The loggingIn class

public class LoggingIn extends Activity {

     protected static final int NOT_CONNECTED_TO_SERVICE = 0;
     protected static final int FILL_BOTH_USERNAME_AND_PASSWORD = 1;
     public static final String AUTHENTICATION_FAILED = "0";
     public static final String FRIEND_LIST = "FRIEND_LIST";
     protected static final int MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT = 2;
     protected static final int NOT_CONNECTED_TO_NETWORK = 3;
     private EditText usernameText;
     private EditText passwordText;

     private JSONObject resultObject;
     public static String userId = null;

     private Manager imService;
     public static final int SIGN_UP_ID = Menu.FIRST;
     public static final int EXIT_APP_ID = Menu.FIRST + 1;

     // For GCM
     String regid;
     GoogleCloudMessaging gcm;
     AtomicInteger msgId = new AtomicInteger();
     SharedPreferences prefs;
     Context context;

     public static final String EXTRA_MESSAGE = "message";
     public static final String PROPERTY_REG_ID = "registration_id";
     private static final String PROPERTY_APP_VERSION = "appVersion";
     private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;

     private ServiceConnection mConnection = new ServiceConnection() {
         public void onServiceConnected(ComponentName className, IBinder service) {
             // This is called when the connection with the service has been
             // established, giving us the service object we can use to
             // interact with the service. Because we have bound to a explicit
             // service that we know is running in our own process, we can
             // cast its IBinder to a concrete class and directly access it.
             imService = ((MessagingService.IMBinder) service).getService();

             if (imService.isUserAuthenticated() == true) {
                 // Intent i = new Intent(LoggingIn.this, ListOfFriends.class);
                 Intent i = new Intent(LoggingIn.this, MainActivity.class);
                 startActivity(i);
                 LoggingIn.this.finish();
             }
         }

         public void onServiceDisconnected(ComponentName className) {
             // This is called when the connection with the service has been
             // unexpectedly disconnected -- that is, its process crashed.
             // Because it is running in our same process, we should never
             // see this happen.
             imService = null;
             Toast.makeText(LoggingIn.this, R.string.local_service_stopped,
                     Toast.LENGTH_SHORT).show();
         }
     };

     /**
      * Called when the activity is first created.
      */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);

              /*
               * Start and bind the imService
               */
         startService(new Intent(getBaseContext(), MessagingService.class));

         // Bind it
         bindService(new Intent(getBaseContext(), MessagingService.class),
                 mConnection, Context.BIND_AUTO_CREATE);

         // Initiate Volley:
         final RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();

         //Remove title bar
         this.requestWindowFeature(Window.FEATURE_NO_TITLE);

         //Remove notification bar
         this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

         // For auto logging in:
         if (!SaveSharedPreference.getUserName(getApplicationContext()).isEmpty()) {

                     setContentView(R.layout.feast_loading_splash_page);

                     final String userName = SaveSharedPreference.getUserName(getApplicationContext());

                     final String password = SaveSharedPreference.getPassword(getApplicationContext());

                    Log.v("TEST GCM Service Login","SharedPref Username is " + userName + " and password " + password);

                     Thread loginThread = new Thread() {
                         private Handler handler = new Handler();

                         @Override
                         public void run() {
                             String result = null;

                             try {

                                 result = imService.authenticateUser(
                                         userName.trim(),
                                         password.trim());

                             } catch (UnsupportedEncodingException e) {

                                 e.printStackTrace();
                             }catch (NullPointerException e) {
                                 e.printStackTrace();
                             }

                             if (result == null || result.equals(AUTHENTICATION_FAILED)) {
                /*
                * Authenticatin failed, inform the user
                */
                                 handler.post(new Runnable() {
                                     public void run() {
                                         Toast.makeText(
                                                 getApplicationContext(),
                                                 R.string.make_sure_username_and_password_correct,
                                                 Toast.LENGTH_LONG).show();

                                         // showDialog(MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT);
                                     }
                                 });

                             } else {

                /*
                * if result not equal to authentication failed, result
                * is equal to friend and group list of the user 0: is
                * for friends, 1: is for groups
                */
                                 handler.post(new Runnable() {
                                     public void run() {
                                         Intent i = new Intent(LoggingIn.this,
                                                 MainActivity.class);
                                         startActivity(i);
                                         LoggingIn.this.finish();

                                     }
                                 });

                             }

                         }
                     };
                     loginThread.start();

                 }


         //setContentView(R.layout.loggin_in);
         setContentView(R.layout.feast_login_page);
         //setTitle("Login");

         ImageButton loginButton = (ImageButton) findViewById(R.id.button1);

             // So don't need to log in manually, just click the button
             usernameText = (EditText) findViewById(R.id.username);
             passwordText = (EditText) findViewById(R.id.password);

             // Used for expeditied login
             //usernameText.setText("kjakah08"); //(EditText) findViewById(R.id.username);
             //passwordText.setText("farside"); // (EditText) findViewById(R.id.password);

             loginButton.setOnClickListener(new OnClickListener() {
                 public void onClick(View arg0) {
                     if (imService == null) {
                         Toast.makeText(getApplicationContext(),
                                 R.string.not_connected_to_service,
                                 Toast.LENGTH_LONG).show();
                         // showDialog(NOT_CONNECTED_TO_SERVICE);
                         return;
                     } else if (imService.isNetworkConnected() == false) {
                         Toast.makeText(getApplicationContext(),
                                 R.string.not_connected_to_network,
                                 Toast.LENGTH_LONG).show();
                         // showDialog(NOT_CONNECTED_TO_NETWORK);

                     } else if (usernameText.length() > 0
                             && passwordText.length() > 0) {

                         Thread loginThread = new Thread() {
                             private Handler handler = new Handler();

                             @Override
                             public void run() {
                                 String result = null;

                                 try {
                                     result = imService.authenticateUser(
                                             usernameText.getText().toString().trim(),
                                             passwordText.getText().toString().trim());
                                 } catch (UnsupportedEncodingException e) {

                                     e.printStackTrace();
                                 }
                                 if (result == null
                                         || result.equals(AUTHENTICATION_FAILED)) {
                                      /*
                                       * Authenticatin failed, inform the user
                                       */
                                     handler.post(new Runnable() {
                                         public void run() {
                                             Toast.makeText(
                                                     getApplicationContext(),
                                                     R.string.make_sure_username_and_password_correct,
                                                     Toast.LENGTH_LONG).show();

                                             // showDialog(MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT);
                                         }
                                     });

                                 } else {

                                      /*
                                       * if result not equal to authentication failed,
                                       * result is equal to friend and group list of
                                       * the user 0: is for friends, 1: is for groups
                                       */
                                     handler.post(new Runnable() {
                                         public void run() {

                                             // If log in successful, then save
                                             // username and password to shared
                                             // preferences:

                                             SaveSharedPreference.setUserName(
                                                     getApplicationContext(),
                                                     usernameText.getText()
                                                             .toString());

                                             SaveSharedPreference.setPassword(
                                                     getApplicationContext(),
                                                     passwordText.getText()
                                                             .toString());

                                             Intent i = new Intent(LoggingIn.this,
                                                     MainActivity.class);
                                             startActivity(i);
                                             LoggingIn.this.finish();

                                         }
                                     });

                                 }

                             }
                         };
                         loginThread.start();

                     } else {
                          /*
                           * Username or Password is not filled, alert the user
                           */
                         Toast.makeText(getApplicationContext(),
                                 R.string.fill_both_username_and_password,
                                 Toast.LENGTH_LONG).show();
                         // showDialog(FILL_BOTH_USERNAME_AND_PASSWORD);
                     }

                     // GET the users id!!
                     JsonObjectRequest getUserId = new JsonObjectRequest(Request.Method.GET,
                             "http://" + Global.getFeastOnline() + "/getUserData/" + usernameText.getText().toString() + ".json", ((String) null),
                             new Response.Listener<JSONObject>() {
                                 @Override
                                 public void onResponse(JSONObject response) {

                                     // Parse the JSON:
                                     try {
                                         resultObject = response.getJSONObject("userInfo");
                                         userId = resultObject.getString("id");

                                         Log.v("USER ID", "The user id is " + userId);

                                     } catch (JSONException e) {
                                         e.printStackTrace();
                                     }

                                 }
                             },
                             new Response.ErrorListener() {
                                 @Override
                                 public void onErrorResponse(VolleyError error) {
                                     Log.d("Error.Response", error.toString());
                                 }
                             });

                     requestQueue.add(getUserId);

                 }
             });

     }

     @Override
     protected Dialog onCreateDialog(int id) {
         int message = -1;
         switch (id) {
             case NOT_CONNECTED_TO_SERVICE:
                 message = R.string.not_connected_to_service;
                 break;
             case FILL_BOTH_USERNAME_AND_PASSWORD:
                 message = R.string.fill_both_username_and_password;
                 break;
             case MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT:
                 message = R.string.make_sure_username_and_password_correct;
                 break;
             case NOT_CONNECTED_TO_NETWORK:
                 message = R.string.not_connected_to_network;
                 break;
             default:
                 break;
         }

         if (message == -1) {
             return null;
         } else {
             return new AlertDialog.Builder(LoggingIn.this)
                     .setMessage(message)
                     .setPositiveButton(R.string.OK,
                             new DialogInterface.OnClickListener() {
                                 public void onClick(DialogInterface dialog,
                                                     int whichButton) {
                                                    /* User clicked OK so do some stuff */
                                 }
                             }).create();
         }
     }

     @Override
     protected void onPause() {
         unbindService(mConnection);
         super.onPause();
     }

     @Override
     protected void onResume() {
         bindService(new Intent(LoggingIn.this, MessagingService.class),
                 mConnection, Context.BIND_AUTO_CREATE);

         super.onResume();
     }

     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
         boolean result = super.onCreateOptionsMenu(menu);

         menu.add(0, SIGN_UP_ID, 0, R.string.sign_up);
         menu.add(0, EXIT_APP_ID, 0, R.string.exit_application);

         return result;
     }

     @Override
     public boolean onMenuItemSelected(int featureId, MenuItem item) {

         switch (item.getItemId()) {
             case SIGN_UP_ID:
                 Intent i = new Intent(LoggingIn.this, SigningUp.class);
                 startActivity(i);
                 return true;
             case EXIT_APP_ID:

                 return true;
         }

         return super.onMenuItemSelected(featureId, item);
     }

 }


Aucun commentaire:

Enregistrer un commentaire