Retrieving font size from SharedPreferences to other activity - java

i am trying to retrieve the font size from the sharedpreferences from other activity. i already add the getPreferences method however it doesnt work. please explain to me i love knowledges.
as on the code, i succesfully changing the textsize using seekbar, and save it to sharedpreferences, however, in trying to retrieve the font size on other activity, it doesnt work.
here is my 1st activity java
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.MenuItem;
import android.widget.SeekBar;
import android.widget.TextView;
import com.google.android.material.navigation.NavigationView;
public class fontsize extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
//textsize
int textSize = 30;
//textView
TextView textViewFont, textViewSize;
//SharedPreferences
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
//variablesmenudrawer
DrawerLayout drawerLayout;
NavigationView navigationView;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fontsize);
sharedPreferences = getSharedPreferences("fontsize", MODE_PRIVATE);
editor = sharedPreferences.edit();
int progress = sharedPreferences.getInt("progress", 0);
//definingtextview
textViewFont = findViewById(R.id.textViewFont);
textViewSize = findViewById(R.id.textViewSize);
//seekbar
SeekBar seekBar = findViewById(R.id.seekbar);
seekBar.setProgress(progress);
textViewFont.setTextSize(textSize+seekBar.getProgress()); // size 30sp
textViewSize.setText(seekBar.getProgress() + "/" + seekBar.getMax()); // 0/30
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressNew = 0;
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
textSize = textSize + (progress - progressNew);
progressNew = progress;
textViewFont.setTextSize(textSize);
editor.putInt("progress", progress);
editor.apply();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
textViewSize.setText(seekBar.getProgress() + "/" + seekBar.getMax()); // 0/30
}
});
//definingmenudrawer
drawerLayout = findViewById(R.id.drawer_layout4);
navigationView = findViewById(R.id.nav_view4);
toolbar = findViewById(R.id.toolbar4);
//toolbar
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
//toolbar.setNavigationIcon(R.drawable.ic_toolbar);
toolbar.setTitle("");
toolbar.setSubtitle("");
//toolbar.setLogo(R.drawable.ic_toolbar);
toolbar.setNavigationIcon(R.drawable.ic_baseline_dehaze_24);
//navdrawermenu
navigationView.bringToFront();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.nav_home);
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
}
else {
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_home:
Intent intent = new Intent(fontsize.this, home.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
case R.id.nav_fontsize:
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}
and my second activity java
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Display;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.google.android.material.navigation.NavigationView;
public class duatawassul extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
TextView textView;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
//variablesmenudrawer
DrawerLayout drawerLayout;
NavigationView navigationView;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_duatawassul);
sharedPreferences = getSharedPreferences("fontsize", MODE_PRIVATE);
textView = findViewById(R.id.duatawassultext);
//definingmenudrawer
drawerLayout = findViewById(R.id.drawer_layout1);
navigationView = findViewById(R.id.nav_view1);
toolbar = findViewById(R.id.toolbar1);
//toolbar
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
//toolbar.setNavigationIcon(R.drawable.ic_toolbar);
toolbar.setTitle("");
toolbar.setSubtitle("");
//toolbar.setLogo(R.drawable.ic_toolbar);
toolbar.setNavigationIcon(R.drawable.ic_baseline_dehaze_24);
//navdrawermenu
navigationView.bringToFront();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.nav_home);
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
}
else {
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_home:
Intent intent = new Intent(duatawassul.this, home.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
case R.id.nav_fontsize:
Intent intent1 = new Intent(duatawassul.this, fontsize.class);
startActivity(intent1);
finish();
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}

in your on create method in the second activity add the following which appears to be missing in your original code
prefs = getSharedPreferences("fontsize", MODE_PRIVATE);
//this line is nowhere found in your second activity
int progress=prefs.getInt("progress",0);

if you want to use the share preferences in your app then you have to add value into the shared preference first like below keep in mind you can put it as a string and as an int, it's up to you that what you are using.
SharedPreferences.Editor editor = context.getSharedPreferences("fontsize", MODE_PRIVATE).edit();
editor.putInt("fontsizeis", 14);
editor.apply();
After adding the values to the share preferences than you have to get the value. you can get the value from anywhere you wants for getting the value you can use this.
SharedPreferences sharePreferences= getSharedPreferences("fontsize", MODE_PRIVATE);
if(sharePreferences.contains("fontsizeis")){
int fontsizeis= sharePreferences.getInt("fontsizeis", 0);
if(fontsizeis != 0){
Toast.makeText(context, "you find your desired value here", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "desired value not found some thing issue", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(context, "Share preferences does not contain this key value pair", Toast.LENGTH_SHORT).show();
}
These conditions are use yo avoid the null point execption

Related

seekbar saved but not text

im trying to create an activity consist of seekbar, sharedpreferences and text.
just simple idea as i am still learning about this.
the idea was to create a seekbar, progressing with text size, including the sharedpreferences to save the current size.
however, the only saved was the seekbar progress, not the text. can anyone help, or giving ideas to me as im still new to this.
here the java
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.SeekBar;
import android.widget.TextView;
import com.google.android.material.navigation.NavigationView;
public class fontsize extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
int textSize = 30;
TextView textViewFont, textViewSize;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
//variablesmenudrawer
DrawerLayout drawerLayout;
NavigationView navigationView;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fontsize);
sharedPreferences = getSharedPreferences("fontresize", MODE_PRIVATE);
editor = sharedPreferences.edit();
int progress = sharedPreferences.getInt("progress", 0);
//definingtextview
textViewFont = findViewById(R.id.textViewFont);
textViewSize = findViewById(R.id.textViewSize);
//seekbar
SeekBar seekBar = findViewById(R.id.seekbar);
textViewFont.setTextSize(textSize); // size 30sp
textViewSize.setText(seekBar.getProgress() + "/" + seekBar.getMax()); // 0/30
seekBar.setProgress(progress);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressNew = 0;
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
textSize = textSize + (progress - progressNew);
progressNew = progress;
textViewFont.setTextSize(textSize);
editor.putInt("progress", progress);
editor.apply();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
//definingmenudrawer
drawerLayout = findViewById(R.id.drawer_layout4);
navigationView = findViewById(R.id.nav_view4);
toolbar = findViewById(R.id.toolbar4);
//toolbar
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
//toolbar.setNavigationIcon(R.drawable.ic_toolbar);
toolbar.setTitle("");
toolbar.setSubtitle("");
//toolbar.setLogo(R.drawable.ic_toolbar);
toolbar.setNavigationIcon(R.drawable.ic_baseline_dehaze_24);
//navdrawermenu
navigationView.bringToFront();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.nav_home);
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
}
else {
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_home:
Intent intent = new Intent(fontsize.this, home.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
case R.id.nav_fontsize:
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}
thank you very much.
I managed to find an answer. I know it just simple newbies error. so here it is
textViewFont.setTextSize(textSize); // size 30sp
in this line , I must add the getProgress in order to include the settextsize value in the progress.
so it must be
textViewFont.setTextSize(textSize+seekBar.getProgress()); // size 30sp

No view found for id 0x7f0a01a2...for fragment

I have an Activity A which implements NavigationView.OnNavigationItemSelectedListener that connects it to fragments 1, 2, 3. Fragment 1 has a viewPager and a pagerAdapter which connects it to fragment 4, 5, 6.
I run this and I get an error when Activity A runs fragment 1, it says "No view found for id...for fragment...". I looked it up, but cant figure it out. Can someone tell me how to solve this? Thanks
Fragment 1 is TimeFragment
Activity A is AdminAddNewMerchantActivity
pagerAdapter is DetailsPageAdapter
Below I have the code:
TimeFragment.java
package com.vision.lateoclocktt.ui.time;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import androidx.fragment.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.google.android.material.tabs.TabItem;
import com.google.android.material.tabs.TabLayout;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.StorageTask;
import com.vision.lateoclocktt.DetailsPageAdapter;
import com.vision.lateoclocktt.R;
import com.vision.lateoclocktt.ui.orders.OrdersAdminViewModel;
/**
* A simple {#link Fragment} subclass.
* Use the {#link TimeFragment} factory method to
* create an instance of this fragment.
*/
public class TimeFragment extends Fragment {
private Uri imageUri, imageUri2;
private static final int GalleryPick = 1, GalleryPickBanner = 2;
private StorageTask uploadTask, uploadTask2;
private OrdersAdminViewModel ordersAdminViewModel;
private RecyclerView orderList;
private DatabaseReference ordersRef;
private String downloadImageUrl, downloadImageUrl2;
private TabLayout tabLayout;
private TabItem tabDetails, tabAddress, tabPrice, tabStart, tabEnd;
private ViewPager viewPager;
DetailsPageAdapter pagerAdapter;
private ImageView inputImage, inputBanner;
private StorageReference storageBannerPictureRef,merchantImageReference;
Button saveMechantAddress;
private String myUrl = "";
private RelativeLayout rLayout;
private String currentFragment, currentNavFragment;
private final String CURRENT_FRAG = "current fragment";
private String NAV_FRAG = "navigation fragment";
SharedPreferences sharedPreferences;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root = inflater.inflate(R.layout.fragment_time, container, false);
tabLayout = root.findViewById(R.id.timeTabLayout);
tabDetails = root.findViewById(R.id.t_merchant_details);
tabAddress = root.findViewById(R.id.t_merchant_address);
tabPrice = root.findViewById(R.id.t_merchant_price);
tabStart = root.findViewById(R.id.t_start_time);
viewPager = root.findViewById(R.id.time_viewPager);
pagerAdapter = new DetailsPageAdapter(getChildFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(pagerAdapter);
//viewPager.onRestoreInstanceState(new );
storageBannerPictureRef = FirebaseStorage.getInstance().getReference().child("Merchant Banner Images");
merchantImageReference = FirebaseStorage.getInstance().getReference().child("Mechant Images");
currentNavFragment = "Details";
sharedPreferences = getActivity().getSharedPreferences("root_preferences", Context.MODE_PRIVATE);
//SharedPreferences sharedPreferences = getSharedPreferences("root_preferences", MODE_PRIVATE);
currentFragment = sharedPreferences.getString(CURRENT_FRAG, "time");
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(NAV_FRAG, currentNavFragment);
editor.commit();
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("tab", tab.getPosition());
editor.commit();
viewPager.setCurrentItem(tab.getPosition());
if(tab.getPosition() == 0) {
pagerAdapter.notifyDataSetChanged();
}
else if(tab.getPosition() == 1)
{
pagerAdapter.notifyDataSetChanged();
}
else if(tab.getPosition() == 2)
{
pagerAdapter.notifyDataSetChanged();
}
else if(tab.getPosition() == 3)
{
pagerAdapter.notifyDataSetChanged();
}
else if(tab.getPosition() == 4)
{
pagerAdapter.notifyDataSetChanged();
}
else if(tab.getPosition() == 5)
{
pagerAdapter.notifyDataSetChanged();
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
//tabLayout.setTabTextColors(Color.parseColor("#000000"), Color.parseColor("#ffffff"));
return root;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if(currentFragment.equals("Find Food Admin"))
{
TabLayout.Tab tab1 = tabLayout.getTabAt(sharedPreferences.getInt("tab",0));
tab1.select();
}
else if(currentFragment.equals("Maps Merchant"))
{
TabLayout.Tab tab1 = tabLayout.getTabAt(sharedPreferences.getInt("tab",0));
tab1.select();
}
else if(currentFragment.equals("Price"))
{
TabLayout.Tab tab1 = tabLayout.getTabAt(sharedPreferences.getInt("tab",0));
tab1.select();
}
else if(currentFragment.equals("Start"))
{
TabLayout.Tab tab1 = tabLayout.getTabAt(sharedPreferences.getInt("tab",0));
tab1.select();
}
else if(currentFragment.equals("Options"))
{
TabLayout.Tab tab1 = tabLayout.getTabAt(sharedPreferences.getInt("tab",0));
tab1.select();
}
else if(currentFragment.equals("Brief"))
{
TabLayout.Tab tab1 = tabLayout.getTabAt(sharedPreferences.getInt("tab",0));
tab1.select();
}
}
private void openGallery(int galleryNumber) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("`image/*");
//startActivityForResult(Intent.createChooser(galleryIntent, "Select Picture"), galleryNumber);
startActivityForResult(galleryIntent, galleryNumber);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onResume() {
super.onResume();
}
}
AdminAddNewMerchantActivity.java
package com.vision.lateoclocktt.Admin;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
//import android.support.v7.widget.Toolbar;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationView;
import com.vision.lateoclocktt.Buyers.MainActivity;
import com.vision.lateoclocktt.Prevalent.Prevalent;
import com.vision.lateoclocktt.R;
import com.vision.lateoclocktt.Sellers.SettingsMerchantActivity;
import com.vision.lateoclocktt.ui.cart.CartFragment;
import com.vision.lateoclocktt.ui.favorites.FavoritesFragment;
import com.vision.lateoclocktt.ui.findFood.FindFoodFragment;
import com.vision.lateoclocktt.ui.map.MapsUserFragment;
import com.vision.lateoclocktt.ui.orders.OrdersAdminFragment;
import com.vision.lateoclocktt.ui.receipts.ReceiptsFragment;
import com.vision.lateoclocktt.ui.time.TimeFragment;
import com.vision.lateoclocktt.ui.userview.UserViewFragment;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import io.paperdb.Paper;
public class AdminAddNewMerchantActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawer;
NavigationView navigationView;
private String currentActivity;
private final String CURRENT_ACT = "current activity";
private String NAV_FRAG = "navigation fragment";
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_add_new_merchant);
currentActivity = "adminaddnewmerchant";
sharedPreferences = getSharedPreferences("root_preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(CURRENT_ACT, currentActivity);
editor.commit();
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar_admin);
setSupportActionBar(toolbar);
toolbar.setTitle("Home");
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_baseline_menu_24));
drawer = findViewById(R.id.container_admin);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = findViewById(R.id.nav_view_admin);
BottomNavigationView navView = findViewById(R.id.bot_nav_view_admin);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_merchant_details_admin, R.id.navigation_user_view, R.id.navigation_orders_admin)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_admin_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navView, navController);
View headerView = navigationView.getHeaderView(0);
TextView name = (TextView)headerView.findViewById(R.id.username);
TextView email = headerView.findViewById(R.id.email);
name.setText(sharedPreferences.getString("name", ""));
email.setText(sharedPreferences.getString("email", ""));
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
switch (item.getItemId()) {
case R.id.navigation_settings:
Intent settingsIntent = new Intent(AdminAddNewMerchantActivity.this, SettingsMerchantActivity.class);
startActivity(settingsIntent);
break;
case R.id.navigation_logout:
currentActivity = "main";
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.putString(CURRENT_ACT,currentActivity);
editor.commit();
Intent logoutIntent = new Intent(AdminAddNewMerchantActivity.this, MainActivity.class);
Paper.book().write(Prevalent.RememberMeMerchant, "false");
Paper.book().write(Prevalent.emailKey, "UserEmail");
Paper.book().write(Prevalent.passwordKey, "UserPassword");
logoutIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//logoutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(logoutIntent);
finish();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
if(!sharedPreferences.getString(NAV_FRAG, "").equals("")){
if(sharedPreferences.getString(NAV_FRAG, "").equals("Details"))
{
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, new TimeFragment()).commit();
navView.setSelectedItemId(R.id.navigation_merchant_details_admin);
}
else if(sharedPreferences.getString(NAV_FRAG, "").equals("Userview"))
{
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, new UserViewFragment()).commit();
navView.setSelectedItemId(R.id.navigation_user_view);
}
else if(sharedPreferences.getString(NAV_FRAG, "").equals("Orders"))
{
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, new OrdersAdminFragment()).commit();
navView.setSelectedItemId(R.id.navigation_orders_admin);
}
}
}
#Override
public void onBackPressed()
{
if(drawer.isDrawerOpen(GravityCompat.START))
{
drawer.closeDrawer(GravityCompat.START);
}
else{
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_merchant_details_admin:
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_admin_fragment, new TimeFragment()).commit();
break;
case R.id.navigation_user_view:
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_admin_fragment, new UserViewFragment()).commit();
break;
case R.id.navigation_orders_admin:
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_admin_fragment, new OrdersAdminFragment()).commit();
break;
}
return true;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
}
}
DetailsPageAdapter.java
package com.vision.lateoclocktt;
import com.vision.lateoclocktt.ui.brief.BriefFragment;
import com.vision.lateoclocktt.ui.findFood.FindFoodAdminFragment;
import com.vision.lateoclocktt.ui.map.MapsMerchantFragment;
import com.vision.lateoclocktt.ui.options.OptionsFragment;
import com.vision.lateoclocktt.ui.price.PriceFragment;
import com.vision.lateoclocktt.ui.time.StartFragment;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
public class DetailsPageAdapter extends FragmentPagerAdapter {
private int numberOfTabs;
public FragmentManager mfm;
public DetailsPageAdapter(#NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
this.mfm = fm;
this.numberOfTabs = behavior;
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new FindFoodAdminFragment();
case 1:
return new MapsMerchantFragment();
case 2:
return new PriceFragment();
case 3:
return new StartFragment();
case 4:
return new OptionsFragment();
case 5:
return new BriefFragment();
default:
return null;
}
}
#Override
public int getCount() {
return numberOfTabs;
}
#Override
public int getItemPosition(#NonNull Object object) {
return POSITION_NONE;
}
}
Errors:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.vision.lateoclocktt, PID: 4500
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.vision.lateoclocktt/com.vision.lateoclocktt.Admin.AdminAddNewMerchantActivity}: java.lang.IllegalArgumentException: No view found for id 0x7f0a01a2 (com.vision.lateoclocktt:id/nav_host_fragment) for fragment TimeFragment{fa4480} (b1d4c74f-3fd0-4e61-9d0b-89212a0bd27a) id=0x7f0a01a2}
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f0a01a2 (com.vision.lateoclocktt:id/nav_host_fragment) for fragment TimeFragment{fa4480} (b1d4c74f-3fd0-4e61-9d0b-89212a0bd27a) id=0x7f0a01a2}
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:315)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1187)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1356)
at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(FragmentManager.java:1434)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1497)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:447)
at androidx.fragment.app.FragmentManager.executeOps(FragmentManager.java:2169)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1992)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1947)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1849)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2629)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2577)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:247)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:541)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:210)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1248)
at android.app.Activity.performStart(Activity.java:6696)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2628)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
I figured it out after getting some sleep. In AdminAddNewMerchantActivity.java I changed R.id.nav_host_fragment to R.id.nav_host_admin_fragment and it worked! The view nav_host_fragment really did not exist. I copied it from another file, expected it to work and didn't read the error message properly.

