-1

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("") && !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>
Avi
  • 362
  • 1
  • 3
  • 11
dub
  • 82
  • 8

3 Answers3

1

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("File_name",Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putString(key,value).commit();
}

invoke below for storing username

storeUserInfo("username",username);

invoke below for storing password

storeUserInfo("password",password);

Use below function in your fragment for retreiving values

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

invoke below for retreiving username

username = getUserInfo("username");

invoke below for retreiving password

password = getUserInfo("password");
Nadeem Shaikh
  • 1,160
  • 9
  • 17
1

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

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

        HomeFragment homeFragment = new HomeFragment(userName);

        //All other required methods to start fragment transaction;
philoopher97
  • 772
  • 1
  • 6
  • 18
  • Hi, the user tries to login inside the Login page (which is an activity) and when its successful it navigates to the home fragment. Knowing this, will this code still work? – dub Oct 04 '20 at 17:24
  • Did you created the `HomeFragment` instance in `MainActivity`? If you did, then you have to start transaction of `HomeFragment` to show the fragment. – philoopher97 Oct 04 '20 at 17:32
  • Yes, the `HomeFragment` is (with 3 other fragments) part of the `MainActivity`. What exactly do you mean with: _start the transaction_? – dub Oct 04 '20 at 17:42
  • https://stackoverflow.com/questions/36100187/how-to-start-fragment-from-an-activity follow this. – philoopher97 Oct 04 '20 at 17:45
0

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("textInputEditTextUsername", 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("MyUserPrefs", Context.MODE_PRIVATE);
    String name = sp.getString("textInputEditTextUsername", "");
    txtName.setText("Welkom, "+name+"!");

      

(Sorry, bad at explaining things but yeah it worked! :) ). Now the title is set to whatever the user has as username.

dub
  • 82
  • 8