On/Off switch android studio - android

I have a on/off switch called audio_switch. In my MainActivity file I want to look if the switch is on, if so, it should set a variable audio = 1. This piece of code mentioned can be found at the bottom of my MainActivity. On the very top after you can see I added a line to find my audio file. A few lines later I used an if(audio == 1) statement to check if the switch is on, so it will play the audio. This however does not work, it does however when I change the statement to audio == audio
package com.joeridukker.main;
import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.support.constraint.ConstraintLayout;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
public static int audio;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer MansNotHot = MediaPlayer.create(this, R.raw.mans_not_hot);
if(audio == 1){
MansNotHot.start();
}
int secondsDelayed = 1;
Handler start = new Handler();
start.postDelayed(new Runnable() {
public void run() {
Animation wait = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.wait);
ConstraintLayout Entire = (ConstraintLayout) findViewById(R.id.Entire);
ImageView Logo = (ImageView) findViewById(R.id.Logo);
TextView Welcome = (TextView) findViewById(R.id.Welcome);
Welcome.startAnimation(wait);
Entire.startAnimation(wait);
Logo.startAnimation(wait);
// Actions to do after 10 seconds
}
}, 0);
Handler animation = new Handler();
animation.postDelayed(new Runnable() {
public void run() {
Animation slide_up = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade_and_slide_upwards);
Animation slide_down = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade_and_slide_downwards);
TextView Welcome = (TextView) findViewById(R.id.Welcome);
ImageView Logo = (ImageView) findViewById(R.id.Logo);
Logo.startAnimation(slide_down);
Welcome.startAnimation(slide_up);
// Actions to do after 10 seconds
}
}, 500);
Handler entire_animation = new Handler();
entire_animation.postDelayed(new Runnable() {
public void run() {
Animation fade_in = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade_in);
ConstraintLayout Entire = (ConstraintLayout) findViewById(R.id.Entire);
TextView Welcome = (TextView) findViewById(R.id.Welcome);
Entire.startAnimation(fade_in);
ObjectAnimator.ofObject(
Welcome,
"textColor",
new ArgbEvaluator(),
Color.argb(140,0,0,0),
Color.WHITE
).setDuration(500)
.start();
}
}, 500);
new Handler().postDelayed(new Runnable() {
public void run() {
Handler splash = new Handler();
int a = 1;
Intent Intent = new Intent(MainActivity.this, Differentiate.class);
Intent.putExtra("HEADER", a);
startActivity(Intent);
overridePendingTransition(R.anim.fade_in_switch_fast,R.anim.fade_out_switch_fast);
finish();
}
}, secondsDelayed * 2500);
}
public static class SettingsActivity extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.pref_general);
//Check the current value in preference.
SharedPreferences switchPrefStatus = PreferenceManager.getDefaultSharedPreferences(getActivity());
boolean switchPrefValue = switchPrefStatus.getBoolean("audio_switch", false);
Toast.makeText(getActivity(), "Current value: " + switchPrefValue, Toast.LENGTH_SHORT).show();
Preference switchPref = (Preference) findPreference("audio_switch");
switchPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object o) {
boolean isOn = (boolean) o;
//Do what you want with the value!:)
if (isOn) {
audio = 1;
}else{
audio = 0;
}
return true;
}
});
}
}
}
My SettingsActivity
package com.joeridukker.main;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.RingtonePreference;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.MenuItem;
import java.util.List;
/**
* A {#link PreferenceActivity} that presents a set of application settings. On
* handset devices, settings are presented as a single list. On tablets,
* settings are split by category, with category headers shown to the left of
* the list of settings.
* <p>
* See <a href="http://developer.android.com/design/patterns/settings.html">
* Android Design: Settings</a> for design guidelines and the <a
* href="http://developer.android.com/guide/topics/ui/settings.html">Settings
* API Guide</a> for more information on developing a Settings UI.
*/
public class SettingsActivity extends AppCompatPreferenceActivity {
/**
* 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 value) {
String stringValue = value.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(null);
} else {
// Set the summary to reflect the new ringtone display
// name.
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
};
/**
* Helper method to determine if the device has an extra-large screen. For
* example, 10" tablets are extra-large.
*/
private static boolean isXLargeTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
/**
* Binds a preference's summary to its value. More specifically, when the
* preference's value is changed, its summary (line of text below the
* preference title) is updated to reflect the value. The summary is also
* immediately updated upon calling this method. The exact display format is
* dependent on the type of preference.
*
* #see #sBindPreferenceSummaryToValueListener
*/
private static void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
// Trigger the listener immediately with the preference's
// current value.
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
// Show the Up button in the action bar.
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
if (!super.onMenuItemSelected(featureId, item)) {
NavUtils.navigateUpFromSameTask(this);
}
return true;
}
return super.onMenuItemSelected(featureId, item);
}
/**
* {#inheritDoc}
*/
#Override
public boolean onIsMultiPane() {
return isXLargeTablet(this);
}
/**
* {#inheritDoc}
*/
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
}
/**
* This method stops fragment injection in malicious applications.
* Make sure to deny any unknown fragments here.
*/
protected boolean isValidFragment(String fragmentName) {
return PreferenceFragment.class.getName().equals(fragmentName)
|| GeneralPreferenceFragment.class.getName().equals(fragmentName)
|| DataSyncPreferenceFragment.class.getName().equals(fragmentName)
|| NotificationPreferenceFragment.class.getName().equals(fragmentName);
}
/**
* This fragment shows general preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
static int audio;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class GeneralPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
setHasOptionsMenu(true);
Preference switchPref = (Preference) findPreference("audio_switch");
switchPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object o) {
boolean isOn = (boolean) o;
if (isOn) {
audio = 1;
}else{
audio = 0;
}
return true;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
/**
* This fragment shows notification preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class NotificationPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_notification);
setHasOptionsMenu(true);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone"));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
/**
* This fragment shows data and sync preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class DataSyncPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_data_sync);
setHasOptionsMenu(true);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("sync_frequency"));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
}

Related

Android Preferences - change font size by user

I am looking for a solution for my app to let the user select the font size via settings menu. Like I am able to do in other apps e.g. Jota+. Here are some screen shots for a better understanding (sorry - my Jota+ is a German version):
As of now I installed already a settingsActivity which is using a FragmentManager to call a PreferenceFragment using my pref_main.xml as resource.
Any idea how I can archive this?
My SettingsActivity:
package com.wbapps.wbshoppinglist;
/**
* Created by Andreas on 2/15/2018.
*/
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.view.MenuItem;
public class SettingsActivity extends AppCompatPreferenceActivity {
private static final String TAG = SettingsActivity.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);
}
}
#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 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;
}
};
}
My AppCompatPreferenceActivity:
package com.wbapps.wbshoppinglist;
/**
* Created by Andreas on 2/15/2018.
*/
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.Toolbar;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A {#link PreferenceActivity} which implements and proxies the necessary calls
* to be used with AppCompat.
*/
public abstract class AppCompatPreferenceActivity extends PreferenceActivity {
private AppCompatDelegate mDelegate;
#Override
protected void onCreate(Bundle savedInstanceState) {
getDelegate().installViewFactory();
getDelegate().onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
getDelegate().onPostCreate(savedInstanceState);
}
public ActionBar getSupportActionBar() {
return getDelegate().getSupportActionBar();
}
public void setSupportActionBar(#Nullable Toolbar toolbar) {
getDelegate().setSupportActionBar(toolbar);
}
#Override
public MenuInflater getMenuInflater() {
return getDelegate().getMenuInflater();
}
#Override
public void setContentView(#LayoutRes int layoutResID) {
getDelegate().setContentView(layoutResID);
}
#Override
public void setContentView(View view) {
getDelegate().setContentView(view);
}
#Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().setContentView(view, params);
}
#Override
public void addContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().addContentView(view, params);
}
#Override
protected void onPostResume() {
super.onPostResume();
getDelegate().onPostResume();
}
#Override
protected void onTitleChanged(CharSequence title, int color) {
super.onTitleChanged(title, color);
getDelegate().setTitle(title);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getDelegate().onConfigurationChanged(newConfig);
}
#Override
protected void onStop() {
super.onStop();
getDelegate().onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
getDelegate().onDestroy();
}
public void invalidateOptionsMenu() {
getDelegate().invalidateOptionsMenu();
}
private AppCompatDelegate getDelegate() {
if (mDelegate == null) {
mDelegate = AppCompatDelegate.create(this, null);
}
return mDelegate;
}
}
My pref_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="#string/pref_header_font_setting">
<Preference
android:summary="#string/pref_font_setting"/>
</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" />
</PreferenceCategory>
</PreferenceScreen>
Here you can see the project structure:
Many thanks
Andreas

