如何修复Android中片段中未找到的视图

时间:2017-10-10 06:21:34

标签: java android android-fragments

在我的应用程序中,我想从服务器获取一些数据并将其显示在RecyclerView中,为此我应该使用Fragment

我希望用户看到fragment调用我的API调用方法。但是当在代码下方使用时,请显示强制关闭错误。

代码:

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser){
        getData(getActivity());
    }
}

错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' on a null object reference
    at com.app.test.Fragments.MainNotificationFrags.NotificationAllFrag.getData(NotificationAllFrag.java:157)
    at com.app.test.Fragments.MainNotificationFrags.NotificationAllFrag.setUserVisibleHint(NotificationAllFrag.java:142)
    at android.support.v4.app.FragmentStatePagerAdapter.setPrimaryItem(FragmentStatePagerAdapter.java:157)
    at android.support.v4.view.ViewPager.populate(ViewPager.java:1266)
    at android.support.v4.view.ViewPager.populate(ViewPager.java:1116)
    at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1642)
    at android.view.View.measure(View.java:17496)
    at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728)
    at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:464)
    at android.view.View.measure(View.java:17496)
    at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1658)
    at android.view.View.measure(View.java:17496)
    at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728)
    at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:464)
    at android.view.View.measure(View.java:17496)
    at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:1081)
    at android.view.View.measure(View.java:17496)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
    at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
    at android.view.View.measure(View.java:17496)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1438)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:724)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:615)
    at android.view.View.measure(View.java:17496)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
    at android.view.View.measure(View.java:17496)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1438)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:724)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:615)
    at android.view.View.measure(View.java:17496)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
    at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2636)
    at android.view.View.measure(View.java:17496)
    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2031)
    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1193)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1400)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1078)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5875)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
    at android.view.Choreographer.doCallbacks(Choreographer.java:580)
    at android.view.Choreographer.doFrame(Choreographer.java:550)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5349)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)

片段完整代码:

public class NotificationAllFrag extends Fragment {

    @BindView(R.id.mainNotification_recyclerView)
    RecyclerView mainNotification_recyclerView;
    @BindView(R.id.mainNotification_noNotificationTxt)
    TextView mainNotification_noNotificationTxt;
    @BindView(R.id.mainNotification_progressBar)
    ProgressBar mainNotification_progressBar;
    @BindView(R.id.newsPageLoadLay)
    RelativeLayout newsPageLoadLay;
    private Context context;
    private List<Datum> model = new ArrayList<>();
    public static NotificationListAdapter notificationListAdapter;
    private SharedPrefrencesHandler prefrencesHandler;
    private String token = "";
    private LinearLayoutManager layoutManager;

