I always get an error message in my Android project.
java.lang.NullPointerException: attempt to call the virtual method 'android.view.View android.app.Activity.findViewById (int)' on an object reference zero
In my MainActivity, I call the FragmentStart class.
FragmentStart.class
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; public class FragmentStart extends Fragment { //Define Listview private ListView startList; private String[] stringList; Activity activity = getActivity(); public FragmentStart() { // } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_start, container, false); // Create ListView start startList = (ListView) rootView.findViewById(R.id.startList); stringList = getResources().getStringArray(R.array.startList); if (activity != null) { ArrayAdapter<String> objAdapter = new ArrayAdapter<String>(activity, android.R.layout.simple_list_item_1, stringList); startList.setAdapter(objAdapter); startList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { switch (startList.getPositionForView(view)) { case 0: // ... break; } } }); } // Create ListView end //New Entry Button add = (Button) activity.findViewById(R.id.add); add.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent myIntent = new Intent(view.getContext(), addItem.class); startActivityForResult(myIntent, 0); } }); return rootView; } }
In addition to what @Selvin pointed out, it looks like this:
Button add = (Button) activity.findViewById(R.id.add);
... should be changed to this:
Button add = (Button) rootView.findViewById(R.id.add);
Use the following code:
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // selectedPosition = position; View newTypeView=listView1.getChildAt(position-listView1.getFirstVisiblePosition()).findViewById(R.id.RelativeLayout); if (newTypeView.getClass().getName().toString().contains("RelativeLayout")) { if (lastTouchedVw != null) lastTouchedVw.setBackgroundColor(Color.parseColor("#ffffff")); // mainImageView.setImageURI(Uri.parse(al.get(position).toString())); //bigImageRelativeLayoutVw.setBackgroundColor(Color.parseColor("#ffb000")); newTypeView.setBackgroundResource(R.drawable.cellbg); lastTouchedVw = newTypeView; }