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)