-1

I'm new in android and I've designed a login form using MySQL and now I want to show user login name in profile fragment as I've Sharedprefernces for the login session.

Here is my login class

public class LoginActivity extends AppCompatActivity {

    private static final String TAG = RegisterActivity.class.getSimpleName();
    private Button btnLogin;
    private Button btnLinkToRegister;
    private EditText inputEmail;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;

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

        inputEmail = findViewById(R.id.email);
        inputPassword = findViewById(R.id.password);
        btnLogin = findViewById(R.id.btnLogin);
        btnLinkToRegister = findViewById(R.id.btnLinkToRegisterScreen);

        // Progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);

        // SQLite database handler
        db = new SQLiteHandler(getApplicationContext());

        // Session manager
        session = new SessionManager(getApplicationContext());

        // Check if user is already logged in or not
        if (session.isLoggedIn()) {
            // User is already logged in. Take him to main activity
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }

        // Login button Click Event
        btnLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                // Check for empty data in the form
                if (!email.isEmpty() && !password.isEmpty()) {
                    // login user
                    checkLogin(email, password);
                } else {
                    // Prompt user to enter credentials
                    Toast.makeText(getApplicationContext(),
                            "Please enter the credentials!", Toast.LENGTH_LONG)
                            .show();
                }
            }

        });

        // Link to Register Screen
        btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),
                        RegisterActivity.class);
                startActivity(i);
                finish();
            }
        });

    }

    /**
     * function to verify login details in mysql db
     */
    private void checkLogin(final String email, final String password) {
        // Tag used to cancel the request
        String tag_string_req = "req_login";

        pDialog.setMessage("Logging in ...");
        showDialog();

        StringRequest strReq = new StringRequest(Request.Method.POST,
                AppConfig.URL_LOGIN, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response);
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    // Check for error node in json
                    if (!error) {
                        // user successfully logged in
                        // Create login session
                        session.setLogin(true);

                        // Now store the user in SQLite
                        String uid = jObj.getString("uid");

                        JSONObject user = jObj.getJSONObject("user");
                        String name = user.getString("name");
                        String email = user.getString("email");
                        String created_at = user.getString("created_at");

                        // Inserting row in users table
                        db.addUser(name, email, uid, created_at);

                        // Launch main activity
                        Intent intent = new Intent(LoginActivity.this,
                                MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        // Error in login. Get the error message
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Login Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<>();
                params.put("email", email);
                params.put("password", password);

                return params;
            }

        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }
}

Here is also SessionManager class

public class SessionManager {
    // LogCat tag
    private static String TAG = SessionManager.class.getSimpleName();

    // Shared Preferences
    private SharedPreferences pref;

    private SharedPreferences.Editor editor;

    // Shared preferences file name
    private static final String PREF_NAME = "AndroidHiveLogin";

    private static final String KEY_IS_LOGGEDIN = "isLoggedIn";

    public SessionManager(Context context) {
        // Shared pref mode
        int PRIVATE_MODE = 0;
        pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }

    public void setLogin(boolean isLoggedIn) {

        editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn);

        // commit changes
        editor.commit();

        Log.d(TAG, "User login session modified!");
    }

    public boolean isLoggedIn(){
        return pref.getBoolean(KEY_IS_LOGGEDIN, false);
    }
}

Here is Profile Fragment

public class ProfileFragment extends Fragment {

    private TextView txtName;
    private SessionManager session;

    public ProfileFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_profile, container, false);
    }

}

How to show here user login name in profile fragment please help me Thanks in advance.

Reaz Murshed
  • 22,528
  • 12
  • 75
  • 92
Mansur Asif
  • 15
  • 1
  • 7

1 Answers1

0

There are many ways of doing that actually. In your case, I think the convenient way of doing this is, storing the login name in the SharedPreferences and then get the value from the SharedPreferences in the ProfileFragment.

So when you are doing the session.setLogin(true);, you can save another key-value pair having the login name into the SharedPreferences and then you can retrieve the value from the SharedPreferences later from the fragment.

Hence, in the onCreateView function of your ProfileFragment, you might do something like the following.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    SessionManager sessionManager = new SessionManager(getActivity());

    // Considering you have the function to store and retrieve the login name from the SharedPreferences in your SessionManager class. 
    String loginName = sessionManager.getLoginName(); // get the login name here

    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_profile, container, false);
}

As I can see, you are storing the user profile information in the database. Hence, you can show the user profile information from the database as well in your fragment. I have a github project where you can see how to store/read in the SQLite database.

