This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
MainActivity.java:
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
int currentPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyListener myListener = new MyListener();
Button startButton = (Button) findViewById(R.id.start);
startButton.setOnClickListener(myListener);
Button pauseButton = (Button) findViewById(R.id.pause);
pauseButton.setOnClickListener(myListener);
}
}
MyListener.java:
import android.media.MediaPlayer;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MyListener extends AppCompatActivity implements View.OnClickListener{
MediaPlayer musicPlayer = MediaPlayer.create(this, R.raw.sound_file);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_listener);
}
#Override
public void onClick(View v){
switch(v.getId()){
case R.id.start:
musicPlayer.start();
break;
case R.id.pause:
musicPlayer.pause();
break;
}
}
}
Logcat shows the following error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.musicplayer/com.example.android.musicplayer.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
I am trying to create an app that plays audio from my res/raw file, but there seems to be something wrong with my code as it is not working, please help me.
Firstly, your MediaPlayer instance should reside within MainActivity, not MyListener, and MyListener should not extend an activity. In fact, you should move all of your code from MyListener into MainActivity, I don't really see a purpose for it in the snippet you've provided.
Secondly, You're creating your MediaPlayer outside of the Activity Lifecycle, while still trying to pass a Context to it:
public class MainActivity extends AppCompatActivity {
MediaPlayer musicPlayer = MediaPlayer.create(this, R.raw.sound_file);
...
}
The activity has no Context (this) until the Activity Lifecycle has started, the way you've written it above is equivalent to defining musicPlayer in a constructor:
public class MainActivity extends AppCompatActivity {
MediaPlayer musicPlayer;
public MyListener() {
musicPlayer = MediaPlayer.create(this, R.raw.sound_file);
}
...
}
This will also fail as the Activity Lifecycle has not yet started. What you need to do is declare musicPlayer as a member of the class, and then create an instance in onCreate() where the Context will have been initialsed:
public class MainActivity extends AppCompatActivity {
MediaPlayer musicPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_listener);
musicPlayer = MediaPlayer.create(this, R.raw.sound_file);
}
...
}
To address your comment, here's an example of how it could all fit in to your MainActivity using lambdas:
public class MainActivity extends AppCompatActivity {
int currentPosition;
MediaPlayer musicPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
musicPlayer = MediaPlayer.create(this, R.raw.sound_file);
Button startButton = (Button) findViewById(R.id.start);
startButton.setOnClickListener(view -> musicPlayer.start());
Button pauseButton = (Button) findViewById(R.id.pause);
pauseButton.setOnClickListener(view -> musicPlayer.pause());
}
}
Related
I'm trying to have MediaPlayer play a roughly two minute long mp3 audio, however only the first second is played then the player stops. I've tired both mp3 and wav formats. Here's my code:
package com.pi.audiodemo;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MediaPlayer mediaPlayer = (MediaPlayer) MediaPlayer.create(this, R.raw.dumb);
mediaPlayer.start();
}
}
You create MediaPlayer within the onCreate function. So it will be deleted right after function returns. Try the following code:
package com.pi.audiodemo;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer = (MediaPlayer) MediaPlayer.create(this, R.raw.dumb);
mediaPlayer.start();
}
}
So, I'm learning and developing a very small app with Android AIDE on my phone, I have code like this:
package com.mycompany.myapp;
import android.app.*;
import android.os.*;
import android.widget.EditText;
import android.widget.Button;
import android.widget.Toast;
import android.view.View;
public class MainActivity extends Activity {
EditText edit1;
Button btn1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edit1 = (EditText) findViewById(R.id.edit1);
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(this);
//Problem (this) from AIDE error info: Method
'android.view.View.setOnClickListener(android.view.View.OnClickListener)' in 'android.widget.Button' can not be applied to '(com.mycompany.myapp.MainActivity)'//
}
public void OnClick(View v) {
switch (v.getId()){
case R.id.btn1:
Toast.makeText(getApplicationContext(),edit1.getText().toString(),Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
}
What is the problem?
Your activity have to implement View.OnClickListener interface
public class MainActivity extends Activity implements View.OnClickListener {
#Override
public void onClick(View view) {}
}
You know what this refers to, don't you? That's a reference for your activity, but setOnClickListener() takes an argument of type View.OnClickListener, not your activity.
Look at the sample code from the official doc:
final Button button = findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Code here executes on main thread after user presses button
}
});
When you create the anonymous inner class with new View.OnClickListener(), that anonymous class implements the OnClick interface.
If you just implement View.OnClickListener on your MainActivity, you'd have to change the way you handle events, and I presume you want to minimize the amount of refactoring.
This Code is working (Tested)
package com.mycompany.myapp;
import android.app.*;
import android.os.*;
import android.widget.EditText;
import android.widget.Button;
import android.widget.Toast;
import android.view.View;
public class MainActivity extends Activity implements View.OnClickListener{
EditText edit12;
Button btn12;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edit12 = (EditText) findViewById(R.id.edit1);
btn12 = (Button) findViewById(R.id.btn1);
btn12.setOnClickListener();
}
public void onClick(View v){
switch (v.getId()){
case R.id.btn12:
Toast.makeText(getApplicationContext(),edit1.getText().toString(),Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
}
I caught the error message
"5-14 12:39:13.104 2518-2518/com.example.fdai3744.neueleereapp E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.fdai3744.neueleereapp, PID: 2518 java.lang.RuntimeException: Unable to instantiate activity ..."
and here's my Java Code
package com.example.fdai3744.neueleereapp;
import android.net.wifi.p2p.WifiP2pManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public Button button_1 = (Button) findViewById(R.id.button1); //Button
public TextView text1 = (TextView)findViewById(R.id.text1); // Textview
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_1.setOnClickListener(new View.OnClickListener() { // Here I add the ActionListener for my button
#Override
public void onClick(View v) {
text1.setText("Button 1 wurde geklickt!");
}
});
}
}
If I start my App the emulator throws an error message "App has stopped". How should I prevent this error?
Well, your view hierarchy needs to be alive before your retrieve individual Views from it and the method setContentView() brings it to life(or instantiates it).
How?
setContentView(View) is a method exclusively available for Activity.
Internally it calls the setContentView(View) of Window. This method
sets the activity content to an explicit view. This view is placed
directly into the activity's view hierarchy. Calling this function
"locks in" various characteristics of the window that can not, from
this point forward, be changed. Hence it is called only once.
So, instead of initializing the Views as instance variables, instantiate them inside onCreate() after setContentView().
Also read: Android: setContentView and LayoutInflater
caused by
public Button button_1 = (Button) findViewById(R.id.button1); //Button
public TextView text1 = (TextView)findViewById(R.id.text1); // Textview
never assign view before setContentView() is called
your modified code
package com.example.fdai3744.neueleereapp;
import android.net.wifi.p2p.WifiP2pManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public Button button_1;
public TextView text1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_1 = (Button) findViewById(R.id.button1); //Button
text1 = (TextView)findViewById(R.id.text1); // Textview
button_1.setOnClickListener(new View.OnClickListener() { // Here I add the ActionListener for my button
#Override
public void onClick(View v) {
text1.setText("Button 1 wurde geklickt!");
}
});
}
}
I'm relatively new at developing applications in Android Studio or Java and recently ran into a problem I just can't figure out. For now, all I'm trying to achieve is to output the content of the EditText field after a Button is been clicked.
Since I will most likely add more buttons to the Activity later on, I thought that it would be more handy to use a generic onClick where you can separate different button actions inside the switch statement.
Here's a working example in which the onClickListener which does not use a generic onClick method:
package com.example.user.myapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
private EditText testText;
private Button testButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize UI elements
final EditText testText = (EditText) findViewById(R.id.testText);
testButton = (Button) findViewById(R.id.testButton);
// set onClick listener
testButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// it will print the content of testText as long as the "testText" variable is declared as final
System.out.println(testText.getText().toString().trim());
}
});
}
}
Now, if I try to use a generic onClick method, I will suddenly receive a following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
Here's the code that that causes the error referred above:
package com.example.user.myapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements View.OnClickListener {
private EditText testText;
private Button testButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize the UI elements
EditText testText = (EditText) findViewById(R.id.testText);
Button testButton = (Button) findViewById(R.id.testButton);
// set onClick Listener
testButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.testButton:
// this will result in an error
System.out.println(testText.getText().toString().trim());
break;
default:
break;
}
}
Am I missing something here?
on your second code you have defined testText twice
that will work
package com.example.user.myapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements View.OnClickListener {
private EditText testText;
private Button testButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize the UI elements
testText = (EditText) findViewById(R.id.testText);
testButton = (Button) findViewById(R.id.testButton);
// set onClick Listener
testButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.testButton:
// this will result in an error
System.out.println(testText.getText().toString().trim());
break;
default:
break;
}
}
Decalre editText globally:
private EditText testText;
Get the view in onCreate():
testText = (EditText) findViewById(R.id.testText);
Use it in the onClick:
System.out.println(testText.getText().toString().trim());
You never initialize the private EditText testText; because you use a local variable instead of referencing the class field in the following call:
final EditText testText = (EditText) findViewById(R.id.testText);
The onClick(View v) is a method of anonymous class implementing the OnClickListener interface and this method references the uninitialized field variable testText.
To fix this, remove the type declaration of a variable before calling findViewById():
this.testText = (EditText) findViewById(R.id.testText)
You have declare EditText 2 time, one is globally and another one is inside the onCreate method, and when you are using Edittext outside the onCreate, you are getting global variable which is not initialize, thats why you are getting this error. use this,
public class MainActivity extends Activity implements View.OnClickListener {
private EditText testText;
private Button testButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize the UI elements
testText = (EditText) findViewById(R.id.testText);
testButton = (Button) findViewById(R.id.testButton);
// set onClick Listener
testButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.testButton:
// this will result in an error
System.out.println(testText.getText().toString().trim());
break;
default:
break;
}
}
This code to change text when the user presses a button doesn't work. i tried to change it in some ways but i can't figure out why won't it change... please give me a bit help
package com.cookbook.simple_activity;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class activity extends Activity {
private TextView txt = (TextView) findViewById(R.id.hello_text);
Button startButton = (Button) findViewById(R.id.trigger);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
txt.setText(R.string.pressthisbutton);
}
});
}
}
Change it to
public class activity extends Activity {
private TextView txt;
Button startButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple);
txt = (TextView) findViewById(R.id.hello_text);
startButton = (Button) findViewById(R.id.trigger);
You need to initialize your Views after inflating your layout with setContentView(). Since your Views exist in your layout, they will return null if you haven't inflated your layout first. You can declare them before your setContentView() but you can't initialize them until after.
Also, since you are trying to access txt inside your listener it must either be final or declared as a member variable as above.
This was a rather easy one to spot but they aren't always. When you post a question try to describe what isn't working and how. Here it would be a NPE I'm guessing when you try to set the listener on your Button so it crashes. When it does crash, please provide the logcat so it is easier for us to spot the problem.
package com.cookbook.simple_activity;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class activity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple);
final TextView txt = (TextView) findViewById(R.id.hello_text);
Button startButton = (Button) findViewById(R.id.trigger);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
txt.setText("your text");
}
});
}
}
try this, I moved your button and textview declaring to the body of the activity.
android life cycle always starts with onCreate() method assign the id inside the onCreate
don't use private modifer for the TextView
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class activity extends Activity {
TextView txt;
Button startButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple);
txt = (TextView) findViewById(R.id.hello_text);
startButton = (Button) findViewById(R.id.trigger);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
txt.setText(R.string.pressthisbutton);
}
});
}
}
Always initialize your textview and other widgets in oncreate method other wise youll get NullPointerException
Try this way
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple);
txt = (TextView) findViewById(R.id.hello_text);
startButton = (Button) findViewById(R.id.trigger);
txt.setText("It Working Now!!");