How to call the method finished() to exit the whole PreferenceActivity

I use the official SettingsActivity as my activity's templete,and my preferenceactivity have two static class "preferencefragment1" and "preferencefragment2".
While the App click the headers of the preferenceactivity, it switch to the specified preferencefragment.Then I call the finished() method in the onkeydown() method with the KEYCODE_BACK event.It will back to the headers view.
However,what I want is it back to the mainactivity from preferencefragment view,make the whole PreferenceActivity to finish instead of just the preferencefragment1 view.
Because I want to use the the preferenceActivity to set the parameters of a bluetooth comunication device,and after parameters finished setting, it can immediately send the parameteres to the deivce in the onActivityResult() method.
But now, I must click the BACK button twice to back to the mainactivity.Is that a possible to skip the header view to show or jump into the preferencefragment view directly?
program flow
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.app.ActionBar;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.SwitchPreference;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import java.util.List;
public class SettingsActivity extends PreferenceActivity {
private static List<Header> headers;
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
}
if (preference instanceof EditTextPreference) {
EditTextPreference editTextPreference = (EditTextPreference) preference;
editTextPreference.setSummary(stringValue);
}
if (preference instanceof SwitchPreference) {
SwitchPreference switchPreference = (SwitchPreference) preference;
switchPreference.setSummary(stringValue);
}
return true;
}
};
private static boolean isXLargeTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Confirm to update system paras?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
setResult(RESULT_OK);
finish();
}
});
builder.setNegativeButton("CANCELED", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.show();
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
System.out.print(resultCode);
}
private static void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
// Trigger the listener immediately with the preference's
// current value.
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// addPreferencesFromResource(R.xml.pref_system);
setupActionBar();
}
private void setupActionBar() {
ActionBar actionBar = getActionBar();
if (actionBar != null) {
// Show the Up button in the action bar.
// actionBar.setDisplayHomeAsUpEnabled(true);
}
}
/**
* {#inheritDoc}
*/
#Override
public boolean onIsMultiPane() {
return isXLargeTablet(this);
}
/**
* {#inheritDoc}
*/
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
headers=target;
}
/**
* This method stops fragment injection in malicious applications.
* Make sure to deny any unknown fragments here.
*/
protected boolean isValidFragment(String fragmentName) {
return PreferenceFragment.class.getName().equals(fragmentName)
|| SystemPreferenceFragment.class.getName().equals(fragmentName);
}
/**
* This fragment shows general preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
public static class SystemPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_system);
setHasOptionsMenu(true);
bindPreferenceSummaryToValue(findPreference("pref_key_ip"));
bindPreferenceSummaryToValue(findPreference("pref_key_port"));
bindPreferenceSummaryToValue(findPreference("pref_key_output1_level"));
bindPreferenceSummaryToValue(findPreference("pref_key_output2_level"));
bindPreferenceSummaryToValue(findPreference("pref_key_output3_level"));
bindPreferenceSummaryToValue(findPreference("pref_key_noportrait"));
bindPreferenceSummaryToValue(findPreference("pref_key_closeeye"));
bindPreferenceSummaryToValue(findPreference("pref_key_yawn"));
bindPreferenceSummaryToValue(findPreference("pref_key_distract"));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
/*
#Override
public void onStop()
{
super.onStop();
AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
builder.setTitle("Confirm to update system paras?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SystemPreferenceFragment.this.getActivity().setResult(RESULT_OK);
}
});
builder.setNegativeButton("CANCELED", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SystemPreferenceFragment.this.getActivity().setResult(RESULT_CANCELED);
}
});
builder.show();
this.getActivity().finish();
}*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class RealtimePreferenceFragment extends PreferenceFragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_realtime);
setHasOptionsMenu(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
}
Use getActivity().finish(); to finish the activity
or
expose a method using interface from fragment to activity to notify back is being pressed
Problem solved!!
step 1:In the MainActivity, add flag "FLAG_ACTIVITY_NO_HISTORY" to the Intent, then start the SettingsActivity.
step 2: Override the onBuildStartFragmentIntent() method of SettingsActivity(PreferenceActivity) for adding flag FLAG_ACTIVITY_FORWARD_RESULT,so that the activityresult can return to the MainActivity.
Like below: #Override
public Intent onBuildStartFragmentIntent (String fragmentName,
Bundle args,
int titleRes,
int shortTitleRes)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClass(this, getClass());
intent.putExtra(EXTRA_SHOW_FRAGMENT, fragmentName);
intent.putExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
intent.putExtra(EXTRA_SHOW_FRAGMENT_TITLE, titleRes);
intent.putExtra(EXTRA_SHOW_FRAGMENT_SHORT_TITLE, shortTitleRes);
intent.putExtra(EXTRA_NO_HEADERS, true);
intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);//the new statement
return intent;
}

Getting Cast Exception Android

I'm creating a simple note app in android. I am basically using two activity classes named as Main Page and Second Activity. I'm storing some data in the shared preferences in second activity and want to use it in my first Activity. I'm storing data in shared preferences as (String,Integer) key-pair. In my main activity class, when i'm getting the value from shared preferences as Integer and compare it with value 0,i'm getting an exception that java.lang.string can't be cast to java.lang.integer. I don't know why this exception is coming. Android studio is not giving me an exception but when i run my app, my app crashes. I have attach the code for reference.
MainActivity class:
package com.example.prateeksharma.noteballondor;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class MainPage extends ActionBarActivity {
Notes notes = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
}
#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_page, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = getSharedPreferences("com.example.prateeksharma.noteballondor", Context.MODE_PRIVATE);
//Map<String, Integer> notesMap = (Map<String, Integer>)sharedPreferences.getAll();
List<Notes> listNotes = new ArrayList<>();
Map<String, ?> prefsMap = sharedPreferences.getAll();
for (Map.Entry<String, ?> entry: prefsMap.entrySet()) {
if (entry.getValue() == 0){
notes = new Notes();
}
notes.setNoteText(entry.getKey());
listNotes.add(notes);
sharedPreferences.edit().putInt(entry.getKey(),2);
}
NotesArrayAdapter notesArrayAdapter = new NotesArrayAdapter(this,R.layout.list_layout, listNotes);
final ListView listview = (ListView) findViewById(R.id.listView);
listview.setAdapter(notesArrayAdapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
/**/
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
notes = (Notes) parent.getItemAtPosition(position);
Intent intent = new Intent(MainPage.this, SecondActivity.class);
intent.putExtra("Notes",notes);
startActivity(intent);
}
});
}
#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
switch (item.getItemId()) {
case R.id.new_link:
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("Notes",(android.os.Parcelable)null);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
SecondActivity Class:
package com.example.prateeksharma.noteballondor;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
public class SecondActivity extends ActionBarActivity {
public SharedPreferences sharedPreferences;
SharedPreferences.Editor edit;
Notes notes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
sharedPreferences = getSharedPreferences("com.example.prateeksharma.noteballondor", Context.MODE_PRIVATE);
edit = sharedPreferences.edit();
}
#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_second, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
Intent intent = getIntent();
notes = (Notes)intent.getParcelableExtra("Notes");
EditText editText = (EditText) findViewById(R.id.editText);
if(notes != null){
editText.setText(notes.getNoteText());
}
else{
editText.setText(null);
}
}
#Override
protected void onStop() {
super.onStop();
getIntent().removeExtra(notes.getNoteText());
}
#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();
Intent intent = getIntent();
//noinspection SimplifiableIfStatement
switch (item.getItemId()) {
case R.id.save:
EditText editText = (EditText)findViewById(R.id.editText);
if (notes != null){
edit.putInt(String.valueOf(editText.getText()),1);
}
else{
edit.putInt(String.valueOf(editText.getText()),0);
}
edit.commit();
return true;
case R.id.delete:
if(notes != null){
edit.remove(notes.getNoteText());
edit.commit();
finish();
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
}
Notes class that I'm using:
package com.example.prateeksharma.noteballondor;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by Dell on 02-06-2015.
*/
public class Notes implements Parcelable {
private String noteText;
public String getNoteText() {
return noteText;
}
public void setNoteText(String noteText) {
this.noteText = noteText;
}
private Notes(Parcel in) {
noteText = in.readString();
}
public Notes(){
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(noteText);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<Notes> CREATOR = new Parcelable.Creator<Notes>() {
#Override
public Notes createFromParcel(Parcel in) {
return new Notes(in);
}
#Override
public Notes[] newArray(int size) {
return new Notes[size];
}
};
}
Can anybody tell me why this error is coming in MainActivity class at this line
if (entry.getValue() == 0)
Thank you..
Try to replace
if ((Integer)entry.getValue() == 0){
With
If((Integer.parseInt( entry.getValue()) ==0){

Sensor Reading keeps increasing even after closing app, Android

I have make this app which calculates Linear Acceleration of device of all dimension, combines it, and calculates net acceleration. Top five acceleration values are stored in Shared Preference key-value pairs.
The problem is when I close the app and reopen it, I find the values increased to a much higher level. I don't seem to catch the point in the code from where it is happening.
Please Help me out.
ShakoMeter.java (this is my main activity where all sensor data is collected and stored)
package com.example.shake_o_meter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class ShakeOMeter extends Activity implements SensorEventListener{
float ro(double ax2) {
DecimalFormat df = new DecimalFormat("#.###");
return Float.valueOf(df.format(ax2));
}
SensorManager smngr;
Sensor sen;
TextView t,t3;
double max=-1;
double ax = 0,ay = 0,az = 0;
SharedPreferences sharedPref;
SharedPreferences.Editor editor;
ArrayList<Float> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shake_ometer);
t = (TextView)findViewById(R.id.TextView1);
// Showing initial message
TextView textview = new TextView(getApplicationContext());
textview.setText("Get ready to Shake It!!");
textview.setBackgroundColor(Color.BLACK);
textview.setTextColor(Color.WHITE);
textview.setTextSize(30);
textview.setPadding(10,10,10,10);
textview.setGravity(Gravity.CENTER_VERTICAL);
Toast toast = new Toast(getApplicationContext());
toast.setView(textview);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setGravity(Gravity.FILL, 0, 0);
toast.show();
//Getting Sensor Control
smngr = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sen = (Sensor) smngr.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
//Obtaining SharedPreferance for storing key-value pairs of high scores.
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
editor = sharedPref.edit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.shake_ometer, menu);
return true;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
list = new ArrayList<Float>();
ax = event.values[0];
ay = event.values[1];
az = event.values[2];
double temp=Math.sqrt(ro(ax)*ro(ax)+ro(ay)*ro(ay)+ro(az)*ro(az));
if(temp>=max){
max=temp;
t.setText(ro(max)+"");
list.add(sharedPref.getFloat("1", 0));
list.add(sharedPref.getFloat("2", 0));
list.add(sharedPref.getFloat("3", 0));
list.add(sharedPref.getFloat("4", 0));
list.add(sharedPref.getFloat("5", 0));
if(max>list.get(0)){
list.remove(0);
list.add((float) max);
Collections.sort(list);
editor.putFloat("1", list.get(0));
editor.putFloat("2", list.get(1));
editor.putFloat("3", list.get(2));
editor.putFloat("4", list.get(3));
editor.putFloat("5", list.get(4));
editor.commit();
System.out.println(sharedPref.getFloat("5", 0)+" "
+sharedPref.getFloat("4", 0)+" "
+sharedPref.getFloat("3", 0)+" "
+sharedPref.getFloat("2", 0)+" "
+sharedPref.getFloat("1", 0));
}
}
}
public void onClickReset(View view){
Intent intent = getIntent();
finish();
startActivity(intent);
}
public void onClickTopFive(View view){
Intent intent = new Intent(getApplicationContext(),TopFive.class);
startActivity(intent);
}
#Override
protected void onResume(){
super.onResume();
final ShakeOMeter sh = this;
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 5s = 5000ms
smngr.registerListener(sh, sen, SensorManager.SENSOR_DELAY_NORMAL);
}
},3000);
}
#Override
protected void onPause() {
super.onPause();
smngr.unregisterListener(this);
}
protected void onStop(){
super.onStop();
smngr.unregisterListener(this);
}
public void onDestroy(){
super.onDestroy();
smngr.unregisterListener(this);
finish();
}
}
TopFive.java (This is a sub Activity where top five activities are displayed)
package com.example.shake_o_meter;
import java.text.DecimalFormat;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class TopFive extends Activity {
float ro(double ax2) {
DecimalFormat df = new DecimalFormat("#.###");
return Float.valueOf(df.format(ax2));
}
SharedPreferences sharedPref;
SharedPreferences.Editor edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_top_five);
// Show the Up button in the action bar.
setupActionBar();
TextView t1 = (TextView) findViewById(R.id.T1);
TextView t2 = (TextView) findViewById(R.id.T2);
TextView t3 = (TextView) findViewById(R.id.T3);
TextView t4 = (TextView) findViewById(R.id.T4);
TextView t5 = (TextView) findViewById(R.id.T5);
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
edit = sharedPref.edit();
t1.setText(ro(sharedPref.getFloat("1", 0))+"");
t2.setText(ro(sharedPref.getFloat("2", 0))+"");
t3.setText(ro(sharedPref.getFloat("3", 0))+"");
t4.setText(ro(sharedPref.getFloat("4", 0))+"");
t5.setText(ro(sharedPref.getFloat("5", 0))+"");
}
public void onClickReset(View view){
edit.putFloat("1", 0);edit.commit();
edit.putFloat("2", 0);edit.commit();
edit.putFloat("3", 0);edit.commit();
edit.putFloat("4", 0);edit.commit();
edit.putFloat("5", 0);edit.commit();
Intent intent = getIntent();
finish();
startActivity(intent);
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.top_five, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}

