在类中获取活动上下文,该类在android中扩展应用程序
亲爱的各位, 我目前正在开发一个android应用程序,需要显示进度对话框。我需要一个上下文对象。 我在扩展应用程序的类中实现的这个任务。但每次我试图访问上下文对象时,它都会显示这一行的名称在类中获取活动上下文,该类在android中扩展应用程序,android,android-layout,android-fragments,android-view,android-context,Android,Android Layout,Android Fragments,Android View,Android Context,亲爱的各位, 我目前正在开发一个android应用程序,需要显示进度对话框。我需要一个上下文对象。 我在扩展应用程序的类中实现的这个任务。但每次我试图访问上下文对象时,它都会显示这一行的名称 Dialog dialog=ProgressDialog.show(getApplicationContext(), "Status", "Downloading The master"); 请帮助我哪里做错了 编辑: 下面是我的代码 public class FlightStatus extends A
Dialog dialog=ProgressDialog.show(getApplicationContext(), "Status", "Downloading The master");
请帮助我哪里做错了
编辑:
下面是我的代码
public class FlightStatus extends Application {
private Context context;
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
SharedPreferences preference=getSharedPreferences("FlightStatus", 1);
if(preference.getBoolean("firstLaunch", true))
{
try {
Dialog dialog=ProgressDialog.show(getApplicationContext(), "Status!", "Downloading The master!!");
XLSReadHelper excelReader=new XLSReadHelper(getApplicationContext());
//excelReader.readExcelFile(Environment.getExternalStorageDirectory()+"/UHCPAudit/cases.xls");
excelReader.readExcelFile();
Log.d("Excel Operation ", "records read!!");
preference.edit().putBoolean("firstLaunch", false).commit();
dialog.dismiss();
} catch (Exception e) {
// TODO: handle exception
Log.d("Excel Operation ", e.getMessage());
}
}
}
}
在
应用程序
中尝试获取上下文
是不正确的,因为在此阶段没有任何活动
被初始化。而是从活动
/片段
显示对话框
如果从活动中显示进度对话框,请使用:
Dialog dialog = ProgressDialog.show(MyActivity.this, "Status", "Downloading The master");
如果您是从片段
显示它,则首先将此成员添加到片段
类:
private Activity activity;
然后在onCreateView()方法中调用此函数:
activity = getActivity();
最后
Dialog dialog = ProgressDialog.show(activity, "Status", "Downloading The master");
可以使用将活动作为上下文的构造函数
public class YourClass extends Application{
private Activity context;
public YourClass(Activity context){
this.context = context;
}
}
然后从您的呼叫活动
:
YourClass yourClass = new YourClass(this);
您还可以尝试在活动
本身中使用进度对话框
,方法可以从自定义类调用:
public void showProgress(){
//Your progress code
}
context.showProgress();
在自定义类中:
public void showProgress(){
//Your progress code
}
context.showProgress();
你好,我是从扩展应用程序的类访问的!当您从活动开始这个类时,您也可以传递上下文,并且可以轻松地使用上下文。@nsm:您如何调用该方法?我在android清单文件中提到了应用程序标记,应用程序类的名称和我正在编写的oncreate中的名称相同line@nsm请在清单中添加您的代码,我认为您在coding@nsm我做了一个编辑,并提出了另一个尝试的建议。