0

Trying to change the name and province name of a city upon clicking it in the application. Below is my code in MainActivity.

cityList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                lastClicked = cityAdapter.getItem(i);
                //System.out.println(lastClicked.getProvinceName());
                AddCityFragment frag= newInstance(lastClicked);



            }


        });

Below is my code for newInstance in the AddCityFragment class

public static AddCityFragment newInstance(City city){
        Bundle args= new Bundle();
        args.putSerializable("city",city);
        AddCityFragment fragment = new AddCityFragment();
        fragment.setArguments(args);
        return fragment;
    }

Below is a segment of code from my onCreateDialog in my AddCityFragment

@NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.add_city_fragment_layout, null);
        cityName = view.findViewById(R.id.city_name_editText);
        provinceName = view.findViewById(R.id.province_editText);
        Bundle bun = getArguments();
        if(bun==null){
            System.out.println("This isn't working");
        }
        City c =(City) bun.getSerializable("city");

I'm trying to pass the city object that I clicked from my mainactivity to the fragment so I can change the name and province name of a city inside of there. For some reason when I try to do this, I keep getting the error

java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.Serializable android.os.Bundle.getSerializable(java.lang.String)' on a null object reference

I don't understand what the issue is here. My city class implements serializable and I'm creating a new fragment on each click that puts the city object in its bundle so shouldn't I be able to access its data? I'm really confused where my city object is disappearing to.

  • new Gson().toJson(city) into stringExtra and get this in fragment using String cityString=bundel.getString("city") , City city=new Gson().fromJson(cityString,City.class) – Amit pandey Feb 08 '21 at 05:43
  • Your `onItemClick` doesn't call `show()` on the fragment you created. Where do you call `show()`? – ianhanniballake Feb 08 '21 at 05:59
  • [Find your solution here. Click on this link](https://stackoverflow.com/questions/12739909/send-data-from-activity-to-fragment-in-android) – Farukh Tariq Feb 08 '21 at 06:13

0 Answers0