So I have a listview that shows 5 chapters of the book of James from the Bible. As the user chooses the chapter he wants to read, the verses from the chapter will show. What I'm trying to do is to get position value from JamesChapter.java to be passed to the next activity Bible.java and use that value as an index value to the array I want to access in my json file that will display the verses. What happens is the app crashes when I click the chapter. I tried using getIntent() and getIntExtra() but I don't know how to use the value from those method to apply as an array index. Appreciate the help on how I can use the value from last activity to the array in my next activity. have a great day
public class JamesChapters extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book_chapters);
ListView listView = findViewById(R.id.listview);
List<String> list = new ArrayList<>();
list.add("Chapter 1");
list.add("Chapter 2");
list.add("Chapter 3");
list.add("Chapter 4");
list.add("Chapter 5");
ArrayAdapter arrayAdapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1,list);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(JamesChapters.this, Bible.class);
intent.putExtra("position", position);
startActivity(intent);
}
});
}
}
public class Bible extends AppCompatActivity {
TextView tvReference, tvVersion, tvVerse;
String reference, version, verse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bible);
Intent intent = getIntent();
int position = intent.getIntExtra("position",0);
displayJArray(position);
}
public void displayJArray(int value){
String rid = rid();
try{
JSONObject json = new JSONObject(rid);
JSONArray jsonarray = json.getJSONArray("James");
JSONObject newjson = jsonarray.getJSONObject(value);
reference = newjson.getString("Reference");
version = newjson.getString("Version");
verse = newjson.getString("Verse");
tvReference.setText(reference);
tvVersion.setText(version);
tvVerse.setText(verse);
} catch (JSONException e) {
e.printStackTrace();
}
}
public String rid(){
String content="";
try{
InputStream ist = getAssets().open("james.json");
int size = ist.available();
byte [] buffer = new byte[size];
ist.read(buffer);
content = new String(buffer);
}catch (IOException e) {
e.printStackTrace();
}
return content;
}
}
This is the format of my json file
{
"James": [
{
"Reference": "James 1:1-27",
"Version": "NIV",
"Verse": "......"
},
{
"Reference": "James 2:1-26",
"Version": "NIV"
"Verse": "....."
}
]}
Here is the error from logcat
2022-11-02 15:51:32.805 25637-25676/ph.edu.nu.soco.finalproject E/eglCodecCommon: GoldfishAddressSpaceHostMemoryAllocator: ioctl_ping failed for device_type=5, ret=-1
2022-11-02 15:51:42.272 25637-25637/ph.edu.nu.soco.finalproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: ph.edu.nu.soco.finalproject, PID: 25637
java.lang.RuntimeException: Unable to start activity ComponentInfo{ph.edu.nu.soco.finalproject/ph.edu.nu.soco.finalproject.Bible}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at ph.edu.nu.soco.finalproject.Bible.displayJArray(Bible.java:37)
at ph.edu.nu.soco.finalproject.Bible.onCreate(Bible.java:25)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
2022-11-02 15:51:43.018 25695-25721/ph.edu.nu.soco.finalproject E/eglCodecCommon: GoldfishAddressSpaceHostMemoryAllocator: ioctl_ping failed for device_type=5, ret=-1
Your app is crashing because you have defined tvReference but it is not initialized and then you're trying to access it in displayJArray() method which results in a NullPointerException at runtime because Android fails to locate the view in Activity. Initialize your textViews in onCreate Method like the example below.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bible);
// Initialize views like this
tvReference = findViewById(R.id.id_of_your_textView_in_xml);
tvVersion = same as above ;
tvVerse = same as above;
Intent intent = getIntent();
int position = intent.getIntExtra("position",0);
displayJArray(position);
}
Related
I'm trying to have it to where after the my "Overview" Button is clicked the next button "Variables" is enabled. The button enables, however the setOnClickListener for my "Variables" sends me to my OverviewActivity, rather than my VariablesActivity. I've been stuck on this for a while.
The Variables Activity is just a multiple choice screen, but i was just setting it up.
I'm really new to Java and Android Studio, so this is getting confusing fast
Code:
public class HomeActivity extends AppCompatActivity {
public Button signOutBtn;
public Button overviewBtn;
public Button varBtn;
FirebaseAuth auth;
boolean overviewDone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
signOutBtn = findViewById(R.id.signOutBtn);
overviewBtn = findViewById(R.id.overviewBtn);
varBtn = findViewById(R.id.varBtn);
auth = FirebaseAuth.getInstance();
overviewDone = false;
signOutBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
auth.signOut();
startActivity(new Intent(HomeActivity.this, SignInActivity.class));
finish();
}
});
overviewBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent overviewBtnIntent = new Intent(HomeActivity.this, OverviewActivity.class);
startActivity(overviewBtnIntent);
}
});
if (getIntent().hasExtra("state")) {
if (getIntent().getStringExtra("state").equals("enable")) {
overviewDone = true;
varBtn.setEnabled(true);
} else {
varBtn.setEnabled(false);
}
} else {
varBtn.setEnabled(false);
}
varBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent varbiesButtonIntent = new Intent(HomeActivity.this, VariablesActivity.class);
startActivity(varbiesButtonIntent);
Log.i("Variable Button", "Going to Variable Activity");
}
});
}
}
public class OverviewActivity extends AppCompatActivity {
public Button backBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_overview);
backBtn = findViewById(R.id.ov_backButton);
backBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(OverviewActivity.this, HomeActivity.class);
intent.putExtra("state", "enable");
startActivity(intent);
}
});
}
}
public class VariablesActivity extends AppCompatActivity {
public RadioGroup radioGroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_variables);
radioGroup = (RadioGroup)findViewById(R.id.RadioGroup);
// getting value of radio button checked
final String value = ((RadioButton)findViewById(radioGroup.getCheckedRadioButtonId())).getText().toString();
if(radioGroup.getCheckedRadioButtonId() == -1){
// no radio buttons checked
} else{
// one the radio buttons are checked
Log.i("Radio Button Clicked", value);
}
}
}
Stacktrace:
2021-11-22 21:45:23.550 4535-4535/com.example.codehorizonapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.codehorizonapplication, PID: 4535
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.codehorizonapplication/com.example.codehorizonapplication.VariablesActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.RadioButton.getText()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.RadioButton.getText()' on a null object reference
at com.example.codehorizonapplication.VariablesActivity.onCreate(VariablesActivity.java:24)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
int checkedId = radioGroup.getCheckedRadioButtonId();
String value = "";
if(checkedId != -1){
value = ((RadioButton)findViewById(checkedId)).getText().toString();
}
radioGroup.getCheckedRadioButtonId() returns -1 if there is nothing checked, -1 isn't a valid Id thus findViewById returns null.
null.getText() is a java.lang.NullPointerException
This is under the assumption that there is nothing selected and the fact that calling radioGroup.getCheckedRadioButtonId() doesn't crash only when you call getText() does it crash means your radioGroup = (RadioGroup)findViewById(R.id.RadioGroup); is correct.
The reason the OverviewActivity is created instead is due to a stack problem caused by the premature end to VariablesActivity due to the exception.
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) {
}
});
}
I am attempting to save a custom ArrayList to SharedPreferences. Ideally the first time this app runs, there should be an empty SharedPreferences, but if I need to fill it with one item, then I can do that with an "Example."
I've tried using debug break points and have isolated the problem to the setAdapter line marked below.
The app crashes at the setAdapter line, but it may be due to the editor not being initialized? the debugger tells me "editor = null"
public class MainActivity extends AppCompatActivity {
ArrayList<PurchaseOrders> purchaseOrders = new ArrayList<PurchaseOrders>();
PurchaseOrderAdapter adapter;
public SharedPreferences sharedPref;
public SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
purchaseOrders = new ArrayList<PurchaseOrders>();
String[] items = new String[]{"1", "2", "3"};
purchaseOrders.add(new PurchaseOrders(false, "purchaseNumber", "Customer", "Date 1", "Date 2", items));
save();
sharedPref = this.getSharedPreferences("com.lochdownstudios.simplePurchaseOrderer", Context.MODE_PRIVATE);
editor = sharedPref.edit();
load();
adapter = new PurchaseOrderAdapter(this, purchaseOrders);
final ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter); // Break Point here.
}
private void save() {
Gson gson = new Gson();
String json = gson.toJson(purchaseOrders);
editor.putString("savedPurchaseOrders", json); //editor = null .... hmmm....
editor.apply();
}
private void load() {
Gson gson = new Gson();
String json = sharedPref.getString("savedPurchaseOrders", "");
Type type = new TypeToken<List<PurchaseOrders>>(){}.getType();
purchaseOrders = gson.fromJson(json, type);
}
}
At the break point (mentioned in comments), my debugger tells me that "editor = null". And then the following step it crashes with the following logcat.
08-23 19:06:02.799 23974-23974/com.lochdownstudios.simplePurchaseOrderer E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.lochdownstudios.simplePurchaseOrderer, PID: 23974
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.lochdownstudios.simplePurchaseOrderer/com.lochdownstudios.simplePurchaseOrderer.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'android.content.SharedPreferences$Editor android.content.SharedPreferences$Editor.putString(java.lang.String, java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3253)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
at android.app.ActivityThread.access$1100(ActivityThread.java:221)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'android.content.SharedPreferences$Editor android.content.SharedPreferences$Editor.putString(java.lang.String, java.lang.String)' on a null object reference
at com.lochdownstudios.simplePurchaseOrderer.MainActivity.save(MainActivity.java:119)
at com.lochdownstudios.simplePurchaseOrderer.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:6876)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3206)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
at android.app.ActivityThread.access$1100(ActivityThread.java:221)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Thoughts? Thanks!
You are calling save which uses editor before you are actually initializing the editor
maybe change the order to
sharedPref = this.getSharedPreferences("com.lochdownstudios.simplePurchaseOrderer",
Context.MODE_PRIVATE);
editor = sharedPref.edit();
save();