I hope that helps.

Update

You might have the following functions in your SessionManager class.

public class SessionManager {
    // LogCat tag
    private static String TAG = SessionManager.class.getSimpleName();

    // Shared Preferences
    private SharedPreferences pref;

    private SharedPreferences.Editor editor;

    // Shared preferences file name
    private static final String PREF_NAME = "AndroidHiveLogin";

    private static final String KEY_IS_LOGGEDIN = "isLoggedIn";
    private static final String KEY_LOGIN_NAME = "loginName";

    public SessionManager(Context context) {
        // Shared pref mode
        int PRIVATE_MODE = 0;
        pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }

    public void setLogin(boolean isLoggedIn) {

        editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn);

        // commit changes
        editor.commit();

        Log.d(TAG, "User login session modified!");
    }

    public boolean isLoggedIn(){
        return pref.getBoolean(KEY_IS_LOGGEDIN, false);
    }

    // These are the new functions that I added in your SessionManager class
    public void setLoginName(String loginName) {
        editor.putString(KEY_LOGIN_NAME, loginName).apply();
    }

    public boolean getLoginName(){
        return pref.getString(KEY_LOGIN_NAME, null);
    }
}

And in the API request section in your LoginActivity, you might consider doing something like the following.

if (!error) {
    // user successfully logged in
    // Create login session
    session.setLogin(true);

    // Now store the user in SQLite
    String uid = jObj.getString("uid");

    JSONObject user = jObj.getJSONObject("user");
    String name = user.getString("name");
    String email = user.getString("email");
    String created_at = user.getString("created_at");

    // Save login name in the SharedPreferences here
    session.setLoginName(name);

    // Inserting row in users table
    db.addUser(name, email, uid, created_at);

    // Launch main activity
    Intent intent = new Intent(LoginActivity.this,
            MainActivity.class);
    startActivity(intent);
    finish();
}  
Reaz Murshed
  • 22,528
  • 12
  • 75
  • 92
  • how to do it i don't get it please guide me // Considering you have the function to store and retrieve the login name from the SharedPreferences in your SessionManager class. String loginName = sessionManager.getLoginName(); // get the login name here – Mansur Asif Feb 24 '20 at 19:18
  • Please check the update of the answer. I hope that clarifies the confusion. – Reaz Murshed Feb 24 '20 at 19:23
  • veriable 'loginName' is never used. How toused it? – Mansur Asif Feb 24 '20 at 19:36
  • In your fragment, use that variable to set the text in a `TextView` or something in your layout? – Reaz Murshed Feb 24 '20 at 19:44
  • I used it as TextView textView=getView().findViewById(R.id.name); textView.setText(loginName); but application crashed – Mansur Asif Feb 24 '20 at 19:46
  • You need to inflate your layout first in your fragment. See this - https://stackoverflow.com/questions/17599450/how-to-inflate-view-inside-fragment – Reaz Murshed Feb 24 '20 at 19:47
  • I've done it like but name is not showing View rootView = inflater.inflate(R.layout.fragment_profile, container, false); SessionManager sessionManager = new SessionManager(Objects.requireNonNull(getActivity())); String loginName = sessionManager.getLoginName(); TextView textView = rootView.findViewById(R.id.name); textView.setText(loginName); return rootView; – Mansur Asif Feb 24 '20 at 20:06
  • Kindly reply i'm stuck here from couple of days – Mansur Asif Feb 25 '20 at 16:46
  • from this your code i'm getting errorr as cannot resolve symbol 'isLoggedIn' public void setLoginName(String loginName) { editor.putString(KEY_LOGIN_NAME, isLoggedIn).apply(); } – Mansur Asif Feb 25 '20 at 17:17
  • Awesome. Great to know that I could help. You are welcome. – Reaz Murshed Feb 25 '20 at 17:24
  • I'll also need you ahead of the app I'm making :D can i ask here questions if i needed any help from you ? – Mansur Asif Feb 25 '20 at 17:28
  • You can always ask separate questions in StackOverflow. You can post the question link here so that I can get a notification as well. Asking a clear and separate questions make it easier to get answers from other developers too. – Reaz Murshed Feb 25 '20 at 17:30
  • Hey man there is next question please guide me in efficient way https://stackoverflow.com/questions/60402156/android-how-to-save-image-automatically-in-mysql-db-when-user-set-change-his-pro – Mansur Asif Feb 25 '20 at 19:52
  • please guide me about user profile pic what will be its scenario to save every user profile pic? – Mansur Asif Feb 26 '20 at 17:32