Skip to content

SharedPreferences 사용자 로그인 유지 및 코드에 navigation bar 추가🌵  #7

@Kumushai9919

Description

@Kumushai9919

1. 현재까지 프로젝트 폴더

Screenshot 2023-04-06 at 7 41 42 PM

Screenshot 2023-04-06 at 7 42 02 PM

2. 사용자 로그인 유지 기능을 만들기 위해서 사용자가 성공적으로 로그인 한 다음 -> 사용자의 token을 요청 응답에서 받고 -> Sharedpreferences 객체 안에다가 저장했다.

  • 먼저 sharedpreferences 추가해서 객체 만들었다:
public static final String MyPREFERENCES = "MyPrefs";
SharedPreferences sharedPreferences;
sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
  • 그 다음에 로그인 success 후 요청 응답에서(response) 사용자 token을 받고 sharedpreferences안에 저장했고 다음 액티비티로 넘어가도록 했다:
                   String TOKEN = response.body().getToken();
                   SharedPreferences.Editor editor = sharedPreferences.edit();
                   editor.putString("TOKEN", TOKEN);
                   editor.commit();

                   Intent intent = new Intent(MainActivity.this, HomeActivity.class);
                   startActivity(intent);
  • 그리고 사용자가 앱을 닫고 매번 들어갈때마다 사용자 token을 확인하고, null 아니면 HomeActivity에 이동하여 계속 로그인 유지하도록 했다:
//        token 확인
        String TOKEN = sharedPreferences.getString("TOKEN", null);
          if(TOKEN != null){
          Intent intent = new Intent(MainActivity.this, HomeActivity.class);
          startActivity(intent);
          finish();
      }
  • HomeActivity에서 navigation bar의 모든 fragment(4개) 를 추가했고, HomeActivity에 이동했을 때 바로 HomeFragment를 보여주도록 했는데, 로그아웃 버튼을 HomeFragment에서 이벤트 발생할 때(버튼 누를 때) sharedprefereneces 에서 token을 삭제하여 다시 로그인 페이지로 이동하도록 했다.

** HomeActivity:*

package com.example.stylerent;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.annotation.SuppressLint; 
import android.os.Bundle;
import android.view.MenuItem;

import com.example.stylerent.fragments.ChattingFragment;
import com.example.stylerent.fragments.FavoriteFragment;
import com.example.stylerent.fragments.HomeFragment;
import com.example.stylerent.fragments.UserFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationBarView;


public class HomeActivity extends AppCompatActivity { 

    BottomNavigationView bottomNavigationView;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        bottomNavigationView = findViewById(R.id.btnNav);
        
        
        fragementRepl(new HomeFragment());

        bottomNavigationView.setOnItemReselectedListener(new NavigationBarView.OnItemReselectedListener() {
            @Override
            public void onNavigationItemReselected(@NonNull MenuItem item) {

                switch ( item.getItemId()) {
                    case R.id.home:

                        fragementRepl(new HomeFragment());
                        break;

                    case R.id.chatting:

                        fragementRepl(new ChattingFragment());

                        break;

                    case R.id.favorite:

                        fragementRepl(new FavoriteFragment());

                        break;

                    case R.id.user:

                        fragementRepl(new UserFragment());

                        break;
                        
                }
            }
        });


    }

    private void fragementRepl(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.frameLayout,fragment);
        fragmentTransaction.commit();

    }
}

** HomeFragment:*


package com.example.stylerent.fragments;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.example.stylerent.MainActivity;
import com.example.stylerent.R;

public class HomeFragment extends Fragment {

    public static final String MyPREFERENCES = "MyPrefs";
    SharedPreferences sharedPreferences;
    Button logoutbtn;
    
    public HomeFragment() {
        // Required empty public constructor
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        logoutbtn = view.findViewById(R.id.logout_btn);
        sharedPreferences = this.getActivity().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

        logoutbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.remove("TOKEN");
                editor.commit();

                Intent intent = new Intent(getActivity(), MainActivity.class);
                startActivity(intent);

            }
        });
        return view;
    }
}

3. 남은 Navigation bar 소스 코드(fragments)를 효은씨가 블로그에 보여줬던처럼 추가했다:

  • 모든 fragment들을 fragments이라는 폴더(new -> package -> 이름-fragments)를 만들어 거기에 드레그하여 놓었다.

Screenshot 2023-04-06 at 8 05 31 PM

변경한 프로젝트 소스 코드:

*MainActivity:

package com.example.stylerent;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.stylerent.auth.ApiInterface;
import com.example.stylerent.auth.LoginRequest;
import com.example.stylerent.auth.LoginResponse;
import com.example.stylerent.auth.RetrofitClient;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "LoginActivity";
    private Button btnlogin;
    private TextView registT;
    private EditText emailText, passwordText;
    public static final String MyPREFERENCES = "MyPrefs";
    SharedPreferences sharedPreferences;



    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        registT = findViewById(R.id.registerTextview);
        btnlogin = findViewById((R.id.login_button));
        emailText = findViewById(R.id.email_edit_text);
        passwordText = findViewById(R.id.password_edit_text);
        sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);


