尝试调用虚方法' java.lang.Object android.app.Activity.getSystemService(java.lang.String)'在null对象引用上

时间:2016-08-31 14:14:22

标签: java android nullpointerexception

这是我的代码:

public class LatestPostFragment  extends Fragment {
private static final String TAG = LatestPostFragment.class.getSimpleName();
View rootView;
LinearLayout grid_view_wrapper;
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private LinearLayout layout_dots;
private TextView[] dots;
private Integer viewPagerLength;

Typeface font;
ArrayList<Post>viewPagerItems = new ArrayList<Post>();
private List<Category> categoriesList;
public LatestPostFragment() {}

@Override
public void onResume() {
    super.onResume();
    //Get a Tracker (should auto-report)
    if (Const.Analytics_ACTIVE) {
        AnalyticsUtil.sendScreenName(getActivity(), TAG);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    rootView = inflater.inflate(R.layout.fragment_latest, container, false);

    //Forcing RTL Layout, If Supports and Enabled from Const file
    Utils.forceRTLIfSupported(getActivity());

    grid_view_wrapper = (LinearLayout) rootView.findViewById(R.id.grid_view_wrapper);

    font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/iran_sans.ttf");

    ConnectionDetector cd = new ConnectionDetector(this.getActivity());
    Boolean isInternetPresent = cd.isConnectingToInternet();
    if (isInternetPresent) {
        getFeaturedPosts();

        categoriesList = AppController.getInstance().getPrefManger().getFeaturedCategories();
        for (Category a : categoriesList) {
            getLatestPosts(a.getId());
        }
    }
    return rootView;
}

private void getFeaturedPosts(){
    String featured_url = Const.URL_BLOG + Const.URL_BLOG_API + Const.URL_FEATURED + "?t=" + System.currentTimeMillis();
    // making fresh volley request and getting json
    JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET, featured_url, null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            if (response != null) {
                try {
                    if (response.has("error")) {
                        String error = response.getString("error");
                        Toast.makeText(getActivity().getApplicationContext(), error, Toast.LENGTH_LONG).show();
                    }else {
                        if (response.isNull("feed")) {

                        }else{
                            viewPagerLength = response.getInt("total_items");

                            JSONArray feedArray = response.getJSONArray("feed");

                            for (int i = 0; i < feedArray.length(); i++) {
                                JSONObject feedObj = (JSONObject) feedArray.get(i);
                                Post item = new Post();
                                item.setId(feedObj.getInt("id"));
                                item.setName(feedObj.getString("name"));
                                item.setCategory(feedObj.getString("category"));
                                String image = feedObj.isNull("image_big") ? null : feedObj.getString("image_big");
                                item.setImge(image);
                                item.setTimeStamp(feedObj.getString("timeStamp"));
                                item.setAuthor(feedObj.getString("author"));
                                // url might be null sometimes
                                String feedUrl = feedObj.isNull("url") ? null : feedObj.getString("url");
                                item.setUrl(feedUrl);
                                viewPagerItems.add(item);
                            }

                            setupViewPager();

                        }
                    }
                }catch (JSONException es) {
                    es.printStackTrace();
                    Toast.makeText(getActivity().getApplicationContext(), "Featured: " + getString(R.string.unknown_error), Toast.LENGTH_LONG).show();
                }
            }else{

            }
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
        }
    }) {
        /** Passing some request headers **/
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            headers.put("ApiKey", Const.AuthenticationKey);
            return headers;
        }
    };

    // Adding request to volley request queue
    AppController.getInstance().addToRequestQueue(jsonReq);
}

public void setupViewPager(){
    layout_dots = (LinearLayout) rootView.findViewById(R.id.layout_dots);
    viewPager   = (ViewPager)    rootView.findViewById(R.id.view_pager);
    addBottomDots(0);
    //  viewpager change listener
    ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            addBottomDots(position);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {

        }

        @Override
        public void onPageScrollStateChanged(int arg0) {

        }
    };

    myViewPagerAdapter = new MyViewPagerAdapter();
    viewPager.setAdapter(myViewPagerAdapter);
    viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
}

