-1

Goal: I am trying to use the RecyclerView to add EditText field(s) and PlaceAutocompleteFragment field(s)

Note: PlaceAutoComplete worked before adding the RecyclerView. Also, EditTexts work fine in RecyclerView, but once I try to use PlaceAutoComplete with it that's when I get the NullPointer Exception

Yes I googled and searched on stackoverflow for this error in conjunction with AutoPlacecomplete such as (Java null pointer exception on google places fragment) and (Didn't find class "android.view.fragment")

Full Error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.location.places.ui.PlaceAutocompleteFragment.setOnPlaceSelectedListener(com.google.android.gms.location.places.ui.PlaceSelectionListener)' on a null object reference
                                                                              at com.netgalaxystudios.timeclock.RegisterBusinessActivity.onCreate(RegisterBusinessActivity.java:119)

Line 119 refers to: autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {

fragment from row_list.xml:

<fragment
     android:id="@+id/place_autocomplete_fragment"
     android:layout_width="0dp"
     android:layout_weight="2.55"
     android:layout_height="wrap_content"
     android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
     />

It seems like from my code that the PlaceAutocomplete is set, so not sure how its NullPointer (especially since it worked before using recycler view...) ??

RegisterBusinessActivity:

public class RegisterBusinessActivity extends Activity {

    //EditText businessLocationET;

    //FIREBASE ITEMS
    private static FirebaseUser currentUser;
    private static final String TAG = "RealtimeDB";
    private FirebaseDatabase database;
    private DatabaseReference dbRef;
    private EditText businessName;
    private EditText businessLocation;

    //RECYCLERVIEW ITEMS
    private Context mContext;
    LinearLayout mLinearLayout;
    LinearLayout mLinearLayout2;
    private RecyclerView mRecyclerView;
    private MyAdapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    int position;
    ArrayList<LinearLayout> linearLayoutList = new ArrayList<LinearLayout>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_businessprofile);

        Button addLocationBtn = (Button) findViewById(R.id.addLocationBtn);

        // Get the widgets reference from XML layout
        mLinearLayout = (LinearLayout) findViewById(R.id.rl);
        mLinearLayout2 = (LinearLayout) findViewById(R.id.rl2);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);

        mContext = getApplicationContext(); 
        linearLayoutList.add(mLinearLayout); 
        linearLayoutList.add(mLinearLayout2);

        // Define a layout for RecyclerView
        mLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(mLayoutManager);
        // Initialize a new instance of RecyclerView Adapter instance
        mAdapter = new MyAdapter(mContext);

        // Set the adapter for RecyclerView
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.updateDataSet(linearLayoutList);
        position = 0;


        //FIREBASE FIELDS
        businessName = (EditText) findViewById(R.id.nameOfBusinessET);
        database = FirebaseDatabase.getInstance();
        dbRef = database.getReference("/data");
        currentUser =
                FirebaseAuth.getInstance().getCurrentUser();



        //CODE FOR LOCATION AUTOCOMPLETE
          PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
                getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);

        autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
            @Override
            public void onPlaceSelected(Place place) {
                // TODO: Get info about the selected place.
                Log.i("TAG", "Place: " + place.getName());
                //businessLocationET.setText(place.getName());
            }

            @Override
            public void onError(Status status) {
                // TODO: Handle the error.
                Log.i("TAG", "An error occurred: " + status);
            }
        });



        //ADD EXTRA LOCATIONS
        addLocationBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                linearLayoutList.add(mLinearLayout);                    
                linearLayoutList.add(mLinearLayout2);
                mAdapter.updateDataSet(linearLayoutList);

            }
        });



    } //END OF ONCREATE



    DatabaseReference.CompletionListener completionListener =
            new DatabaseReference.CompletionListener() {
                @Override
                public void onComplete(DatabaseError databaseError,
                                       DatabaseReference databaseReference) {

                    if (databaseError != null) {
                        notifyUser(databaseError.getMessage());
                    }
                }
            };


    private void notifyUser(String message) {
        Toast.makeText(RegisterBusinessActivity.this, message,
                Toast.LENGTH_SHORT).show();
    }


}

MyAdapter:

class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{
    private ArrayList<LinearLayout> mDataSet;
    private Context mContext;
    private Random mRandom = new Random();

    public MyAdapter(Context context){

        mContext = context;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder{
        public EditText mTextEditName, mTextEditLocation;
        public LinearLayout mRelativeLayout; //from the (Main)Activity XML
        public ViewHolder(View v){
            super(v);
            mTextEditName = (EditText) v.findViewById(R.id.nameOfBusinessET);
            //mTextEditLocation = (EditText) v.findViewById(R.id.bizLocation);

            mRelativeLayout = (LinearLayout) v.findViewById(R.id.rl);
        }
    }

    void updateDataSet(ArrayList<LinearLayout> myArrayList) {
        mDataSet = myArrayList;
        notifyDataSetChanged();
    }

    @Override
    public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
        // Create a new View
        View v = LayoutInflater.from(mContext).inflate(R.layout.row_layout,parent,false);
        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

    //A ViewHolder object stores each of the component views inside the tag field of the Layout, so you can immediately access them without the need to look them up repeatedly.
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        //holder.mTextEditName.setText("");

    }



    @Override
    public int getItemCount(){
        return mDataSet.size();
    }

}
j doe
  • 73
  • 3
  • 11

1 Answers1

0

You're finding the Fragment from the Activity (activity_register_businessprofile.xml) not the row list in the adapter. Therefore it's null

Personally, I would not suggest putting Fragments into an Recyclerview Adapter. Try using just a PlaceAutocomplete widget instead, or move the Fragment into the Activity, not the adapter layout

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • hi cricket_007: A few questions. 1. You mention my fragment is being "found" from activityregisterbusinessprofile.xml , but its in the row_layout.xml so I'm not sure I understand what you mean by this? Why would the edit text work fine but not the fragment even though they are both in the row_layout.xml that the RecyclerView looks to? – j doe Nov 22 '17 at 15:23
  • 2. I am using PlaceAutocomplete so I'm also not sure what you mean here. It can be seen in my RegisterBusinessActivity.java (android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment" ) and ( PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment); autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() { ) – j doe Nov 22 '17 at 15:26
  • Do you understand how `getFragmentManager().findFragmentById()` works? The RecyclerView Adapter has no control over the Fragment Manager, so it is not able to find it. I'm pretty sure your two edit texts are also **part of the Activity**, not the `MyAdapter` class (which you have not shown) – OneCricketeer Nov 22 '17 at 16:40