0

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);

        }
        }


    }
  • post your xml and class from where you calling this – Pavan Oct 27 '15 at 15:54
  • I edited my post with the Fragment class! – PectoralisMajor Oct 28 '15 at 11:58
  • your textview userName is in fragment or anywhere else – Pavan Oct 28 '15 at 12:09
  • Textview userName is inside CustomView – PectoralisMajor Oct 28 '15 at 12:22
  • you don't understanding the point if your view is in activity xml then simply call findviewbyid if in fragment call it yourfragmentview.findviewbyid or it in external xml not in current activity layout you have to inflate it as @Peter suggested – Pavan Oct 28 '15 at 12:39
  • You are right, I don't understand. When I create the new CustomView, I have to pass a CONTEXT. I'm passing the context of Fragment to my CustomView. Inside of CustomView, I can't inflate the layout because then it will crash. – PectoralisMajor Oct 28 '15 at 13:59

3 Answers3

2

Your code is not complete, so I'm not sure, but I think you need to inflate your custom view somewhere. From what I see, you're not doing that.

Something like:

View view= getLayoutInflater().inflate(R.layout.CustomView, null);
userNameToSet = (TextView)view.findViewById(R.id.userName);
Peter
  • 870
  • 6
  • 20
0

As far as I know, findViewById() can be called from any activity, in that case it will look for the View inside the layout set with setContentView().

Otherwise you should call it from the layout that contains the view.

Usually you dont need to pass the Context between your activity/fragment classes.

If your View is loaded at the parent Activity then you should call

getActivity().findViewById()

If your View is inside your fragment you must call it from the container view, usually inside of

onCreateView(LayoutInflater, ViewGroup, Bundle) //Cant see this method in the code you posted

Right before you inflate your layout.

Hope this helps.

Abhinav Singh Maurya
  • 3,313
  • 8
  • 33
  • 51
Nanoc
  • 2,381
  • 1
  • 20
  • 35
0

thank you all for trying to help me!

I just couldn't get it to work the way I set it up, so I created an Adapter for my custom listView items. Now it works perfectly!

If anyone has a similar problem, please check out this tutorial which helped me: http://www.ezzylearning.com/tutorial/customizing-android-listview-items-with-custom-arrayadapter