private void addBottomDots(int currentPage) {
    dots = new TextView[viewPagerLength];

    layout_dots.removeAllViews();
    for (int i = 0; i < Const.FeaturedView; i++) {
        dots[i] = new TextView(getActivity());
        dots[i].setText(Html.fromHtml("&#8226;"));
        dots[i].setTextSize(35);
        dots[i].setTextColor(getResources().getColor(R.color.viewpager_inactive));
        layout_dots.addView(dots[i]);
    }

    if (dots.length > 0)
        dots[currentPage].setTextColor(getResources().getColor(R.color.viewpager_active));
}

public class MyViewPagerAdapter extends PagerAdapter {
    private LayoutInflater layoutInflater;

    public MyViewPagerAdapter() {
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.viewpager_item, container, false);

        final Post p = viewPagerItems.get(position);

        TextView name = (TextView) view.findViewById(R.id.name);
        name.setTypeface(font);
        name.setTextSize(20);
        name.setText(Html.fromHtml(p.getName()));

        TextView category = (TextView) view.findViewById(R.id.category);
        category.setText(Html.fromHtml(p.getCategory()));

        ImageView img = (ImageView) view.findViewById(R.id.feedImage1);
        Picasso.with(getActivity()).load(p.getImge()).into(img);

        //TextView post_author = (TextView) view.findViewById(R.id.post_author);
        //post_author.setText(String.format(getString(R.string.post_by), Html.fromHtml(p.getAuthor())));

        CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
                Long.parseLong(p.getTimeStamp()),
                System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
        TextView timestamp = (TextView) view.findViewById(R.id.timestamp);
        // amin time
        DateTime dateTime = new DateTime(Long.parseLong(p.getTimeStamp()));
        dateTime.withZone(DateTimeZone.forID("Asia/Tehran"));
        Roozh jCal = new Roozh();
        jCal.GregorianToPersian(dateTime.getYear(), dateTime.getMonthOfYear(), dateTime.getDayOfMonth());
        CharSequence timeAmin = jCal.toString();
        // view time
        if(System.currentTimeMillis() - Long.parseLong(p.getTimeStamp())<604800000)
            timestamp.setText(String.format(getString(R.string.publish_on), timeAgo));
        else
            timestamp.setText(String.format(getString(R.string.publish_on), timeAmin));

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent();
                i.setClass(getActivity(), PostViewActivity.class);
                i.putExtra(PostViewActivity.TAG_SEL_POST_ID, "P" + p.getId());
                i.putExtra(PostViewActivity.TAG_SEL_POST_TITLE, p.getName());
                startActivity(i);
            }
        });

        container.addView(view);

        return view;
    }

    @Override
    public int getCount() {
        return viewPagerItems.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object obj) {
        return view == obj;
    }


    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        View view = (View) object;
        container.removeView(view);
    }
}

