我正在为ProgressBar
创建常见的java类,我收到如下错误
java.lang.NullPointerException: Attempt to invoke virtual method 'void app.bridgecenterandstaffmanagament.com.bridgecenterandstaffmanagament.CommonClass.Singletonclass_obj.showProgressBar(android.content.Context)' on a null object reference
at app.bridgecenterandstaffmanagament.com.bridgecenterandstaffmanagament.Fragments.NotificationFragment.onCreateView(NotificationFragment.java:41)
片段
public class NotificationFragment extends Fragment {
public NotificationFragment() {
// Required empty public constructor
}
RecyclerView recyclerView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_notification, container, false);
recyclerView = v.findViewById(R.id.recylierview_notification);
// Singletonclass_obj.getInstance().showProgressBar(getActivity());
Singletonclass_obj.getInstance().showProgressBar(getContext());
// print();
return v;
}
}
Java 类
public class Singletonclass_obj extends Application{
private ProgressBar progressBar;
private static Singletonclass_obj singletonclassobj;
public static Singletonclass_obj getInstance() {
return singletonclassobj;
}
@Override
public void onCreate() {
super.onCreate();
singletonclassobj = this;
}
public void showProgressBar(Context context)
{
// Toast.makeText(context, "welcometoindia", Toast.LENGTH_SHORT).show();
progressBar = new ProgressBar(context, null, android.R.attr.progressBarStyleSmall);
}
public void hideProgressBar()
{
if (progressBar !=null && progressBar.isShown())
progressBar.setVisibility(View.INVISIBLE);
}
}
相同的代码工作正常我的上一个Project..please帮助我任何一个。
答案 0 :(得分:5)
根据我的问题above comment
尝试将Singletonclass_obj
添加到application tag like below code
<application
android:name=".Singletonclass_obj"<!--add here your Singletonclass_obj class -->
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
答案 1 :(得分:3)
问题是您没有正确初始化应用程序类。基本上,系统不了解您的课程,因此不会创建。您需要在<application>
的{{1}}标记中添加以下内容,它才有效:
Manifest
并将其称为:android:name=".Singletonclass_obj"
但是,正如我在评论中所说,您不需要将应用程序类创建为单例,因为它已经是。所以你的应用程序类将是这样的:
((Singletonclass_obj)getActivity().getApplication()).showProgressBar(getContext());
即使这样可以解决您关于NPE的问题,但您仍然无法使用public class Singletonclass_obj extends Application {
private ProgressBar progressBar;
@Override
public void onCreate() {
super.onCreate();
}
public void showProgressBar(Context context)
{
// Toast.makeText(context, "welcometoindia", Toast.LENGTH_SHORT).show();
progressBar = new ProgressBar(context, null, android.R.attr.progressBarStyleSmall);
}
public void hideProgressBar()
{
if (progressBar !=null && progressBar.isShown())
progressBar.setVisibility(View.INVISIBLE);
}
}
,因为您没有添加视图(该应用程序没有&#39;有观点)。