seekbarpreference library com.yokkomi:seekbar-preference:1.0 return default value

Hello friends i am using seekbarpefernce library "com.yokkomi:seekbar-preference:1.0 " in my project the problem is that when i try to get value from this seekbar its always give me default value which i set in getting value from sharedperfernce please help me how to get the seekbar value when its changed here is my code geting sharedperfe value inside speakout method please look below speakout method in my code!
library link here:https://github.com/ghkim3221/SeekBarPreference
My perfernce sacreen:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<SwitchPreference
android:defaultValue="false"
android:key="autospeak"
android:title="Auto Speak"
android:summary="Turn on/off auto verse read"/>
<com.yokkomi.commons.preference.seekbar.SeekBarPreference
android:defaultValue="11"
android:dialogTitle="Verse Reading Speed"
android:key="versespeed"
android:summary="Adjust verse reading speed"
android:title="Verse Speed"
app:explain="Drag it left or right"
app:maxValue="20"
app:padding="3"/>
<com.yokkomi.commons.preference.seekbar.SeekBarPreference
android:defaultValue="8"
android:dialogTitle="Voice Picth Settings"
android:key="voicepitch"
android:summary="Adjust verse reading pitch"
android:title="Voice Pitch"
app:explain="Drag it left or right"
app:maxValue="20"
app:padding="3"/>
<SwitchPreference
android:defaultValue="false"
android:key="switchmode"
android:title="Turn on Dark Mode"
android:summary="Reading in night mode"/>
package bible.swordof.God;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.yokkomi.commons.preference.seekbar.SeekBarPreference;
import java.util.ArrayList;
import java.util.Locale;
import es.dmoral.toasty.Toasty;
public class ALLVERSE extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener,TextToSpeech.OnInitListener {
private ListView mylistview;
private ArrayList<String>versenumber;
private ArrayList<String>verselist;
private ArrayList<String>id;
private ArrayList<String>refernce;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
private int booknumber;
private int chapternumber;
private String bookname;
public int versepos;
private TextView booknametitle;
TextToSpeech textToSpeech;
private static SharedPreferences sharedPreferences;
int result;
private static final int MY_DATA_CHECK_CODE = 0;
private FullverseAdopter fullverseAdopter;
RelativeLayout linearLayout;
#Override
protected void onDestroy() {
if (textToSpeech!= null) {
textToSpeech.stop();
textToSpeech.shutdown();
}
super.onDestroy();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_allverse);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
booknametitle = findViewById(R.id.bookname);
linearLayout=findViewById(R.id.color);
final Intent mIntent = getIntent();
booknumber = mIntent.getIntExtra("Boooknumber", 0);
chapternumber = mIntent.getIntExtra("Chapternumber", 0);
bookname = mIntent.getStringExtra("Bookname");
versepos=mIntent.getIntExtra("versenumber",1);
SharedPreferences sharedPreferences=this.getSharedPreferences("DATA",MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putInt("versenumber",versepos);
editor.commit();
booknametitle.setText(bookname.toString() + " " + chapternumber);
setSupportActionBar(toolbar);
toolbar.setTitle("ALL VERSE");
textToSpeech=new TextToSpeech(this,this);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
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);
setData();
mylistview = findViewById(R.id.mylistview);
BaseAdapter baseAdapter = new BaseAdopter(this, versenumber, id, verselist, refernce);
mylistview.setAdapter(baseAdapter);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if(DefaultSettings.autospeak(ALLVERSE.this)){
speakOut(verselist.get(versepos-1));
}
//speak after 1000ms
}
}, 1000);
mylistview.setSelection(Integer.valueOf(versepos)-1);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
private void setData() {
versenumber=new ArrayList<>();
verselist=new ArrayList<>();
refernce=new ArrayList<>();
id=new ArrayList<>();
mDBHelper = new DatabaseHelper(this);
mDb = mDBHelper.getReadableDatabase();
Cursor cursor = mDb.rawQuery("SELECT id, v, t from t_kjv where b="+booknumber+" AND c="+chapternumber+";", new String[]{});
if(cursor!=null && cursor.getCount() > 0)
{ if (cursor.moveToFirst())
{
do {
id.add(cursor.getString(0));
versenumber.add(cursor.getString(1));
verselist.add(cursor.getString(2));
refernce.add(bookname+" "+chapternumber);
}
while (cursor.moveToNext());
}
}
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Fragment fragment;
int id = item.getItemId();
if (id == R.id.home) {
Intent intent=new Intent(this,MainActivity.class);
startActivity(intent);
} else if (id == R.id.favoruite)
{ Intent intent=new Intent(this,Favourite.class);
startActivity(intent);
} else if (id == R.id.setting) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
// here is getingperfernces always return 11 which i set as default value
private void speakOut(String text) {
sharedPreferences=getSharedPreferences("versespeed",MODE_PRIVATE);
float speed=(float)sharedPreferences.getInt("versespeed",11)/50;
if(speed<0.1)speed=0.1f;
/* float pitch=(float)sharedPreferences.getInt("voicepitch",11)/50;
if(pitch<0.1)pitch=0.1f;
textToSpeech.setPitch(pitch);*/
textToSpeech.setSpeechRate(speed);
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
Toast.makeText(this, ""+speed, Toast.LENGTH_SHORT).show();
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.US);
// tts.setPitch(5); // set pitch level
// tts.setSpeechRate(2); // set speech speed rate
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
}
} else {
Log.e("TTS", "Initilization Failed");
}
}
}
I'm the developer of SeekBarPreference.
The SeekBarPreference is currently inoperative and not maintained.
I'm really sorry, and you'd better find another library.

