Webview在注销后显示旧用户数据

时间:2017-04-11 13:57:38

标签: android webview

在我的应用程序中使用webview登录后显示用户数据,但一旦从应用程序注销并在webview中使用新用户登录。它显示旧用户数据而不是新用户数据。在登录之前已经清理了cookie,会话和数据库,但它无法正常工作。

这是我的登录页面代码

public class Login_Activity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    private EditText et_username, et_password;
    private List<String> categories = new ArrayList<String>();
    private List<String> categoriesLink = new ArrayList<String>();
    private ArrayAdapter<String> dataAdapter;
    private Spinner spinner;
    private ProgressDialog prDialog;
    private CheckBox saveLoginCheckBox;
    private SharedPreferences loginPreferences;
    private SharedPreferences.Editor loginPrefsEditor;
    private Boolean saveLogin;
    private DatabaseHandler databaseHandler;
    private String txt_username, txt_password;
    private String pre_username;

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

        getSupportActionBar().setTitle("");


        /* .. NewworkonMain ThradException error solution*/

       if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        databaseHandler = new DatabaseHandler(Login_Activity.this);
        setcontent();
    }

    private void setcontent() {
        et_username = (EditText) findViewById(R.id.et_username);
        et_password = (EditText) findViewById(R.id.et_password);
        saveLoginCheckBox = (CheckBox) findViewById(R.id.saveLoginCheckBox);
        loginPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);
        loginPrefsEditor = loginPreferences.edit();

        // Spinner element
        spinner = (Spinner) findViewById(R.id.spinner);
        //  spinner.setPrompt("Service Name");
        saveLogin = loginPreferences.getBoolean(AppConstant.PREF_SAVE_LOGIN, false);
        if (saveLogin == true) {
            et_username.setText(loginPreferences.getString(AppConstant.PREF_USER_NAME, ""));
            // et_password.setText(loginPreferences.getString("password1", ""));
            saveLoginCheckBox.setChecked(true);
        }
        // Login Button
        Button btn_login = (Button) findViewById(R.id.btn_login);
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // Internet Connection
                if (!Common.isInternetOn(Login_Activity.this)) {
                    Toast.makeText(Login_Activity.this, "Please check your Internet Connection", Toast.LENGTH_SHORT).show();
                    return;
                }
                // Null Value Validation
                int pos = spinner.getSelectedItemPosition();
                if (pos == 0 || pos == -1) {
                    Toast.makeText(Login_Activity.this, "Please add service name", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty((et_username.getText().toString().trim()))) {
                    Toast.makeText(Login_Activity.this, "Please add username", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty((et_password.getText().toString().trim()))) {
                    Toast.makeText(Login_Activity.this, "Please add password", Toast.LENGTH_SHORT).show();
                    return;
                }

                pre_username = et_username.getText().toString();
                //    String passoed1 = et_password.getText().toString();

                if (saveLoginCheckBox.isChecked()) {
                    loginPrefsEditor.putBoolean(AppConstant.PREF_SAVE_LOGIN, true);
                    loginPrefsEditor.putString(AppConstant.PREF_USER_NAME, pre_username);
                    loginPrefsEditor.putString(AppConstant.PREF_SELECTED_SERVICE, spinner.getSelectedItem().toString());
                    // loginPrefsEditor.putString("password1", passoed1);
                    loginPrefsEditor.commit();
                } else {
                    loginPrefsEditor.clear();
                    loginPrefsEditor.commit();
                }

                // add http logic
                if (categories != null && categories.size() > 0) {
                    selectedPath = categoriesLink.get(pos);
                    if (!TextUtils.isEmpty(selectedPath)) {
                        if (!selectedPath.toLowerCase().contains("http"))
                            selectedPath = "http://" + selectedPath;
                        new SaveAppData().execute();
                    }
                }
            }
        });

        //Add Button
        Button btn_add = (Button) findViewById(R.id.btn_add);
        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Login_Activity.this, AddServiceName_Activity.class);
                startActivityForResult(intent, 999);
            }
        });
        checkPermission();
    }

    private void fillUpSpinner() {
        categories.clear();
        categoriesLink.clear();
        List<ServiceDetails> serviceList = databaseHandler.getAllServiceList();
        for (int i = 0; i < serviceList.size(); i++) {
            ServiceDetails serviceDetail = serviceList.get(i);
            categories.add(serviceDetail.getName());
            categoriesLink.add(serviceDetail.getUrl());
        }
        if (categories.size() > 0) {
            categories.add(0, "Select service name");
            categoriesLink.add(0, "");
        } else {
            categories.add("Add service name");
            categoriesLink.add("");
        }

        if (dataAdapter == null) {
            dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
            // Drop down layout style - list view with radio button
            dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            // attaching data adapter to spinner
            spinner.setAdapter(dataAdapter);
            if (saveLogin) {
                String selectedService = loginPreferences.getString("selected_service", "");
                if (!TextUtils.isEmpty(selectedService)) {
                    int pos = categories.indexOf(selectedService);
                    spinner.setSelection(pos);
                }
            }
            spinner.setOnItemSelectedListener(this);
        } else {
            dataAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 999) {
            if (resultCode == Activity.RESULT_OK) {
             /*   String serName = data.getStringExtra("serName");
                String serUrl = data.getStringExtra("serUrl");*/
                fillUpSpinner();
                /*categories.clear();
                categoriesLink.clear();*/
                /*categories.add(0, serName);
                categoriesLink.add(0, serUrl);
                dataAdapter.notifyDataSetChanged();
                spinner.setSelection(0);*/
            } else {
                if (!saveLoginCheckBox.isChecked()) {
                    // spinner.setSelection(0);
                    et_username.setText("");
                    et_password.setText("");
                }
            }
        }
    }

    String selectedPath = null;

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        // On selecting a spinner item
        // String item = parent.getItemAtPosition(position).toString();
        // Showing selected spinner item
        //   Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }

    // SaveAppData Web API Method
    public class SaveAppData extends AsyncTask<String, Void, String> {
        String str = "A";

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            prDialog = new ProgressDialog(Login_Activity.this);
            prDialog.setMessage("Please wait ...");
            prDialog.show();
        }

        Response responseValue;

        @Override
        protected String doInBackground(String... params) {
            TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
            String device_id = telephonyManager.getDeviceId();

            // String url = "http://192.168.0.122:5000/api/Login/SaveAppData?deviceID=" + device_id + "&deviceType=" + str;
            if (!selectedPath.endsWith("/")) {
                selectedPath = selectedPath + "/";
            }

            SharedPreferences sp = getApplicationContext().getSharedPreferences(AppConstant.PREF_SELECTED_PATH, 0);
            SharedPreferences.Editor editor = sp.edit();
            editor.putString(AppConstant.PREF_URI_SELECTEDPATH, selectedPath);
            editor.commit();

            String url = (selectedPath + "api/Login/SaveAppData?deviceID=" + device_id + "&deviceType=" + str);
            JSONObject jsonObject = new JSONObject();
            //WebAPI.PostData(url, jsonObject.toString());
            responseValue = WebAPI.PostDataWithStatusCode(Login_Activity.this, url, jsonObject.toString());
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
           /* if(prDialog!=null){
                prDialog.dismiss();
            }*/
            try {
                if (responseValue != null) {
                    int code = responseValue.code();
                    String str = responseValue.body().string();

                    if (code == 200) {
                        parseResponseAndSaveDefaultURL(str);
                        new AuthenticateUser().execute();
                    } else {
                        Toast.makeText(Login_Activity.this, "Please enter valid Host Name", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(Login_Activity.this, "Please enter valid Host Name", Toast.LENGTH_SHORT).show();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    // get WebURL from SaveAppData Response
    private void parseResponseAndSaveDefaultURL(String str) {
        try {
            String res = str;
            JSONArray jsonArray = new JSONArray(res);
            JSONObject jsonObject = jsonArray.getJSONObject(1);
            String url = jsonObject.getString("value");
            if (!TextUtils.isEmpty(url)) {
                SharedPreferences pref_token = PreferenceManager.getDefaultSharedPreferences(Login_Activity.this);
                SharedPreferences.Editor editor = pref_token.edit();
                editor.putString(AppConstant.PREF_RESPONCE_DEFAULT_URL, url);
                editor.commit();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    // AuthenticateUser Web API Method
    public class AuthenticateUser extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
           /* prDialog = new ProgressDialog(Login_Activity.this);
            prDialog.setMessage("Please wait ...");
            prDialog.show();*/
            txt_username = et_username.getText().toString();
            txt_password = et_password.getText().toString();
        }

        Response responseValue;

        @Override
        protected String doInBackground(String... params) {
            TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
            String device_id = telephonyManager.getDeviceId();
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("username", txt_username);
                jsonObject.put("password", txt_password);
                jsonObject.put("deviceID", device_id);
                /*String response = WebAPI.PostData("http://192.168.0.122:5000//api/Login/AuthenticateUser", jsonObject.toString());*/
                if (!selectedPath.endsWith("/")) {
                    selectedPath = selectedPath + "/";
                }
                //      String response = WebAPI.PostData(Login_Activity.this,selectedPath+"api/Login/AuthenticateUser",jsonObject.toString());
                responseValue = WebAPI.PostDataWithStatusCode(Login_Activity.this, selectedPath + "api/Login/AuthenticateUser", jsonObject.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (prDialog != null) {
                prDialog.dismiss();
            }
            try {
                if (responseValue != null) {
                    int code = responseValue.code();
                    String str = responseValue.body().string();
                    if (code == 200) {

                       CookieSyncManager.createInstance(Login_Activity.this);
                       CookieManager cookieManager = CookieManager.getInstance();
                       cookieManager.removeAllCookie();
                       cookieManager.removeSessionCookie();
                       cookieManager.setAcceptCookie(false);
                       clearCacheFromWebView();

                       WebViewDatabase.getInstance(Login_Activity.this).clearHttpAuthUsernamePassword();
                       WebViewDatabase.getInstance(Login_Activity.this).clearUsernamePassword();
                       WebViewDatabase.getInstance(Login_Activity.this).clearFormData();
                       deleteDatabase("webview.db");
                       deleteDatabase("webviewCache,db");

                        Intent intent = new Intent(Login_Activity.this, Home_Activity.class);
                        startActivity(intent);
                        finish();

                        SharedPreferences pref_token = PreferenceManager.getDefaultSharedPreferences(Login_Activity.this);
                        SharedPreferences.Editor editor = pref_token.edit();
                        editor.putString(AppConstant.PREF_RESPONCE_TOKEN, str);
                        editor.commit();
                    } else {
                        Toast.makeText(Login_Activity.this, "Please enter valid username or password", Toast.LENGTH_SHORT).show();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(Login_Activity.this);
            SharedPreferences.Editor editor = pref.edit();
            editor.putString(AppConstant.PREF_USER_NAME, txt_username);
            editor.putString(AppConstant.PREF_PASSWORD, txt_password);
            editor.commit();
        }
    }

1 个答案:

答案 0 :(得分:0)

我猜您正在从SharedPreferences值确定当前用户。因此,您必须在启动HomeActivity之前对SharedPreferences进行更改。

希望它对你有所帮助。感谢。

更新(代码)

protected void onPostExecute(String s) {
        super.onPostExecute(s);
        if (prDialog != null) {
            prDialog.dismiss();
        }
        try {
            if (responseValue != null) {
                int code = responseValue.code();
                String str = responseValue.body().string();
                if (code == 200) {

                   CookieSyncManager.createInstance(Login_Activity.this);
                   CookieManager cookieManager = CookieManager.getInstance();
                   cookieManager.removeAllCookie();
                   cookieManager.removeSessionCookie();
                   cookieManager.setAcceptCookie(false);
                   clearCacheFromWebView();

                   WebViewDatabase.getInstance(Login_Activity.this).clearHttpAuthUsernamePassword();
                   WebViewDatabase.getInstance(Login_Activity.this).clearUsernamePassword();
                   WebViewDatabase.getInstance(Login_Activity.this).clearFormData();
                   deleteDatabase("webview.db");
                   deleteDatabase("webviewCache,db");

                    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(Login_Activity.this);
                    SharedPreferences.Editor editor = pref.edit();
                    editor.putString(AppConstant.PREF_USER_NAME, txt_username);
                    editor.putString(AppConstant.PREF_PASSWORD, txt_password);
                    editor.commit();

                    Intent intent = new Intent(Login_Activity.this, Home_Activity.class);
                    startActivity(intent);
                    finish();

                    SharedPreferences pref_token = PreferenceManager.getDefaultSharedPreferences(Login_Activity.this);
                    SharedPreferences.Editor editor = pref_token.edit();
                    editor.putString(AppConstant.PREF_RESPONCE_TOKEN, str);
                    editor.commit();
                } else {
                    Toast.makeText(Login_Activity.this, "Please enter valid username or password", Toast.LENGTH_SHORT).show();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
}