I am building an app where the user creates a listView and then the user is able to click on one of the listViews and a dialog will pop up and let the user edit that listView that they clicked on.
Here is my EditCityFragment where once the user clicks on the listView this fragment is called. also I am using an arraylist to store my data, I have figured out how to add a city.
static AddCityFragment newInstance(City city){
AddCityFragment fragment = new AddCityFragment();
Bundle args = new Bundle();
args.putSerializable("city", city);
fragment.setArguments(args);
return fragment;
}
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState){
View view = LayoutInflater.from(getActivity()).inflate(R.layout.add_city_fragment_layout, null);
AddCityFragment.newInstance(savedInstanceState);
cityName = view.findViewById(R.id.city_name_editText);
provinceName = view.findViewById(R.id.province_editText);
city = (City) getArguments().getSerializable("city");
String s = city.getCityName();
String p = city.getProvinceName();
cityName.setText(s);
provinceName.setText(p);
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
return builder
.setView(view)
.setTitle("Edit City")
.setNegativeButton("Cancel", null)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String city = cityName.getText().toString();
String province = provinceName.getText().toString();
listener.onOkPressed(new City(city, province));
}}).create();
}
}
here is the error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.simpleparadox.listycity, PID: 13929
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.Serializable android.os.Bundle.getSerializable(java.lang.String)' on a null object reference
at com.example.simpleparadox.listycity.EditCityFragment.onCreateDialog(EditCityFragment.java:57)
at androidx.fragment.app.DialogFragment.onGetLayoutInflater(DialogFragment.java:330)
at androidx.fragment.app.Fragment.performGetLayoutInflater(Fragment.java:1308)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:802)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
at androidx.fragment.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Related
Here is the code
public RadioButton selectedSex;
public int selectedRadioButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
setContentView(R.layout.activity_personal_data);
progressDialog = new ProgressDialog(this);
// 0=FULL_NAME
// 1 =BIRTHDAY
//2=ADDRESS_LINE
// 3=CITY
//4=STATE
// 5=PINCODE
// 6=PHONE
mUserPersonalInfo[0] = findViewById(R.id.user_name);
mUserPersonalInfo[1]=findViewById(R.id.user_birth_date);
mUserPersonalInfo[2]=findViewById(R.id.user_address_line);
mUserPersonalInfo[3]=findViewById(R.id.user_city);
mUserPersonalInfo[4]=findViewById(R.id.user_state);
mUserPersonalInfo[5] = findViewById(R.id.userPhoneNumber);
mUserPersonalInfo[6] = findViewById(R.id.user_pincode);
mAuth = FirebaseAuth.getInstance();
mSex=findViewById(R.id.user_sex);
mNext = findViewById(R.id.personal_details_next_button);
sharedpreferences = getSharedPreferences("personalPref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
selectedRadioButton = mSex.getCheckedRadioButtonId();
selectedSex = findViewById(selectedRadioButton);
mUserPersonalInfo[1].setText( sharedpreferences.getString("userDOB", null));
mUserPersonalInfo[0].setText(sharedpreferences.getString("userName", null));
mUserPersonalInfo[2].setText(sharedpreferences.getString("userAddressline", null));
mUserPersonalInfo[3].setText(sharedpreferences.getString("userCity", null));
mUserPersonalInfo[4].setText( sharedpreferences.getString("userState", null));
mUserPersonalInfo[5].setText( sharedpreferences.getString("userPhone", null));
mUserPersonalInfo[6].setText(sharedpreferences.getString("userPincode", null));
selectedSex.setSelected( sharedpreferences.getBoolean("userSex", false));
// mNext.setProgress(0);
// FirebaseDatabase.getInstance().setPersistenceEnabled(true);
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// mNext.setProgress(1);
final String Birthday = mUserPersonalInfo[1].getText().toString();
UserName = mUserPersonalInfo[0].getText().toString();
final String Addressline = mUserPersonalInfo[2].getText().toString();
final String City = mUserPersonalInfo[3].getText().toString();
final String State = mUserPersonalInfo[4].getText().toString();
PhoneNumber = mUserPersonalInfo[5].getText().toString();
final String Pincode = mUserPersonalInfo[6].getText().toString();
editor.putString("userName", UserName);
editor.putString("userPhone", PhoneNumber);
editor.putString("userDOB", Birthday);
editor.putBoolean("userSex", selectedSex.isChecked());
editor.putString("userAddressline", Addressline);
editor.putString("userCity", City);
editor.putString("userPincode", Pincode);
editor.putString("userState", State);
editor.apply();
Process: com.teepe.teepe, PID: 18864
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.teepe.teepe/com.teepe.teepe.KYC.personalData}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RadioButton.setSelected(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RadioButton.setSelected(boolean)' on a null object reference
at com.teepe.teepe.KYC.personalData.onCreate(personalData.java:92)
at android.app.Activity.performCreate(Activity.java:6662)
It seems mSex.getCheckedRadioButtonId() is not returning correct Id.
Because of this findViewById(selectedRadioButton) is not able to find the View. and Hence, NullPointerException in the setSelected method call.
In this is not find the view
RadioButton selectedSex = findViewById(selectedRadioButton);
must be like :
RadioButton selectedSex = findViewById(R.id.selectedRadioButton);
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Null pointer Exception - findViewById()
(12 answers)
Closed 5 years ago.
My app is crashing everytime I try to click a button that inputs text into a listView, I am getting the "java.lang.IllegalStateException: Could not execute method for android:onClick"; I've tried other solutions to the problem but I can't seem to find my own solution. Any help is appreciated.
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<String> arrayList;
ArrayAdapter<String> arrayAdapter;
String infoText;
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread = new Thread(new Runnable(){
#Override
public void run(){
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean isFirstStart = getPrefs.getBoolean("started",true);
if(isFirstStart)
{
startActivity(new Intent (MainActivity.this,Intro.class));
SharedPreferences.Editor e = getPrefs.edit();
e.putBoolean("started", false);
e.apply();
}
}
});
thread.start();
listView = (ListView) findViewById(R.id.ListView);
arrayList = new ArrayList<>();
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent();
intent.setClass(MainActivity.this,EditMessageClass.class);
intent.putExtra(Intent_Constants.INTENT_INFO_DATA,arrayList.get(position).toString());
intent.putExtra(Intent_Constants.INTENT_ITEM_POSITION,position);
startActivityForResult(intent,Intent_Constants.INTENT_REQUEST_CODE_2);
}
});
}
public void onClick(View v){
Intent intent = new Intent();
intent.setClass(MainActivity.this,EditFieldClass.class);
startActivityForResult(intent,Intent_Constants.INTENT_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (resultCode==Intent_Constants.INTENT_REQUEST_CODE){
infoText = data.getStringExtra(Intent_Constants.INTENT_INFO_FIELD);
arrayList.add(infoText);
arrayAdapter.notifyDataSetChanged();
}
else if(resultCode==Intent_Constants.INTENT_REQUEST_CODE_2){
infoText = data.getStringExtra(Intent_Constants.INTENT_CHANGED_INFO);
position = data.getIntExtra(Intent_Constants.INTENT_ITEM_POSITION,-1);
arrayList.remove(position);
arrayList.add(position,infoText);
arrayAdapter.notifyDataSetChanged();
}
}
}
Intent_Constants.java
public class Intent_Constants {
public final static int INTENT_REQUEST_CODE=1;
public final static int INTENT_RESULT_CODE=1;
public final static int INTENT_REQUEST_CODE_2=2;
public final static int INTENT_RESULT_CODE_2=2;
public final static String INTENT_INFO_FIELD="info_field";
public final static String INTENT_INFO_DATA="info_data";
public final static String INTENT_ITEM_POSITION="item_position";
public final static String INTENT_CHANGED_INFO="changed_info";
EditMessageClass.java
public class EditMessageClass extends AppCompatActivity {
String infoText;
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_promo_layout);
Intent intent = getIntent();
infoText = intent.getStringExtra(Intent_Constants.INTENT_INFO_DATA);
position = intent.getIntExtra(Intent_Constants.INTENT_ITEM_POSITION,-1);
EditText infoData = (EditText) findViewById(R.id.info);
infoData.setText(infoText);
}
public void saveButtonClicked(View v){
String changedinfoText = ((EditText)findViewById(R.id.info)).getText().toString();
Intent intent = new Intent();
intent.putExtra(Intent_Constants.INTENT_CHANGED_INFO,changedinfoText);
intent.putExtra(Intent_Constants.INTENT_ITEM_POSITION, position);
setResult(Intent_Constants.INTENT_RESULT_CODE_2,intent);
finish();
}
}
EditFieldClass.java
public class EditFieldClass extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_promo_layout);
}
public void saveButtonClicked(View v){
String infoText = ((EditText)findViewById(R.id.info)).getText().toString();
if(infoText.equals("")){
}
else{
Intent intent = new Intent();
intent.putExtra(Intent_Constants.INTENT_INFO_FIELD,infoText);
setResult(Intent_Constants.INTENT_RESULT_CODE,intent);
finish();
}
}
}
Logs
FATAL EXCEPTION: main
Process: gabriel.com.prototype, PID: 15435
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at gabriel.com.prototype.EditFieldClass.saveButtonClicked(EditFieldClass.java:27)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
According to your logcat message, I can say that your EditText object is null
the problem is caused by this line.
((EditText)findViewById(R.id.info)).getText().toString()
Make sure you have EditText with id 'info' in EditFieldClass.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at gabriel.com.prototype.EditFieldClass.saveButtonClicked(EditFieldClass.java:27)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
your EditText is null , check editText id .
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm writing a program to save user input from the edit text and inserting the text into a listview. I keep getting this null exception even though I've declared the Edit Text already.
public class AddEditAlbum extends AppCompatActivity {
/**
* These keys are to send back and forth information between the bundles and intents
*/
public static final String ALBUM_INDEX = "albumIndex";
public static final String ALBUM_NAME = "albumName";
EditText input;
Button save, cancel;
int albumIndex;
#Override
protected void onCreate(Bundle savedInstanceState) {
save = (Button) findViewById(R.id.save);
cancel = (Button) findViewById(R.id.cancel);
input = (EditText) findViewById(R.id.add);
// see if info was passed in to populate field
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
albumIndex = bundle.getInt(ALBUM_INDEX);
input.setText(bundle.getString(ALBUM_NAME));
}
super.onCreate(savedInstanceState);
setContentView(R.layout.add_album);
}
public void Cancel(View view) {
setResult(RESULT_CANCELED);
finish(); //Returns to previous page on call stack
}
public void addAlbum(View view){
String name = input.getText().toString(); //Fix this, goes to null pointer
//Checks to see if input is null and returns
if(name == null || name.length()==0){
Toast.makeText(AddEditAlbum.this, "Enter valid album name", Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
bundle.putString(AlbumDialog.MESSAGE_KEY, "Album Name Required");
DialogFragment newFragment = new AlbumDialog();
newFragment.setArguments(bundle);
newFragment.show(getFragmentManager(), "badfields");
return;
}
//Toast.makeText(AddEditAlbum.this, "Enter valid album name", Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
bundle.putInt(ALBUM_INDEX, albumIndex);
bundle.putString(ALBUM_NAME, name);
// send back to caller
Intent intent = new Intent();
intent.putExtras(bundle);
setResult(RESULT_OK,intent);
finish();
}
}
public class MainActivity extends AppCompatActivity {
ListView listView;
private ArrayList<Album> albums;
public static final int EDIT_ALBUM_CODE = 1;
public static final int ADD_ALBUM_CODE = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
listView = (ListView) findViewById(R.id.album_list);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void Create(View view){
Intent intent = new Intent(this, AddEditAlbum.class);
startActivityForResult(intent, ADD_ALBUM_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode != RESULT_OK) {
return;
}
Bundle bundle = intent.getExtras();
if (bundle == null) {
return;
}
// gather all info passed back by launched activity
String name = bundle.getString(AddEditAlbum.ALBUM_NAME);
int index = bundle.getInt(AddEditAlbum.ALBUM_INDEX);
if (requestCode == EDIT_ALBUM_CODE){
Album album = albums.get(index);
album.albumName = name;
}
else if (requestCode == ADD_ALBUM_CODE){
ArrayList<Photo> photos = new ArrayList<>();
albums.add(new Album(name, photos));
}
// redo Adapter since source content has changed
//listView.setAdapter(new ArrayAdapter<Album>(this, album, albums));
}
So this is the full error I'm getting,
FATAL EXCEPTION: main
Process: com.example.mustu.androidphotos31, PID: 9965
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.mustu.androidphotos31.AddEditAlbum.addAlbum(AddEditAlbum.java:54)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
super.onCreate(savedInstanceState);
setContentView(R.layout.add_album);
This has to be executed first, otherwise the contentView is not set and findViewById will not find anything, resulting in the EditText being null.
update your onCreate() like this.
we should call setContentView(R.layout.your_layout) for passing the layout to the java class, then only it's views can be used.. failing to do so, will lead to NPE.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_album);
save = (Button) findViewById(R.id.save);
cancel = (Button) findViewById(R.id.cancel);
input = (EditText) findViewById(R.id.add);
// see if info was passed in to populate field
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
albumIndex = bundle.getInt(ALBUM_INDEX);
input.setText(bundle.getString(ALBUM_NAME));
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.album_list);
}
Also You are calling your listview before onCreate method thus giving you a NPE
This question already has answers here:
Can not find a View with findViewById()
(4 answers)
Closed 6 years ago.
When I start my SettingsActivity, I get the following Error, but I don't know why, because I have done everything as always.
ERROR:
FATAL EXCEPTION: main Process: com.android.niklasvlach.vertretung, PID: 9175
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.niklasvlach.vertretung/com.android.niklasvlach.vertretung.SettingsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setOnItemSelectedListener(android.widget.AdapterView$OnItemSelectedListener)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2358) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420) at android.app.ActivityThread.access$900(ActivityThread.java:154) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5294) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setOnItemSelectedListener(android.widget.AdapterView$OnItemSelectedListener)' on a null object reference at com.android.niklasvlach.vertretung.SettingsActivity.onCreate(SettingsActivity.java:28) at android.app.Activity.performCreate(Activity.java:5990) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420) at android.app.ActivityThread.access$900(ActivityThread.java:154) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5294) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
The Code:
public class SettingsActivity extends AppCompatActivity {
Spinner select;
EditText username;
EditText password;
#Override
protected void onCreate(Bundle savedInstanceState) {
select = (Spinner) findViewById(R.id.selectclass);
username = (EditText) findViewById(R.id.username_view);
password = (EditText) findViewById(R.id.password_view);
select.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long text) {
Toast.makeText(SettingsActivity.this,"" + text,Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
}
}
If anything else is needed, I will post it!
You need to do your UI work after setting the layout of the Activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
select = (Spinner) findViewById(R.id.selectclass);
username = (EditText) findViewById(R.id.username_view);
password = (EditText) findViewById(R.id.password_view);
select.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long text) {
Toast.makeText(SettingsActivity.this,"" + text,Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
Below is my MainActivity.java (I have removed some of unnecessary code. My main activity was a Navigation Viewer activity)
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<MainStoryTile> list = new ArrayList<MainStoryTile>();
int[] image_id = { R.drawable.sample, R.drawable.sample, R.drawable.sample};
String[] name, email, mobile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = getResources().getStringArray(R.array.person_name);
email = getResources().getStringArray(R.array.person_email);
mobile = getResources().getStringArray(R.array.person_mobile);
int count = 0;
for(String NAME: name){
MainStoryTile contact = new MainStoryTile(image_id[count], NAME, email[count], mobile[count]);
count++;
list.add(contact);
}
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new MainStoryAdapter(list);
recyclerView.setAdapter(adapter);
}
#Override
public void onBackPressed() {
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
return true;
}
}
Below is my Adapter class. (Note : there is an inner class)
public class MainStoryAdapter extends RecyclerView.Adapter<MainStoryAdapter.StoryViewHolder>{
ArrayList<MainStoryTile> contacts = new ArrayList<MainStoryTile>();
public MainStoryAdapter(ArrayList<MainStoryTile> contacts){
this.contacts = contacts;
}
#Override
public StoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_main,parent,false );
StoryViewHolder storyViewHolder = new StoryViewHolder(view);
return storyViewHolder;
}
#Override
public void onBindViewHolder(StoryViewHolder holder, int position) {
MainStoryTile CON = contacts.get(position);
holder.person_img.setImageResource(CON.getImage_id());
holder.person_name.setText(CON.getName());
holder.person_email.setText(CON.getEmail());
holder.person_mobile.setText(CON.getMobile());
}
#Override
public int getItemCount() {
return contacts.size();
}
public static class StoryViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
ImageView person_img;
TextView person_name, person_email, person_mobile;
public StoryViewHolder(View view){
super(view);
person_img = (ImageView) view.findViewById(R.id.person_image);
person_name = (TextView) view.findViewById(R.id.person_name);
person_email = (TextView) view.findViewById(R.id.person_email);
person_mobile = (TextView) view.findViewById(R.id.person_mobile);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Log.d("MY LOG", "sdurfhiusrhdidysdysdysdysdys r");
}
}
}
When I click on a item, my app crashes. below is error log :
03-17 15:20:38.638 28744-28744/com.storyteller.pro.storyteller E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.storyteller.pro.storyteller, PID: 28744
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4286)
at android.view.View.performClick(View.java:5242)
at android.view.View$PerformClick.run(View.java:21196)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4281)
at android.view.View.performClick(View.java:5242)
at android.view.View$PerformClick.run(View.java:21196)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:4277)
at android.view.ViewGroup.addView(ViewGroup.java:4127)
at android.view.ViewGroup.addView(ViewGroup.java:4068)
at android.view.ViewGroup.addView(ViewGroup.java:4041)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:247)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:114)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4281)
at android.view.View.performClick(View.java:5242)
at android.view.View$PerformClick.run(View.java:21196)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
03-17 15:20:43.048 28744-28744/com.storyteller.pro.storyteller I/Process: Sending signal. PID: 28744 SIG: 9
Update: Even after I commented the following line in the view.setOnClickListener(this); in the MainStoryAdapter, my app still crashing when I click on an item.
Below is the project for those who like to see more > project zip version
I checked your project and you, why ever, define android:onClick="setContentView" in your content_main.xml layout for the CardView.
Remove that attribute and it works.