Access EditText Preference dialog box - android

I'm confused on where I should I place this code using sharedPreferences. I'm trying to find out how the dialog box gets created. I want to access the EditTextPreference dialog box and once the user inputs their name I want to save it to a file using this code below
SharedPreferences mySharedPreferences = getSharedPreferences("MyData",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putString("user_name",userName.getText().toString());
editor.commit();
Here is my main activity
public class MainActivity extends AppCompatActivity {
EditText userName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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();
}
});
Button myButton = (Button) findViewById(R.id.show_button_id);
myButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent i = new Intent(MainActivity.this,UserPreferenceActivity.class);
startActivity(i);
//return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is my UserPreferenceFragment java class
public class UserPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//LOAD THE PRFERENCE FROM AN XML RESOURCE FILE
addPreferencesFromResource(R.xml.preferences);
}//ends OnCreate
}
here is my UserPreferenceActivity java class
public class UserPreferenceActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
setContentView(R.layout.content_main);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.
*/
getFragmentManager().beginTransaction()
.replace(android.R.id.content,new UserPreferenceFragment())
.commit();
}
here is my preferences xml file
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="show_background_pic"
android:title="#string/show_background_pic_title"
android:summary="#string/show_background_pic_summary"
android:defaultValue="true">
</CheckBoxPreference>
<EditTextPreference
android:key="user_name"
android:title="#string/user_acct_name_title"
android:summary="#string/user_acct_name_summary"
android:defaultValue="NONAME">
</EditTextPreference>
Lastly my main content
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/Shared_preferences_label"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/show_button_label"
android:id="#+id/show_button_id"
android:layout_below="#+id/textView"
android:layout_alignParentStart="true" />
</RelativeLayout>

Using setOnPreferenceChangeListener method of Preference class and Preference.OnPreferenceChangeListener interface. something like this:
pref_general.xml:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference
android:capitalize="words"
android:defaultValue="#string/pref_default_display_name"
android:inputType="textCapWords"
android:key="#string/key_example_text"
android:maxLines="1"
android:selectAllOnFocus="true"
android:singleLine="true"
android:title="#string/pref_title_display_name" />
</PreferenceScreen>
SettingPreferenceFragment.java:
public class SettingPreferenceFragment extends PreferenceFragment {
public final String TAG = "SettingActivity";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
EditTextPreference location = (EditTextPreference) findPreference("example_text");
location.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String locstr = newValue.toString();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("example_text", locstr);
editor.commit();
Log.e(TAG, "" + locstr);
return true;
}
});
return view;
}
}

Related

NullPointerException: Attempt to invoke virtual method 'void SettingsFragment.loadFromSharedPreferences()' on a null object reference

