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. 【tvm解析】PACKFUNC机制

    为实现多种语言支持,需要满足以下几点: 部署:编译结果可以从python/javascript/c++调用. Debug: 在python中定义一个函数,在编译函数中调用. 链接:编写驱动程序以调用设 ...

  2. 前端vue uni-app百度地图定位组件,显示地图定位,标记点,并显示详细地址

    快速实现前端百度地图定位组件,显示地图定位,标记点,并显示详细地址; 下载完整代码请访问uni-app插件市场地址:https://ext.dcloud.net.cn/plugin?id=12677 ...

  3. SQL Sever 基础语法(增)

    SQL Sever  插入(Insert)基础语法详解 在SQL中,向表中插入数据是最基础的,任何对数据处理的基础就是数据库有数据,对于SQL而言,向表中插入数据有多种方法,本文列举3种: (一) 标 ...

  4. Unity的Console的控制类LogEntries:深入解析与实用案例

    使用Unity Console窗口的LogEntries私有类实现自定义日志系统 在Unity开发过程中,我们经常需要使用Console窗口来查看程序运行时的日志信息.Unity内置的日志系统提供了基 ...

  5. 微信小程序 WXSS模板样式,全局和页面配置,网络请求

    [黑马程序员前端微信小程序开发教程,微信小程序从基础到发布全流程_企业级商城实战(含uni-app项目多端部署)] https://www.bilibili.com/video/BV1834y1676 ...

  6. Windows同时安装多个JDK

    一.下载并安装JDK这一步选择你需要的JDK并下载安装,记得要记住安装的路径. 二.为JDK配置环境变量①找到系统环境变量 ②新建如下三个环境变量 第一个表示默认Java的home路径,以后在更改JD ...

  7. 基于Taro开发京东小程序小记

    一.小程序基础模型 这里要从微信小程序的历史说起,从前身到现在大概分为3个阶段: 阶段1: 微信网页需要用到app的原生能力,微信官方推出了js-sdk 阶段2: 解决移动端白屏问题,采用微信web资 ...

  8. 2021-7-30 MySql进阶2

    创建临时表只需在table前面加temporary CREATE TEMPORARY TABLE mytable#创建临时表,在断开数据库连接时销毁 ( ID INT NOT NULL, userna ...

  9. Powe AutoMate:列表操作

    大纲 记录对列表的操作 创建列表 向列表中添加元素 添加多个 合并列表 运行结果 反转列表 反转前 反转后 删除列表中的重复项 结果: 减去列表 结果:

  10. tensorflow.js 对视频 / 直播人脸检测和特征点收集

    前言: 这里要介绍的是 Tensorflow.js 官方提供的两个人脸检测模型,分别是 face-detection 和 face-landmarks-detection.他们不但可以对视频中的人间进 ...