Saving float from seekbar using dialogue preference

I'm using a custom dialog preference to generate a seekbar in my preferences menu.
After researching seekbar implementation, to obtain the float value I need from the seekbar I have written the following code:
public void onProgressChanged(SeekBar seek, int newValue,
boolean fromTouch) {
// Round the value to the closest integer value.
if (stepSize >= 1) {
value = Math.round(newValue/stepSize)*stepSize;
}
else {
value = newValue;
}
// Set the valueText text.
float sValue = newValue*10;
sValue = sValue/100;
valueText.setText(Float.toString(sValue));
Which produces the float that I want. However, I want to be able to use this float in my main activity. I have attempted to store it using SharedPreferences using:
userPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
Editor editor = userPrefs.edit()
editor.putFloat("mpm", sValue);
editor.commit();
Which is how I've learned to use SharedPreferences in a class extending Activity.
However as this seekbar extends Dialogue Preference I cannot use
getBaseContext()
As I get the error that the method getBaseContext is undefined for this type.
I have tried changing getBaseContext() to getContext() but this has been unsuccessful although that may be because I am unfamiliar with this implementation.
How can I save this float from the dialogue preference and use the value in a different class?
The code I am using to retrieve SharedPreferences:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.logbook);
initialise();
userPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
list = userPrefs.getString("list", "10");
userswallstring = userPrefs.getString("height", "10.0");
try {
usersWall = Float.valueOf(userswallstring.trim());
} catch (Exception e) {
// TODO: handle exception
}
mpm = userPrefs.getFloat("mpm", 2);
Mpm.class:
package com.gbclimber.ep;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.TypedArray;
import android.preference.DialogPreference;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
public class Mpm extends
DialogPreference implements SeekBar.OnSeekBarChangeListener {
// Layout widgets.
private SeekBar seekBar = null;
private TextView valueText = null;
// Custom xml attributes.
private int maximumValue = 0;
private int minimumValue = 0;
private int stepSize = 0;
private String units = null;
private int value = 0;
SharedPreferences userPrefs;
/**
* The SeekBarDialogPreference constructor.
* #param context of this preference.
* #param attrs custom xml attributes.
*/
public Mpm(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray = context.obtainStyledAttributes(attrs,
R.styleable.Mpm);
maximumValue = typedArray.getInteger(
R.styleable.Mpm_maximumValue, 0);
minimumValue = typedArray.getInteger(
R.styleable.Mpm_minimumValue, 0);
stepSize = typedArray.getInteger(
R.styleable.Mpm_stepSize, 1);
units = typedArray.getString(
R.styleable.Mpm_units);
typedArray.recycle();
}
/**
* {#inheritDoc}
*/
protected View onCreateDialogView() {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
View view = layoutInflater.inflate(
R.layout.mpmdp, null);
seekBar = (SeekBar)view.findViewById(R.id.seekbar);
valueText = (TextView)view.findViewById(R.id.valueText);
// Get the persistent value and correct it for the minimum value.
value = getPersistedInt(minimumValue) - minimumValue;
// You're never know...
if (value < 0) {
value = 0;
}
seekBar.setOnSeekBarChangeListener(this);
seekBar.setKeyProgressIncrement(stepSize);
seekBar.setMax(maximumValue - minimumValue);
seekBar.setProgress(value);
return view;
}
/**
* {#inheritDoc}
*/
public void onProgressChanged(SeekBar seek, int newValue,
boolean fromTouch) {
// Round the value to the closest integer value.
if (stepSize >= 1) {
value = Math.round(newValue/stepSize)*stepSize;
}
else {
value = newValue;
}
// Set the valueText text.
float sValue = newValue*10;
sValue = sValue/100;
userPrefs = PreferenceManager
.getDefaultSharedPreferences(getContext());
Editor editor = userPrefs.edit();
editor.putFloat("mpm", sValue);
editor.commit();
valueText.setText(Float.toString(sValue));
callChangeListener(value);
}
/**
* {#inheritDoc}
*/
public void onStartTrackingTouch(SeekBar seek) {
}
/**
* {#inheritDoc}
*/
public void onStopTrackingTouch(SeekBar seek) {
}
/**
* {#inheritDoc}
*/
public void onClick(DialogInterface dialog, int which) {
// if the positive button is clicked, we persist the value.
if (which == DialogInterface.BUTTON_POSITIVE) {
if (shouldPersist()) {
persistInt(value + minimumValue);
}
}
super.onClick(dialog, which);
}
#Override
protected void onDialogClosed(boolean positiveResult) {
// TODO Auto-generated method stub
super.onDialogClosed(positiveResult);
persistInt(value + minimumValue);
}
}
Just did a quick search but for your context try
this.getDialog().getContext()

Categories

Resources