Change Floating Action Button Background - java

I am using a floating action button and its image changes when its clicked. i have a flag and i store it in shared preferences. when it is true icon becomes like.png, when it is false icon becomes dislike.png.
I want to change its icon according to flag variable but when the app starts its icon is default which is true.png
How can I set the icon via shared preferences?
public class ReadActivity extends AppCompatActivity {
private FloatingActionButton fab;
private boolean flag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read);
fab = (FloatingActionButton) findViewById(R.id.fab);
getRate(getWindow().getDecorView().getRootView());
if(flag==false){
fab.setImageResource(R.drawable.like);
}
else if(flag==true){
fab.setImageResource(R.drawable.dislike);
}
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getRate(v);
if(flag==false) {
rateUp();
Snackbar.make(v, "Vote +1", Snackbar.LENGTH_LONG).show();
saveRate(v, true);
fab.setImageResource(R.drawable.dislike);
}
else if(flag==true){
rateDown();
Snackbar.make(v, "Vote -1", Snackbar.LENGTH_LONG).show();
saveRate(v, false);
fab.setImageResource(R.drawable.like);
}
}
});
}
public void rateUp() {};
public void rateDown() {};
public void saveRate(View view, boolean flag){
SharedPreferences sharedPreferences = getSharedPreferences("Rates", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(id, flag);
editor.commit();
}
public void getRate(View view){
SharedPreferences sharedPreferences = getSharedPreferences("Rates", MODE_PRIVATE);
flag = sharedPreferences.getBoolean(id, false);
}
}

Try this code :
public class ReadActivity extends AppCompatActivity {
private FloatingActionButton fab;
private string getSharedPreferencesId="getSharedPreferencesId";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read);
fab = (FloatingActionButton) findViewById(R.id.fab);
boolean flag=getRate();
if(flag==false){
fab.setImageResource(R.drawable.like);
}
else if(flag==true){
fab.setImageResource(R.drawable.dislike);
}
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean flag=getRate();
if(flag==false) {
rateUp();
Snackbar.make(v, "Vote +1", Snackbar.LENGTH_LONG).show();
saveRate(true);
fab.setImageResource(R.drawable.dislike);
}
else if(flag==true){
rateDown();
Snackbar.make(v, "Vote -1", Snackbar.LENGTH_LONG).show();
saveRate(false);
fab.setImageResource(R.drawable.like);
}
}
});
}
public void rateUp() {};
public void rateDown() {};
public void saveRate(boolean flag){
SharedPreferences sharedPreferences = getSharedPreferences("Rates", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(getSharedPreferencesId, flag);
editor.commit();
}
public boolean getRate(){
SharedPreferences sharedPreferences = getSharedPreferences("Rates", MODE_PRIVATE);
flag = sharedPreferences.getBoolean(getSharedPreferencesId, false);
}
}

I made some improvements on your code:
public class ReadActivity extends AppCompatActivity {
private FloatingActionButton fab;
private boolean flag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read);
fab = (FloatingActionButton) findViewById(R.id.fab);
flag = getRate();
if(flag)
fab.setImageResource(R.drawable.dislike);
else
fab.setImageResource(R.drawable.like);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flag = getRate();
if(flag) {
rateDown();
Snackbar.make(v, "Vote -1", Snackbar.LENGTH_LONG).show();
saveRate(false);
fab.setImageResource(R.drawable.like);
}
else{
rateUp();
Snackbar.make(v, "Vote +1", Snackbar.LENGTH_LONG).show();
saveRate(true);
fab.setImageResource(R.drawable.dislike);
}
}
});
}
public void rateUp() {};
public void rateDown() {};
public void saveRate(boolean flag){
SharedPreferences sharedPreferences = getSharedPreferences("Rates", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(id, flag);
editor.commit();
}
public boolean getRate(){
SharedPreferences sharedPreferences = getSharedPreferences("Rates", MODE_PRIVATE);
boolean flag = sharedPreferences.getBoolean(id, false);
return flag;
}
}
Also check your activity_read.xml file. If you have set an image on your xml FloatingActionButton, it will always use that image as default.

