Playing sound via button crash (Android) - java

I have 3 buttons, when the buttons are tapped a sound will play. But for some reason i am starting to get this error now, after i implemented all 3 buttons. When i did just 1 button, it played the sound with no error. After i implemented 2 more, the app started to always crash.
Here is my code for the button in my .xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play!"
android:id="#+id/play1"
android:layout_below="#+id/imageView"
android:layout_toLeftOf="#+id/play3"
android:layout_toStartOf="#+id/play3" />
And here is my code in the mainactivity.java
// final MediaPlayer mp = MediaPlayer.create(this, R.raw.sounds1);
// final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.sounds2);
// final MediaPlayer mp3 = MediaPlayer.create(this, R.raw.sounds3);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Button play_button = (Button)this.findViewById(R.id.play1);
//// Button play_button2 = (Button)this.findViewById(R.id.play2);
//// Button play_button3 = (Button)this.findViewById(R.id.play3);
//
// play_button.setOnClickListener(new View.OnClickListener() {
// public void onClick(View v) {
//
//
// mp.start();
// }
// });
//
// play_button2.setOnClickListener(new View.OnClickListener() {
// public void onClick(View v) {
//
//
// mp2.start();
// }
// });
//
// play_button3.setOnClickListener(new View.OnClickListener() {
// public void onClick(View v) {
//
//
// mp3.start();
// }
// });
}
Here is the log too!
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.sounds.apps.sounds/com.sounds.apps.sounds.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:85)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:74)
at android.media.MediaPlayer.create(MediaPlayer.java:919)
at android.media.MediaPlayer.create(MediaPlayer.java:902)
at com.sounds.apps.sounds.MainActivity.<init>(MainActivity.java:14)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1572)
at android.app.Instrumentation.newActivity(Instrumentation.java:1065)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2199)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            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:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.sounds1);
final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.sounds2);
final MediaPlayer mp3 = MediaPlayer.create(this, R.raw.sounds3);
Button play_button = (Button)this.findViewById(R.id.play1);
Button play_button2 = (Button)this.findViewById(R.id.play2);
Button play_button3 = (Button)this.findViewById(R.id.play3);
play_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp.start();
}
});
play_button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp2.start();
}
});
play_button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp3.start();
}
});
}

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.

My app is crashing when I try to go to another activity

I'm trying to make a clickable image button redirect to the mainactivity
But since I've putted this code, the app crash when I click on the button to go to the 2nd Activity.
This id the first time I'm making an application.
Activity_good.java
public class Activity_good extends AppCompatActivity {
private Button backGood;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_good);
final TextView txtBien = (TextView) findViewById(R.id.txtBien);
Button genBien = (Button) findViewById(R.id.genBien);
final String[] pBien={"« Pour réussir, votre désir de réussite doit être plus grand que votre peur de l’échec. » Bill Cosby", "trql", "oui", "non"};
genBien.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int rando = (int) (Math.random()*4);
txtBien.setText(pBien[rando]);
}
});
backGood = (Button) findViewById(R.id.backGood);
backGood.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openMainActivity();
}
});
}
public void openMainActivity(){
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer pianoman = MediaPlayer.create(this, R.raw.piano);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pianoman.start();
openActivity_good();
}
});
}
public void openActivity_good() {
Intent intent = new Intent(this, Activity_good.class);
startActivity(intent);
}
}
Crash log ?
E/MediaPlayer: error (1, -19)
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: fr.gab.artapp, PID: 9016
java.lang.RuntimeException: Unable to start activity ComponentInfo{fr.gab.artapp/fr.gab.artapp.Activity_good}: java.lang.ClassCastException: android.support.v7.widget.AppCompatImageButton cannot be cast to android.widget.Button
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
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.ClassCastException: android.support.v7.widget.AppCompatImageButton cannot be cast to android.widget.Button
at fr.gab.artapp.Activity_good.onCreate(Activity_good.java:30)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
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) 
Application terminated.
I exprected to to get back on mainactivity when I click on the button backGood.+
Change this line:
backGood = (Button) findViewById(R.id.backGood);
To this:
backGood = (AppCompatImageButton) findViewById(R.id.backGood);
You are casting a AppCompatImageButton as a Button.

