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

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;
}

Related

How to add Back Button from an Activity to a Fragment

I'm using a fragment because I used a nav drawer menu. After I click "Category" menu it will take me to "Category" fragment and in that fragment, I have added a floating action bar that will take you to "Add category" activity.
Since fragments can't be viewed in AndroidManifest.xml file, I can't make a fragment as a parent. What I want is to add a "Back Button" from "Add category" activity, display a toast message (If sure to leave without saving changes..etc) and will go back to "Category" fragment.
I have tried using "onBackPressed()" and "getSuppoerActionBar()" that will show a toast but when running the app, the toast message will just show up in a few seconds and will go back to "Category" fragment.
Please help. Thanks!
Here is my code.
CategoriesFragment.java
package com.example.devcash;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class CategoriesFragment extends Fragment {
public CategoriesFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_categories, container, false);
//add floating action button
FloatingActionButton categories_fab = view.findViewById(R.id.addcategories_fab);
categories_fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// when add fab is pressed, go to add product activity
Intent addprod = new Intent(getActivity(), AddCategoryActivity.class);
startActivity(addprod);
}
});
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Categories");
}
}
AddCategoryActivity.java
package com.example.devcash;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
public class AddCategoryActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_category);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Unsaved changes");
builder.setMessage("Are you sure you want to leave without saving changes?");
builder.setPositiveButton("LEAVE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
AddCategoryActivity.super.onBackPressed();
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.show();
super.onBackPressed();
}
}
You need to remove below code from onBackPressed() as it is calling super class method and eventually destroying activity.
super.onBackPressed();
To handle toolbar back add following code
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// todo: goto back activity from here
onBackPressed();
default:
return super.onOptionsItemSelected(item);
}
}
Your AddCategoryActivity should be like this
public class AddCategoryActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_category);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public void onBackPressed() {
quitActivity();
}
private void quitActivity() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Unsaved changes");
builder.setMessage("Are you sure you want to leave without saving changes?");
builder.setPositiveButton("LEAVE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
quitActivity();
return true;
} else
return super.onOptionsItemSelected(item);
}
}
you can use EventBus.
class Activity{
fun backToFragment(){
EventBus.postEvent(BackToFragmentEvent())
}
}
class HomeActivity{
EventBus.register{
fragmentmanager.replace(CategoriesFragment)
}
}

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 can I show a DialogFragment from a BasePreferenceActivity?

I have a SettingsPreferenceActivity that Extends BasePreferenceActivity, and in that list of preferences I have an item called Upgrade. When clicking this upgrade item, I need to show a DialogFragment which is my upgrade screen. Here is the code I'm trying to use...
DialogFragment dialogFragment =
UpgradeDialogFragment.dialogWithEntry("leftMenuUpgrade");
dialogFragment.show(this.getSupportFragmentManager(), "purchase");
I'm getting an error saying "Cannot resolve method getSupportFragmentManager()".
I've tried using getFragmentManager() as well, and I get the same issue.
How can I show this DIalogFragment from my BasePreferenceActivity?
The old developers used this code...
Intent data = new Intent();
data.putExtra(EXTRA_UPGRADE, true);
setResult(RESULT_OK, data);
finish();
but it doesn't work. Nothing happens at all, so I'm trying to fix this for a client.
Full Activity...
package com.tp.activity;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceCategory;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.NavUtils;
import android.support.v4.app.FragmentManager;
import android.view.MenuItem;
import com.tp.Constants;
import com.tp.HubApplication;
import com.tp.MixpanelConstants;
import com.tp.R;
import com.tp.VariantConstants;
import com.tp.app.settings.ProfileActivity;
import com.tp.auth.Group;
import com.tp.auth.Session;
import com.tp.payment.PurchaseDialogFragment;
import com.tp.payment.UpgradeDialogFragment;
import com.tp.payment.UpgradePolicy;
import android.support.v4.app.DialogFragment;
import com.tp.payment.UpgradeDialogFragment;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.inject.Inject;
public class SettingsPreferenceActivity extends BasePreferenceActivity {
private static final String MANAGE_HUBS_KEY = "MANAGE_HUBS";
private static final String PROFILE_KEY = "PROFILE";
private static final String UPGRADE_KEY = "UPGRADE";
private static final String CALENDAR_KEY = "CALENDAR";
private static final String FEEDBACK_KEY = "FEEDBACK";
private static final String HELP_KEY = "HELP";
private static final int INTENT_SEND_FEEDBACK_REQUEST = 23986;
public static final String EXTRA_UPGRADE = "upgrade";
#Inject
Session mSession;
#Inject
UpgradePolicy mUpgradePolicy;
private HubApplication mApp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mApp = (HubApplication) getApplication();
addPreferencesFromResource(R.xml.settings);
findPreference(PROFILE_KEY).setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent(SettingsPreferenceActivity.this, ProfileActivity.class);
startActivity(intent);
return true;
}
});
if (mUpgradePolicy.shouldPromoteUpgrade()) {
findPreference(UPGRADE_KEY).setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
// Intent data = new Intent();
// data.putExtra(EXTRA_UPGRADE, true);
// setResult(RESULT_OK, data);
// finish();
DialogFragment dialogFragment =
UpgradeDialogFragment.dialogWithEntry("leftMenuUpgrade");
dialogFragment.show(getSupportFragmentManager(), EXTRA_UPGRADE);
return true;
}
});
} else {
findPreference(UPGRADE_KEY).setTitle("Upgraded");
}
findPreference(CALENDAR_KEY).setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent(SettingsPreferenceActivity.this, CalendarSettingsActivity.class);
startActivity(intent);
return true;
}
});
findPreference(FEEDBACK_KEY).setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
mApp.getMixPanel().track(MixpanelConstants.FEEDBACK_CLICKED, null);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{VariantConstants.FEEDBACK_EMAIL});
try {
startActivityForResult(intent, INTENT_SEND_FEEDBACK_REQUEST);
} catch (ActivityNotFoundException e) {
}
return true;
}
});
findPreference(HELP_KEY).setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent(SettingsPreferenceActivity.this, HelpActivity.class);
startActivity(intent);
return true;
}
});
getSupportActionBar().setTitle(R.string.settings_settings);
}
#Override
protected void onResume() {
super.onResume();
PreferenceCategory hubCategory = (PreferenceCategory) findPreference(MANAGE_HUBS_KEY);
hubCategory.removeAll();
List<Group> allGroups = new ArrayList<Group>(mSession.getGroups());
Collections.sort(allGroups, new Comparator<Group>() {
#Override
public int compare(Group lhs, Group rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
for (final Group group : allGroups) {
Preference groupPref = new Preference(this);
groupPref.setTitle(group.getName());
groupPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent(SettingsPreferenceActivity.this, GroupSettingsActivity.class);
intent.putExtra(Constants.ITEM_ID, group.getId());
startActivity(intent);
return true;
}
});
hubCategory.addPreference(groupPref);
}
Preference createHubPref = new Preference(this);
createHubPref.setTitle(R.string.settings_create_hub);
createHubPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent(SettingsPreferenceActivity.this, AddGroupActivity.class);
startActivity(intent);
return true;
}
});
hubCategory.addPreference(createHubPref);
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
finish();
return true;
default:
return super.onMenuItemSelected(featureId, item);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == INTENT_SEND_FEEDBACK_REQUEST && resultCode == Activity.RESULT_OK) {
mApp.getMixPanel().track(MixpanelConstants.FEEDBACK_SENT, null);
}
}
}

On/Off switch android studio

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);
}
}
}

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){

Categories

Resources