Try invoking the virtual method 'java.lang.Object android.app.Activity.getSystemService (java.lang.String)' on a null object reference

advertisements

This question already has an answer here:

  • Android. Fragment getActivity() sometimes returns null 7 answers

this is my code:

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("•"));
        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);
}

}

I have an error in this line:

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

Throwing this:

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


Well your getActivity() can return null if the context is lost after a long running background call like when running your jsonRequest.

Maybe the user clicks the home button while the request is running, and when it returns in the onResponse method, the activity is already destroyed, thus the getActivity() call returns a null object.

There are multiple solutions to this; easiest is a null check after the getActivity() return. Also you could check this stackoverflow question