I try to invoke loadFromSharedPreferences() function from SettingsFragment in MainActivity with fragment variable, but fragment becomes null when I instance it. I tried findFragmentById() and findFragmentByTag() methodes and neither of them worked. Is there another way to do it? Why findFragmentById() methode won't work? I also tried to change FragmentLayout to ConstraintLayout and didn't work.
MainActivity class:
public class MainActivity extends AppCompatActivity {
FragmentManager manager;
SettingsFragment fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//loadFromSharedPreferences()
manager = getSupportFragmentManager();
fragment = (SettingsFragment) manager.findFragmentById(R.id.settingsFragment);
fragment.loadFromSharedPreferences();
if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
setTheme(R.style.AppThemeDark);
} else {
setTheme(R.style.AppTheme);
}
setContentView(R.layout.activity_main);
final DrawerLayout drawerLayout = findViewById(R.id.drawerLayout);
findViewById(R.id.imageMenu).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view){
drawerLayout.openDrawer(GravityCompat.START);
}
});
NavigationView navigationView = findViewById(R.id.navigationView);
navigationView.setItemIconTintList(null);
NavController navController = Navigation.findNavController(this, R.id.navHostFragment);
NavigationUI.setupWithNavController(navigationView, navController);
final TextView textTitle = findViewById(R.id.textTitle);
navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
#Override
public void onDestinationChanged(#NonNull NavController controller, #NonNull NavDestination destination, #Nullable Bundle arguments) {
textTitle.setText(destination.getLabel());
}
});
}
//AppCompatDelegate.setDefaultNightMode will cause your activities to reload automatically
public void ToggleTheme( boolean isChecked ){
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
else{
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
}
SettingsFragment class:
public class SettingsFragment extends Fragment {
public SettingsFragment() {
// Required empty public constructor
}
public static final String SAVE_SWITCH = "saveSwitch";
public static final String IS_CHECKED = "isChecked";
Switch switchTheme;
SharedPreferences sharedPreferences;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_settings, container, false);
switchTheme = (Switch) view.findViewById(R.id.switchMode);
sharedPreferences = getActivity().getApplicationContext()
.getSharedPreferences( SAVE_SWITCH , Context.MODE_PRIVATE);
// loadFromSharedPreferences();
switchTheme.setChecked(sharedPreferences.getBoolean(IS_CHECKED,false));
switchTheme.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
SharedPreferences.Editor editor = sharedPreferences.edit();
//Scriere in fis SharedPreferences
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
editor.putBoolean(IS_CHECKED,true);
switchTheme.setChecked(true);
editor.apply();
((MainActivity) getActivity()).ToggleTheme(isChecked);
}
else{
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
editor.putBoolean(IS_CHECKED, false);
switchTheme.setChecked(false);
editor.apply();
((MainActivity) getActivity()).ToggleTheme(isChecked);
}
}
});
return view;
}
//Citire din fis SharedPreferences
public void loadFromSharedPreferences() {
boolean ischecked = sharedPreferences.getBoolean(IS_CHECKED, false);
switchTheme.setChecked(ischecked);
((MainActivity) getActivity()).ToggleTheme(ischecked);
}
}
SettingdFragment XML:
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/settingsFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SettingsFragment"
tools:ignore="MissingClass">
<!-- android:tag="settingsTag"-->
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/textView6"
android:layout_width="113dp"
android:layout_height="49dp"
android:layout_gravity="top"
android:layout_marginStart="131dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="137dp"
android:text="#string/settings"
android:textSize="28sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="#+id/tvDarkSide"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/tvDarkSide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:text="#string/light_dark_mode"
android:textColor="#F10000"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="#+id/switchMode"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/switchMode" />
<Switch
android:id="#+id/switchMode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="110dp"
android:layout_marginEnd="23dp"
android:text="Switch"
android:textSize="18sp"
android:checked="false"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/tvLanguage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="28dp"
android:layout_marginTop="44dp"
android:text="#string/select_the_language"
android:textColor="#F10000"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tvDarkSide" />
<Spinner
android:id="#+id/spinnerSelectLanguage"
android:layout_width="370dp"
android:layout_height="22dp"
android:background="?attr/colorBackground"
android:text="Language"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.682"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView6"
app:layout_constraintVertical_bias="0.248" />
</androidx.constraintlayout.widget.ConstraintLayout>
There are several issues with your code.
First of all, the id R.id.settingsFragment does not refer to the fragment itself, but rather the ConstraintLayout that is part of the fragment's layout.
Secondly, you have not created the fragment at all, nor did you add it to your activity, naturally the supportFragmentManager would return null when you attempt to find your fragment.
UPDATE
Your sharedPreferences is null when you call fragment.loadFromSharedPreferences(), that is because the property preferences is initialized in your fragment's onCreateView() function. fragment = new SettingsFragment(); just creates the fragment's instance, it takes time for the fragment's view to finish inflating. Access the preferences only when you are sure it has been initialized. Furthermore, you set your switch's check state on too many (wrong) occasions, which caused looping of the app. The check should be set programatically only once at the creation of the fragment's view, then the check state is changed by user interaction, no reason to change it programatically anywhere else. For your specific code to work, do:
public class SettingsFragment extends Fragment {
public SettingsFragment() {
// Required empty public constructor
}
public static final String SAVE_SWITCH = "saveSwitch";
public static final String IS_CHECKED = "isChecked";
Switch switchTheme;
SharedPreferences sharedPreferences;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_settings, container, false);
switchTheme = (Switch) view.findViewById(R.id.switchMode);
sharedPreferences = getActivity().getSharedPreferences( SAVE_SWITCH , Context.MODE_PRIVATE);
boolean initChecked = sharedPreferences.getBoolean(IS_CHECKED,false);
switchTheme.setChecked(initChecked);
// use clickListener instead. As the activity and the fragment is recreated when the theme is switched,
// the isCheckedListener was called every time as you call switchTheme.setChecked() above. Use clickListener
// to react to user interction only.
switchTheme.setOnClickListener(new View.OnClickListener() {
SharedPreferences.Editor editor = sharedPreferences.edit();
#Override
public void onClick(View view) {
if (switchTheme.isChecked()) {
editor.putBoolean(IS_CHECKED,true);
// editor.apply() may have a delay, editor.commit() saves the changes immediately
editor.commit();
((MainActivity) getActivity()).toggleTheme(true);
}
else{
editor.putBoolean(IS_CHECKED, false);
editor.commit();
((MainActivity) getActivity()).toggleTheme(false);
}
}
});
return view;
}
#Override
public void onDestroyView() {
switchTheme.setOnCheckedChangeListener(null);
super.onDestroyView();
}
// here `onCreateView` has finished, i.e. preferences has been initialized and we can safely access it.
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
boolean isChecked = sharedPreferences.getBoolean(IS_CHECKED, false);
// Then we tell the activity about this event.
((MainActivity) getActivity()).onSettingsFragmentViewCreated(isChecked);
}
}
And for your activity:
...
import android.util.Log;
public class MainActivity extends AppCompatActivity {
FragmentManager manager;
SettingsFragment fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.AppTheme);
// inflate the activity's view first
setContentView(R.layout.activity_main);
// refer to this activity's fragment manager
manager = getSupportFragmentManager();
// create the fragment first
fragment = new SettingsFragment();
// attach it to this activity's default fragment container using the fragment manager
manager.beginTransaction().add(android.R.id.content, fragment, "SettingsFragment").commit();
}
public void onSettingsFragmentViewCreated(Boolean ischecked) {
// once the preferences are created, you can access them anywhere in the app using the corresponding name
// SharedPreferences sharedPreferences = getSharedPreferences( SAVE_SWITCH , Context.MODE_PRIVATE);
// but in our case we don't need the preferences itself
toggleTheme(ischecked);
}
public void toggleTheme(boolean isChecked ){
// improve conditions to avoid setting the same theme
if (isChecked && AppCompatDelegate.getDefaultNightMode() != AppCompatDelegate.MODE_NIGHT_YES) {
Log.d("AAAA", "switched to MODE_NIGHT_YES");
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
else if (!isChecked && AppCompatDelegate.getDefaultNightMode() != AppCompatDelegate.MODE_NIGHT_NO) {
Log.d("AAAA", "switched to MODE_NIGHT_NO");
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
}

Load Preferences Settings in Swipable Tabs with Fragment

I have searched the web but didnt find any proper solution.
I am trying to load some preference Settings in Tab Fragments.
In the first Image, When I use menu Inflator, I get those 3 dotted buttons, I dont need those, insted I want the menu to load in my Tab Fragment.
Below is the code of my
SettingPrefActivity.java
public class SettingsPrefActivity extends AppPreferenceActivity {
private static final String TAG = SettingsPrefActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// load settings fragment
getFragmentManager().beginTransaction().replace(android.R.id.content, new MainPreferenceFragment()).commit();
}
public static class MainPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_main);
// gallery EditText change listener
bindPreferenceSummaryToValue(findPreference(getString(R.string.key_gallery_name)));
// notification preference change listener
bindPreferenceSummaryToValue(findPreference(getString(R.string.key_notifications_new_message_ringtone)));
// feedback preference click listener
Preference myPref = findPreference(getString(R.string.key_send_feedback));
myPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
sendFeedback(getActivity());
return true;
}
});
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
private static void bindPreferenceSummaryToValue(Preference preference) {
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
/**
* A preference value change listener that updates the preference's summary
* to reflect its new value.
*/
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String stringValue = newValue.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
} else if (preference instanceof RingtonePreference) {
// For ringtone preferences, look up the correct display value
// using RingtoneManager.
if (TextUtils.isEmpty(stringValue)) {
// Empty values correspond to 'silent' (no ringtone).
preference.setSummary(R.string.pref_ringtone_silent);
} else {
Ringtone ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue));
if (ringtone == null) {
// Clear the summary if there was a lookup error.
preference.setSummary(R.string.summary_choose_ringtone);
} else {
// Set the summary to reflect the new ringtone display
// name.
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}
} else if (preference instanceof EditTextPreference) {
if (preference.getKey().equals("key_gallery_name")) {
// update the changed gallery name to summary filed
preference.setSummary(stringValue);
}
} else {
preference.setSummary(stringValue);
}
return true;
}
};
/**
* Email client intent to send support mail
* Appends the necessary device information to email body
* useful when providing support
*/
public static void sendFeedback(Context context) {
String body = null;
try {
body = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
body = "\n\n-----------------------------\nPlease don't remove this information\n Device OS: Android \n Device OS version: " +
Build.VERSION.RELEASE + "\n App Version: " + body + "\n Device Brand: " + Build.BRAND +
"\n Device Model: " + Build.MODEL + "\n Device Manufacturer: " + Build.MANUFACTURER;
} catch (PackageManager.NameNotFoundException e) {
}
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"contact#androidhive.info"});
intent.putExtra(Intent.EXTRA_SUBJECT, "Query from android app");
intent.putExtra(Intent.EXTRA_TEXT, body);
context.startActivity(Intent.createChooser(intent, context.getString(R.string.choose_email_client)));
}}
SettingsActivity.java
public class SettingsActivity extends Fragment {
private static final String TAG = SettingsPrefActivity.class.getSimpleName();
/*public SettingsActivity() {
// Required empty public constructor
}*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.setting_layout, container, false);
}
/*public boolean onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
// launch settings activity
startActivity(new Intent(SettingsActivity.this, SettingsPrefActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}*/
}
pref_main.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="General">
<EditTextPreference
android:defaultValue="#string/default_gallery_storage"
android:key="#string/key_gallery_name"
android:summary="#string/default_gallery_storage"
android:title="#string/title_gallery_storage" />
<CheckBoxPreference
android:defaultValue="true"
android:key="#string/key_upload_over_wifi"
android:summary="#string/summary_upload_over_wifi"
android:title="#string/title_auto_upload" />
<ListPreference
android:defaultValue="3"
android:dialogTitle="#string/title_upload_quality"
android:entries="#array/pref_upload_quality_entries"
android:entryValues="#array/pref_upload_quality_values"
android:key="#string/key_upload_quality"
android:summary="#string/summary_upload_video_quality"
android:title="#string/title_upload_quality" />
</PreferenceCategory>
<PreferenceCategory android:title="#string/pref_title_notifications">
<SwitchPreference
android:defaultValue="true"
android:key="#string/notifications_new_message"
android:title="#string/title_new_notification_sound" />
<RingtonePreference
android:defaultValue="content://settings/system/notification_sound"
android:dependency="notifications_new_message"
android:key="#string/key_notifications_new_message_ringtone"
android:ringtoneType="notification"
android:summary="#string/summary_choose_ringtone"
android:title="#string/pref_title_ringtone" />
<SwitchPreference
android:defaultValue="true"
android:key="#string/key_vibrate"
android:summary="#string/summary_vibrate"
android:title="#string/title_vibrate" />
</PreferenceCategory>
<PreferenceCategory android:title="#string/pref_header_about">
<Preference
android:selectable="false"
android:summary="#string/summary_about" />
<Preference
android:summary="#string/app_version"
android:title="#string/title_version" />
<Preference
android:key="#string/key_send_feedback"
android:summary="#string/summary_support"
android:title="#string/title_send_feedback" />
<!-- preference opens url in browser -->
<Preference
android:summary="#string/summary_faq"
android:title="#string/title_faq">
<intent
android:action="android.intent.action.VIEW"
android:data="#string/url_faq" />
</Preference>
<Preference android:title="#string/privacy_policy">
<intent
android:action="android.intent.action.VIEW"
android:data="#string/url_privacy" />
</Preference>
<Preference android:title="#string/title_terms">
<intent
android:action="android.intent.action.VIEW"
android:data="#string/url_terms" />
</Preference>
</PreferenceCategory>
</PreferenceScreen>
menu_main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="settings.MainActivity">
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never" />
</menu>
settings_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is Settings Page!! Coming Soon!"
android:textSize="30dp"
android:textStyle="bold"
android:layout_centerInParent="true"/>
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {R.drawable.ic_action_name};
String[] tabTitle={"","All"};
int[] unreadCount={0,5,3,0,12,3,9,0};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(1);
setupTabIcons();
}
private View prepareTabView(int pos) {
View view = getLayoutInflater().inflate(R.layout.custom_tab,null);
TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
TextView tv_count = (TextView) view.findViewById(R.id.tv_count);
tv_title.setText(tabTitle[pos]);
if(unreadCount[pos]>0)
{
tv_count.setVisibility(View.VISIBLE);
tv_count.setText(""+unreadCount[pos]);
}
else
tv_count.setVisibility(View.GONE);
return view;
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
/*TabLayout.Tab tabitem = tabLayout.newTab();
tabitem.setCustomView(prepareTabView(i));
tabLayout.addTab(tabitem);*/
for(int i = 1; i < unreadCount.length; i++)
{
/*TabLayout.Tab tabitem = tabLayout.newTab();
tabitem.setCustomView(prepareTabView(i));
tabLayout.addTab(tabitem);*/
tabLayout.getTabAt(i).setCustomView(prepareTabView(i));
}
}
private TabLayout.OnTabSelectedListener onTabSelectedListener(final
ViewPager viewPager) {
return new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
};
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new
ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new SettingsActivity(), "");
adapter.addFragment(new AllTab(), "All");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="inc.apperz.passmanager.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"
app:tabSelectedTextColor="#color/colorGreen"
app:tabTextColor="#color/colorWhite"
app:tabIndicatorColor="#color/colorWhite"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.constraint.ConstraintLayout>
Is there any possibility that I can include my main_menu.xml into my setting_layout.xml? such that it will get bind to my SettingsActivity.java?
If its possible, that would be great, but I tried that way and didn't find appropriate way to include it.
Can someone guide me to how to achieve this..
Try adding this to your fragment:
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item= menu.findItem(R.id.action_settings);
item.setVisible(false);
super.onPrepareOptionsMenu(menu);
return true;
}