I will tell you the logic. Assumed you have many different contents and you want to save rating data for each content.
First, you need to store your each content's rating data into somewhere(Local or Remote DB, SharedPreferences, File etc.)
After starting your ReadActivity,
Set your flag to default value you wanted to be.
Set your FAB icon as default.
Get your related content rating data(boolean) from where you stored before.
Check if your rating data is true or false.
If it's true set your icon R.drawable.dislike, else set R.drawable.like
When you clicked the FAB, change your flag value and FAB icon
Save your new boolean value to where you stored before
The important point is, you must have different values for each content you have.
EDIT:
Try using getApplicationContext() before using getSharedPreferences()
Also you can try editor.apply() instead of editor.commit();
commit() and apply() does the same work but there are two differences, apply() works asynchronously and commit() returns boolean value.
public void saveRate(View view, boolean flag){
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("Rates", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(id, flag);
editor.apply();
}
public void getRate(View view){
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("Rates", MODE_PRIVATE);
flag = sharedPreferences.getBoolean(id, false);
}

Related

How to carry SharedPreferences into a new function of the same activity? (Android Studio)

I'm using SharedPreferences to create settings on one activity that will be applied on other activities. I've created the SharedPreferences in OnCreate, but then I need to set them in a second function that is called when a button is pressed. At the moment the app keeps crashing on launch if I put SharedPreferences anywhere except for OnCreate.
Problem is I don't seem to be able to carry sharedPreferences into the openNextPage function, as all mentions of it in openNextPage bring up an error saying :
Cannot resolve symbol sharedPreferences
So how can I carry the editor over to this function?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_screen);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Button nextBtn = findViewById(R.id.confSetBtn);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openNextPage();
}
});
}
public void openNextPage(){
SharedPreferences.Editor editor = sharedPreferences.edit();
if(checkBox1.isChecked()){
editor.putBoolean("value1", true);
}
if(checkBox2.isChecked()){
editor.putBoolean("value2", true);
}
editor.apply();
boolean none = sharedPreferences.getBoolean("value1", false);
if(none){
finish();
}
else{
Intent intent = new Intent(welcomeScreen.this, newSettingsActivity.class);
startActivity(intent);
}
}
You can try it like this i have edited your code. I have declared this as property in your class.
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_screen);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Button nextBtn = findViewById(R.id.confSetBtn);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openNextPage();
}
});
}
public void openNextPage(){
SharedPreferences.Editor editor = sharedPreferences.edit();
if(checkBox1.isChecked()){
editor.putBoolean("value1", true);
}
if(checkBox2.isChecked()){
editor.putBoolean("value2", true);
}
editor.apply();
boolean none = sharedPreferences.getBoolean("value1", false);
if(none){
finish();
}
else{
Intent intent = new Intent(welcomeScreen.this, newSettingsActivity.class);
startActivity(intent);
}
}
To access a variable across app declare it as:
public static SharedPreferences object;
Follow this link to understand how to use shared preferences in your app.
Link
Cheers!
Pass instance of SharedPreferences as an argument as follows
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_screen);
// update 1
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Button nextBtn = findViewById(R.id.confSetBtn);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// update 2
openNextPage(sharedPreferences);
}
});
}
// update 3
public void openNextPage(SharedPreferences sharedPreferences){
SharedPreferences.Editor editor = sharedPreferences.edit();
if(checkBox1.isChecked()){
editor.putBoolean("value1", true);
}
if(checkBox2.isChecked()){
editor.putBoolean("value2", true);
}
editor.apply();
boolean none = sharedPreferences.getBoolean("value1", false);
if(none){
finish();
}
else{
Intent intent = new Intent(welcomeScreen.this, newSettingsActivity.class);
startActivity(intent);
}
}

