In my android application, I set title name of an activity in AndroidManifest.xaml
like below:
<activity
android:name=".LoginSuccess"
android:label="Home" > // this is title name
</activity>
And activity title name is Home
and I wan to get this actitvity title name in my actitvity's java page, I am trying like below:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_sample);
android.support.v7.app.ActionBar actionBar = getSupportActionBar();
pageTitle = actionBar.getTitle().toString();
}
But I am getting below exception at this line pageTitle = actionBar.getTitle().toString();
:
java.lang.NullPointerException
Kindly suggest me, what can I do to resolve this issue,
waiting for reply.
Thanks.
You can also get like this from PackageManager
ActivityInfo activityInfo = getPackageManager().getActivityInfo(
getComponentName(), PackageManager.GET_META_DATA);
String title = activityInfo.loadLabel(getPackageManager())
.toString();
ActionBar actionBar = getActionBar();
String classTitle = actionBar.getTitle().toString();
It's because you trying to get title before it creates.
You can try do it with delay in your onCreate
method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_sample);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
android.support.v7.app.ActionBar actionBar = getSupportActionBar();
pageTitle = actionBar.getTitle().toString();
}
}, 500);
}
It works fine.
在Strings.xml中定义你的字符串,然后尝试做延迟它可能工作相同的事情。
I know it´s been a while since the last post but for those (like me) searching a solution for this issue.... you don´t need action bar to get the Manifest´s activities label, just do the follow in your Activity´s onStart:
@Override
protected void onStart() {
super.onStart();
String pageTitle = getTitle();// it´s not available in onCreate yet
}
请尝试以下代码以获取类文件中的当前活动名称。
this.getClass().getSimpleName()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.