I used Toast to make notification, but it seems it will appear even its activity is not in the current screen and some other activity has been started.
I want to check this situation, when the activity is not the current one, I'd not send the Toast notification. But how to do ?
When your Activity comes to the foreground, its onResume() method will be invoked. When another Activity comes in front of your Activity, its onPause() method will be invoked. So all you need to do is implement a boolean indicating if your Activity is in the foreground:
private boolean isInFront;
#Override
public void onResume() {
super.onResume();
isInFront = true;
}
#Override
public void onPause() {
super.onPause();
isInFront = false;
}
ArrayList<String> runningactivities = new ArrayList<String>();
ActivityManager activityManager = (ActivityManager)getBaseContext().getSystemService (Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> services = activityManager.getRunningTasks(Integer.MAX_VALUE);
for (int i1 = 0; i1 < services.size(); i1++) {
runningactivities.add(0,services.get(i1).topActivity.toString());
}
if(runningactivities.contains("ComponentInfo{com.app/com.app.main.MyActivity}")==true){
Toast.makeText(getBaseContext(),"Activity is in foreground, active",1000).show();
}
This way you will know if the pointed activity is the current visible activity.
I prefer not to handle the state by myself, so I have implemented a class that does this for me.
package mypackage;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
// Mine extends AppCompatActivity - your's might need to extend Activity, depending on whether
// you use the support library or not.
public class StateTrackingActivity extends AppCompatActivity {
public enum ActivityState {
CREATED, RESUMED, STARTED, PAUSED, STOPPED, DESTROYED
}
private ActivityState _activityState;
protected ActivityState getActivityState() { return _activityState; }
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_activityState = ActivityState.CREATED;
}
#Override
protected void onResume() {
super.onResume();
_activityState = ActivityState.RESUMED;
}
#Override
protected void onStart() {
super.onStart();
_activityState = ActivityState.STARTED;
}
#Override
protected void onPause() {
super.onPause();
_activityState = ActivityState.PAUSED;
}
#Override
protected void onStop() {
super.onStop();
_activityState = ActivityState.STOPPED;
}
#Override
protected void onDestroy() {
super.onDestroy();
_activityState = ActivityState.DESTROYED;
}
}
Then your activity can extend this one and you can get the state by calling getActivityState().
This is my ultimate isActivityVisible function.
protected boolean isActivityVisible() {
if (this.mActivity != null) {
Class klass = this.mActivity.getClass();
while (klass != null) {
try {
Field field = klass.getDeclaredField("mResumed");
field.setAccessible(true);
Object obj = field.get(this.mActivity);
return (Boolean)obj;
} catch (NoSuchFieldException exception1) {
// Log.e(TAG, exception1.toString());
} catch (IllegalAccessException exception2) {
// Log.e(TAG, exception2.toString());
}
klass = klass.getSuperclass();
}
}
return false;
}
if (BaseActivity.this instanceof Faq)
{
Toast.makeText(BaseActivity.this, "You are in the Same Page", Toast.LENGTH_SHORT).show();
}else {
Intent intent = new Intent(BaseActivity.this, Faq.class);
startActivity(intent);
drawer.closeDrawer(GravityCompat.START);
}
//// here am All my activities are extending on Activity called BaseActivity
There is Activity#isTaskRoot() method
if ( getActivity() instanceof ManageCardActivity){
// your code
}
Related
I want to have background music playing while the user is playing a game. The music starts when the user starts the application, pauses when they leave it, and it resumes when they go back to the application.
I tried using this method, I edited it a bit:
public class MainActivity extends Activity {
private boolean bounded;
private BackgroundSoundService backgroundSoundService;
ServiceConnection connection = new ServiceConnection() {
#Override
public void onServiceDisconnected( ComponentName name ) {
bounded = false;
backgroundSoundService = null;
}
#Override
public void onServiceConnected( ComponentName name, IBinder service ) {
bounded = true;
BackgroundSoundService.LocalBinder localBinder = (BackgroundSoundService.LocalBinder) service;
backgroundSoundService = localBinder.getServiceInstance();
}
};
#Override
public void onCreate( Bundle savedInstanceState ) {
super.onCreate(savedInstanceState);
// (code that's not necessary)
backgroundSoundService.start(); // this is where the error is thrown
}
#Override
public void onPause() {
super.onPause();
backgroundSoundService.pause();
}
#Override
public void onResume() {
super.onResume();
backgroundSoundService.resume();
}
#Override
public void onStop() {
super.onStop();
backgroundSoundService.pause();
}
#Override
public void onStart() {
super.onStart();
Intent intent = new Intent(this, BackgroundSoundService.class);
bindService(intent, connection, BIND_AUTO_CREATE);
backgroundSoundService.start();
}
#Override
public void onDestroy() {
super.onDestroy();
backgroundSoundService.destroy();
}
}
I use an activity to play, pause and resume background music. I'll leave out the unecessary methods/lines for this question here:
public class BackgroundSoundService extends Service {
private static final String TAG = null;
public IBinder binder = new LocalBinder();
public IBinder onBind( Intent arg0 ) {
return binder;
}
public IBinder onUnBind( Intent arg0 ) {
return null;
}
public class LocalBinder extends Binder {
public BackgroundSoundService getServiceInstance() {
return BackgroundSoundService.this;
}
}
}
However, when I run the application I get a NullPointerException in the MainActivity class (in the onCreate method, I commented it in the code).
The variable doesn't seem to be initialized yet, but I do need to start the music when the user opens the application.
I also tried removing the backgroundSoundService.start(); from the onCreate method, so the music would start when onStart is called. However, when I do that, I get the same error.
So, how can I initialize backgroundSoundService before it is used to call its methods?
first of all remove this backgroundSoundService.start() from onCreate and add it inside onServiceConnected() method
u need to check null before doing any backgroundSoundService related stuffs like below
#Override
public void onPause() {
super.onPause();
if(backgroundSoundService != null){
backgroundSoundService.pause();
}
}
add this kind of null check in all appearance of backgroundSoundService
i'm trying to play stream radio using Mediaplayer with MP1 as variable of Mediaplayer i want to play it in all Fragments app,expect one activity (ActivityOne) which is contains another Mediaplayer MP2 to play,so i want to stop MP1 when i'm in (ActivityOne) activity, and play MP2 , and when i return from (ActivityOne) i want to resume MP1, my big problem is the (ActivityOne) called when i click button which is exist in fragment
my code below works only in one direction :
when i return from (ActivityOne) activity, the music stops.
structure of the app : MainAcitivty > Fragment > ActivityOne
MainActivity.java
MediaPlayer MP1;
boolean prepared = false;
boolean started = false;
PlayerTask playerTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer = new MediaPlayer();
playerTask = new PlayerTask();
playerTask.execute(stream);
/**/
MusicButton = findViewById(R.id.toggleButton);
MusicButton.setVisibility(View.INVISIBLE);
MusicButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (started && MusicButton.isChecked()) {
started = false;
MP1.pause();
MusicButton.setChecked(true);
} else {
started = true;
MP1.start();
MusicButton.setChecked(false);
}
}
});
}
#SuppressLint("StaticFieldLeak")
public class PlayerTask extends AsyncTask<String, Void, Boolean> {
ProgressBar loadingRL = findViewById(R.id.progressBar);
#Override
protected void onPreExecute() {
super.onPreExecute();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
AudioAttributes attribs = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build();
MP1.setAudioAttributes(attribs);
} else {
MP1.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
loadingRL.setVisibility(View.VISIBLE);
}
#Override
protected Boolean doInBackground(String... strings) {
try {
MP1.setDataSource(strings[0]);
MP1.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
MP1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer MP1) {
MP1.start();
}
});
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
MusicButton.setVisibility(View.VISIBLE);
MusicButton.setChecked(true);
loadingRL.setVisibility(View.VISIBLE);
}
ActivityOne.java
MediaPlayer MP2;
boolean prepared = false;
boolean started = false;
ToggleButton music;
PlayerTask playerTask = null;
CoordinatorLayout coordinatorLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pop_for_ringtone);
coordinatorLayout = findViewById(R.id.coord);
MP2 = new MediaPlayer();
playerTask = new PlayerTask();
playerTask.execute(url);
}
#SuppressLint("StaticFieldLeak")
public class PlayerTask extends AsyncTask<String, Void, Boolean> {
ProgressBar pb = findViewById(R.id.progress);
#Override
protected void onPreExecute() {
super.onPreExecute();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
AudioAttributes attribs = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build();
MP2.setAudioAttributes(attribs);
} else {
MP2.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
}
#Override
protected Boolean doInBackground(String... strings) {
if (!isCancelled()) {
try {
MP2.setDataSource(strings[0]);
MP2.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
MP2.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer MP2) {
MP2.start();
}
});
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
music.setEnabled(true);
music.setVisibility(View.VISIBLE);
music.setChecked(true);
all.setVisibility(View.VISIBLE);
}
#Override
protected void onCancelled(Boolean aBoolean) {
if (isCancelled() && MP2.isPlaying()) {
MP2.stop();
}
}
}
#Override
public void onBackPressed() {
if (playerTask != null && playerTask.getStatus() == AsyncTask.Status.FINISHED) {
if (MP2.isPlaying()) {
MP2.stop();
}
} else if (playerTask != null && playerTask.getStatus() != AsyncTask.Status.FINISHED) {
playerTask.cancel(true);
}
super.onBackPressed();
}
i spent 2 days to resolve this problem without any result ,please someone help me i will be thankful to him
You could solve this by using Otto library. First create a new Java class but choose enum instead and inside enum you can add: PLAY and PAUSE for example:
public enum PlaybackEvent {
PLAY, PAUSE
}
Then if you are not using custom Application class create one and extend Application and override inside onCreate method. Inside your app gradle add compile 'com.squareup:otto:1.3.8' then create an instance of Bus inside Application class and register. For example this would look like this:
public class MApplication extends Application {
public static Bus sBus = new Bus(ThreadEnforcer.MAIN);
#Override
public void onCreate() {
super.onCreate();
sBus.register(this);
}
Don't forget to replace in manifest default application class with your new one
<application
android:name="com.packagename.MApplication"
After that in your MainActivity class override and register/unregister your event bus in onResume and in onPause.
#Override
protected void onResume() {
super.onResume();
try {
MApplication.sBus.register(this);
}
catch(Exception e){
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
MApplication.sBus.unregister(this);
}
catch(Exception e){
e.printStackTrace();
}
}
After that in MainActivity create a public void method passing as parameter PlayBackEvent and Subscribe so you can listen a message which will be send from your fragment class. For example:
#Subscribe
public void handlePlaybackEvent(PlaybackEvent event) {
switch (event) {
case PLAY:
if(MP1.isPlaying())
MP1.pause();
break;
case PAUSE:
if(!MP1.isPlaying())
MP1.play();
break;
}
}
And last thing you have to do is to send the message from your fragment when starting second activity and that will go:
MApplication.sBus.post(PlaybackEvent.PAUSE);
and of course you can also send a message to play again MP1 from second activity overriding onBackPressed putting inside line of code:
MApplication.sBus.post(PlaybackEvent.PLAY);
Hope this will help you to resolve the problem.
Have you tried using startActivityForResult()?
Basically I have a loading splash screen which will be executed when button was clicked:
public void onClick(View v) {
// Load the loading splash screen
Intent loadingIntent = new Intent(context, LoadingScreen.class);
context.startActivity(loadingIntent);
}
});
And in the LoadingScreen class:
public class LoadingScreen extends Activity{
//A ProgressDialog object
private ProgressDialog progressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//Initialize a LoadViewTask object and call the execute() method
new LoadViewTask().execute();
}
//To use the AsyncTask, it must be subclassed
private class LoadViewTask extends AsyncTask<Void, Integer, Void>
{
//Before running code in separate thread
#Override
protected void onPreExecute()
{
progressDialog = ProgressDialog.show(LoadingScreen.this,"Getting routes...",
"Loading data, please wait...", false, false);
}
//The code to be executed in a background thread.
#Override
protected Void doInBackground(Void... params)
{
try
{
//Get the current thread's token
synchronized (this)
{
//Initialize an integer (that will act as a counter) to zero
int counter = 0;
//While the counter is smaller than four
while(counter <= 4)
{
//Wait 850 milliseconds
this.wait(750);
//Increment the counter
counter++;
//Set the current progress.
//This value is going to be passed to the onProgressUpdate() method.
publishProgress(counter*25);
}
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return null;
}
//Update the progress
#Override
protected void onProgressUpdate(Integer... values)
{
//set the current progress of the progress dialog
progressDialog.setProgress(values[0]);
}
//after executing the code in the thread
#Override
protected void onPostExecute(Void result)
{
finish();
//close the progress dialog
progressDialog.dismiss();
}
}
}
With these codes, the loading splash screen did came out. But I wonder is there any other way to show only the pop out dialogue for loading progress bar which on top on my previous screen?
Let's say my previous screen was event details. Then when user selected the button, only the dialogue box with loading progress bar will be shown instead of a new intent with a dialogue box.
Any ideas? Thanks in advance.
EDIT
public void onClick(View v) {
// Load the loading splash screen
new LoadViewTask().execute();
ENeighbourhoodActivity.tvDirection.setText("");
eventModel.setEventX(String.valueOf(eventModel.getEventX()));
eventModel.setEventY(String.valueOf(eventModel.getEventY()));
new GetEventDirectionAsyncTask(new GetEventDirectionAsyncTask.OnRoutineFinished() {
public void onFinish() {
//Hide the callout and plot user location marker
ENeighbourhoodActivity.callout.hide();
EventController.getUserLocation(context);
getActivity().finish();
}
}).execute(eventModel);
}
});
public class GetRegisteredEventAsyncTask extends
AsyncTask<String, Integer, Double> {
static EventController eventCtrl = new EventController();
public static ArrayList<Event> upcomingModel = new ArrayList<Event>();
public static ArrayList<Event> pastModel = new ArrayList<Event>();
public interface OnRoutineFinished { // interface
void onFinish();
}
private OnRoutineFinished mCallbacks;
public GetRegisteredEventAsyncTask(OnRoutineFinished callback) {
mCallbacks = callback;
}
public GetRegisteredEventAsyncTask() {
} // empty constructor to maintain compatibility
#Override
protected Double doInBackground(String... params) {
try {
upcomingModel = eventCtrl.getRegisteredUpcomingEvent(params[0]);
pastModel = eventCtrl.getRegisteredPastEvent(params[0]);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Double result) {
if (mCallbacks != null)
mCallbacks.onFinish(); // call interface on finish
}
protected void onProgressUpdate(Integer... progress) {
}
}
In your onClick() method you could write something like:
new LoadViewTask().execute();
and the progress dialog will be shown in that page itself.
what are you doing man, just call your AsyncTask not the intent
public void onClick(View v)
{
new LoadViewTask().execute();
}
});
do your intent in postExecute
#Override
protected void onPostExecute(Void result)
{
finish();
//close the progress dialog
progressDialog.dismiss();
//START YOUR ACTIVITY HERE
Intent loadingIntent = new Intent(context, LoadingScreen.class);
context.startActivity(loadingIntent);
}
Must read the documentation of AsynTask
Currently I have two java class, 1 with AsyncTask and another one is with extend DialogFragment.
I would like to call CreateGroupTask(AsyncTask) in ChooseAddContact java class.
I have tried several recommended ways to execute the AsyncTask java but all failed.
Any recommendation or solution to that?
public class ChooseAddContact extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.pick_add)
.setItems(R.array.contact_array, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == 0){
AddContactDialog dialog2 = new AddContactDialog();
dialog2.show(getFragmentManager(), "AddContactDialog");
} else if (which == 1){
**How should I CALL it here??
//new CreateGroupTask().execute();
//makegroup = new CreateGroupTask();
//makegroup.execute();
}**
}
});
return builder.create(); }
}
And
public class CreateGroupTask extends AsyncTask<Void, Void, String> {
private Context mContext;
private ProgressDialog pd;
public CreateGroupTask() {
}
public CreateGroupTask(Context mContext) {
super();
this.mContext = mContext;
}
#Override
protected void onPreExecute() {
pd = ProgressDialog.show(mContext, null, "Creating group...");
}
#Override
protected String doInBackground(Void... params) {
String chatId = ServerUtilities.create();
if (chatId == null) return null;
try {
...
} catch (SQLException sqle) {}
return chatId;
}
#Override
protected void onCancelled() {
pd.dismiss();
}
#Override
protected void onPostExecute(String result) {
pd.dismiss();
if (result != null) {
Toast.makeText(mContext, "Group created " + result, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(mContext, "Group creation failed. Please retry later.", Toast.LENGTH_LONG).show();
}
}
}
In Dialog Fragment
To Start the async task you need context. In dialog Fragment you can get the context by calling getActivity(); or else you can get the context or activity reference in onAttach() lifecycle method of dialog fragment. Already parametrized constructor is there better to remove zero parametrized constructor.
new CreateGroupTask(getActivity()).execute();
(OR)
private Activity activity;
onAttach(Activity activity){
this.activity=activity;
//store this activity reference
}
//Then Call
new CreateGroupTask(activity).execute();
You can create an object of the class CreateGroupTask and execute wherever you want.
CreateGroupTask createGroupTask = new CreateGroupTask();
then
` if (which == 0){ AddContactDialog dialog2 = new AddContactDialog();
dialog2.show(getFragmentManager(), "AddContactDialog");
} else if (which == 1){
createGroupTask.execute();
// Or new CreateGroupTask().execute();
}`
try this and tell us if any error
What you are missing in AsyncTask is Context. you are using mContext in below code
pd = ProgressDialog.show(mContext, null, "Creating group...");
but you are not initializing that object in default constructor.
Use getActivity while calling task
new CreateGroupTask(getActivity()).execute();
Also remove following constructor from your code
public CreateGroupTask() {
}
I have the following AsyncTask in my Android application. This AsyncTask is contained with within the OnCreate() method of a class that extends PreferenceFragment.
public class NotificationsPreferenceFragment extends PreferenceFragment {
private static Context context;
public NotificationsPreferenceFragment() {
}
public NotificationsPreferenceFragment(Context context) {
this.context = context;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_notifications);
getPreferenceManager().findPreference(getString(R.string.send_all_notifications))
.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
class NotificationSendTask extends DialogAsyncTask {
public static final String TAG = "NotificationFragment";
public NotificationSendTask(Activity activity, String dialogMsg) {
super(activity, dialogMsg);
}
#Override
protected String doInBackground(String... params) {
String url = PreferenceManager.getDefaultSharedPreferences(getActivity()).getString(getString(R.string.notification_web_service_url), getString(R.string.default_notification_web_service_url));
if (NetworkingHelper.isNetworkAvailable(getActivity())) {
NotificationDao notificationDao = new NotificationDaoImpl(DatabaseManager.getInstance(getActivity().getApplicationContext()), getActivity().getApplicationContext());
List<Notification> unsentNotificationList = notificationDao.findAllNotSent();
if (unsentNotificationList.size() != 0) {
NotificationSenderTask ns = new NotificationSenderTask(url, context);
try {
if (ns.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (unsentNotificationList)).get()) {
return getString(R.string.success);
}
} catch (InterruptedException e) {
Log.e(TAG, e.getMessage());
} catch (ExecutionException e) {
Log.e(TAG, e.getMessage());
}
return getString(R.string.failed_to_send_notifications);
} else {
return getString(R.string.no_notifications_to_send);
}
} else {
return getString(R.string.no_connection_notifications);
}
}
public void onPostExecute(String result) {
super.onPostExecute(result);
if (dialog != null && dialog.isShowing()) {
dialog.hide();
}
Toast.makeText(activity, result, Toast.LENGTH_SHORT).show();
}
}
NotificationSendTask notificationSendTask = new NotificationSendTask(getActivity(), "Sending unsent notifications...");
notificationSendTask.execute();
return true;
}
});
getPreferenceManager().findPreference(getString(R.string.export_notifications)).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
NotificationExportTask notificationExportTask = new NotificationExportTask(NotificationsPreferenceFragment.this.getActivity(), 1);
notificationExportTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
return true;
}
});
}
}
I am getting the following exception:
java.lang.IllegalStateException: Fragment NotificationsPreferenceFragment{416092f8} not attached to Activity
at android.app.Fragment.getResources(Fragment.java:741)
at android.app.Fragment.getString(Fragment.java:763)
Can someone please explain to me why this is happening and suggest ways to fix this issue?
UPDATE:
Here is the code for the Activity:
public class SettingsActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
}
}
Since you are performing background task in your app. there is no guarantee that user will stay on same screen until task finishes so if user navigates to other screen or presses home button before task is completed; your fragment is detached from activity. So always make sure that you have fragment attached with the Activity.
try checking with
if (isAdded) {
//Do your UI stuff here
}
add above check wherever you get callback
Move your code from onCreate to onActivityCreated instead of trying to getActivity # onCreate.
That's because the fragment can be created when the activity is not yet ready, that's when you are trying to use it.
That is of course if you are adding the fragment to an activity like:
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(android.R.id.content, new PreferenceFragment()).commit();