Android: I’m confused about how to get the right context to find my Views

I’ve got my MainTabbedActivity.xml which holds a Fragment.xml.
Fragment.xml holds a ListView.
ListView gets populated with an array of CustomView.xml.
CustomView.xml holds a TextView which I wanna pass a string to.

So it’s like:

MainTabbedActivity.xml
-Fragment.xml
--CustomView.xml

I create the new CustomViews inside of Fragment.java and populate the ListView with them. This is working fine. But as soon as I try to find my TextView to set the Text, it crashes because it is NULL. I’m pretty new to Android, but after a day of googleing it looks like I’m passing the wrong context. I just don’t know how to get the right one.

This is how I pass the context in Fragment.java:

customView newCV = new customView (getActivity.getApplicationContext());
newCV.setName("HELLO");

Here’s what my CustomView.java looks like, including the line where it returns null:

public class customView extends FrameLayout{

    String name;
    //Views
    TextView userNameToSet;

    public String getName(){
        return name;
    }

    public void setName(String name){
        this.name = name;
    }

    public customView(Context context){
        super(context);

        userNameToSet = (TextView)findViewById(R.id.userName); //this always returns NULL...
        userNameToSet.setText(getName()); //...and this crashes because of it
    }

}

Thanks for any help 🙂

EDIT: Here is the Fragment.java which creates the CustomViews

    public class StatusFragment extends Fragment {
        ListView listView;

        customView cvCollection[];

        public static final MediaType JSON
                = MediaType.parse("application/json; charset=utf-8");

        OkHttpClient client = new OkHttpClient();

        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static StatusFragment newInstance(int sectionNumber) {
            StatusFragment fragment = new StatusFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public StatusFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_status_tabbed, container, false);

            //Get Statuslist from Server
            getStatusListFromServer(rootView);

            return rootView;
        }  


        private void getStatusListFromServer(final View inflatedView){

            //JSON SERVICE *********************************
            String json = "{'userID' : '1'}";
            RequestBody body = RequestBody.create(JSON,json);
            Request request = new Request.Builder()
                    .url("example.com")
                    .post(body)
                    .build();
            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {

                }

                @Override
                public void onResponse(Response response) throws IOException {

                    if (response.isSuccessful()) {
                        try {
                            String jsonString = response.body().string();

                            JSONArray jArray = new JSONArray(jsonString);
                            cvCollection = new customView[jArray.length()];

                            for (int i=0; i<jArray.length() -1; i++){
                                final JSONObject statusRow = jArray.getJSONObject(i);

                                customView newCV = new customView(inflatedView.getContext());
                                newCV.setName(statusRow.getString("userID"));
                                newCV.setStatus(statusRow.getString("text"));
                                newCV.setErstellt(statusRow.getString("erstellt"));
                                newCV.setFavorite(false);

                                cvCollection[i] = newCV;
                            }
                            //Put them into my List
                            fillList(inflatedView, cvCollection);
                        }catch(JSONException ex){

                        }
                        //Log.w("JSON***************", response.body().string());
                    } else{
                        Toast.makeText(getActivity(), "Error", Toast.LENGTH_SHORT).show();
                    }
                }
            });
}

public void fillList(View inflatedView, customView[] statsList){
            listView = (ListView) inflatedView.findViewById(R.id.statusList);

            //Get my stats
            customView customView_data[] = statsList;

            //Load them into the adapter
            customViewAdapter adapter = new customViewAdapter(getActivity(), R.layout.customView, customView_data);

            //Load adapter into ListView
            listView.setAdapter(adapter);

        }
        }


    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s