How to get toolbar in my PreferenceActivity

I've been trying to get a Toolbar to show up in my PreferenceActivity following the answer from Gabor using AppCompatPreferenceActivity shown here: Creating a Preference Screen with support (v21) Toolbar . However I can not get it to work. my code:
Settings.java:
public class Settings extends AppCompatPreferenceActivity{
#Override
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.preferences, target);
setContentView(R.layout.settings_page);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar bar = getSupportActionBar();
bar.setHomeButtonEnabled(true);
bar.setDisplayHomeAsUpEnabled(true);
bar.setDisplayShowTitleEnabled(true);
bar.setHomeAsUpIndicator(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
bar.setTitle("Test2");
}
#Override
protected boolean isValidFragment(String fragmentName) {
return MyPreferenceFragment.class.getName().equals(fragmentName);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
}
return super.onOptionsItemSelected(item);
}
public static class MyPreferenceFragment extends PreferenceFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
Preference removeMedalsButton = findPreference("removeMedals");
removeMedalsButton.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Toast.makeText(getActivity(),"Medailles verwijderd",Toast.LENGTH_SHORT).show();
removeMedals(getActivity());
return true;
}
});
Preference removeWorkoutsButton = findPreference("removeWorkouts");
removeWorkoutsButton.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Toast.makeText(getActivity(),"Workouts verwijderd",Toast.LENGTH_SHORT).show();
removeWorkouts();
return true;
}
});
Preference removeProfileButton = findPreference("removeProfile");
removeProfileButton.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Toast.makeText(getActivity(),"Profiel verwijderd",Toast.LENGTH_SHORT).show();
removeProfile();
return true;
}
});
}
}
public static void removeMedals(Context context){
AchievementTracker.removeMedals(context);
}
public static void removeWorkouts(){
}
public static void removeProfile(){
}
}
settings_page.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="0dp"
android:orientation="vertical"
android:padding="0dp">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="#style/ToolbarTheme"/>
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
preference.xml:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:title="#string/reminder_preference"
android:defaultValue="false"
android:summary="#string/reminder_preference_summary"
android:key="reminderPreference" />
<Preference android:title="#string/remove_medals"
android:key="removeMedals"
android:summary="#string/remove_medals_summary"/>
<Preference android:title="#string/remove_profile"
android:key="removeProfile"
android:summary="#string/remove_profile_summary"/>
<Preference android:title="#string/remove_workouts"
android:key="removeWorkouts"
android:summary="#string/remove_workouts_summary"/>
</PreferenceScreen>
The error i'm getting is:
XML document must start with <preference-headers> tag; foundPreferenceScreen at Binary XML file line #2
I think it's because i'm calling setContentView(R.Layout.settings_page) but that's how i'm supposed to do this according to Gabor's answer.

