-2
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnScan = (Button)findViewById(R.id.scan);
    listViewIp = (ListView)findViewById(R.id.listviewip);
    bar = (ProgressBar) findViewById(R.id.pbar);
    bar.setVisibility(View.INVISIBLE);

    ipList = new ArrayList();
    adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, android.R.id.text1, ipList);
    listViewIp.setAdapter(adapter);

    btnScan.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new ScanIpTask().execute();
        }
    });

convert it to fragment

ArrayList ipList; ArrayAdapter adapter;

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

    btnScan = (Button)rootView.findViewById(R.id.scan);
    listViewIp = (ListView)rootView.findViewById(R.id.listviewip);
    bar = (ProgressBar) rootView.findViewById(R.id.pbar);
    bar.setVisibility(View.INVISIBLE);

    ipList = new ArrayList();
    adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, android.R.id.text1, ipList);
    listViewIp.setAdapter(adapter);

    btnScan.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new ScanIpTask().execute();
        }
    });


    return rootView;
}

it shows error in this line

adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, android.R.id.text1, ipList);

  • What is error?? – Lokesh Apr 08 '18 at 13:17
  • See the answer below . And do not just rename the class name . First read the classes you are using . `Activity` and `Fragment` are way too different classes. – ADM Apr 08 '18 at 13:18

2 Answers2

0

ArrayAdapter constructor's first argument is Context. And Fragment is not a child of Context. You need to pas the Context of the parent Activity.

ArrayAdapter(Context context, int resource, int textViewResourceId)

Use getActivity() to get the context of parent Activity.

 adapter = new ArrayAdapter<String>(getActivity(),
        android.R.layout.simple_list_item_1, android.R.id.text1, ipList);
listViewIp.setAdapter(adapter);

getActivity() inside onCreateView() can return null sometimes cause fragment not attached yet. To clear the concept pls read This post or similar.

ADM
  • 20,406
  • 11
  • 52
  • 83
0

Replace the code with

adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, ipList);
pradithya aria
  • 657
  • 5
  • 10