private void getLatestPosts(final String category_id){
    String featured_url = Const.URL_BLOG + Const.URL_BLOG_API + Const.URL_FEATURED_CATEGORY_POST.replace("_CAT_ID_", category_id) + "?t=" + System.currentTimeMillis();
    Log.d(TAG, featured_url);
    // making fresh volley request and getting json
    JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET, featured_url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            if (response != null) {
                try {
                    if (response.has("error")) {
                        String error = response.getString("error");
                        Toast.makeText(getActivity().getApplicationContext(), error, Toast.LENGTH_LONG).show();
                    }else {
                        if (response.isNull("feed")) {

                        }else{
                                LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                                View view = layoutInflater.inflate(R.layout.gridview_category, null, false);

                                final TextView category_button = (TextView) view.findViewById(R.id.btnCategory);

                                final String category_name = response.getString("category");
                                TextView category_title = (TextView) view.findViewById(R.id.category_title);
                                category_title.setText(Html.fromHtml(category_name));
                                category_title.setTypeface(font);
                                category_title.setTextSize(20);


                                category_button.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        ((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle(category_name);
                                        Fragment fragment = GridFragment.newInstance(GridFragment.PageType.CATEGORY, category_id, category_name);
                                        FragmentManager fragmentManager = getFragmentManager();
                                        fragmentManager.beginTransaction()
                                                .replace(R.id.frame_container, fragment).commit();
                                    }
                                });

                                LinearLayout hsv = (LinearLayout) view.findViewById(R.id.recycler_view);

                                JSONArray feedArray = response.getJSONArray("feed");
                                for (int i = 0; i < feedArray.length(); i++) {
                                    JSONObject feedObj = (JSONObject) feedArray.get(i);
                                    View lvg = layoutInflater.inflate(R.layout.listview_item_grid, null, false);

                                    TextView post_name = (TextView) lvg.findViewById(R.id.post_name);
                                    post_name.setText(Html.fromHtml(feedObj.getString("name")));

                                    ImageView img = (ImageView) lvg.findViewById(R.id.feedImage1);
                                    Picasso.with(getActivity()).load(feedObj.getString("image_big")).into(img);

                                    final Post item = new Post();
                                    item.setId(feedObj.getInt("id"));
                                    item.setName(feedObj.getString("name"));
                                /*item.setCategory(feedObj.getString("category"));
                                String image = feedObj.isNull("image_big") ? null : feedObj.getString("image_big");
                                item.setImge(image);
                                item.setTimeStamp(feedObj.getString("timeStamp"));
                                // url might be null sometimes
                                String feedUrl = feedObj.isNull("url") ? null : feedObj.getString("url");
                                item.setUrl(feedUrl);
                                postList.add(item);*/

                                    lvg.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            Intent i = new Intent();
                                            i.setClass(getActivity(), PostViewActivity.class);
                                            i.putExtra(PostViewActivity.TAG_SEL_POST_ID, "P" + item.getId());
                                            i.putExtra(PostViewActivity.TAG_SEL_POST_TITLE, item.getName());
                                            startActivity(i);
                                        }
                                    });


                                    hsv.addView(lvg);
                                }
                                grid_view_wrapper.addView(view);
                        }
                    }
                }catch (JSONException es) {
                    es.printStackTrace();
                    Toast.makeText(getActivity().getApplicationContext(), getString(R.string.unknown_error), Toast.LENGTH_LONG).show();
                }
            }else{

            }
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
        }
    }) {
        /** Passing some request headers **/
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            headers.put("ApiKey", Const.AuthenticationKey);
            return headers;
        }
    };

    // Adding request to volley request queue
    AppController.getInstance().addToRequestQueue(jsonReq);
}

}

我在这行中有错误:

LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE) 

扔掉这个:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.app.Activity.getSystemService(java.lang.String)' on a null object reference

2 个答案:

答案 0 :(得分:1)

如果在长时间运行的后台调用(如运行getActivity()后)上下文丢失,则null可以返回jsonRequest

也许用户在请求运行时单击主页按钮,当它在onResponse方法中返回时,活动已被销毁,因此getActivity()调用返回null对象。

这有多种解决方案;最简单的是getActivity()返回后的空检查。你也可以check this stackoverflow question

答案 1 :(得分:1)

我建议给PagerAdapter提供一个Context

public class MyViewPagerAdapter extends PagerAdapter {
    private Context mContext;

    public MyViewPagerAdapter(Context ctx) {
        this.mContext = ctx;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View view = inflater.inflate(R.layout.viewpager_item, container, false);

现在,您可以在任何上下文中使用该类,但是从Fragment中可以使用

myViewPagerAdapter = new MyViewPagerAdapter(getActivity());

尽管如此,出于其他原因,这可能仍然是空的。