onCreateView() and onActivityCreated() in MyAddFragment class invokes a lot more than required by working with dynamic fragment

I am new at android app development.I have a problem with my app.I am doing a simple 'Todo List App'. When I deploy my app to android phone.First time it works well.When I change orientation of device, onCreateView() and onActivityCreated() in MyAddFragment works multiple.And 'Add Button' doesn't work after changing orientation.****Please help me how to get rid of the problem.
The following my activity and fragment classes and xml files.
public class MainActivity extends Activity implements Communicator{
FragmentManager man;
private ArrayAdapter<String> todoArrayAdapter;
private ArrayList<String> todoItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
man = getFragmentManager();
MyAddFragment f1 = new MyAddFragment();
MyListFragment f2 = new MyListFragment();
FragmentTransaction transaction = man.beginTransaction();
transaction.add(R.id.frameLayout1, f1, "Add");
transaction.add(R.id.frameLayout2, f2,"List");
Log.i("a", "onCreate - ADDED FRAGMENT");
if (savedInstanceState == null) {
todoItems = new ArrayList<String>();
}else {
todoItems = savedInstanceState.getStringArrayList("veri");
}
todoArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,todoItems);
f2.setListAdapter(todoArrayAdapter);
transaction.commit();
}
public void respond(String data) {
MyListFragment fb = (MyListFragment) man.findFragmentById(R.id.frameLayout2);
todoItems.add(data);
todoArrayAdapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putStringArrayList("veri", todoItems);
}
}
public class MyAddFragment extends Fragment{
Button btnAdd;
EditText txtEdit;
Communicator comm;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_add, container,false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
btnAdd = (Button) getActivity().findViewById(R.id.btnAdd);
txtEdit = (EditText) getActivity().findViewById(R.id.txtEdit);
comm = (Communicator) getActivity();
btnAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String newRecord = txtEdit.getText().toString();
comm.respond(newRecord);
txtEdit.setText("");
}
});
}
}
public class MyListFragment extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list, container,false);
return view;
}
}
public interface Communicator {
public void respond(String data);
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.ceng389hw1.MainActivity" >
<FrameLayout
android:id="#+id/frameLayout1"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:background="#ab3e0f" >
</FrameLayout>
<FrameLayout
android:id="#+id/frameLayout2"
android:layout_width="fill_parent"
android:layout_height="20dp"
android:layout_alignParentBottom="true"
android:layout_below="#+id/frameLayout1"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:background="#ab3eab"
>
</FrameLayout>
</RelativeLayout>
fragment_add.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ab3e0f">
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="#string/btnStringAdd" />
<EditText
android:id="#+id/txtEdit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/btnAdd"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#+id/btnAdd"
android:ems="10"
android:inputType="text" />
</RelativeLayout>
fragment_list.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"
android:background="#ab5810" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
You should change two files in your Application.
First step, you should add following code in androidmanifest file.
android:configChanges="orientation|screenSize"
After you add the code to Androidmanifest, Your androidmanifes file must be like below.
<activity
android:name="com.example.ceng389hw1.MainActivity"
android:configChanges="orientation|screenSize"
android:label="#string/app_name" >
Secon Step, You must be override onConfigurationChanged function like below.
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText( this, "landscape", Toast.LENGTH_SHORT ).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
For more detail -> http://developer.android.com/guide/topics/resources/runtime-changes.html#HandlingTheChange
In your main activity check is fragment already added in activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
...
if(getFragmentManager().getFragment("Add")==null) {
//initialize fragment, create transaction and commit
}
...
}
You can add configChanges parametre inside manifest.xml it will provide you to ignore reinilizating after config changes you can do it simply like that
<activity
android:name="com.youractivity"
android:configChanges="orientation" />
I hope it will help you :)

