The method showDialog(int) from the type Activity is deprecated.

What's the reason? and how to solve it?

7down voteaccepted

What's the reason?

http://developer.android.com/reference/android/app/Activity.html#showDialog(int)

Android DialogFragment vs Dialog

How to solve it?

Use the new DialogFragment class with FragmentManager instead; this is also available on older platforms through the Android compatibility package.

http://android-developers.blogspot.in/2012/05/using-dialogfragments.html

 

Google recommends that we use DialogFragment instead of a simple Dialog by using Fragments API, but it is absurd to use an isolated DialogFragment for a simple Yes-No confirmation message box. What is the best practice in this case?

asked Nov 2 '11 at 8:18
skayred
2,23432049
 

4 Answers

Yes use DialogFragment and in onCreateDialog you can simply use an AlertDialog builder anyway to create a simple AlertDialog with Yes/No confirmation buttons. Not very much code at all.

With regards handling events in your fragment there would be various ways of doing it but I simply define a message Handler in my Fragment, pass it into the DialogFragment via its constructor and then pass messages back to my fragment's handler as approprirate on the various click events. Again various ways of doing that but the following works for me.

In the dialog hold a message and instantiate it in the constructor:

private Message okMessage;
...
okMessage = handler.obtainMessage(MY_MSG_WHAT, MY_MSG_OK);