    public NotificationAllFrag() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_notification_all, container, false);

        //Initialize
        ButterKnife.bind(this, view);
        context = getActivity();
        notificationListAdapter = new NotificationListAdapter(context, model);
        prefrencesHandler = new SharedPrefrencesHandler(context);
        layoutManager = new LinearLayoutManager(context);
        //RecyclerView
        mainNotification_recyclerView.setLayoutManager(layoutManager);
        mainNotification_recyclerView.setHasFixedSize(true);

        //Get token
        token = prefrencesHandler.getFromShared(SharedPrefrencesKeys.TOKEN.name());
        // Lazy loader
        newsPageLoadLay.setVisibility(View.GONE);
        mainNotification_recyclerView.setOnScrollListener(new EndlessRecyclerLinearPage1(layoutManager) {
            @Override
            public void onLoadMore(int current_page) {
                ExploreSendData sendData = new ExploreSendData();
                sendData.setPageIndex(current_page);
                sendData.setPageSize(10);
                sendData.setShowFollows(true);
                sendData.setShowMovies(false);
                sendData.setShowNews(false);
                sendData.setShowReplies(true);
                sendData.setShowSeries(false);
                sendData.setShowSuggestions(true);

                newsPageLoadLay.setVisibility(View.VISIBLE);

                InterfaceApi api = ApiClient.getClient().create(InterfaceApi.class);
                Call<ExploreResponse> call = api.getExplore(token, sendData);

                call.enqueue(new Callback<ExploreResponse>() {
                    @Override
                    public void onResponse(Call<ExploreResponse> call, Response<ExploreResponse> response) {
                        if (response.body().getData() != null && response.body().getStatusCode() != 401
                                && response.body().getStatusCode() != 402) {
                            if (response.body().getData().size() > 0) {
                                notificationListAdapter.addNewItem(response.body().getData());
                                //Gone no explore
                                newsPageLoadLay.setVisibility(View.GONE);
                            }
                        } else {
                            prefrencesHandler.remove(SharedPrefrencesKeys.TOKEN.name());
                            startActivity(new Intent(context, LoginActivity.class));
                        }

                        newsPageLoadLay.setVisibility(View.GONE);
                    }

                    @Override
                    public void onFailure(Call<ExploreResponse> call, Throwable t) {
                        newsPageLoadLay.setVisibility(View.GONE);
                    }
                });
            }
        });

        getData(getActivity());

        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser){
            getData(getActivity());
        }
    }

    public void getData(final Context context) {
        ExploreSendData sendData = new ExploreSendData();
        sendData.setPageIndex(1);
        sendData.setPageSize(10);
        sendData.setShowFollows(true);
        sendData.setShowMovies(false);
        sendData.setShowNews(false);
        sendData.setShowReplies(true);
        sendData.setShowSeries(false);
        sendData.setShowSuggestions(true);

        mainNotification_progressBar.setVisibility(View.VISIBLE);

        InterfaceApi api = ApiClient.getClient().create(InterfaceApi.class);
        Call<ExploreResponse> call = api.getExplore(
                new SharedPrefrencesHandler(context).getFromShared(SharedPrefrencesKeys.TOKEN.name()), sendData);

        call.enqueue(new Callback<ExploreResponse>() {
            @Override
            public void onResponse(Call<ExploreResponse> call, Response<ExploreResponse> response) {
                if (response.body().getData() != null && response.body().getStatusCode() != 401
                        && response.body().getStatusCode() != 402) {
                    if (response.body().getData().size() > 0) {
                        model.clear();
                        model.addAll(response.body().getData());
                        notificationListAdapter.notifyDataSetChanged();
                        mainNotification_recyclerView.setAdapter(notificationListAdapter);
                        //Gone no explore
                        mainNotification_noNotificationTxt.setVisibility(View.GONE);

                    } else {
                        mainNotification_noNotificationTxt.setVisibility(View.VISIBLE);
                        mainNotification_recyclerView.setVisibility(View.GONE);
                    }
                } else {
                    prefrencesHandler.remove(SharedPrefrencesKeys.TOKEN.name());
                    startActivity(new Intent(context, LoginActivity.class));
                }

                mainNotification_progressBar.setVisibility(View.GONE);
            }

            @Override
            public void onFailure(Call<ExploreResponse> call, Throwable t) {
                mainNotification_progressBar.setVisibility(View.GONE);
            }
        });
    }

我该如何解决?请帮忙

4 个答案:

答案 0 :(得分:1)

似乎在class SwaggerTest { public static void main(String[] args) { SwaggerTest st = new SwaggerTest(); st.validate(); } private void validate() { try { String content = new String(Files.readAllBytes(Paths.get("petstore.yml"))); SwaggerParser swaggerParser = new SwaggerParser(); SwaggerDeserializationResult result = swaggerParser.readWithInfo(content); swaggerParser.parse(content); Swagger swagger = result.getSwagger(); if (swagger == null) { System.out.println("Unable to validate swagger"); }else { System.out.println("Read the swagger"); } List<String> messageList = result.getMessages(); for(String message: messageList) { System.out.println(message); } } catch(Exception e) { System.out.println("Error!! "+ e.getMessage()); } } } 之前调用了setUserVisibleHint()

观看此link

答案 1 :(得分:1)

这不是正确的解决方案,但它100%正常工作

 @Override
 public void setUserVisibleHint(boolean isVisibleToUser) {
     super.setUserVisibleHint(isVisibleToUser);
     if (isVisibleToUser && mainNotification_recyclerView!=null){
         getData(getActivity());
     }
 }



 @Override
 public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
     super.onViewCreated(view, savedInstanceState);
     if (getUserVisibleHint()) {
         getData(getActivity());
     }
 }
  

当用户在标签上进行初始化数据时,它可以使用多个或单个标签

     

它可以帮助更快地加载数据,甚至可以同时加载所有片段

答案 2 :(得分:1)

试试这个

我们应该知道setUserVisibleHint之前已加载onCreateView

private boolean isVisible = false;
private View view;

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        isVisible = true;
        onVisible();
    }
}

// onVisible method
private void onVisible() {
    // edited here 
    if (isVisible && view != null && mainNotification_progressBar != null) {
        getData(getActivity());
    }
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragment_notification_all, container, false);
    // add ButterKnife here
    ButterKnife.bind(this, view);
    onVisible();
    return view;
}

答案 3 :(得分:0)

试试这个

 @Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser){
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                getData(getActivity());
            }
        },3000);

    }
}

希望这有助于你...如果你需要任何帮助,你可以问