Can't change the text in TextView of second activity on Android

I'm trying to make an android application. It has two activities: MainActivity and Activity_Service. In MainActivity, there is a button "service" used to pass to Activity_Service. I want to send a string from MainActivity to Activity_Service and then display it in a textview. I would like to show you the codes.
Create the Intent in the MainActivity:
service.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String message = "bla bla bla";
Intent intent = new Intent(MainActivity.this, ActivityService.class);
intent.putExtra("message", message);
startActivity(intent);
}
});
And onCreate() method in the Activity_Service:
public class ActivityService extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");
System.out.println(message);
//TextView txtView = new TextView(this);
TextView txtView = (TextView)findViewById(R.id.name);
txtView.setText(message);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_activity,
container, false);
return rootView;
}
}
}
The XML files created by Eclipse while creating the new activity (Activity_Service):
activity_service.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.alljoynandroid.ActivityService"
tools:ignore="MergeRootFrame" />
Fragment_activity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.example.alljoynandroid.ActivityService$PlaceholderFragment" >
<TextView
android:id = "#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
In onCreate() method of Activity_Service, if I use TextView txtView = new TextView(this);, It works: It can pass from MainActivity to Activity_Service, but then we can't setText. Other side, if I use TextView txtView = (TextView)findViewById(R.id.name);, it doesn't work all. Could you please help me to solve it? I was trying for 2 days and now I have no idea.
Remove this code part from your Activity
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
and change
setContentView(R.layout.activity_service);
to
setContentView(R.layout.fragment_activity);

Categories

Resources