I have created a login page which users can just enter their username (No passowrd or auth needed) and it will be displayed on the next activity. But every time you open the app you have to enter your username. How do i make it remember the username. (Language-Java)
Thanks!
(I am a beginner)
package com.example.app; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends AppCompatActivity { Button btn; EditText et; String st; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn= findViewById(R.id.button); et=findViewById(R.id.edittext); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i=new Intent(MainActivity.this, Welcome.class); st=et.getText().toString(); i.putExtra("Value",st); startActivity(i); finish();
(This one is the activity where user enters their username)
package com.example.app; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class Welcome extends AppCompatActivity { TextView tv; String st; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome); tv=findViewById(R.id.textView); st=getIntent().getExtras().getString("Value"); tv.setText(st); } }
(This is the welcome activity)
Advertisement
Answer
I think you need to save the user username in Sharedpreferences and then when you start your app get the value from sharedpreferences and check if the value is null or empty then let the user enter his username else you can set the username from sharedpreferences .
Try this Code :
///save sharedpreferences SharedPreferences sharedPreferences = getSharedPreferences("prefs",Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("username","put here your username"); editor.apply(); ///get sharedpreferences SharedPreferences sharedPreferences1 = getSharedPreferences("prefs",Context.MODE_PRIVATE); String username = sharedPreferences1.getString("username",""); tv.setText(username);