App Crashing - java.lang.IllegalStateException: Could not execute method for android:onClick [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Null pointer Exception - findViewById()
(12 answers)
Closed 5 years ago.
My app is crashing everytime I try to click a button that inputs text into a listView, I am getting the "java.lang.IllegalStateException: Could not execute method for android:onClick"; I've tried other solutions to the problem but I can't seem to find my own solution. Any help is appreciated.
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<String> arrayList;
ArrayAdapter<String> arrayAdapter;
String infoText;
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread = new Thread(new Runnable(){
#Override
public void run(){
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean isFirstStart = getPrefs.getBoolean("started",true);
if(isFirstStart)
{
startActivity(new Intent (MainActivity.this,Intro.class));
SharedPreferences.Editor e = getPrefs.edit();
e.putBoolean("started", false);
e.apply();
}
}
});
thread.start();
listView = (ListView) findViewById(R.id.ListView);
arrayList = new ArrayList<>();
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent();
intent.setClass(MainActivity.this,EditMessageClass.class);
intent.putExtra(Intent_Constants.INTENT_INFO_DATA,arrayList.get(position).toString());
intent.putExtra(Intent_Constants.INTENT_ITEM_POSITION,position);
startActivityForResult(intent,Intent_Constants.INTENT_REQUEST_CODE_2);
}
});
}
public void onClick(View v){
Intent intent = new Intent();
intent.setClass(MainActivity.this,EditFieldClass.class);
startActivityForResult(intent,Intent_Constants.INTENT_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (resultCode==Intent_Constants.INTENT_REQUEST_CODE){
infoText = data.getStringExtra(Intent_Constants.INTENT_INFO_FIELD);
arrayList.add(infoText);
arrayAdapter.notifyDataSetChanged();
}
else if(resultCode==Intent_Constants.INTENT_REQUEST_CODE_2){
infoText = data.getStringExtra(Intent_Constants.INTENT_CHANGED_INFO);
position = data.getIntExtra(Intent_Constants.INTENT_ITEM_POSITION,-1);
arrayList.remove(position);
arrayList.add(position,infoText);
arrayAdapter.notifyDataSetChanged();
}
}
}
Intent_Constants.java
public class Intent_Constants {
public final static int INTENT_REQUEST_CODE=1;
public final static int INTENT_RESULT_CODE=1;
public final static int INTENT_REQUEST_CODE_2=2;
public final static int INTENT_RESULT_CODE_2=2;
public final static String INTENT_INFO_FIELD="info_field";
public final static String INTENT_INFO_DATA="info_data";
public final static String INTENT_ITEM_POSITION="item_position";
public final static String INTENT_CHANGED_INFO="changed_info";
EditMessageClass.java
public class EditMessageClass extends AppCompatActivity {
String infoText;
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_promo_layout);
Intent intent = getIntent();
infoText = intent.getStringExtra(Intent_Constants.INTENT_INFO_DATA);
position = intent.getIntExtra(Intent_Constants.INTENT_ITEM_POSITION,-1);
EditText infoData = (EditText) findViewById(R.id.info);
infoData.setText(infoText);
}
public void saveButtonClicked(View v){
String changedinfoText = ((EditText)findViewById(R.id.info)).getText().toString();
Intent intent = new Intent();
intent.putExtra(Intent_Constants.INTENT_CHANGED_INFO,changedinfoText);
intent.putExtra(Intent_Constants.INTENT_ITEM_POSITION, position);
setResult(Intent_Constants.INTENT_RESULT_CODE_2,intent);
finish();
}
}
EditFieldClass.java
public class EditFieldClass extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_promo_layout);
}
public void saveButtonClicked(View v){
String infoText = ((EditText)findViewById(R.id.info)).getText().toString();
if(infoText.equals("")){
}
else{
Intent intent = new Intent();
intent.putExtra(Intent_Constants.INTENT_INFO_FIELD,infoText);
setResult(Intent_Constants.INTENT_RESULT_CODE,intent);
finish();
}
}
}
Logs
FATAL EXCEPTION: main
Process: gabriel.com.prototype, PID: 15435
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5637) 
at android.view.View$PerformClick.run(View.java:22429) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at gabriel.com.prototype.EditFieldClass.saveButtonClicked(EditFieldClass.java:27)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:5637) 
at android.view.View$PerformClick.run(View.java:22429) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
According to your logcat message, I can say that your EditText object is null
the problem is caused by this line.
((EditText)findViewById(R.id.info)).getText().toString()
Make sure you have EditText with id 'info' in EditFieldClass.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at gabriel.com.prototype.EditFieldClass.saveButtonClicked(EditFieldClass.java:27)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
your EditText is null , check editText id .

How can i solve getApplicationContext() java.lang.NullPointerExeception

