RadioGroup issue - java

i'm trying to get the radiobutton text from the radiogroup but issue is: it didn't get the value. i searched on other links but didn't helpful for me.
private EditText FirstName;
private EditText LastName;
private RadioGroup Gender;
private EditText MobileNo;
private RadioButton btn_gender;
private Button BtnNext;
private ProgressBar progressBar;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.registration_form);
Firebase.setAndroidContext(this);
FirstName=(EditText)findViewById(R.id.firstname);
LastName=(EditText)findViewById(R.id.lastname);
Gender=(RadioGroup) findViewById(R.id.radio_group);
MobileNo=(EditText)findViewById(R.id.btn_mobile);
BtnNext=(Button)findViewById(R.id.btn_regform);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
int selectedId=Gender.getCheckedRadioButtonId();
btn_gender=(RadioButton)findViewById(selectedId);
BtnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progressBar.setVisibility(View.VISIBLE);
Firebase ref=new Firebase(config_firebaseurl.FIREBASE_URL);
String fname=FirstName.getText().toString().trim();
String lname=LastName.getText().toString().trim();
String gender=btn_gender.getText().toString().trim();
String phoneno=BtnNext.getText().toString().trim();
registration_form reg=new registration_form();
reg.setFirstName(fname);
reg.setLastName(lname);
reg.setGender(gender);
reg.setmobileNo(phoneno);
ref.child("registration_form").setValue(reg);
Toast.makeText(getApplicationContext(),"Registration Error", Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
});
}
}
and i'm getting this error:
FATAL EXCEPTION: main
Process: associate.aclass.associate1, PID: 28847
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.CharSequence android.widget.RadioButton.getText()' on a
null object reference
at
associate.aclass.associate1.registration_form_handler$2.onClick(registration_form_handler.java:81)
at android.view.View.performClick(View.java:4856)
at android.view.View$PerformClick.run(View.java:19956)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5389)
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:1020)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)

btn_gender is null you need to do this outside of Gender.setOnCheckedChangeListener to initialize btn_gender
btn_gender = (RadioButton)findViewById(R.id.radioButtonID); // use your id

Related

startActivity sending to wrong activity: Android

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.

I want to get the selected radiobutton using saved prefrences but the activity is not opening?

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);

Null Pointer Exception on Edit Text Android [duplicate]

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

NullPointerException: Attempt to invoke virtual method ... on a null object reference [duplicate]

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) {
}
});
}

App crashes when Intent is passed

I've MainActivity as following:
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDb;
TextView textView;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb =new DatabaseHelper(this);
Cursor res= myDb.getAllData();
if(res.getCount()==0)
{
textView = (TextView)findViewById(R.id.textView);
textView.setText("No Reminders");
button = (Button)findViewById(R.id.button);
button.setText("Create a Reminder");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) { //on click 2nd activity is called.
Intent myIntent = new Intent(MainActivity.this, Main2Activity.class);
//myIntent.putExtra("key", value); //Optional parameters
startActivity(myIntent);
}
});
return;
}
StringBuffer buffer=new StringBuffer();
while(res.moveToNext())
{
buffer.append("Id : " +res.getString(0)+"\n");
buffer.append("Event : " +res.getString(1)+"\n");
buffer.append("Location : " +res.getString(2)+"\n");
}
textView = (TextView)findViewById(R.id.textView);
textView.setText(buffer.toString());
}
}
I've another activity named main2activity. But when I press the button in 1st activity, The app crashes and log gives NullPointerException. But this is not duplicate of any other such NullPointerException questions.
Because when I run only my second activity Main2Activity, separately, it does not give to this error. But when It is called from mainActivity, It is giving error. I can't understand why setting listener on button giving NullPointerException.
My Main2Activity is :
public class Main2Activity extends AppCompatActivity {
private static final int PLACE_PICKER_REQUEST = 1;
private TextView mName;
private TextView mAddress;
private TextView mAttributions;
private GoogleApiClient mGoogleApiClient;
public TextView tv4;
private static final LatLngBounds BOUNDS_MOUNTAIN_VIEW = new LatLngBounds(
new LatLng(37.398160, -122.180831), new LatLng(37.430610, -121.972090));
private boolean flag = false;
DatabaseHelper myDb;
EditText newevent;
Button submit;
Button viewremainders;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.activity_main);
myDb =new DatabaseHelper(this);
newevent=(EditText)findViewById(R.id.newEvent);
submit=(Button)findViewById(R.id.submit);
viewremainders=(Button)findViewById(R.id.view);
Button pickerButton = (Button) findViewById(R.id.pickerButton);
tv4 = (TextView)findViewById(R.id.textView4);
pickerButton.setOnClickListener(new View.OnClickListener() { // <-- Error is here. (NullPointerException.)
#Override
public void onClick(View v) {
try {
PlacePicker.IntentBuilder intentBuilder =
new PlacePicker.IntentBuilder();
intentBuilder.setLatLngBounds(BOUNDS_MOUNTAIN_VIEW);
Intent intent = intentBuilder.build(Main2Activity.this);
startActivityForResult(intent, PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException
| GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
});
AddData();
viewremainders();
}
Here I've mentioned where the error is occurring in comment. And I've other methods with this but only included necessary part.
Thanks in advance!
EDIT:
Log:
08-18 21:48:05.421 29655-29655/com.example.kaushal28.locationbasedreminder E/test: Exception
08-18 21:48:05.424 29655-29655/com.example.kaushal28.locationbasedreminder E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.kaushal28.locationbasedreminder/com.example.kaushal28.locationbasedreminder.Main2Activity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2306)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
at android.app.ActivityThread.access$600(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5299)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.kaushal28.locationbasedreminder.Main2Activity.onCreate(Main2Activity.java:85)
at android.app.Activity.performCreate(Activity.java:5182)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358) 
at android.app.ActivityThread.access$600(ActivityThread.java:156) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:153) 
at android.app.ActivityThread.main(ActivityThread.java:5299) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600) 
at dalvik.system.NativeStart.main(Native Method) 
You are setting the same layout in both activities. Make sure and add correct layout.
setContentView(R.layout.activity_main);
public class Main2Activity extends AppCompatActivity {
.
.
.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.activity_main); // here is issue same layout is used for both activity
}
}

Categories