How to functionate the second activity through a radio button in the Main_activity?

if I have two activities.
1.Main_Activity
which contain a radio button and an image button.
2.Second_activity extended from Main_activity.
which is intent in Main_activity and contain three radio buttons with the saved state in shared preference.
the vibration, normal and silent mode work on these radio buttons.
the Drvset activity is already intent through the image button.
I want to retrieve the saved state of the radio buttons and Load it through the radio button in the main activity.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton buttonOne = findViewById(R.id.drvedit);
RadioButton buttondr=findViewById(R.id.drvbtn);
buttonOne.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println("Button Clicked");
Intent activity2Intent = new Intent(getApplicationContext(), drvset.class);
startActivity(activity2Intent);
}
});
}
}
public class drvset extends MainActivity {
private RadioButton normal;
private RadioButton silent;
private RadioButton vibrate;
private AudioManager myAudioManager;
final String KEY_SAVED_RADIO_BUTTON_INDEX = "SAVED_RADIO_BUTTON_INDEX";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drvset);
LoadPreferences();
normal = (RadioButton) findViewById(R.id.radioNormal);
silent = (RadioButton) findViewById(R.id.radioSilent);
vibrate=(RadioButton)findViewById(R.id.radiovibrate);
normal.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
normalEnable(v);
}
});
silent.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
silentEnable(v);
}
});
vibrate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
vibrateEnable(v);
}
});
myAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
}
public void vibrateEnable(View view){
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
status.setText("Current Status: Vibrate Mode");
}
public void normalEnable(View view){
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
status.setText("Current Status: Ring Mode");
}
public void silentEnable(View view){
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
status.setText("Current Status: Silent Mode");
}
}};
public void SavePreferences(String key, int value){
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.apply();
}
public void LoadPreferences(){
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
int savedRadioIndex = sharedPreferences.getInt(KEY_SAVED_RADIO_BUTTON_INDEX, 0);
RadioButton savedCheckedRadioButton = (RadioButton)radioGroup.getChildAt(savedRadioIndex);
savedCheckedRadioButton.setChecked(true);
}
}

How do I get my theme to programmatically get carried over into other activities?

