【问题标题】:Android - display username form database to TextView [closed]Android - 将用户名表单数据库显示到 TextView [关闭]
【发布时间】:2020-10-04 12:49:34
【问题描述】:

所以我正在制作一个安卓应用程序。我已经设法创建了一个登录和注册页面(两者都有效,数据存储在 MySQL 数据库中)。

接下来我要做的是,当用户登录时,他/她的用户名将显示在主页上的 TextView 中(一个不同的活动,由片段组成。所以要清楚,MainActivity 由 4 个片段组成,当用户登录时,他会导航到 HomeFragment)。

我是 Java 和一般应用程序开发的新手,因此我们将不胜感激! 所以我想要完成的是将数据库中的用户名存储在一个键或变量(?)中,并将主页片段上的 TextView 设置为此用户名。 下面是 Login 和 Homefragment 脚本。

Login.java

package com.example.parrealityapp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.content.SharedPreferences;

import com.google.android.material.textfield.TextInputEditText;
import com.vishnusivadas.advanced_httpurlconnection.PutData;

public class LogIn extends AppCompatActivity {
    TextInputEditText textInputEditTextUsername, textInputEditTextPassword;
    Button btnlogin;
    ProgressBar progressBar;
    TextView textViewSignUp;

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

        textInputEditTextUsername = findViewById(R.id.usernameLogin);
        textInputEditTextPassword = findViewById(R.id.passwordLogin);
        btnlogin = findViewById(R.id.btnlogin);
        textViewSignUp = findViewById(R.id.signUpTxt);
        progressBar = findViewById(R.id.progress);

        textViewSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v){
                Intent intent = new Intent(getApplicationContext(), SignUp.class);
                startActivity(intent);
                finish();
            }
        });

        btnlogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String username, password;
                username = String.valueOf(textInputEditTextUsername.getText());
                password = String.valueOf(textInputEditTextPassword.getText());



                if (!username.equals("") && !password.equals("")) {

                    progressBar.setVisibility(View.VISIBLE);
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(new Runnable() {
                        @Override
                        public void run() {

                            String[] field = new String[2];
                            field[0] = "username";
                            field[1] = "password";

                            String[] data = new String[2];
                            data[0] = username;
                            data[1] = password;
                            PutData putData = new PutData("http://192.168.75.129/loginregister/login.php", "POST", field, data);
                            if (putData.startPut()) {
                                if (putData.onComplete()) {
                                    progressBar.setVisibility(View.GONE);
                                    String result = putData.getResult();

                                    if (result.equals("Login Success")) {
                                        Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
                                        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                                        startActivity(intent);
                                        finish();
                                    } else {
                                        Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
                                    }
                                }
                            }
                        }
                    });
                }
                else {
                    Toast.makeText(getApplicationContext(), "Vul alle velden in.", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

fragment_home.XML

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.home.HomeFragment">

<TextView
    android:id="@+id/txtName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="132dp"
    android:layout_marginEnd="250dp"
    android:textSize="45sp"
    android:text="@string/dashboard"
    android:fontFamily="@font/roboto_black"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />



</androidx.constraintlayout.widget.ConstraintLayout>

【问题讨论】:

    标签: java android mysql


    【解决方案1】:

    在 LogIn 类中声明以下变量为全局变量

    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    

    使用下面的函数来存储用户名

    private void storeUserInfo(String key,String value)
    {
    sharedPreferences = getSharedPreferences("File_name",Context.MODE_PRIVATE);
    editor = sharedPreferences.edit();
    editor.putString(key,value).commit();
    }
    

    在下面调用以存储用户名

    storeUserInfo("username",username);
    

    在下面调用以存储密码

    storeUserInfo("password",password);
    

    在您的片段中使用以下函数来检索值

    public String getUserInfo(String key){
            String value = "";
            value = sharedPreferences.getString(key, defValue);
            return  value;
        }
    

    在下面调用以检索用户名

    username = getUserInfo("username");
    

    在下面调用以检索密码

    password = getUserInfo("password");
    

    【讨论】:

      【解决方案2】:

      我认为您正在尝试将用户名传递给另一个活动。当用户成功登录到home_fragment 相关活动时,您希望将用户名显示给textView 的fragment_home.xml。如果我的猜测是正确的,那么您可以按照以下示例进行操作。

      为此,在与fragment_home.xml 相关的类中,例如HomeFragment.class,请遵循此代码并根据您的需要进行调整:

      public class HomeFragment extends Fragment {
          private TextView textView;
          private String userName;
      
          public HomeFragment(String username) {
              this.userName = userName;
          }
      
          @Override
          public void onCreate(@Nullable Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
          }
          
          @Nullable
          @Override
          public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
              View rootView =  inflater.inflate(R.layout.fragment_home, container, false); 
              textView = rootView.findViewById(R.id.txtName);
              return rootView;
          }
      
          @Override
          public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
              super.onViewCreated(view, savedInstanceState);
              textView.setText(userName);
          }
      

      您再次启动了活动。(从 loginActivity 到 mainActivity)但您没有将任何数据传递给意图。如果您想显示userName,那么您将如何获取数据?可以有两种方式。首先,从数据库中获取数据,另一种方法是将数据与意图一起传递。

      第二种方法:

      if (result.equals("Login Success")) {
          Toast.makeText(getApplicationContext(), result,Toast.LENGTH_SHORT).show();
          Intent intent = new Intent(getApplicationContext(), MainActivity.class);
          intent.putExtra("UNIQUE_KEY_FOR_USERNAME",userName);
          startActivity(intent);
          finish();
      

      并通过在MainActivity 中调用getIntent() 从intent 中获取数据:

      public class MainActivity extends AppCompatActivity { 
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main); 
              
      
              Intent intent = getIntent();
              String userName = intent.getStringExtra("UNIQUE_KEY_FOR_USERNAME");
      
              HomeFragment homeFragment = new HomeFragment(userName);
      
              //All other required methods to start fragment transaction;
      

      【讨论】:

      • 嗨,用户尝试在登录页面(这是一个活动)内登录,当它成功时它导航到主页片段。知道了这一点,这段代码还能用吗?
      • 您是否在MainActivity 中创建了HomeFragment 实例?如果你这样做了,那么你必须启动HomeFragment 的事务才能显示片段。
      • 是的,HomeFragment 是(与其他 3 个片段)MainActivity 的一部分。你到底是什么意思:开始交易?
      【解决方案3】:

      解决方案

      所以,经过一些研究(并得到了回答的人的帮助),我终于设法让它发挥作用。 SharedPreferences 是关键。在 Login.Java 中,我将输入的值存储为如下键:

                  nameStr = Objects.requireNonNull(textInputEditTextUsername.getText()).toString();
                  SharedPreferences.Editor editor = sp.edit();
                  editor.putString("textInputEditTextUsername", nameStr);
                  editor.apply();
      

      然后在 fragment(放置 TextView 的位置)中,我只需调用它并将 TextView 设置为存储输入值的变量。

          txtName = v.findViewById(R.id.txtName);
      
          SharedPreferences sp = requireActivity().getApplicationContext().getSharedPreferences("MyUserPrefs", Context.MODE_PRIVATE);
          String name = sp.getString("textInputEditTextUsername", "");
          txtName.setText("Welkom, "+name+"!");
      
            
      

      (抱歉,不擅长解释,但确实有效!:))。 现在标题设置为用户的用户名。

      【讨论】:

        猜你喜欢
        • 2014-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-21
        • 1970-01-01
        • 1970-01-01
        • 2017-02-28
        • 2012-12-17
        相关资源
        最近更新 更多