I am trying to connect to an azure application, using android, but I am getting this error. Here is my code and my logs.
I have checked everything and it seen to be right, but the problem I think is with getApplicationContext(). I am unable to debug.
can someone help me please?
public class login extends Activity {
UserServicesImpl usv;
private EditText txtemail;
private EditText txtpassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
txtemail = (EditText) findViewById(R.id.txtemail);
txtpassword = (EditText) findViewById(R.id.txtpassword);
}
public void LoginKarrega(View view){
usv = new UserServicesImpl();
AlertDialog alertDialog = new AlertDialog.Builder(login.this).create();
alertDialog.setTitle("Alert");
if(usv.exist(txtemail.getText().toString(), txtpassword.getText().toString()) == true) {
alertDialog.setMessage("Sucessful login");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
else {
alertDialog.setMessage("wrong login");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
alertDialog.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_login, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Logcat:
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4007)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4002)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            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:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:105)
at com.microsoft.windowsazure.mobileservices.notifications.MobileServicePush.<init>(MobileServicePush.java:134)
at com.microsoft.windowsazure.mobileservices.MobileServiceClient.initialize(MobileServiceClient.java:1473)
at com.microsoft.windowsazure.mobileservices.MobileServiceClient.<init>(MobileServiceClient.java:182)
at com.microsoft.windowsazure.mobileservices.MobileServiceClient.<init>(MobileServiceClient.java:158)
at ao.co.karrega.services.customers.UserServicesImpl.<init>(UserServicesImpl.java:39)
at ao.co.karrega.login.LoginKarrega(login.java:32)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at android.view.View$1.onClick(View.java:4002)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            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:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Use below code to solve this error. Currently you are using this instead of getApplicationContext().
try {
mClient = new MobileServiceClient(
"https://newvbdemo.azure-mobile.net/",
"SUFYiOYEAlbEoKfsDgfWNIywaPSMhC29",
getApplicationContext()
);
mTable = mClient.getTable("Users",Users.class);
}catch (MalformedURLException e) {
e.printStackTrace();
}
Your class UserServicesImpl extends Activity but it does not seem to be an Activity.
In particular, activities usually don't have an explicit constructor, and you cannot use an Activity as a Context before its onCreate() lifecycle method. Construction phase <init> in your stacktrace is too early.
The stacktrace also shows that you're trying to instantiate an activity with new in LoginKarrega. Never instantiate an activity with new yourself.
Looks like you should be removing the extends Activity and pass a Context as an argument instead.

java.lang.RuntimeException: Unable to instantiate service: java.lang.NullPointerException

I' m a complete newcome to android and java and I'm writing an android app with android studio that should show some points on a map each 5 seconds (it's just a test). When I run the app on the emulator I get this on the logcat:
03-13 13:22:28.373 2964-2964/com.example.francesca.geoapp
E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.francesca.geoapp, PID: 2964
java.lang.RuntimeException: Unable to instantiate service com.example.francesca.geoapp.DataService: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.app.ActivityThread.handleCreateService(ActivityThread.java:2716)
at android.app.ActivityThread.access$1800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1361)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:105)
at android.support.v4.content.LocalBroadcastManager.getInstance(LocalBroadcastManag er.java:102) at com.example.francesca.geoapp.DataService.<init> (DataService.java:56)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1572)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:2713)
            at android.app.ActivityThread.access$1800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1361)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            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:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
the intentService DataService code is
public class DataService extends IntentService {
private LocalBroadcastManager BroadcastNotifier ;
private Timer timer = new Timer();
private List dataList = new ArrayList<testData>();
int i = 0;
//constructor
public DataService() {
super("DataService");
dataList.add(new testData(new LatLng(52.519804, 13.404988), new LatLng(52.519125, 13.406061), 50, 30));
dataList.add(new testData(new LatLng(52.520692, 13.403722), new LatLng(52.519804, 13.404988), 60, 40));
dataList.add(new testData(new LatLng(52.522023, 13.404730), new LatLng(52.520692, 13.403722), 50, 30));
dataList.add(new testData(new LatLng(52.523388, 13.407143), new LatLng(52.522023, 13.404730), 40, 20));
dataList.add(new testData(new LatLng(52.522911, 13.408807), new LatLng(52.523388, 13.407143), 80, 30));
dataList.add(new testData(new LatLng(52.523982, 13.409623), new LatLng(52.522911, 13.408807), 50, 40));
dataList.add(new testData(new LatLng(52.524713, 13.407434), new LatLng(52.523982, 13.409623), 30, 50));
BroadcastNotifier = LocalBroadcastManager.getInstance(this);
timer.scheduleAtFixedRate(task, 0, 5000 );
}
protected void onHandleIntent(Intent i) {
}
//timerTask to send request to the webservice
TimerTask task = new TimerTask() {
#Override
public void run() {
if(i <7 ) {
testData test = (testData) dataList.get(i);
data.setCurrentPosition(test.currentPosition);
data.setLatestPosition(test.latestPosition);
data.setSpeed(test.speed);
data.setMediumSpeed(test.mediumSpeed);
i++;
}
}
};
//method to tell subscribers that a newData has arrived
private void OnNewDataSeen() {
Intent localIntent = new Intent();
localIntent.setAction("com.example.android.threadsample.BROADCAST");
localIntent.addCategory(Intent.CATEGORY_DEFAULT);
// Broadcasts the Intent
BroadcastNotifier.sendBroadcast(localIntent);
}
}
And the MenuActivity that should start the intentService is
public class MenuActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
Intent mServiceIntent = new Intent(this, DataService.class);
this.startService(mServiceIntent);
}
public void goToMap(View view){
Intent intent = new Intent(this, MapActivity.class);
startActivity(intent);
}
public void goToData(View view){
Intent intent = new Intent(this, ShowDataActivity.class);
startActivity(intent);
}
}
What have I done wrong?
You can't have this
BroadcastNotifier = LocalBroadcastManager.getInstance(this);
in you constructor. Put it into the onHandleIntent()
this isn't fully initialised in your constructor and a Context cannot be obtained, which it why it is null and you get that NPE.
You should leave constructor with super call only and use onCreate lifecycle callback method.

Categories