0

I have a listview in fragment android , I had added a onclick event not working.

whenever I launch the APP , it give me the app stoped working error.

I follow this post Can not show Toast in OnItemClickListener inside Fragment but not working for me

public class UserFragment extends Fragment implements View.OnClickListener {

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    String[] user_listview_item = {"Log In","Sign Up","Fund In","Fund Out","Wallet"};

    View view = inflater.inflate(R.layout.fragment_user, container, false);
    TextView textView = (TextView) view.findViewById(R.id.testing1);


    final ListView user_list_view = (ListView) view.findViewById(R.id.user_listview_id);

    //arayadaptor
    ArrayAdapter<String> ListViewAdapter = new ArrayAdapter<String>(
        getActivity(),
        android.R.layout.simple_list_item_2,
            user_listview_item
    );
    user_list_view.setAdapter(ListViewAdapter);

    user_list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Toast.makeText(getActivity(), user_list_view.getItemAtPosition(i).toString(), Toast.LENGTH_LONG).show();
        }
    });


    textView.setOnClickListener(this);
    return view ;
}



@Override
public void onClick(View view) {

    switch(view.getId()){

        case R.id.testing1:
            Toast.makeText(getActivity(), "Click!", Toast.LENGTH_SHORT).show();
            Log.d("testing1","Result is FAIL 2");
            break;
        default:
            break;
    }

}

thanks advances

Mehul Kabaria
  • 6,404
  • 4
  • 25
  • 50
Leong
  • 139
  • 13
  • If by "it give me the app stoped working error", you mean it's crashing, you'll need to look at [the stack trace](https://stackoverflow.com/a/23353174) to determine the cause of the crash. – Mike M. Sep 12 '19 at 10:25
  • java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView this is the error @MikeM. M – Leong Sep 12 '19 at 10:38
  • 1
    You're using the `simple_list_item_2` layout, which is not just a simple ``. Did you mean to use `simple_list_item_1` instead? – Mike M. Sep 12 '19 at 10:45
  • 1
    it works after I change simple_list_item_1 thanks bro – Leong Sep 12 '19 at 10:53

1 Answers1

0

you have to get an item from String Array like below in Toast.

user_list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Toast.makeText(getActivity(), user_list_view[i].toString(), Toast.LENGTH_LONG).show();
        }
    });
Mehul Kabaria
  • 6,404
  • 4
  • 25
  • 50