'Offline login only when a valid user login online

I am developing an app. My goal is that user can login online and offline both, but for the first time user should login online enters their credentials (userid and password) and save the user's credentials when user is valid for offline mode(remote location where internet is not available). To check the credentials I used a webservice which will check that user id and password whether valid or not. I am able to consume webservice, its also check whether user is valid or not and able to save the userid and encrypted password and also achieve to compare passwrod with store password in database. But the problem I am facing is that when the userid or password is not correct it saves the credentials in sqlite database. And when I'm on offline mode I can login with incorrect password. I don't want that I want it saves credential only when user is authenticated. Below I shared my code. Need help I don't get it in where line I have to call offline method. Thanks in advance. Fuction for Login Button:

login.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // preventing double, using threshold of 1000 ms
                    if (SystemClock.elapsedRealtime() - lastClickTimeBtnLogin < Utilities.BTN_DOUBLE_CLICK_STOP_TIME) {
                        return;
                    }
                    lastClickTimeBtnLogin = SystemClock.elapsedRealtime();

//

                    // Login Logic
                      try {
                          String mail = email.getText().toString().trim();
                                  String pwd = password.getText().toString().trim();

                          if (iCD.checkMobileInternetConn()) {
                              if (isLocationEnabled) {
//                                  
                                  if (mail.equals("")) {
                                      Toast.makeText(getApplicationContext(), "Please enter UserName", Toast.LENGTH_SHORT).show();
                                  } else if (pwd.equals("")) {
                                      Toast.makeText(getApplicationContext(), "Please enter Password", Toast.LENGTH_LONG).show();
                                  }
                                                                    else {
                                          if (offlineMode.isChecked()){
                                          boolean i =global.getDb().addUser(mail,pwd);
                                          if (i== true){
                                              Toast.makeText(getApplicationContext(), "Inserted", Toast.LENGTH_LONG).show();
                                        
                                          }else {
                                              Toast.makeText(getApplicationContext(), "Not inserted", Toast.LENGTH_LONG).show();
                                          }
                                      }
                                      global.setUserName(email.getText().toString().trim());
                                      srv = new GenericServiceCalling(mContext, cb);
                                      JSONObject obj = new JSONObject();
                                      obj.put("userID", mail);
                                      obj.put("password", pwd);

                                      JSONObject mainObj = new JSONObject();
                                      mainObj.put("value", obj);
                                      showCustomLoader();
                                      srv.execute(Utilities.LOGIN, mainObj.toString());


                                  }

                              } else {


Toast.makeText(getApplicationContext(), "Enable location", Toast.LENGTH_LONG).show();
                              }
                          }
//
                          else {
                              offlineLogin();
                              }
                      }
                      catch (JSONException e) {
                          e.printStackTrace();

                      } catch (Exception e) {
                          e.printStackTrace();
//                          
                      }

                }
            });

Check response code==200:

  @Override
    public void onTaskComplete(String result) {
        mCustomLoader.dismiss();
        Log.e(TAG, "Response from url: " + result);
        String[] resultResponse = result.split("\\|", 2);
        int responseCode = Integer.valueOf(resultResponse[0].trim());
        String responseBody = resultResponse[1].trim();


        if (responseCode == 200) {
            try {
                JSONObject jsonObj = new JSONObject(responseBody);
                if (jsonObj.has("LoginResult")){
                    parseLoginResult(jsonObj);

                }

                else {


                }


            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG).show();
                    }
                });

            }

        }
        else {
            if(responseCode == Utilities.EXCEPTION_RESPONSE_CODE){
                showCustomAlertOneBtn("Alert", "Something wrong Response Code: "+responseCode+" = "+responseBody );
            }
            else{
                showCustomAlertOneBtn("Alert", "Internal server error. ResponseCode : "+responseCode +" Message "+ responseBody );
            }

        }

    }
 private void parseLoginResult(JSONObject object) {
        try {
            if(object.getString("LoginResult").equals("null")){
                mCustomLoader.dismiss();
                Log.e(TAG, "Authenticaion Failed" );
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Authenticaion Failed",
                                Toast.LENGTH_LONG).show();
                    }
                });
            }else {
              
              if(object.getJSONObject("LoginResult").getString("responseCode").equals("200")) {

                    Intent intent = new Intent(MainActivity.this, list.class);
                    startActivity(intent);
                }

                else{                      
                    Toast.makeText(getApplicationContext(), object.getJSONObject("LoginResult").getString("responseMessage"),
                            Toast.LENGTH_LONG).show();
                }
            }
        }catch (final JSONException e) {
            mCustomLoader.dismiss();
            Log.e(TAG, "Json parsing error: " + e.getMessage());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Json parsing error: " + e.getMessage(),
                            Toast.LENGTH_LONG).show();
                }
            });

        }catch (Exception e) {
            mCustomLoader.dismiss();
            Log.e(TAG, "Exception Occur: " + e.getMessage());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Exception Occur: " + e.getMessage(),
                            Toast.LENGTH_LONG).show();
                }
            });

        }

    }

offline login Method:

 public void offlineLogin(){
        iCD.hideCustomAlert();

        if (isLocationEnabled) {
            String mail = email.getText().toString().trim();
            String pwd = password.getText().toString().trim();
            String pwd1 = md5(pwd);

            if (mail.equals("")) {
                Toast.makeText(getApplicationContext(), "Please enter UserName", Toast.LENGTH_SHORT).show();
            } else if (pwd.equals("")) {
                Toast.makeText(getApplicationContext(), "Please enter Password", Toast.LENGTH_LONG).show();
            }
            else{

                    Boolean res = global.getDb().checkUser(mail, pwd1);
//                Boolean res = helper.checkUser(mail, pwd1);

                if(res == true) {
                    Intent intent = new Intent(MainActivity.this, list.class);
                    startActivity(intent);

                    Toast.makeText(MainActivity.this, "Successfully Logged In", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "Login Error",
                            Toast.LENGTH_SHORT).show();
                }
            }
        } else {
Toast.makeText(MainActivity.this, "enabled Location",
                                Toast.LENGTH_SHORT).show();
           
        }
    }


Solution 1:[1]

const data = [
    {
       "name": "Hebert",
       "timestamp": 1640371815, // 15:50:15
    },{
       "name": "Brien",
       "timestamp": 1640373855, // 16:24:15
    },{
       "name": "Hebert",
       "timestamp": 1640363601 // 13:33:21 
    },{
       "name": "Mary",
       "timestamp": 1640356701 // 11:38:21
    },{
       "name": "Mary",
       "timestamp": 1640356521 // 11:35:21 
    },{
       "name": "Mary",
       "timestamp": 1640356401 // 11:33:21
   }
];

const seen = {};
const dataModified = [];

data.forEach((elem) => {
  const index = seen[elem.name];
  
  if(index == undefined){
    dataModified.push(elem);
    seen[elem.name] = dataModified.length - 1;
  } else if(dataModified[index].timestamp < elem.timestamp){
    dataModified.splice(index, 1, elem);
  }
});

console.log(dataModified);

Solution 2:[2]

data.sort((a,b) => a.name.localeCompare(b.name))
.filter((chat, index, self) => self.findIndex(c => c.name === chat.name && c.timestamp > chat.timestamp)<0)

The idea is that findIndex would only return the index when there exists another duplicate with greater timestamp, else it'd return -1.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vektor
Solution 2