I've created a function in the settings page of my app which contains a switch - that when pressed - switches to a secondary "Night" theme. I followed this tutorial for the most part. However, I don't know how to carry this night mode into my other activities? I've tried calling the "if switch checked" in my main activity, but it obviously doesn't see that switch. What I mainly need to know is, how do I check a switch state in another activity? And is this even the right way of doing it? Let me know if I've missed anything else in this question.
// ======== CODE FOR THE SETTINGS PAGE ======== //
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
// ======== Night Mode ======== //
SwitchCompat switchCompat;
final SharedPref sharedPref;
sharedPref = new SharedPref(this);
if (sharedPref.loadNightModeState()) {
setTheme(R.style.AppTheme_Night);
getSupportActionBar().setBackgroundDrawable(getDrawable(R.drawable.actionbar));
actionBarDrawerToggle.getDrawerArrowDrawable().setColor(getResources().getColor(R.color.BackgroundLight));
} else setTheme(R.style.AppTheme);
setContentView(R.layout.activity_settings);
switchCompat = (SwitchCompat) findViewById(R.id.night_switch);
if (sharedPref.loadNightModeState()) {
switchCompat.setChecked(true);
}
switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
sharedPref.setNightModeState(true);
restartApp();
} else {
sharedPref.setNightModeState(false);
restartApp();
}
}
});
}
private void restartApp() {
Intent intent = new Intent(getApplicationContext(), SettingsActivity.class);
startActivity(intent);
finish();
}
// ======== SharedPref CODE ======== //
public class SharedPref {
private SharedPreferences sharedPreferences;
public SharedPref(Context context) {
sharedPreferences = context.getSharedPreferences("filename", Context.MODE_PRIVATE);
}
public void setNightModeState(Boolean state) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("NightMode",state);
editor.apply();
}
public Boolean loadNightModeState (){
Boolean state = sharedPreferences.getBoolean("NightMode", false);
return state;
}
In you application class inside onCreate
SharedPreferences sharedPreferences = getSharedPreferences("Your_Shared_pref", Context.MODE_PRIVATE);
boolean nightMode = sharedPreferences.getBoolean(SettingsActivity.DARK_THEME_PREFERENCE_KEY, false);
AppCompatDelegate.setDefaultNightMode(nightMode ? MODE_NIGHT_YES : MODE_NIGHT_NO);
Than in your activity, do this:
switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
AppCompatDelegate.setDefaultNightMode(isChecked ? MODE_NIGHT_YES : MODE_NIGHT_NO);
if (isChecked) {
sharedPref.setNightModeState(true);
recreate();
} else {
sharedPref.setNightModeState(false);
recreate();
}
}
});
#Override
public void recreate() {
finish();
overridePendingTransition(R.anim.anime_fade_in,
R.anim.anime_fade_out);
startActivity(getIntent());
overridePendingTransition(R.anim.anime_fade_in,
R.anim.anime_fade_out);
}
you can find the animation xml online.
I put this between my onCreate and my super.onCreate. The code I used was taken from my settings java page. It turns out that it was pretty easy to figure, I just needed someone to put it into perspective!
#Override
protected void onCreate(Bundle savedInstanceState) {
final SharedPref sharedPref;
sharedPref = new SharedPref(this);
if (sharedPref.loadNightModeState()) {
setTheme(R.style.AppTheme_Night);
//restartApp();
//getSupportActionBar().setBackgroundDrawable(getDrawable(R.drawable.actionbar));
//actionBarDrawerToggle.getDrawerArrowDrawable().setColor(getResources().getColor(R.color.BackgroundLight));
} else setTheme(R.style.AppTheme);
//restartApp();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Progress bar for counting checkboxes

I need every click on the checkbox to increase the percentage in progressBar.
Example: I have two checkboxes, each corresponding to 50% within the progressBar.
I tried several codes, but none worked, I'm a beginner in java
Can someone help me? Please.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
final CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox);
final CheckBox checkBox2 = (CheckBox) findViewById(R.id.checkBox2);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
if (preferences.contains("checkbox1") && preferences.getBoolean("checkbox1", false) == true) {
checkBox.setChecked(true);
} else {
checkBox.setChecked(false);
}
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (checkBox.isChecked()) {
editor.putBoolean("checkbox1", true);
editor.apply();
} else {
editor.putBoolean("checkbox1", false);
editor.apply();
}
}
});
if (preferences.contains("checkbox2") && preferences.getBoolean("checkbox2", false) == true) {
checkBox2.setChecked(true);
} else {
checkBox2.setChecked(false);
}
checkBox2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (checkBox2.isChecked()) {
editor.putBoolean("checkbox2", true);
editor.apply();
} else {
editor.putBoolean("checkbox2", false);
editor.apply();
}
}
});
}
}

Android app stuck on sharing username from 1 activity to another but not getting it through SharedPreferences

