-1

Learning Android and Java.

I have lot of strings and tedious to type long methods chain so decided to create a class so can use on multiple fragments and activities.

This class method should allows to get string by it's name. For instance

Instead of using this code in fragment

getResources().getString(R.string.string_name);

I want result using the class method

utils.getStringItem("string_name");

Java Class

import android.content.Context;

public class Utils {
    Context context;
    String  resource;

    public Utils(Context context) {
        this.context = context;
    }

    public String getStringItem(String resource) {
        String packageName = context.getPackageName();
        int    resId       = context.getResources().getIdentifier(resource, "string", packageName);
        return context.getString(resId);
    }
}

Fragment Class

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;


/**
 * A simple {@link Fragment} subclass.
 */
public class PlacesFragment extends Fragment {

    ArrayList<Place>           mPlaces;
    RecyclerView               mRecyclerView;
    RecyclerView.LayoutManager mLayoutManager;
    RecyclerView.Adapter       mAdapter;
    Utils                      utils = new Utils(getActivity());


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


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

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

        mRecyclerView = rootView.findViewById(R.id.recyclerView);

        mPlaces = new ArrayList<>();

        mPlaces.add(new Place(
                utils.getStringItem("string_name"),
                "content text goes here.",
                R.drawable.img.cdd,
                4.0f
        ));

        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(getActivity());
        mAdapter = new PlacesAdapter(mPlaces);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);

        return rootView;

    }

}

This is giving me error and app is getting crash on startup.

Error Message

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
        at com.codepaints.myapp.Utils.getStringItem(Utils.java:14)
        at com.codepaints.myapp.PlacesFragment.onCreateView(PlacesFragment.java:48)
Code Lover
  • 8,099
  • 20
  • 84
  • 154

3 Answers3

3

Context is null. See that even thou you are passing context into constructor, it may be null. And in you case it is. You are initializing Utils in wrong place.

Try to move initialization to onCreateView method - context from there should not be null.

Lukas Novicky
  • 921
  • 1
  • 19
  • 44
2

try this ....

public class PlacesFragment extends Fragment {

    ArrayList<Place>           mPlaces;
    RecyclerView               mRecyclerView;
    RecyclerView.LayoutManager mLayoutManager;
    RecyclerView.Adapter       mAdapter;
    Utils                      utils ; //change line


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


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

        utils = new Utils(getActivity());//add line

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

        mRecyclerView = rootView.findViewById(R.id.recyclerView);

        mPlaces = new ArrayList<>();

        mPlaces.add(new Place(
                utils.getStringItem("string_name"),
                "content text goes here.",
                R.drawable.img.cdd,
                4.0f
        ));

        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(getActivity());
        mAdapter = new PlacesAdapter(mPlaces);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);

        return rootView;

    }

}

Note:- You are getting NPE bcoz Utils utils = new Utils(getActivity()); here getActivity() is null. So context you are using in Utility is giving you NPE

Always try to get your activity instance in onAttach() method. It is good practice for further uses or you will get lots of Exception in future bcoz of using getActivity() method.

Like this ...

private Activity activity;

 @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        activity = (Activity) context;
        utils = new Utils(context);
    }
sushildlh
  • 8,986
  • 4
  • 33
  • 77
0

initialise utils here

@Override
public void onAttach(Activity activity){
    utils = new Utils(getActivity());
}
akshay_shahane
  • 4,423
  • 2
  • 17
  • 30