Android – 将数据库中的用户名显示到 TextView 中

huangapple go评论98阅读模式
英文:

Android - display username form database to TextView

问题

这是您提供的代码的翻译部分:

Login.java

package com.example.parrealityapp;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
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;

    @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);
        progressBar = findViewById(R.id.progress);

        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(), "Please fill in all fields.", 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>

请注意,代码的翻译可能会有一些微小的差异,但我已尽力保持原意和结构的一致性。

英文:

So I'm making an android app. I've already managed to create a Login & Registration page (both works, data gets stored in a MySQL database).

The next thing I want to do is when the user logs in his/her username will be displayed in a TextView on the homepage (a different activity, which consists of fragments. So to be clear, the MainActivity consists of 4 fragments, and when the user logs in he navigates to the HomeFragment).

I'm new to Java and app development in general so any help would be appreciated!
So what I want to accomplish is to store the username from the database in a key or variable (?) and set the TextView on the home fragment to this username.
Here are the Login and Homefragment scripts.

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(&quot;&quot;) &amp;&amp; !password.equals(&quot;&quot;)) {
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] = &quot;username&quot;;
field[1] = &quot;password&quot;;
String[] data = new String[2];
data[0] = username;
data[1] = password;
PutData putData = new PutData(&quot;http://192.168.75.129/loginregister/login.php&quot;, &quot;POST&quot;, field, data);
if (putData.startPut()) {
if (putData.onComplete()) {
progressBar.setVisibility(View.GONE);
String result = putData.getResult();
if (result.equals(&quot;Login Success&quot;)) {
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(), &quot;Vul alle velden in.&quot;, Toast.LENGTH_SHORT).show();
}
}
});
}
}

fragment_home.XML

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
xmlns:tools=&quot;http://schemas.android.com/tools&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;match_parent&quot;
tools:context=&quot;.ui.home.HomeFragment&quot;&gt;
&lt;TextView
android:id=&quot;@+id/txtName&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:layout_marginTop=&quot;132dp&quot;
android:layout_marginEnd=&quot;250dp&quot;
android:textSize=&quot;45sp&quot;
android:text=&quot;@string/dashboard&quot;
android:fontFamily=&quot;@font/roboto_black&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot;
app:layout_constraintStart_toStartOf=&quot;parent&quot;
app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;
&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;

答案1

得分: 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");
英文:

Declare below variables inside class LogIn as global variables

private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;

Use below function for storing username

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

invoke below for storing username

storeUserInfo(&quot;username&quot;,username);

invoke below for storing password

storeUserInfo(&quot;password&quot;,password);

Use below function in your fragment for retreiving values

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

invoke below for retreiving username

username = getUserInfo(&quot;username&quot;);

invoke below for retreiving password

password = getUserInfo(&quot;password&quot;);

答案2

得分: 1

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

为此,在与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);
    }
}

再次启动了活动(从loginActivitymainActivity),但没有将任何数据传递给意图。如果你想显示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()获取意图中的数据:

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);

        // 所有其他启动片段事务所需的方法;
英文:

I think your are trying to pass the Username to another activity. When user successfully login into home_fragment related activity, you want to show the User name to that textView of fragment_home.xml. If my guess is right then you can follow the below example.

For this purpose inside the class that is related to fragment_home.xml, say HomeFragment.class follow this code and adjust per your need:

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);
    }

Again you started the activity.(from loginActivity to mainActivity) but you haven't pass any data to the intent. If you want to show the userName then how will you get the data? There can be two way. Firstly, getting the data from database and another way is to pass the data along with the intent.

For second method:

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

and get the data from intent by calling getIntent() in MainActivity:

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(&quot;UNIQUE_KEY_FOR_USERNAME&quot;);

        HomeFragment homeFragment = new HomeFragment(userName);

        //All other required methods to start fragment transaction;

答案3

得分: 0

解决方案

经过一些研究(以及那些提供答案的人的帮助),我最终成功让它工作起来了。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("欢迎," + name + "!");

(抱歉,不擅长解释事情,但是是的,它起作用了! Android – 将数据库中的用户名显示到 TextView 中 ) 现在标题根据用户的用户名设置。

英文:

SOLUTION

So, after some research (and help from they guys who answered) I finally managed to make it work. SharedPreferences was the key. In the Login.Java i stored the value of the input as a key like this:

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

And then in the fragment (where the TextView was placed) I simply had to call it and set the TextView to the variable in which the value of the input was stored.

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

(Sorry, bad at explaining things but yeah it worked! Android – 将数据库中的用户名显示到 TextView 中 ). Now the title is set to whatever the user has as username.

huangapple
  • 本文由 发表于 2020年10月4日 20:49:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/64194816.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定