.setText using SharedPreferences doesnt work

I came here with another problem, this time it concerns Android app.
I've made an app with Login activity (no NavigationView) which move us after login to Home activity where is NavigationView. User data is saved in SharedPreferences, I'm using Constants class.
My problem is that I can't setText on Home activity using SharedPreferences, but it working on Login activity (email address is inserted in EditText).
Here is my code:
Login.java
package com.example.appname;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.example.appname.models.ServerRequest;
import com.example.appname.models.ServerResponse;
import com.example.appname.models.User;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class Login extends AppCompatActivity {
private CoordinatorLayout coordinatorLayout;
private AppCompatButton btn_login;
private EditText et_email,et_password;
private TextView tv_register;
private ProgressBar progress;
private SharedPreferences pref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
pref = getPreferences(0);
btn_login = (AppCompatButton)findViewById(R.id.btn_login);
tv_register = (TextView)findViewById(R.id.tv_register);
et_email = (EditText)findViewById(R.id.et_email);
et_email.setText(pref.getString(Constants.EMAIL, ""));
et_password = (EditText)findViewById(R.id.et_password);
progress = (ProgressBar)findViewById(R.id.progress);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = et_email.getText().toString();
String password = et_password.getText().toString();
if(!email.isEmpty() && !password.isEmpty()) {
progress.setVisibility(View.VISIBLE);
loginProcess(email,password);
} else {
Snackbar snackbar = Snackbar
.make(coordinatorLayout, R.string.empty_fields, Snackbar.LENGTH_LONG);
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.GREEN);
snackbar.show();
}
}
});
tv_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), Register.class);
startActivity(intent);
finish();
}
});
}
private void loginProcess(String email,String password){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterface requestInterface = retrofit.create(RequestInterface.class);
User user = new User();
user.setEmail(email);
user.setPassword(password);
ServerRequest request = new ServerRequest();
request.setOperation(Constants.LOGIN_OPERATION);
request.setUser(user);
Call<ServerResponse> response = requestInterface.operation(request);
response.enqueue(new Callback<ServerResponse>() {
#Override
public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {
ServerResponse resp = response.body();
Snackbar.make(coordinatorLayout, resp.getMessage(), Snackbar.LENGTH_LONG).show();
if(resp.getResult().equals(Constants.SUCCESS)){
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean(Constants.IS_LOGGED_IN,true);
editor.putString(Constants.EMAIL,resp.getUser().getEmail());
editor.putString(Constants.NAME,resp.getUser().getName());
editor.putString(Constants.UNIQUE_ID,resp.getUser().getUnique_id());
editor.putString(Constants.POINTS,resp.getUser().getPoints());
editor.apply();
goToHome();
}
progress.setVisibility(View.INVISIBLE);
}
#Override
public void onFailure(Call<ServerResponse> call, Throwable t) {
progress.setVisibility(View.INVISIBLE);
Log.d(Constants.TAG,"failed");
Snackbar.make(coordinatorLayout, t.getLocalizedMessage(), Snackbar.LENGTH_LONG).show();
}
});
}
private void goToHome(){
Intent intent = new Intent(getApplicationContext(), Home.class);
startActivity(intent);
}
}
Home.java
package com.examle.appname;
import android.app.ActivityOptions;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.internal.NavigationMenuPresenter;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.View;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class Home extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawerLayout;
private Toolbar toolbar;
private SharedPreferences pref;
private TextView tvname, tvpoints;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
pref = getPreferences(0);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tvname = (TextView)findViewById(R.id.tv_name);
tvpoints = (TextView)findViewById(R.id.tv_points);
tvname.setText(pref.getString(Constants.NAME, ""));
tvpoints.setText(pref.getString(Constants.POINTS, "") +R.string.act_points);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.drawer_open, R.string.drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nvView);
navigationView.setNavigationItemSelectedListener((NavigationView.OnNavigationItemSelectedListener) this);
View headerView = navigationView.getHeaderView(0);
TextView tvemail = (TextView) headerView.findViewById(R.id.tv_email);
tvemail.setText(pref.getString(Constants.EMAIL, ""));
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
public boolean onNavigationItemSelected(MenuItem item) {
int id=item.getItemId();
switch (id){
case R.id.navigation_home:
Intent h= new Intent(Home.this,Home.class);
startActivity(h);
break;
case R.id.navigation_showall:
Intent i= new Intent(Home.this,ShowAllUsers.class);
startActivity(i);
break;
case R.id.navigation_about:
Intent g= new Intent(Home.this,About.class);
startActivity(g);
break;
case R.id.navigation_settings:
Intent s= new Intent(Home.this,AccountSettings.class);
startActivity(s);
case R.id.navigation_support:
Intent t= new Intent(Home.this,Support.class);
startActivity(t);
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Try this way
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (sharedpreferences.contains(Constants.NAME))
{
tvname.setText(sharedpreferences.getString(Constants.NAME, ""));
}
Use getSharedPreferences instead of this getPreferences
Because you are using two different instance of the SharedPreference in different activity use single instance. for more info check - https://stackoverflow.com/a/11567825/3912847

Using Nav Drawer Settings in different Activity

So I am creating an app that I want the user to be able to decide if they want to use WiFi or 4G to fetch the data after logging in (I will make another question about implementing the decision later, unless anyone wants to add that here too). So currently I have a MainActivity.java that will be handling the logging in (which I have yet to implement) and I have a NavDrawerActivity.java for the Navigation Drawer. Now obviously once I do the "log in" it goes to the Nav Drawer. However, I want the user to be able to choose whether or not to use Wifi or Data before logging in as well as being able to choose once they log in. So I guess this is a two part question, how would you implement this as well as, is it a good idea to put that in the login screen? Or should I just default it to always use wifi unless they change it and if I detect WiFi isn't enabled, have them enable it?
MainActivity.java code
package com.example.jamessingleton.chffrapi;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
EditText emailText;
TextView responseView;
ProgressBar progressBar;
static final String API_KEY = "USE_YOUR_OWN_API_KEY";
static final String API_URL = "https://api.fullcontact.com/v2/person.json?";
static final String ClientId= "";
static final String ClientSecret = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
responseView = (TextView) findViewById(R.id.responseView);
emailText = (EditText) findViewById(R.id.emailText);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
final Context context = this;
Button queryButton = (Button) findViewById(R.id.queryButton);
queryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new RetrieveFeedTask().execute();
Intent intent = new Intent(context, NavDrawerActivity.class);
startActivity(intent);
}
});
}
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
private Exception exception;
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
responseView.setText("");
}
protected String doInBackground(Void... urls) {
String email = emailText.getText().toString();
// Do some validation here
try {
URL url = new URL(API_URL + "email=" + email + "&apiKey=" + API_KEY);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(response);
// TODO: check this.exception
// TODO: do something with the feed
// try {
// JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
// String requestID = object.getString("requestId");
// int likelihood = object.getInt("likelihood");
// JSONArray photos = object.getJSONArray("photos");
// .
// .
// .
// .
// } catch (JSONException e) {
// e.printStackTrace();
// }
}
}
}
NavDrawerActivity.java code
package com.example.jamessingleton.chffrapi;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RadioButton;
import android.widget.RadioGroup;
public class NavDrawerActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//.setAction("Action", null).show();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
});
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.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.nav_drawer, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
FragmentManager fragmentSettingsManager = getFragmentManager();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
fragmentSettingsManager.beginTransaction().replace(R.id.content_frame, new SettingsFragment()).commit();
setTitle(R.string.action_settings);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setVisibility(View.GONE);
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.nav_first_layout) {
fragmentManager.beginTransaction().replace(R.id.content_frame, new FirstFragment()).commit();
setTitle(R.string.speed_graph);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setVisibility(View.VISIBLE);
} else if (id == R.id.nav_second_layout) {
fragmentManager.beginTransaction().replace(R.id.content_frame, new SecondFragment()).commit();
setTitle(R.string.drive_player);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setVisibility(View.VISIBLE);
} else if (id == R.id.nav_third_layout) {
fragmentManager.beginTransaction().replace(R.id.content_frame, new ThirdFragment()).commit();
setTitle(R.string.google_maps);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setVisibility(View.VISIBLE);
} else if (id == R.id.nav_share) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Go Check Out All Driving Data in the Play Store!");
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Let me know if there is anything else you guys need and thank you guys for all the help :)
Here is the WifivsDataDialog code
package com.example.jamessingleton.chffrapi;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
/**
* Created by James Singleton on 8/9/2016.
*/
public class WifivsDataDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_box)
.setPositiveButton(R.string.WiFi, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// FIRE ZE MISSILES!
}
})
.setNegativeButton(R.string.Cell_Data, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
It's not entirely clear what you would like to achieve.
Is it mandatory to fetch the data? What if the user has both Wi-Fi and mobile network disabled on the device? What if they choose to use Wi-Fi, but have only mobile network enabled on the device?
I would create a Dialog at the start of the app that explains this stuff and let the user choose if they would like to allow fetching data on mobile network, or Wi-Fi only, with a "Do not show this dialog again" CheckBox.
If the user chooses with the CheckBox checked, then that will be the default behaviour on further launches (and can be changed in the Preferences/Settings).
You could show the Dialog from the onCreate() of your login Activity.
For example:
connection_dialog.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Would you like to allow fetching data on mobile network?"/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Yes"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No, allow Wi-Fi only"/>
</RadioGroup>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:text="OK"/>
</LinearLayout>
ConnectionDialogFragment.java:
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ConnectionDialogFragment extends DialogFragment {
public ConnectionDialogFragment() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.connection_dialog, container, false);
// set up your View here
return view;
}
}
And in your Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity_layout);
// ...
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(prefs.getBoolean("show_dialog", true)) {
showDialog();
}
}
private void showDialog() {
ConnectionDialogFragment dialog = new ConnectionDialogFragment();
dialog.show(getSupportFragmentManager(), "connection_dialog");
}
Check out the developer's guide on Dialogs.
When the user has chosen whether they want to use Wi-Fi only, or allow mobile network also, you could check the available connection with something like this:
// this method will return either
// ConnectivityManager.TYPE_MOBILE
// or
// ConnectivityManager.TYPE_WIFI
// or -1 (if no connection is available)
private int checkAvailableConnectionType() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
int type = activeNetwork.getType();
if(activeNetwork.isConnected() && (type == ConnectivityManager.TYPE_MOBILE ||
type == ConnectivityManager.TYPE_WIFI)) {
return type;
}
return -1;
}
And do your stuff according to the user's choice and the currently active connection (advise the user to turn on Wi-Fi, for example).

Categories

Resources