【问题标题】:Android Studio with MySQL - SharedPreferences?带有 MySQL 的 Android Studio - SharedPreferences?
【发布时间】:2018-09-26 16:34:27
【问题描述】:

您好,我想弄清楚 SharedPreferences 如何在我的 android 应用程序中工作,因为我的登录过程由不同的 Java 活动处理。我确实有一个想要实现的“记住我”复选框。

MainActivity - 登录页面

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;



public class MainActivity extends AppCompatActivity {

EditText UsernameEt, PasswordEt;
CheckBox rem_userpass;

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

    UsernameEt = (EditText)findViewById(R.id.etUserName);
    PasswordEt = (EditText)findViewById(R.id.etPassword);
    rem_userpass = (CheckBox)findViewById(R.id.rem_userpass);

    PasswordEt.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            int digits = PasswordEt.getText().toString().length();
            if (digits > 1)
                lastChar = PasswordEt.getText().toString().substring(digits-1);
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            int digits = PasswordEt.getText().toString().length();
            Log.d("LENGTH",""+digits);
            if (!lastChar.equals("-")) {
                if (digits == 3 || digits == 7) {
                    PasswordEt.append("-");
                }
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
}

public void OnLogin(View view) {
    String username = UsernameEt.getText().toString();
    String password = PasswordEt.getText().toString();

    String type = "login";
    BackgroundWorker backgroundWorker = new BackgroundWorker(this);
    backgroundWorker.execute(type, username, password);
}

@Override
public void onBackPressed() {
    moveTaskToBack(true);
}
}

BackgroundWorker

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

/**
 * Created by ProgrammingKnowledge on 1/5/2016.
 */
public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;

BackgroundWorker (Context ctx) {
    context = ctx;
}
@Override
protected String doInBackground(String... params) {
    String type = params[0];
    String login_url = "https://treatmentpartnersofamerica.com/amadin/login.php";
    if(type.equals("login")) {
        try {
            String username = params[1];
            String password = params[2];
            URL url = new URL(login_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8")+"&"
                    +URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
            String result="";
            String line="";
            while((line = bufferedReader.readLine())!= null) {
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

@Override
protected void onPreExecute() {
    alertDialog = new AlertDialog.Builder(context).create();
    alertDialog.setTitle("Login Status");
}

@Override
protected void onPostExecute(String result) {
    if(result.contains("Login Success")) // msg you get from success like "Login Success"
    {
        Intent i = new Intent(context,MenuActivity.class);
        context.startActivity(i);
        Toast.makeText(context, result, Toast.LENGTH_SHORT).show();

    }
    else
    {
        Toast.makeText(context, "Certificate ID or Phone Number is incorrect", Toast.LENGTH_LONG).show();
    }
}


@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}

}

对不起,如果代码是一团糟......我正在制作很多这样的东西......

【问题讨论】:

    标签: mysql login phpmyadmin sharedpreferences


    【解决方案1】:

    您可以像传递上下文一样在后台类中传递用户名、密码值。这样做你可以将用户名、密码放在异步任务的 onPostExecute() 方法中的 SharedPreferences 中。

    public class BackgroundWorker extends AsyncTask<String,Void,String> {
    Context context;
    AlertDialog alertDialog;
    String usename = null, password = null;
    
    BackgroundWorker (Context ctx, String username, String password) {
        context = ctx;
        this.username = username;
        this.password = password;
    
    }
    @Override
    protected String doInBackground(String... params) {
        String type = params[0];
        String login_url = "https://treatmentpartnersofamerica.com/amadin/login.php";
        if(type.equals("login")) {
            try {
                URL url = new URL(login_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                String post_data = URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8")+"&"
                        +URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
                bufferedWriter.write(post_data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String result="";
                String line="";
                while((line = bufferedReader.readLine())!= null) {
                    result += line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return result;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    
    @Override
    protected void onPreExecute() {
        alertDialog = new AlertDialog.Builder(context).create();
        alertDialog.setTitle("Login Status");
    }
    
    @Override
    protected void onPostExecute(String result) {
        if(result.contains("Login Success")) // msg you get from success like "Login Success"
        {
            Intent i = new Intent(context,MenuActivity.class);
            context.startActivity(i);
            Toast.makeText(context, result, Toast.LENGTH_SHORT).show();
            SharedPreferences.Editor editor = 
            context.getSharedPreferences("shared_pref", MODE_PRIVATE).edit();
            editor.putString("username", username);
            editor.putString("password", password);
            editor.commit();
    
        }
        else
        {
            Toast.makeText(context, "Certificate ID or Phone Number is incorrect", Toast.LENGTH_LONG).show();
        }
    }
    
    
    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }
    
    }
    

    并修改login()方法

    public void OnLogin(View view) {
        String username = UsernameEt.getText().toString();
        String password = PasswordEt.getText().toString();
    
        String type = "login";
        BackgroundWorker backgroundWorker = new BackgroundWorker(this, username, 
        password);
        backgroundWorker.execute(type);
    }
    

    【讨论】:

    • 看起来怎么样?我不太确定。我想到了类似的东西,但我不知道如何实现它。
    • 不知道怎么试。
    • 是否需要在其中添加 if - else 语句?我按照你说的做了,它似乎确实在保存数据,但我不确定如何访问它来绕过登录屏幕。是 rem_user 通行证作为布尔值出现的地方吗?就像如果选中 - getSharedPrefrences 然后开始活动,否则继续常规登录过程?还是我应该实现一个启动画面来检查?
    • 我想我明白了。
    • 我明白了!谢谢我刚刚在 MainActivity 的 onCreate 中添加了一个 if 语句,并在我的菜单中添加了一个注销按钮。非常感谢
    【解决方案2】:

    我明白了!我将此添加到 on create 中。

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    UsernameEt = (EditText)findViewById(R.id.etUserName);
    PasswordEt = (EditText)findViewById(R.id.etPassword);
    rem_userpass = (CheckBox) findViewById(R.id.rem_userpass);
    
    SharedPreferences pref = getSharedPreferences("shared_pref", Context.MODE_PRIVATE);
    String name = pref.getString("username", null);
    String pass = pref.getString("password", null);
    if (name != null && pass != null )
    {
        Intent i = new Intent(this, MenuActivity.class);
        startActivity(i);
    }
    

    那我要创建一个注销按钮来清除数据

    【讨论】:

      猜你喜欢
      • 2011-07-08
      • 2015-12-06
      • 2016-10-12
      • 2016-03-17
      • 2016-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多