This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
Application is continuously crashing when running my MaintenanceActvity. The LogCat points to a NullPointerException on line 60 of the code. However, having recycled the code from a similar activity, I can't seem to figure out why this seems to be an issue.
I would appreciate a nod in the right direction on this one as it has been bugging me for over a day now. I assume it is something relatively simple to fix, but alas, I'm yet to find a solution.
I have checked other SO threads on this type of LogCat error, but can't find a solution that works for me.
LogCat
03-01 11:00:03.619 5705-5705/? E/UncaughtException: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.***.myapplication/com.example.***.myapplication.MaintenanceActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.***.myapplication.MaintenanceActivity.onCreate(MaintenanceActivity.java:60)
at android.app.Activity.performCreate(Activity.java:7009)
at android.app.Activity.performCreate(Activity.java:7000)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
OnClickLister (Starting # Line 60)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maintenance);
databaseMaintenance = FirebaseDatabase.getInstance().getReference("maintenance");
editTextTitle = (EditText) findViewById(R.id.editTextTitle);
editTextDesc = (EditText) findViewById(R.id.editTextDesc);
buttonSubmit = (Button) findViewById(R.id.buttonSubmit);
spinnerPrimary = (Spinner) findViewById(R.id.spinnerPrimary);
spinnerSecondary = (Spinner) findViewById(R.id.spinnerSecondary);
spinnerProperty = (Spinner) findViewById(R.id.spinnerProperty);
listViewIssues = (ListView) findViewById(R.id.listViewIssues);
maintenanceList = new ArrayList<>();
buttonSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addMaintenance();
}
});
addMaintenance() method
private void addMaintenance(){
String title = editTextTitle.getText().toString().trim();
String desc = editTextDesc.getText().toString().trim();
String primary = spinnerPrimary.getSelectedItem().toString();
String secondary = spinnerSecondary.getSelectedItem().toString();
String property = spinnerProperty.getSelectedItem().toString();
if(!TextUtils.isEmpty(title)){
String id = databaseMaintenance.push().getKey();
Maintenance maintenance = new Maintenance (id, title, desc, primary, secondary, property);
databaseMaintenance.child(id).setValue(maintenance);
Toast.makeText(this, "Maintenance Added", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "You must enter a maintenance record", Toast.LENGTH_LONG).show();
}
}
Possibly you are supplying wrong id to button
buttonSubmit=(Button)findViewById(R.id.buttonSubmit);
check id of button in xml file.
Check your xml file which you use in your activity and then check your id for your button
then check your activity
XML button id & button initialization id in activity should be same.
With the help of some of the answers provided, it turns out the Android Studio had duplicated the activity_maintenance.xml files to make a v16 version in the side bar. I just had to delete both files and have one activity_maintenance.xml file.
Thanks all.
Related
I am trying to make something that converts the text i write into EditText to speech when i press button01.
It works fine on the virtual machine with Android API 23, but it crashes and makes a NullPointerException and crashes on the virtual machine with Android API 30. Here's the code:
public MainActivity() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
button01 = (Button) findViewById(R.id.button01);
final TextView textView1 = (TextView) findViewById(R.id.text1) ;
textView1.setText("\n");
tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != ERROR) {
// 언어를 선택한다.
tts.setLanguage(Locale.ENGLISH);
} else {
textView1.setText("TTS 작업에 오류가 생기거나 지원되지 않는 언어입니다.");
tts.speak("TTS 작업에 오류가 생기거나 지원되지 않는 언어입니다.", TextToSpeech.STOPPED, null);
}
}
});
button01.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// editText에 있는 문장을 읽는다.
tts.speak(editText.getText().toString(), TextToSpeech.QUEUE_FLUSH, null);
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
// TTS 객체가 남아있다면 실행을 중지하고 메모리에서 제거한다.
if(tts != null){
tts.stop();
tts.shutdown();
tts = null;
}
}
}
When i view Logcat, it showes this:
2020-07-09 02:10:56.036 7700-7700/com.example.myapplication2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication2, PID: 7700
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication2/com.example.myapplication2.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.speech.tts.TextToSpeech.speak(java.lang.String, int, java.util.HashMap)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.speech.tts.TextToSpeech.speak(java.lang.String, int, java.util.HashMap)' on a null object reference
at com.example.myapplication2.MainActivity$1.onInit(MainActivity.java:42)
at android.speech.tts.TextToSpeech.dispatchOnInit(TextToSpeech.java:836)
at android.speech.tts.TextToSpeech.initTts(TextToSpeech.java:814)
at android.speech.tts.TextToSpeech.<init>(TextToSpeech.java:745)
at android.speech.tts.TextToSpeech.<init>(TextToSpeech.java:724)
at android.speech.tts.TextToSpeech.<init>(TextToSpeech.java:708)
at com.example.myapplication2.MainActivity.onCreate(MainActivity.java:34)
at android.app.Activity.performCreate(Activity.java:7995)
at android.app.Activity.performCreate(Activity.java:7979)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
It's happening in the else part in onInit of your listener. When there was an error in initializing the TextToSpeech instance, onInit will be called with ERROR as input while tts is not yet initialized and is null.
It may happen when your device doesn't support text to speech or the engine is missing necessary data.
Don't call anything on tts in case of an error. (There was an error in initializing text to speech. So, how can it speak your text?!)
Apps targeting Android 11 that use text-to-speech should declare TextToSpeech.Engine.INTENT_ACTION_TTS_SERVICE in the queries elements of their manifest:
<queries>
...
<intent>
<action android:name="android.intent.action.TTS_SERVICE" />
</intent>
</queries>
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
Hello i have a question that is the one which i put in title.
I have this example that i extract from my code
String text = "Test";
EditText editText = (EditText) findViewById(R.id.idField);
editText.setText(text);
And I can't convert int o charSequence
My objective is put a string into the editText.setText();
Here is my onCreate:
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
try {
fileExist();
sessionTimeOut();
passwordValidation(getLocalPassword());
} catch (FileNotExistException e) {
setLoginActivity();
} catch (SessionTimeOutException e) {
String text="Sometext";
EditText editText = (EditText) findViewById(R.id.usernameField);
setLoginActivity(R.string.sessionOut);
editText.setText(text);
} catch (PasswordInvalidException e) {
setLoginActivity(R.string.criterios);
}
setWelcomeBackLayout();
}
The error is located where editText.setText(text); is located
There is my error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: pt.edu.es_loule, PID: 3498
java.lang.RuntimeException: Unable to start activity ComponentInfo{pt.edu.es_loule/pt.edu.es_loule.LoginActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
at pt.edu.es_loule.LoginActivity.onCreate(LoginActivity.java:46)
at android.app.Activity.performCreate(Activity.java:6999)
at android.app.Activity.performCreate(Activity.java:6990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Check your layout xml file, you editText variable is null because your reference "idField" is incorrect.
Don't forget to call setContentView(R.layout.yourlayout) before you get the reference of your view.
UPDATE
You forgot to call to setContentView method
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout_file);
...
String implements CharSequence so String.valueOf(aInt) does works as argument.
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
(2 answers)
Closed 5 years ago.
Its just a Caesar Cipher, and I found it online.
The app doesn't crash when I run the encrypt method, the app crashes when I start this activity.
My code:
package com.example.brend.securityreach;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class EncryptActivity extends AppCompatActivity {
EditText thingToEncrypt = (EditText) findViewById(R.id.editText3);
EditText offsets = (EditText) findViewById(R.id.editText4);
String offsetting = thingToEncrypt.toString();
int offset = Integer.valueOf(offsetting);
EditText encryptedText = (EditText) findViewById(R.id.editText2);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_encrypt);
}
public void encrypt(View view) {
char[] words = thingToEncrypt.toString().toCharArray();
for (int i = 0; i < words.length; i++) {
char letter = words[i];
letter = (char) (letter + offset);
if (letter > 'z') {
letter = (char) (letter - 26);
} else if (letter < 'a') {
letter = (char) (letter + 26);
}
words[i] = letter;
}
}
}
Logcat errors:
06-19 12:49:55.587 3766-3766/com.example.brend.securityreach E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.brend.securityreach, PID: 3766
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.brend.securityreach/com.example.brend.securityreach.EncryptActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
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:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:116)
at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:147)
at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:27)
at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:50)
at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:29)
at android.support.v7.app.AppCompatDelegateImplN.<init>(AppCompatDelegateImplN.java:29)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:197)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:181)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:521)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
at com.example.brend.securityreach.EncryptActivity.<init>(EncryptActivity.java:9)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2538)
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:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Edit
I figured it out, with try catch and changing things with variables. Thank you to all who invested time and effort into this question and showing me how to declare EditText variables and the like.
Please follow the Android examples more closely:
public class EncryptActivity extends AppCompatActivity {
EditText thingToEncrypt = (EditText) findViewById(R.id.editText3); //no! don't do this
Don't use field initialisation with findViewById(int id) as you have done above.
You need to put it in onCreate(Bundle savedInstanceState):
EditText thingToEncrypt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_encrypt);
thingToEncrypt = (EditText) findViewById(R.id.editText3);
}
Why? Views like EditText do not become available until setContentView(int layoutId) has been called. Please read the official guide to understand Activity lifecycles.
The scenario might be, you have not declared your activity in AndroidManifest.xml file. kindly check it.
Provide complete details about the error, so we can direct you in correct path.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
i try to add onClick this button then create contact in database
Here is code i try to add it to main_fragment
final Button addBtn = (Button) view.findViewById(R.id.btnadd);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri imageUri = Uri.parse("android.resource://org.intracode.contactmanager/drawable/no_user_logo.png");
import_fragment.Contact contact = new import_fragment.Contact(dbHandler.getContactsCount(), String.valueOf(nametxt.getText()), String.valueOf(phoneTxt.getText()), String.valueOf(emailTxt.getText()), String.valueOf(addressTxt.getText()), imageUri);
if (!contactExists(contact)) {
dbHandler.createContact(contact);
Contacts.add(contact);
contactAdapter.notifyDataSetChanged(); // Error in this line
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(nametxt.getText()) + " has been added to your Contacts!", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(nametxt.getText()) + " already exists. Please use a different name.", Toast.LENGTH_SHORT).show();
}
});
When i press this button in my app, 'app has stopped working'
Here is my logcat
01-22 08:31:04.014 29398-29398/com.al3almya.users.al3almya E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.al3almya.users.al3almya, PID: 29398
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ArrayAdapter.notifyDataSetChanged()' on a null object reference
at com.al3almya.users.al3almya.main_fragment$1.onClick(main_fragment.java:77)
at android.view.View.performClick(View.java:4848)
at android.view.View$PerformClick.run(View.java:20262)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5637)
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:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Either the contactAdapter is not initialized(contactAdater is null) or the object on which the adapter is set is null.
Make sure you have initialized all the variables. Else try running dubugger.
It appears that the variable contactAdapter has not been set.