Basically i want to use the email id from which user log in to store and use in any activity for fetching the data from server. Please help me.
First Activity Sign_In
public class Sign_In extends AppCompatActivity {
public static final String LOGIN_URL="url";
public static final String KEY_EMAIL="email";
public static final String KEY_PASSWORD="password";
public static final String LOGIN_SUCCESS="success";
public static final String SHARED_PREF_NAME="tech";
public static final String EMAIL_SHARED_PREF="email";
public static final String LOGGEDIN_SHARED_PREF="loggedin";
private EditText editTextEmail;
private EditText editTextPassword;
private Button BtnLogin;
private boolean loggedIn=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign__in);
editTextEmail=(EditText)findViewById(R.id.editText3);
editTextPassword=(EditText)findViewById(R.id.editText2);
BtnLogin=(Button)findViewById(R.id.button);
BtnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
}
});
}
private void login() {
final String email = editTextEmail.getText().toString().trim().toLowerCase();
final String password = editTextPassword.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().equalsIgnoreCase(LOGIN_SUCCESS)){
SharedPreferences sharedPreferences = Sign_In.this.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(LOGGEDIN_SHARED_PREF, true);
editor.putString(EMAIL_SHARED_PREF, email);
editor.apply();
Intent intent = new Intent(Sign_In.this, HomePage.class);
startActivity(intent);
}
else {
Toast.makeText(Sign_In.this,"Invalid credentials",Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> prams = new HashMap<>();
prams.put(KEY_EMAIL, email);
prams.put(KEY_PASSWORD, password);
return prams;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
loggedIn = sharedPreferences.getBoolean(LOGGEDIN_SHARED_PREF, false);
if (loggedIn){
Intent intent = new Intent(Sign_In.this, HomePage.class);
startActivity(intent);
}
}
}
Second Activity HomePage
import static in.borrowfunds.build30.Sign_In.EMAIL_SHARED_PREF;
import static in.borrowfunds.build30.Sign_In.SHARED_PREF_NAME;
public class HomePage extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if (keyCode==KeyEvent.KEYCODE_BACK){
AlertDialog.Builder alertbox=new AlertDialog.Builder(HomePage.this);
alertbox.setTitle("You want to Exit?");
alertbox.setCancelable(false);
alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), Sign_In.class);
startActivity(intent);
finish();
}
});
alertbox.setNegativeButton("No", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertbox.show();
}
return super.onKeyDown(keyCode,event);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_b) {
Intent intent = new Intent(getApplicationContext(), B.class);
startActivity(intent);
return true;
}
else if (id == R.id.nav_l) {
Intent intent = new Intent(getApplicationContext(), L.class);
startActivity(intent);
return true;
}
else if (id == R.id.nav_p) {
Intent intent = new Intent(getApplicationContext(), P.class);
startActivity(intent);
return true;
}
else if (id == R.id.nav_e) {
Intent intent = new Intent(getApplicationContext(), E.class);
startActivity(intent);
return true;
}
else if (id == R.id.nav_pr) {
Intent intent = new Intent(getApplicationContext(), Pr.class);
startActivity(intent);
return true;
}
else if (id == R.id.nav_logout) {
SharedPreferences sharedpreferences = getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.clear();
editor.commit();
HomePage.this.finish();
Intent intent = new Intent(getApplicationContext(), Sign_In.class);
startActivity(intent);
return true;
}
else if (id == R.id.nav_email) {
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto","contact#hgdcsa.net",null));
try {
startActivity(intent);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(this, "Mail account not configured", Toast.LENGTH_SHORT).show();
}
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
After you retreive the data, whatever it may be, you can use SharedPreferences to store and access it locally on the device:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getContext());
String pref = preferences.getString("preference_key", "default-username");
// if the pref isn't set, you can designate a default value
Any activity you want to access this data, you can call preferences.getString (or any type) to access what the user stored.
You can store data in the SharedPreferences by edit and commiting changes:
preferences.edit().putString("preference_key", "username").commit();
Preferences come in all kinds of types, notably:
String
int
boolean
I got the answer by myself, what a relief, was stuck on this for about 10 days.
Btw thanks for the anwers and i'm providing the solution for future purpose.
First Activity
SharedPreferences sharedPreferences = Sign_In.this.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(LOGGEDIN_SHARED_PREF, true);
editor.putString(EMAIL_SHARED_PREF, email);
editor.apply();
Intent intent = new Intent(Sign_In.this, HomePage.class);
intent.putExtra(EMAIL_SHARED_PREF,email);
startActivity(intent);
Second Activity
TextView email1;
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
String email = sharedPreferences.getString(EMAIL_SHARED_PREF, "");
email1=(TextView)findViewById(R.id.textView18);
email1.setText(email);

Categories