//        token 확인
        String TOKEN = sharedPreferences.getString("TOKEN", null);
          if(TOKEN != null){
          Intent intent = new Intent(MainActivity.this, HomeActivity.class);
          startActivity(intent);
          finish();
      }

        btnlogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnloginClicked();
            }
        });

        registT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }

    private void btnloginClicked() {

        String email = emailText.getText().toString();
        String password = passwordText.getText().toString();

        if(email.isEmpty()){
            Toast.makeText(getApplicationContext(), "Please Enter Email", Toast.LENGTH_SHORT).show();
        }else if(password.isEmpty()){
            Toast.makeText(getApplicationContext(), "Please Enter Password", Toast.LENGTH_SHORT).show();
        }else{


            //Login Request
            ApiInterface apiInterface = RetrofitClient.getRetrofitInstance().create(ApiInterface.class);
            Call<LoginResponse> call = apiInterface.getLoginInformation(new LoginRequest(email, password));
            call.enqueue(new Callback<LoginResponse>() {
                @Override
                public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {

                    if(response.body() == null){
                        Toast.makeText(MainActivity.this, "Incorrect email or password", Toast.LENGTH_SHORT).show();
                    }else{

                        Toast.makeText(MainActivity.this, "Logged in successul", Toast.LENGTH_SHORT).show();

                        //when login is success -> get user TOKEN (email,password data) and Save on shared preferences with key TOKEN

                        String TOKEN = response.body().getToken();
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putString("TOKEN", TOKEN);
                        editor.commit();

                        Intent intent = new Intent(MainActivity.this, HomeActivity.class);
                        startActivity(intent);
                    }
                    Log.e(TAG, "onResponse: "+ response.code());
                    Log.e(TAG, "onResponse: "+ response.body());
                }

                @Override
                public void onFailure(Call<LoginResponse> call, Throwable t) {
                    Log.e(TAG, "onFailure: "+ t.getMessage());
                    Toast.makeText(MainActivity.this, "Incorrect Email or password", Toast.LENGTH_SHORT).show();
                }

                });
            }
        }


}

** RegisterActivity:*

package com.example.stylerent;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.stylerent.auth.ApiInterface;
import com.example.stylerent.auth.RegisterRequest;
import com.example.stylerent.auth.RegisterResponse;
import com.example.stylerent.auth.RetrofitClient;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RegisterActivity extends AppCompatActivity {

    private static final String TAG = "RegisterActivity";
    private Button btnregister;
    private EditText usernameText, emailText, passwordText;
    private TextView loginText;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        usernameText = findViewById(R.id.username_text);
        emailText = findViewById(R.id.email_text);
        passwordText = findViewById(R.id.password_text);
        btnregister = findViewById(R.id.registerBtn1);

        loginText = findViewById(R.id.loginTextview);

        btnregister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnregisterClicked();
            }
        });

        loginText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }

    private void btnregisterClicked() {
        String username = usernameText.getText().toString();
        String email = emailText.getText().toString();
        String password = passwordText.getText().toString();

        if(username.isEmpty()){
            Toast.makeText(RegisterActivity.this, "Please Enter Username!!", Toast.LENGTH_SHORT).show();
        }else if(email.isEmpty()){
            Toast.makeText(RegisterActivity.this, "Please Enter Email!!", Toast.LENGTH_SHORT).show();
        }else if(password.isEmpty()){
            Toast.makeText(RegisterActivity.this, "Please Enter Password!!", Toast.LENGTH_SHORT).show();
        }else{

            //Registration request

            ApiInterface apiInterface = RetrofitClient.getRetrofitInstance().create(ApiInterface.class);

            Call<RegisterResponse> call = apiInterface.getRegisterInformation(new RegisterRequest(username, email, password));
            call.enqueue(new Callback<RegisterResponse>() {
                @Override
                public void onResponse(Call<RegisterResponse> call, Response<RegisterResponse> response) {

                    if(response.body().getError() != null){
                        Toast.makeText(RegisterActivity.this, response.body().getError(), Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(RegisterActivity.this, "Registration successful: Your Token->" + response.body().getToken(), Toast.LENGTH_SHORT).show();
                    }

                    Log.e(TAG, "onResponse: " + response.code());
                    Log.e(TAG, "onResponse: " + response.body());

                }


                @Override
                public void onFailure(Call<RegisterResponse> call, Throwable t) {
                    Log.e(TAG, "onFailure: "+ t.getMessage());

                }
            });


        }



    }
}

** HomeActivity:*

package com.example.stylerent;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.MenuItem;

import com.example.stylerent.fragments.ChattingFragment;
import com.example.stylerent.fragments.FavoriteFragment;
import com.example.stylerent.fragments.HomeFragment;
import com.example.stylerent.fragments.UserFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationBarView;


public class HomeActivity extends AppCompatActivity {

    BottomNavigationView bottomNavigationView;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        bottomNavigationView = findViewById(R.id.btnNav);


        fragementRepl(new HomeFragment());

        bottomNavigationView.setOnItemReselectedListener(new NavigationBarView.OnItemReselectedListener() {
            @Override
            public void onNavigationItemReselected(@NonNull MenuItem item) {

                switch ( item.getItemId()) {
                    case R.id.home:

                        fragementRepl(new HomeFragment());
                        break;

                    case R.id.chatting:

                        fragementRepl(new ChattingFragment());

                        break;

                    case R.id.favorite:

                        fragementRepl(new FavoriteFragment());

                        break;

                    case R.id.user:

                        fragementRepl(new UserFragment());

                        break;

                }
            }
        });


    }

    private void fragementRepl(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.frameLayout,fragment);
        fragmentTransaction.commit();

    }
}

** HomeFragment를 위에 올린 것을 참고하고, 남은 3 fragment를 효은씨 코드에서 참고하면 된다*

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions