Java Android Studio,绝对新手-尝试将用户名变量添加到其他活动

Java Android Studio,绝对新手-尝试将用户名变量添加到其他活动,java,android-studio,variables,Java,Android Studio,Variables,我知道已经有很多类似我的问题了。但实际上我很难理解他们。我是一个纯粹的新手,只看youtube教程,并且已经尝试了一段时间。我正在尝试创建一个具有LoginActivity的项目,该项目将进入一个仪表板,根据从mysql在线数据库获取的给定用户名显示用户信息 我相信我的POST请求和SQL查询是正确的。我可以登录我的应用程序并在仪表板上显示信息,但只能使用预设用户名 我不知道如何从LoginActivity EditText字段中为我的用户名设置变量。 我已经研究了一段时间,并且尝试了一些我不确

我知道已经有很多类似我的问题了。但实际上我很难理解他们。我是一个纯粹的新手,只看youtube教程,并且已经尝试了一段时间。我正在尝试创建一个具有LoginActivity的项目,该项目将进入一个仪表板,根据从mysql在线数据库获取的给定用户名显示用户信息

我相信我的POST请求和SQL查询是正确的。我可以登录我的应用程序并在仪表板上显示信息,但只能使用预设用户名

我不知道如何从LoginActivity EditText字段中为我的用户名设置变量。 我已经研究了一段时间,并且尝试了一些我不确定我是否做得对的事情,因为它们不起作用

我试图用getter和setter将它绑定到一个Username类上(我不确定这个词),但我认为我做得不对。(这是我认为我能理解的最多的一次)

这是我的LoginActivity课程

public class LoginActivity extends AppCompatActivity {

    Button loginButton;
    EditText usernameET, passwordET;


    @Override
    protected void onStart() {
        super.onStart();

        checkSession();

    }

    private void checkSession() {

        // check if user is logged in
        // if user is logged in -> moved to activity_dashboard
        SessionManager sessionManager = new SessionManager(LoginActivity.this);
        int userID = sessionManager.getSession();

        if (userID != -1 ){
            //user id logged in and so move to activity_dashboard
            moveToActivityDashboard();
        }
        else {
            //do nothing
        }
    }

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

        loginButton = (Button)findViewById(R.id.loginButton);
        usernameET = (EditText)findViewById(R.id.user_id);
        passwordET = (EditText)findViewById(R.id.user_pw);




    }




    public void onLogin(View view) {

        String username  = usernameET.getText().toString(),
                password = passwordET.getText().toString();
                String type = "login";

                
                Username u = new Username();
                u.setUsername(username);

                BackgroundWorker backgroundWorker = new BackgroundWorker(this);
                //is this even working?
                backgroundWorker.setLoginUsername(username);
                backgroundWorker.execute(type, username, password);
    }




    private void moveToActivityDashboard() {
        Intent intent = new Intent(LoginActivity.this, dashboard.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }
}
这是我的背景工人课上写的

public class BackgroundWorker extends AsyncTask<String,Void,String> {
    Context context;
    AlertDialog alertDialog;
    String loginUsername;


    BackgroundWorker (Context ctx) {
        context = ctx;
    }

    public void setLoginUsername(String loginUsername) {
        this.loginUsername = loginUsername;
    }
    public String getLoginUsername() {
        return loginUsername;
    }

    @Override
    protected String doInBackground(String... params) {
        String type = params[0];
        String login_url = "https://tesfas.000webhostapp.com/app/login.php";
        if (type.equals("login")) {
            try {
                String user_name = 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("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"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.equals("login success")) {

            saveToUser();
            context.startActivity(new Intent(context, dashboard.class));

        }else {
            alertDialog.setMessage(result+". incorrect login credentials");
            alertDialog.show();
           // Toast toast= Toast.makeText(context, "Email or password is wrong", Toast.LENGTH_SHORT);
           // toast.show();
        }


    }

    private void saveToUser(){

        BackgroundWorker a = new BackgroundWorker(context);
        User user = new User(1,a.getLoginUsername());
        SessionManager sessionManager = new SessionManager(context);
        sessionManager.saveSession(user);
    }


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

}

我想我解决了。我尝试使用这种方法是因为不知何故,我对SharedReference的工作原理感到困惑。现在我有点理解了它,并用它来存储我的username变量。
    public class dashboard extends AppCompatActivity {

    private static final String userLoginApi = "https://tesfas.000webhostapp.com/app/userLoginApi.php";

    RecyclerView recyclerView;
    ProfileAdapter adapter;

    List<UserProfile>userProfileInfo;

    Username u = new Username();
    final String loginUsername = u.getUsername();


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

        getJSON(userLoginApi);

        userProfileInfo = new ArrayList<>();

        recyclerView = (RecyclerView)findViewById(R.id.dashboard_recyclerView);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));



    }






    //this method is actually fetching the json string
    private void getJSON(final String urlWebService) {
        /*
         * As fetching the json string is a network operation
         * And we cannot perform a network operation in main thread
         * so we need an AsyncTask
         * The constrains defined here are
         * Void -> We are not passing anything
         * Void -> Nothing at progress update as well
         * String -> After completion it should return a string and it will be the json string
         * */
        class GetJSON extends AsyncTask<Void, Void, String> {

            //this method will be called before execution
            //you can display a progress bar or something
            //so that user can understand that he should wait
            //as network operation may take some time
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            //this method will be called after execution
            //so here we are displaying a toast with the json string
            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                //putting this toast to just incase i need to know if we're actually fetching the data from DB
                //Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
                try {
                    loadIntoProfile(s);
                } catch (JSONException e) {

                }
            }



            //in this method we are fetching the json string
            @Override
            protected String doInBackground(Void... voids) {


                try {
                    //creating a URL
                    URL url = new URL(urlWebService);

                    //Opening the URL using HttpURLConnection
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();

                    ///------------------------------------------------------------------
                    //THIS IS WRONG /// LoginActivity loginActivity = new LoginActivity();
                    //BackgroundWorker backgroundWorker = new BackgroundWorker(dashboard.this );

                    String username = "admin";
                    con.setRequestMethod("POST");
                    con.setDoOutput(true);
                    con.setDoInput(true);
                    OutputStream outputStream = con.getOutputStream();
                    BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF -8"));
                    String post_data = URLEncoder.encode("username", "UTF-8")+"="+URLEncoder.encode(username, "UTF-8");
                    bufferedWriter.write(post_data);
                    bufferedWriter.flush();
                    bufferedWriter.close();
                    outputStream.close();


                    ///------------------------------------------------------------------


                    //StringBuilder object to read the string from the service
                    StringBuilder sb = new StringBuilder();

                    //We will use a buffered reader to read the string from service
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

                    //A simple string to read values from each line
                    String json;

                    //reading until we don't find null
                    while ((json = bufferedReader.readLine()) != null) {

                        //appending it to string builder
                        sb.append(json + "\n");
                    }

                    //finally returning the read string
                    return sb.toString().trim();
                } catch (Exception e) {
                    return null;
                }

            }
        }

        //creating asynctask object and executing it
        GetJSON getJSON = new GetJSON();
        getJSON.execute();
    }

    private void loadIntoProfile(String json) throws JSONException {
        JSONArray profiles = new JSONArray(json);
        for (int i = 0; i < profiles.length(); i++) {
            JSONObject profileObject = profiles.getJSONObject(i);

            int id = profileObject.getInt("id");
            String employee_id = profileObject.getString("employee_id");
            String fname = profileObject.getString("fname");
            String mname = profileObject.getString("mname");
            String lname = profileObject.getString("lname");
            String desig = profileObject.getString("desig");
            String profilePicture = profileObject.getString("img_url");


            //variables have to be in the same position as UserProfile class variables or else magsasakmumo it na mga depota
            UserProfile userProfile = new UserProfile(id, lname, fname, mname, desig, employee_id, profilePicture);
            userProfileInfo.add(userProfile);
        }
        adapter = new ProfileAdapter(dashboard.this,userProfileInfo);
        recyclerView.setAdapter(adapter);
    }


        // OnLogout will logout your session by removeSession and forward you to LoginActivity with moveToLoginActivity() function
    public void OnLogout(View view) {
        //this function will remove the session
        SessionManager sessionManager = new SessionManager(dashboard.this);
        sessionManager.removeSession();

        moveToLoginActivity();

    }
    private void moveToLoginActivity() {
        Intent intent = new Intent(dashboard.this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }
    
}
public class Username {
    String username;


    public void setUsername(String username) {
        this.username = username;
    }

    public String getUsername() {
        return username;
    }

}