Implement the `onClickListener' in your dialog and then call the handler as appropriate:

public void onClick(.....
if (which == DialogInterface.BUTTON_POSITIVE) {
final Message toSend = Message.obtain(okMessage);
toSend.sendToTarget();
}
}

Edit

And as Message is parcelable you can save it out in onSaveInstanceState and restore it

outState.putParcelable("okMessage", okMessage);

Then in onCreate

if (savedInstanceState != null) {
okMessage = savedInstanceState.getParcelable("okMessage");
}
answered Nov 2 '11 at 11:50
PJL
5,48234754
 
1  
How do you persist okMessage? The problem is that when the activity is restarted (orientation change or whatever), your custom constructor is not called and thus your okMessage will be null. –  hrnt Nov 2 '11 at 11:59
1  
The problem is not okMessage - the problem is okMessage's target which will be null if you load it from a Bundle. If the target of a Message is null, and you use sendToTarget, you will get a NullPointerException - not because the Message is null, but because its target is. –  hrnt Nov 2 '11 at 12:44
4  
Why We should be using DialogFragment instead of plain Dialogs ????? –  Amit Nov 10 '12 at 7:03
1  
What the advantages of using DialogFragment instead of a Dialog? –  Raphael Petegrosso Dec 7 '12 at 14:43
13  
The advantage of using a DialogFragment is that all the life cycle of the dialog will be handled for you. You will never get the error 'dialog has leaked...' again. Go to DialogFragment and forget Dialogs. –  Snicolas Mar 13 '13 at 10:06
 

I would recommend using DialogFragment.

Sure, creating a "Yes/No" dialog with it is pretty complex considering that it should be rather simple task, but creating a similar dialog box with Dialog is surprisingly complicated as well.

(Activity lifecycle makes it complicated - you must let Activity manage the lifecycle of the dialog box - and there is no way to pass custom parameters e.g. the custom message to Activity.showDialog if using API levels under 8)

The nice thing is that you can usually build your own abstraction on top of DialogFragment pretty easily.

answered Nov 2 '11 at 8:40
hrnt
5,8401728
 
    
How you will handle alert dialog callbacks (yes, no)? –  Alexey Zakharov Nov 2 '11 at 8:49 
    
The easiest way would be to implement a method in the hosting Activity that takes a String parameter. When the user clicks "Yes", for example, the dialog calls the Activity's method with parameter "agree". These parameters are specified when showing the dialog, for example AskDialog.ask("Do you agree to these terms?", "agree", "disagree"); –  hrnt Nov 2 '11 at 8:54
3  
But i need callback inside fragment, not activity. I can use setTargetFragment and cast it to interface. But it is hell. –  Alexey Zakharov Nov 2 '11 at 8:59
    
You could also fetch the target fragment by setting a tag to the target and using FragmentManager's findFragmentByTag. But yeah, it requires a fair bit of code. –  hrnt Nov 2 '11 at 9:53

Use DialogFragment over AlertDialog:


  • Since the introduction of API level 13:

    the showDialog method from Activity is deprecated. Invoking a dialog elsewhere in code is not advisable since you will have to manage the the dialog yourself (e.g. orientation change).

  • Difference DialogFragment - AlertDialog

    Are they so much different? From Android reference regarding DialogFragment:

    A DialogFragment is a fragment that displays a dialog window, floating on top of its activity's window. This fragment contains a Dialog object, which it displays as appropriate based on the fragment's state. Control of the dialog (deciding when to show, hide, dismiss it) should be done through the APIhere, not with direct calls on the dialog.

  • Other notes

    • Fragments are a natural evolution in the Android framework due to the diversity of devices with different screen sizes.
    • DialogFragments and Fragments are made available in the support library which makes the class usable in all current used versions of Android.
answered Jun 14 '13 at 23:27
user1281750
2,64421442
 

You can create generic DialogFragment subclasses like YesNoDialog and OkDialog, and pass in title and message if you use dialogs a lot in your app.

public class YesNoDialog extends DialogFragment
{
public YesNoDialog()
{ } @Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
Bundle args = getArguments();
String title = args.getString("title", "");
String message = args.getString("message", ""); return new AlertDialog.Builder(getActivity())
.setTitle(title)
.setMessage(message)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, null);
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_CANCELED, null);
}
})
.create();
}
}

Then call it using the following:

    DialogFragment dialog = new YesNoDialog();
Bundle args = new Bundle();
args.putString("title", title);
args.putString("message", message);
dialog.setArguments(args);
dialog.setTargetFragment(this, YES_NO_CALL);
dialog.show(getFragmentManager(), "tag");

And handle the result in onActivityResult.

answered Jan 9 at 22:51
ashishduh
1,7241512
 
    
can it work after activity being recreated (screen rotated) –  Malachiasz Jan 30 at 10:22
    
Yes, DialogFragment handles all lifecycle events for you. –  ashishduh Jan 30 at 14:45
1  
I think it doesn't because after rotation old Dialog still exists and it keeps assignent to old not existing fragment (dialog.setTargetFragment(this, YES_NO_CALL);) so after rotation getTargetFragment().onActivityResult doesn't work –  Malachiasz Jan 30 at 15:21
    
I use this code for all my dialogs and they work fine when screen is rotated. setTargetFragment uses FragmentManager methods to retain state of Fragments. –  ashishduh Jan 30 at 19:32 
    
I think that only way for it to work is to have the Fragment setRetainInstance(true) or (Activity not being destroyed). And this is unwanted in many cases. –  Malachiasz Feb 3 at 10:20

The method dismissDialog(int) from the type Activity is deprecated的更多相关文章

  1. hibernate3和4中 HibernateSessionFactory中不同之处 The method applySettings(Map) from the type ServiceRegistryBuilder is deprecated - The type ServiceRegistryBuilder is deprecated

    hibernate3和4中 HibernateSessionFactory中不同之处 //serviceRegistry = new ServiceRegistryBuilder().applySet ...

  2. .replace(R.id.container, new User()).commit();/The method replace(int, Fragment) in the type FragmentTransaction is not app

    提示错误:The method replace(int, Fragment) in the type FragmentTransaction is not applicable for the arg ...

  3. 错误:The method replace(int, Fragment) in the type FragmentTransaction is not applicable for the arguments (int, MyFragment)

    Fragment newfragment =new MyFragment();fragmentTransaction.replace(R.layout.activity_main,newfragmen ...

  4. The method replace(int, Fragment, String) in the type FragmentTransaction is not applicable for the arguments (int, SettingFragment, String)

    The method replace(int, Fragment, String) in the type FragmentTransaction is not applicable for the ...

  5. The method setPositiveButton(int, DialogInterface.OnClickListener) in the type AlertDialog.Builder is not applicable for the arguments

    The method setPositiveButton(int, DialogInterface.OnClickListener) in the type AlertDialog.Builder i ...

  6. The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (new View.OnClickListener(){}, String, int)

    package comxunfang.button; import android.support.v7.app.ActionBarActivity; import android.os.Bundle ...

  7. delete attempted to return null from a method with a primitive return type (int)

    今天被自己给蠢死了 今天在代码中遇到这个错误, 百度翻译一下:映射方法,从一org.system.mapper.child.chmorganizationexaminationmapper.delet ...

  8. attempted to return null from a method with a primitive return type (int).

    java接口文件 package com.cyb.ms.mapper; import org.apache.ibatis.annotations.Param; public interface Acc ...

  9. The method setPositiveButton(int, DialogInterface.OnClickListener) in the type AlertDialog.Builder i

    参考资料: http://blog.csdn.net/competerh_programing/article/details/7377950 在创建Dialog的时候,出现: The method ...

  10. Mapper method 'com.xxxx.other.dao.MyDao.getNo attempted to return null from a method with a primitive return type (int)

    使用myBatis调用存储过程的返回值,提示错误信息: org.apache.ibatis.binding.BindingException: Mapper method 'com.xxxx.othe ...

随机推荐

  1. 现代C++学习指南-方向篇

    C++是一门有着四十年历史的语言,先后经历过四次版本大升级(诞生.98.11.17(20),14算小升级).每次升级都是很多问题和解决方案的取舍.了解这些历史,能更好地帮助我们理清语言的发展脉络.所以 ...

  2. Nashorn引擎导致metaspace oom

          从报错内容很清楚是Metaspace区域oom了 大部分情况下,程序运行中不会出现过多的类加载数量的变动,先导入dump文件检查是否有异常的classLoader或者有异常动态生成的cla ...

  3. 学生课程分数的Spark SQL分析

    读学生课程分数文件chapter4-data01.txt,创建DataFrame. url = "file:///D:/chapter4-data01.txt" rdd = spa ...

  4. 续《基于C# 开发的SOL SERVER 操作数据库类(SQLHelp》 ——第二弹

    续上一节,本节给出SQLHelp的具体实现方法--<YSFSQLHelp>,个人根据自己需要新建适合的类,本节根据参考网上资料,根据自己的需要编写的SQL帮助类.下面直接给出具体实现: / ...

  5. 图像增强—自适应直方图均衡化(AHE)-限制对比度自适应直方图均衡(CLAHE)

    一.自适应直方图均衡化(Adaptive histgram equalization/AHE) 1.简述 自适应直方图均衡化(AHE)用来提升图像的对比度的一种计算机图像处理技术.和普通的直方图均衡算 ...

  6. 平时容易忽视的地方之一:java在抽取方法时,什么时候该用void

    当一个类中多个方法有相同编码,或该部分编码可以作为一个整体,适合抽取出一个方法时,要注意这个抽取的方法的返回值,什么时候可以用void,什么时候不能用void? 先看代码: import lombok ...

  7. 解决Oracle jdbc驱动包maven下载失败问题

    由于Oracle版权限制,其jdbc驱动包不让人随便下载,这就给maven的下载和编译带来了麻烦. 解决办法是先获取jar包(方法一:去oracle官网下载,方法二:去oracle安装目录如produ ...

  8. SpringBoot整合WebService(实用版)

    SpringBoot整合WebService 简介 WebService就是一种跨编程语言和跨操作系统平台的远程调用技术 此处就不赘述WebService相关概念和原理了,可以参考:https://b ...

  9. 应用debezium将postgresql数据送至kafka(官网示例,本地docker部署)

    版本 conncet 2.2 postgresql 15.2 1 postgresql 1.1 获取 docker pull debezium/example-postgres 1.2 运行 dock ...

  10. python打包方法

    在Python中,要编写setup.py文件,用于构建和打包你的Python项目,你可以遵循以下步骤: 创建项目目录结构:首先,你需要创建项目的目录结构,包括源代码文件.资源文件等.一个常见的项目结构 ...