0

I'm developing a basic android application with just a login page and a home page, where on the home page consists of the WebView in it. What I'm doing here is I'm trying to save the login details(username and password) with the help of shared preferences in the login page and retrieve those on the home page through the localStorage of the WebView.

This is how I'm saving my login credentials in the login page through shared preferences

@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity);

        usernameEdit = findViewById(R.id.et_login_email);
        passwordEdit = findViewById(R.id.et_login_pass);

private void loginActivity(){
        String username = usernameEdit.getText().toString().trim();
        String password = passwordEdit.getText().toString().trim();
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(KEY_USERNAME, username);
        editor.putString(KEY_PASSWORD, password);
        editor.commit();

        startActivity(new Intent(LoginActivity.this, HomePage.class));
    }

ANd this is my homepage where I'm using the LocalStorage in the WebView

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home_activity);

        Window window = HomePage.this.getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.setStatusBarColor(ContextCompat.getColor(HomePage.this, R.color.colorPrimary));
        }

        swipeRefreshLayout = findViewById(R.id.swipelayout);
        myWebView = findViewById(R.id.webview);

        WebSettings settings = myWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDatabasePath("/data/data/" + this.getPackageName() + "/databases/");
        settings.setDomStorageEnabled(true);
        myWebView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onConsoleMessage(String message, int lineNumber, String sourceID) {
                Log.d("WebView", "Line: " + lineNumber + "," + message);
            }

            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                return false;
            }
        });
        myWebView.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
        myWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

        final AlertDialog alertDialog = new AlertDialog.Builder(this).create();

        progressBar = ProgressDialog.show(HomePage.this, "WebView Example", "Loading...");

        myWebView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            public void onPageFinished(WebView view, String url) {
                if (progressBar.isShowing()) {
                    progressBar.dismiss();
                }
                if (url.equals("https://www.codecell.in/jkdapp") == true){
                    SharedPreferences preferences = getPreferences(MODE_PRIVATE);
                    String username = preferences.getString(KEY_USERNAME, "");
                    String password = preferences.getString(KEY_PASSWORD, "");
                    if (username == null || password == null) {
                        return;
                    }
                    view.loadUrl("javascript:fillvalues(" + username + "," + password + ");");

                }
            }

            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(HomePage.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();
                alertDialog.setTitle("Error");
                alertDialog.setMessage(description);
                alertDialog.show();
            }
        });
        myWebView.addJavascriptInterface(new JavascriptInterface(), "Android");
        myWebView.loadUrl("https://www.codecell.in/jkdapp");

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                myWebView.reload();
            }
        });
    }

    private class JavascriptInterface{
        public void saveValues(String name, String pass){
            if (name == null || pass == null){
                return;
            }

            SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
            editor.putString(KEY_USERNAME, name);
            editor.putString(KEY_PASSWORD, pass);
            editor.apply();
        }
    }
Samet ÖZTOPRAK
  • 3,112
  • 3
  • 32
  • 33
Niroop Nife
  • 356
  • 1
  • 5
  • 18

1 Answers1

0
public class StoreManager {
private SharedPreferences.Editor editor;
private Context _context;
public SharedPreferences pref;
private int PRIVATE_MODE = 0;
private static final String PREF_NAME = "_store";

public StoreManager(Context _context) {
    this._context = _context;
    pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    editor = pref.edit();
}

public void setToken(String Token) {
    editor.putString("Token", Token);
    System.out.println("token saved" + " " + Token);
    editor.commit();
}
public String getToken() {
    return pref.getString("Token", "");
}

}

I saved my data as tring in shared pref like this and when you login get data from there and call setToken of shared pref

StoreManager storeManager = new StoreManager(getApplicationContext());
storeManager.setToken("Your Username here");

and you can get data in same way by simply calling

StoreManager storeManager = new StoreManager(getApplicationContext());
storeManager.getToken();
Anushree
  • 98
  • 9