SharedPreferences-我无法保存会话数据

时间:2019-12-22 22:03:08

标签: android authentication sharedpreferences

我正在为我的大学项目开发​​一个小型移动应用程序,但是在用户登录后,关闭该应用程序,然后再次打开,该应用程序再次请求登录数据。

我在代码中做错了吗?

注意:我在Android Studio中没有经验,所以我无法理解自己的错误。

MainActivity.java

package esan.ds.pm.flynow;

    import ...

    public class MainActivity extends AppCompatActivity {

    RelativeLayout rellay0, rellay1, rellay2;

    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            rellay0.setVisibility(View.VISIBLE);
            rellay1.setVisibility(View.VISIBLE);
            rellay2.setVisibility(View.VISIBLE);
        }
    };

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

        rellay0 = (RelativeLayout) findViewById(R.id.rellay0);
        rellay1 = (RelativeLayout) findViewById(R.id.rellay1);
        rellay2 = (RelativeLayout) findViewById(R.id.rellay2);

        handler.postDelayed(runnable, 2000); //2000 is the timeout for the splash

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        String s = preferences.getString("login", "");
        if(s.equals("")) {
            Intent intent = new Intent(getApplicationContext(), MenuActivity.class);
            startActivity(intent);
        } else {
            Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
            startActivity(intent);

            this.finish();

        }

    }

    public void openRegisterPage(View view) {
        Intent intent = new Intent (this,RegisterActivity.class);
        startActivity(intent);
    }

    public void closeLoginPage(View view) {
        Intent intent = new Intent (this,MenuActivity.class);
        startActivity(intent);
    }

    public void Login(View view) {

        final EditText email = findViewById(R.id.txtEmail);
        EditText password = findViewById(R.id.txtPassword);

        Map<String,String> post = new HashMap();
        post.put("email",email.getText().toString());
        post.put("password",password.getText().toString());
        new HTTPActivity(this, post) {
            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                if(s.equals("0")) {
                    Intent intent = new Intent(getApplicationContext(), MenuActivity.class);
                    startActivity(intent);
                    Toast.makeText(getApplicationContext(), "SESSÃO INICIADA COM SUCESSO!", Toast.LENGTH_SHORT).show();
                } else
                Toast.makeText(getApplicationContext(), "ACESSO NEGADO!" + "\n" + "Por favor, verifique os dados introduzidos!", Toast.LENGTH_SHORT).show();
            }
        }.execute("https://esan-tesp-ds-paw.web.ua.pt/tesp-ds-g16/PM/login.php");
    }
    }

RegisterActivity.java

package esan.ds.pm.flynow;

    import...

    public class RegisterActivity extends AppCompatActivity {

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

    public void openLoginPage(View view) {
        Intent intent = new Intent (this,LoginActivity.class);
        startActivity(intent);
    }

    public void closeLoginPage(View view) {
        Intent intent = new Intent (this,MenuActivity.class);
        startActivity(intent);
    }

    public void Register(View view) {

        EditText nome = findViewById(R.id.txtNome);
        EditText email = findViewById(R.id.txtEmail);
        EditText password = findViewById(R.id.txtPassword);

        Map<String,String> post = new HashMap();
        post.put("nome",nome.getText().toString());
        post.put("email",email.getText().toString());
        post.put("password",password.getText().toString());
        new HTTPActivity(this, post) {
            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                if(s.equals("0")) {
                    Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
                    startActivity(intent);
                    Toast.makeText(getApplicationContext(), "CONTA CRIADA COM SUCESSO!", Toast.LENGTH_SHORT).show();
                } else
                    Toast.makeText(getApplicationContext(), "ACESSO NEGADO!" + "\n" + "Por favor, verifique os dados introduzidos.", Toast.LENGTH_SHORT).show();
            }
        }.execute("https://esan-tesp-ds-paw.web.ua.pt/tesp-ds-g16/PM/register.php");
    }

    }

HTTPActivity.java

package esan.ds.pm.flynow;

import ...

public class HTTPActivity extends AsyncTask<String,Void,String> {

private String result = null;
private Context context;
private Map post = new HashMap();
private ProgressDialog pDialog;

public HTTPActivity(Context c) {
    context = c;
}
public HTTPActivity(Context c, Map<String, String> postArgs) {
    context = c;
    post = postArgs;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    // Iniciar a ProgressDialog
    pDialog = new ProgressDialog(context);
    pDialog.setMessage("Por favor, aguarde...");
    pDialog.setCancelable(false);
    pDialog.show();
}

@Override
protected String doInBackground(String... args) {
    HttpManager manager = new HttpManager();
    if(!this.post.isEmpty()) {
        manager.read(args[0],post);
    } else {
        manager.read(args[0]);
    }
    return result;
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    // end the ProgressDialog
    if (pDialog.isShowing())
        pDialog.dismiss();
}

private class HttpManager {

    private HttpURLConnection urlConnection;
    private InputStream inputStream = null;

    void read(String strUrl) {
        try {
            URL url = new URL(strUrl);
            urlConnection = (HttpURLConnection) url.openConnection();
            inputStream = new BufferedInputStream(urlConnection.getInputStream());
            result = _Stream_to_String(inputStream);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    void read(String strUrl, Map<String, String> postArgs) {
        try {
            URL url = new URL(strUrl);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("POST");
            OutputStream outputStream = urlConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = "";
            for(Map.Entry<String,String> entry : postArgs.entrySet()) {
                post_data += URLEncoder.encode(entry.getKey(), "UTF-8")+"="+URLEncoder.encode(entry.getValue(),"UTF-8")+"&";
            }
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            inputStream = new BufferedInputStream(urlConnection.getInputStream());
            result = _Stream_to_String(inputStream);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String _Stream_to_String(InputStream stream) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                //sb.append(line).append('\n');
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return sb.toString();
    }
}
}

app / build.gradle

apply plugin: 'com.android.application'

android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
    applicationId "esan.ds.pm.flynow"
    minSdkVersion 21
    targetSdkVersion 29
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android- 
optimize.txt'), 'proguard-rules.pro'
    }
 }
 }

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.material:material:1.0.0'
implementation 'androidx.navigation:navigation-fragment:2.0.0'
implementation 'androidx.navigation:navigation-ui:2.0.0'
implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}

2 个答案:

答案 0 :(得分:0)

注册或登录时尚未将数据保存到SharedPreference。因此,您的Shared Preference没有任何状态。 这对我有用。首先为SharedPreference创建一个类。

public class SharedHelper {
public static SharedPreferences sharedPreferences;
public static SharedPreferences.Editor editor;

public static void putKey(Context context, String Key, String Value) {
    sharedPreferences = context.getSharedPreferences("Cache", Context.MODE_PRIVATE);
    editor = sharedPreferences.edit();
    editor.putString(Key, Value);
    editor.commit();

}

public static String getKey(Context contextGetKey, String Key) {
    sharedPreferences = contextGetKey.getSharedPreferences("Cache", Context.MODE_PRIVATE);
    String Value = sharedPreferences.getString(Key, "");
    return Value;

}

public static void clearSharedPreferences(Context context)
{
    sharedPreferences = context.getSharedPreferences("Cache", Context.MODE_PRIVATE);
    sharedPreferences.edit().clear().commit();
}
}

然后在成功注册注册后设置登录状态。

   SharedHelper.putKey(context, "loggedIn", "true");

然后像这样检查:

if (SharedHelper.getKey(context, "loggedIn").equalsIgnoreCase("true")) {
 //Your action
}

答案 1 :(得分:0)

我可以将SharedHelper.putKey (context," logIn "," true ") function;放入LoginActivity.java吗?