I am making an app to display data from a database into a list view. When an item on the list view is clicked, it takes the user to a new activity where they can view more details about that item. I want to make the details page dynamic to display the details and have managed to show the title of the list view item in a toast.
Now, I am trying to display this by using setText() to show the title in a string but am getting the error:
AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.kathe.parenttripapp, PID: 22849
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.kathe.parenttripapp/com.example.kathe.parenttripapp.Details}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.Serializable android.content.Intent.getSerializableExtra(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.Serializable android.content.Intent.getSerializableExtra(java.lang.String)' on a null object reference
at com.example.kathe.parenttripapp.Details.<init>(Details.java:23)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
this is the class the error occurs at:
TextView titletext;
final List<Activitytable> activityTable = Activitytable.listAll(Activitytable.class);
String data = getIntent().getSerializableExtra("listPosition").toString();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
TextView titletext = (TextView) findViewById(R.id.titletext);
String data = getIntent().getSerializableExtra("listPosition").toString();
Toast.makeText(getBaseContext(),String.valueOf(data),Toast.LENGTH_LONG).show();
setData();
}
private void setData() {
Intent i = getIntent();
Bundle b = i.getExtras();
if (data != null) {
String j = (String) b.get("listPosition");
titletext.setText(j);
}
else{
titletext.setText("Hello");
}
}
This is the activity it has come from:
final ListView listView = (ListView) findViewById(R.id.viewAll_listview);
long count = Activitytable.count(Activitytable.class);
if(count>0) {
final List<Activitytable> activitytable = Activitytable.listAll(Activitytable.class);
final ViewAllListView madapter = new ViewAllListView(getApplicationContext(), activitytable);
listView.setAdapter(madapter);
listView.setClickable(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?>parent, View v, int position, long id) {
String title = activitytable.get(position).Title.toString();
Activitytable AT = Activitytable.findById(Activitytable.class,activitytable.get(position).getId());
Intent i = new Intent(getApplicationContext(),Details.class);
i.putExtra("listPosition",title);
startActivity(i);
}
public Object getItem(int position) {return position;}
});
}
else
{
Toast.makeText(getApplicationContext(), "No Data Available in Table", Toast.LENGTH_LONG);
}
}
What I would like to do is to put the intent data into the TextView 'titletext' and then do an if statement saying if the passed intent data is equal to an activity title then display the following data but can't work out what is going wrong. I have tried using getStringExtra() instead of getSerializableExtra but no such luck. Works on toast but not on TextView.
If you don't have some good understanding of why you are doing so, try not to initialize your variables until you are in onCreate, also to prevent a NullPointerException, it is a good habit to use if (variable != null).
And you are storing an int, so use getIntExtra
TextView titletext;
List<Activitytable> activityTable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
activityTable = Activitytable.listAll(Activitytable.class);
titletext = (TextView) findViewById(R.id.titletext);
Intent i = getIntent();
if (i != null) {
String data = i.getStingExtra("listPosition");
titletext.setText(String.valueOf(data));
}
}
In onCreate() and don't do it as a member variable.
Bundle intentBundle = getIntent().getExtras();
if (intentBundle != null) {
lastPosition = getInt( "lastPostion" );
}
The null pointer you are receiving is in the Details class on line 23
at com.example.kathe.parenttripapp.Details.<init>(Details.java:23)
Related
Everytime the application gets to my second activity it crashes, giving the error.
My activity:
public class SecondActivity extends AppCompatActivity {
EditText barcodeText = findViewById(R.id.barcodeText);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
IntentFilter filter = new IntentFilter();
filter.addCategory(Intent.CATEGORY_DEFAULT);
filter.addAction(getResources().getString(R.string.activity_intent_filter_action));
registerReceiver(myBroadcastReceiver, filter);
}
private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Bundle b = intent.getExtras();
if (action.equals(getResources().getString(R.string.activity_intent_filter_action))) {
try {
displayScanResult(intent);
} catch (Exception e) {
}
}
}
};
private void displayScanResult(Intent initiatingIntent)
{
String decodedSource = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_source));
String decodedData = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_data));
String decodedLabelType = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_label_type));
barcodeText.setText(decodedData);
}
}
Logcat:
07-01 12:37:03.373 349-349/com.example.provatimer E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.provatimer, PID: 349
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.provatimer/com.example.provatimer.SecondActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5256)
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 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:149)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:99)
at android.content.Context.obtainStyledAttributes(Context.java:438)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
at com.example.provatimer.SecondActivity.<init>(SecondActivity.java:14)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5256)
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)
I think it may have something to do with the context in the BroadcastReceiver, but I tried to declare it in the onCreate method but nothing changed.
Maybe I don't initialize correctly the intent in which the data should be stored, if so, how can I do it correctly?
All the Strings should be correct int the string.xml file, if the error may come from that I'll write them.
I think the error is happening here:
EditText barcodeText = findViewById(R.id.barcodeText);
You are invoking findViewById() directly in the class member declaration.
You have invoke findViewById() after setContentView()
EditText barcodeText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
barcodeText = findViewById(R.id.barcodeText);
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I want to enter details from EnterDetails class and view saved details in MainActivity.
public class MainActivity extends AppCompatActivity {
EditText nameBox ;
EditText sclBox;
Spinner genderMenu;
EditText ageBox;
SharedPreferences sharedPref;
TextView label ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameBox = findViewById(R.id.editText);
sclBox = findViewById(R.id.editText3);
ageBox = findViewById(R.id.editText2);
genderMenu = findViewById(R.id.spinner);
sharedPref = getSharedPreferences("mypref",Context.MODE_PRIVATE);
label = findViewById(R.id.textView);
if(isDetailsEmpty(0)){
label.setText("Enter new Details");
}else{
setDetails();
}
}
public boolean isDetailsEmpty(int i){
if(i ==0) {
if (sharedPref.getString("txtName", "").isEmpty() || sharedPref.getString("txtAge", "").isEmpty() || sharedPref.getString("txtScl", "").isEmpty()) {
return true;
} else {
return false;
}
}{
if(nameBox.getText().toString().isEmpty() || ageBox.getText().toString().isEmpty() || sclBox.getText().toString().isEmpty()){
return true;
}else{
return false;
}
}
}
public void setDetails(){
label.setText("Name : " +sharedPref.getString("txtName","Default")+"\n"+
"Age : " +sharedPref.getString("txtAge","Default")+"\n"+
"Gender : " +sharedPref.getString("optGender","Default")+"\n"+
"School : " +sharedPref.getString("txtScl","Default")+"\n");
}
public void onClickLoadIntent(View v){
Intent enterDet = new Intent(this, EnterDetails.class);
startActivity(enterDet);
}
}
`public class EnterDetails extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.enter_details);
}
public void onClickSave(View v){
if(isDetailsEmpty(1)) {
Toast.makeText(EnterDetails.this,"Empty Details!", Toast.LENGTH_SHORT).show();
}else{
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("txtName", nameBox.getText().toString());
editor.putString("txtAge", ageBox.getText().toString());
editor.putString("optGender", genderMenu.getSelectedItem().toString());
editor.putString("txtScl", sclBox.getText().toString());
editor.commit();
Toast.makeText(EnterDetails.this,"Saved", Toast.LENGTH_SHORT).show();
startActivity(new Intent(this,MainActivity.class));
}
}
}
`
I want to enter details from EnterDetails class and view saved details in MainActivity. But I get the folloing error.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.userdetails, PID: 31945
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
at android.view.View.performClick(View.java:5646)
at android.view.View$PerformClick.run(View.java:22473)
at android.os.Handler.handleCallback(Handler.java:761)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6517)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:5646)
at android.view.View$PerformClick.run(View.java:22473)
at android.os.Handler.handleCallback(Handler.java:761)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6517)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
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.userdetails.MainActivity.isDetailsEmpty(MainActivity.java:64)
at com.example.userdetails.EnterDetails.onClickSave(EnterDetails.java:20)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:5646)
at android.view.View$PerformClick.run(View.java:22473)
at android.os.Handler.handleCallback(Handler.java:761)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6517)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
How to fix this? I have already extended EnterDetails to MainActivity.
Similar Question : What is a NullPointerException, and how do I fix it?
What you are doing is wrong. EnterDetails has its own layout called R.layout. enter_details, so when you set setContentView(R.layout.enter_details);, it will override the whole content so all views and layouts in MainActivity is no longer accessible. What you need to do is implement EnterDetails normally and use Intent to send data between activities.
public class EnterDetails extends AppCompatActivity {
private boolean isDetailsEmpty = false;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.enter_details);
isDetailsEmpty = getIntent().getBooleanExtra("test1", false)
}
public void onClickSave(View v){
if(isDetailsEmpty) {
...
}
}
And pass data from your MainActivity
public void onClickLoadIntent(View v){
Intent enterDet = new Intent(this, EnterDetails.class);
enterDet.putExtra("test1", isDetailsEmpty(1))
startActivity(enterDet);
}
Finally, please do more research on how Activity works https://medium.com/#peterekeneeze/passing-data-between-activities-2d0ef122f19d
I am trying to transport variables that I get through an EditText into the next activity. At first, I tried it with just one variable and it worked fine. But once I added the second activity, the app started to crash
once I tried it out. The app crashes when I try to press the button to get to the second activity.
Maybe you can find the mistake?
Following is my code.
First Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button weiter = (Button) findViewById(R.id.weiter1);
weiter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText inputHeight = (EditText) findViewById(R.id.inputheight);
EditText inputlenght = (EditText) findViewById(R.id.inputlenght);
Double height = Double.parseDouble(inputHeight.getText().toString());
String Höhe = new Double(height).toString();
Double lenght = Double.parseDouble(inputlenght.getText().toString());
String Länge = new Double(lenght).toString();
Intent i = new Intent(getApplicationContext(), Main2Activity.class);
i.putExtra("HöheName", Höhe);
i.putExtra( "LängeName", Länge);
startActivity(i);
}
});
}
Second Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent intent = getIntent();
String Höhe = intent.getExtras().getString("HöheName");
String Länge = intent.getExtras().getString( "längeName");
double höhe = Double.valueOf(Höhe);
double länge = Double.valueOf(Länge);
double längemalhöhe = höhe + länge;
String ergebnis = new Double(längemalhöhe).toString();
TextView Test = (TextView) findViewById(R.id.Test);
Test.setText(ergebnis);
Button weiter = (Button) findViewById(R.id.weiter2);
weiter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = getIntent();
String Höhe = intent.getExtras().getString("HöheName");
Intent i = new Intent(getApplicationContext(), Main3Activity.class);
i.putExtra("HöheName", Höhe);
startActivity(i);
}
});
}
Third Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
Intent intent = getIntent();
String Höhe = intent.getExtras().getString("HöheName");
TextView Test = (TextView) findViewById(R.id.Ergebnis2);
Test.setText(Höhe);
}
Here is the Logcat:
12-27 23:02:42.760 30997-30997/com.example.june.test E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.june.test, PID: 30997
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.june.test/com.example.june.test.Main2Activity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.trim()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
at android.app.ActivityThread.access$1100(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7331)
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 virtual method 'java.lang.String java.lang.String.trim()' on a null object reference
at java.lang.StringToReal.parseDouble(StringToReal.java:263)
at java.lang.Double.parseDouble(Double.java:301)
at java.lang.Double.valueOf(Double.java:338)
at com.example.june.test.Main2Activity.onCreate(Main2Activity.java:22)
at android.app.Activity.performCreate(Activity.java:6904)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
at android.app.ActivityThread.access$1100(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7331)
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)
I don't know if it's just a typo, but you have the line: String Länge = intent.getExtras().getString( "längeName"); where "längeName" is not capital, however, you initially did this: i.putExtra( "LängeName", Länge); where "LängeName" is capital. So the problem might be that the two strings aren't the same. When you try to do the following:
String Länge = intent.getExtras().getString( "längeName");
The string is initialized to null because there is no value assign to "längeName", which can then lead to a NullPointerException if the string is attempted to be used.
From the logcat, I see it says java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.trim() so your app crashes because a you are trying to use a String that is null. You need to check if the Strings you are working with are not null it avoid these crashes.
Notice:
i.putExtra( "LängeName", Länge);
...
String Länge = intent.getExtras().getString( "längeName");
LängeName and längeName are different two keys.
To avoid the simple mistake pointed out by LAD, it is a good practice to store the string with a final modifier.
First Activity
final static String HOHE_NAME = "HöheName";
final static String LANGE_NAME = "LängeName";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//....
Intent i = new Intent(getApplicationContext(), Main2Activity.class);
i.putExtra(HOHE_NAME, Höhe);
i.putExtra(LANGE_NAME, Länge);
startActivity(i);
}
Second Activity
Intent intent = getIntent();
String Höhe = intent.getExtras().getString(MainActivity.HOHE_NAME);
String Länge = intent.getExtras().getString(MainActivity.LANGE_NAME);
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying for hours to do an extremely simple thing, but for some reason it doesn't work...
I'm trying to go from an activity that is used for Log in, to another activity that is used for signing up.
The rest of the code works perfectly, but whenever I press the textview that supposes to bring me to the Registration screen, the app crashes.
I tried everything, even to use a button instead of textview, and many ways of intents I found online, with "finish" and without "finish", but nothing worked, do you guys have any idea what went wrong?
The Activity is added to the manifest.
Thank you!
public class LoginActivityU extends AppCompatActivity implements View.OnClickListener {
String Uname, Pass;
Button loginButton;
EditText userEt;
EditText passwordEt;
HashMap<String, String> hashMap;
ProgressDialog p;
Boolean check = false;
SharedPreferences sp;
SharedPreferences.Editor editor;
TextView tvSignUp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
sp=this.getSharedPreferences("LocalLogInData", 0);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
Intent intent = getIntent();
setSupportActionBar(toolbar);
loginButton = (Button) findViewById(R.id.btn_login);
userEt = (EditText) findViewById(R.id.input_uname);
passwordEt = (EditText) findViewById(R.id.input_password);
tvSignUp = (TextView) findViewById(R.id.link_signup);
loginButton.setOnClickListener(this);
tvSignUp.setOnClickListener(this);
Uname = sp.getString("Uname", null);
Pass = sp.getString("Pass", null);
Log.d("dds", Uname + Pass);
if (Uname != null && Pass != null)
{
userEt.setText(Uname);
passwordEt.setText(Pass);
hashMap = new HashMap<String, String>();
hashMap.put("username",userEt.getText().toString());
hashMap.put("password",passwordEt.getText().toString());
Login login=new Login();
login.execute("https://example.com");
if(check == false)
{
editor=sp.edit();
editor.remove("Uname");
editor.remove("Pass");
editor.commit();
}
}
}
#Override
public void onClick(View view) {
if (loginButton.isPressed())
{
hashMap = new HashMap<String, String>();
hashMap.put("username",userEt.getText().toString());
hashMap.put("password",passwordEt.getText().toString());
editor=sp.edit();
editor.putString("Uname",userEt.getText().toString());
editor.putString("Pass",passwordEt.getText().toString());
Login login=new Login();
login.execute("https://peulibrary.co.il/api/user/generate_auth_cookie/");
editor.commit();
}
else if (tvSignUp.isPressed())
{
Intent intent = new Intent(this, SignUpActivity.class);
startActivity(intent);
finish();
}
}
Log of crash:
02-03 14:35:51.661 10836-10836/com.example.negev.peulibraryv201 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.negev.peulibraryv201, PID: 10836
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.example.example/com.example.example.example.SignUpActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.negev.peulibraryv201.SignUpActivity.onCreate(SignUpActivity.java:22)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Looking at the crash log, it seems that you are attaching a click listener to your FloatingActionButton before instantiating it. Please make sure that you call findViewById and instantiate the view first, and only call setOnClickListener after. The problem is in SignUpActivity.
seeing the logs it is clear that the Problem should be in your signup activity.
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.support.design.widget.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)'
indicates that there is a widget you are referring is not initialized or null
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm making an Android app, it should ask for arithmetic equations and check the answer. There should be different difficulty levels as well. My app crashes when choosing the difficulty level from AlertDialog. I have no errors in Android Studio.
Here is the code for choosing level:
public void onClick(View view) {
if(view.getId()==R.id.play_btn){
//play button
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose a level")
.setSingleChoiceItems(levelNames, 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//start gameplay
startPlay(which);
}
});
AlertDialog ad = builder.create();
ad.show();
}
private void startPlay(int chosenLevel){
//start gameplay
Intent playIntent = new Intent(this, PlayGame.class);
playIntent.putExtra("level", chosenLevel);
this.startActivity(playIntent);
}
Can someone help me understand why my app crashes?
Here is the log:
9758-9758/org.example.braintraining E/AndroidRuntime: FATAL EXCEPTION: main
Process: org.example.braintraining, PID: 9758
java.lang.RuntimeException: Unable to start activity ComponentInfo{org.example.braintraining/org.example.braintraining.PlayGame}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2693)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
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:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference
at org.example.braintraining.PlayGame.onCreate(PlayGame.java:104)
at android.app.Activity.performCreate(Activity.java:6289)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
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:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
Here is the code for onCreate method of PlayGame class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playgame);
gamePrefs = getSharedPreferences(GAME_PREFS, 0);
//text and image views
question = (TextView)findViewById(R.id.question);
answerTxt = (TextView)findViewById(R.id.answer);
response = (ImageView)findViewById(R.id.response);
scoreTxt = (TextView)findViewById(R.id.score);
//hide tick cross initially
response.setVisibility(View.INVISIBLE);
//number, enter and clear buttons
btn1 = (Button)findViewById(R.id.btn1);
btn2 = (Button)findViewById(R.id.btn2);
btn3 = (Button)findViewById(R.id.btn3);
btn4 = (Button)findViewById(R.id.btn4);
btn5 = (Button)findViewById(R.id.btn5);
btn6 = (Button)findViewById(R.id.btn6);
btn7 = (Button)findViewById(R.id.btn7);
btn8 = (Button)findViewById(R.id.btn8);
btn9 = (Button)findViewById(R.id.btn9);
btn0 = (Button)findViewById(R.id.btn0);
enterBtn = (Button)findViewById(R.id.enter);
clearBtn = (Button)findViewById(R.id.clear);
//listen for clicks
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
btn7.setOnClickListener(this);
btn8.setOnClickListener(this);
btn9.setOnClickListener(this);
btn0.setOnClickListener(this);
enterBtn.setOnClickListener(this);
clearBtn.setOnClickListener(this);
//get passed level number
if(savedInstanceState!=null){
//restore state
}
else{
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
int passedLevel = extras.getInt("level", -1);
if(passedLevel>=0) level = passedLevel;
level=savedInstanceState.getInt("level");
int exScore = savedInstanceState.getInt("score");
scoreTxt.setText("Score: "+exScore);
}
}
//initialize random
random = new Random();
//play
chooseQuestion();
}
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference at org.example.braintraining.PlayGame.onCreate(PlayGame.java:104)
Either the code might be failing in two scenarios:
You are starting new activity by passing the playIntent. Please check the code in PlayGame.java, in onCreate() you should be getting the string value (level) from Intent rather than from Bundle, something like
String chosenLevel;
Intent i = this.getIntent();
if(i != null){
chosenLevel = i.getStringExtra("level");
}
2.if you are rotating the screen, once you are in the play game activity where you are not saving the required value before the activity is destroyed and trying to retrieve it back once the activity is recreated .
Solution would be to use the put methods to store values in onSaveInstanceState():
protected void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
bundle.putString("value", chosenLevel);
}
And restore the value from Bundle in onCreate() or you can use onRestoreInstanceState(), which is called after onStart(), whereas onCreate() is called before onStart().:
public void onCreate(Bundle bundle) {
if (bundle!= null){
chosenValue = bundle.getString("value");
}
}