Error on MediaPlayer.onCreate method / Android Music app - java

I have problem with my music app. I have made a MediaPlayer and application is crashing on this:
2021-08-03 22:54:09.621 6494-6494/com.example.musiclistenerremake E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.musiclistenerremake, PID: 6494
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.musiclistenerremake/com.example.musiclistenerremake.PlayerActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
...
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at com.example.musiclistenerremake.PlayerActivity.getIntentMethod(PlayerActivity.java:106)
at com.example.musiclistenerremake.PlayerActivity.onCreate(PlayerActivity.java:36)
...
Full logcat log:
2021-08-03 22:54:09.621 6494-6494/com.example.musiclistenerremake E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.musiclistenerremake, PID: 6494
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.musiclistenerremake/com.example.musiclistenerremake.PlayerActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
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:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at com.example.musiclistenerremake.PlayerActivity.getIntentMethod(PlayerActivity.java:106)
at com.example.musiclistenerremake.PlayerActivity.onCreate(PlayerActivity.java:36)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
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:2016) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:7356) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 
2021-08-03 22:54:15.300 6494-6509/com.example.musiclistenerremake W/MediaPlayer-JNI: MediaPlayer finalized without being released
In my opinion I did initialize MediaPlayer correctly, I tried to move mediaPlayer before if statement (I don't know why I thought it will help) only, don't have idea what is wrong here.
Im using Android API 29.
private void getIntentMethod() {
position = getIntent().getIntExtra("position", -1);
listSongs = musicFiles;
if (listSongs != null)
{
playPauseBtn.setImageResource(R.drawable.ic_baseline_pause_24);
uri = Uri.parse(listSongs.get(position).getPath());
}
if (mediaPlayer != null)
{
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = MediaPlayer.create(getApplicationContext(), uri);
mediaPlayer.start();
}
else
{
mediaPlayer = MediaPlayer.create(getApplicationContext(), uri);
mediaPlayer.start();
}
seekBar.setMax(mediaPlayer.getDuration() / 1000);
}
Here is full code of this activity (PlayerActivity):
package com.example.musiclistenerremake;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import static com.example.musiclistenerremake.MainActivity.musicFiles;
public class PlayerActivity extends AppCompatActivity {
TextView song_name, artist_name, duration_played, duration_total;
ImageView cover_art, nextBtn, prevBtn, backBtn, shuffleBtn, repeatBtn;
FloatingActionButton playPauseBtn;
SeekBar seekBar;
int position = -1;
static ArrayList<MusicFiles> listSongs = new ArrayList<>();
static Uri uri;
static MediaPlayer mediaPlayer;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
initViews();
getIntentMethod();
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(mediaPlayer != null && fromUser)
{
mediaPlayer.seekTo(progress * 1000);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
PlayerActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if(mediaPlayer != null)
{
int mCurrentPosition = mediaPlayer.getCurrentPosition() / 1000;
seekBar.setProgress(mCurrentPosition);
duration_played.setText(formattedTime(mCurrentPosition));
}
handler.postDelayed(this, 1000);
}
});
}
private String formattedTime(int mCurrentPosition) {
String totalOut = "";
String totalNew = "";
String seconds = String.valueOf(mCurrentPosition % 60);
String minutes = String.valueOf(mCurrentPosition / 60);
totalOut = minutes + ":" + seconds;
totalNew = minutes + ":" + "0" + seconds;
if (seconds.length() == 1)
{
return totalNew;
}
else
{
return totalOut;
}
}
private void getIntentMethod() {
position = getIntent().getIntExtra("position", -1);
listSongs = musicFiles;
if (listSongs != null)
{
playPauseBtn.setImageResource(R.drawable.ic_baseline_pause_24);
uri = Uri.parse(listSongs.get(position).getPath());
}
if (mediaPlayer != null)
{
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = MediaPlayer.create(getApplicationContext(), uri);
mediaPlayer.start();
}
else
{
mediaPlayer = MediaPlayer.create(getApplicationContext(), uri);
mediaPlayer.start();
}
seekBar.setMax(mediaPlayer.getDuration() / 1000);
}
private void initViews() {
song_name = findViewById(R.id.song_name);
artist_name = findViewById(R.id.song_artist);
duration_played = findViewById(R.id.durationPlayed);
duration_total = findViewById(R.id.durationTotal);
cover_art = findViewById(R.id.cover_art);
nextBtn = findViewById(R.id.id_next);
prevBtn = findViewById(R.id.id_prev);
backBtn = findViewById(R.id.back_btn);
shuffleBtn = findViewById(R.id.shuffle);
repeatBtn = findViewById(R.id.id_repeat);
playPauseBtn = findViewById(R.id.play_pause);
seekBar = findViewById(R.id.seekBar);
}
}

Don't use mediaplayer.release()
because after resetting player after mediaplayer.reset() is uninitialized state and if the player is not initialized then it will throw an exception

Related

android studio error E/AndroidRuntime: FATAL EXCEPTION: main [duplicate]

This question already has answers here:
java.lang.InstantiationException: class com.e has no zero argument constructor
(5 answers)
Closed 1 year ago.
This a error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.loginappaplication, PID: 20994
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.loginappaplication/com.example.loginappaplication.MainActivity}: java.lang.InstantiationException: java.lang.Class<com.example.loginappaplication.MainActivity> has no zero argument constructor
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3703)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
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:2216)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7948)
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:1075)
Caused by: java.lang.InstantiationException: java.lang.Class<com.example.loginappaplication.MainActivity> has no zero argument constructor
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1251)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3437)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3703) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
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:2216) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:237) 
at android.app.ActivityThread.main(ActivityThread.java:7948) 
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:1075) 
public class MainActivity extends AppCompatActivity {
private EditText eName;
private EditText ePassword;
private Button eLogin;
private TextView eAttemptsInfo;
private String Username = "Azahracaca";
private String Password = "Caca12345";
boolean isvalid = false;
private int counter = 3;
public MainActivity(Button eLogin) {
this.eLogin = eLogin;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eName = findViewById(R.id.IdName);
ePassword = findViewById(R.id.etPassword);
eAttemptsInfo = findViewById(R.id.tvAttemptsInfo);
eLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String inputName = eName.getText().toString();
String inputPassword = ePassword.getText().toString();
if (inputName.isEmpty() || inputPassword.isEmpty())
{
Toast.makeText(MainActivity.this, "Pastikan Semuanya Benar !", Toast.LENGTH_SHORT).show();
}else{
isvalid = valited(inputName, inputPassword);
if(!isvalid){
counter--;
Toast.makeText(MainActivity.this, "Salah Memasukkan Data !", Toast.LENGTH_SHORT).show();
eAttemptsInfo.setText("Jumlah Login Tersisa : 3 Kali" + counter);
if(counter == 0){
eLogin.setEnabled(false);
}
}else {
Toast.makeText(MainActivity.this, "Login Sukses !", Toast.LENGTH_SHORT).show(); //ke menu selanjutnya
Intent intent = new Intent(MainActivity.this, HomePage.class);
startActivity(intent);
}
}
}
});
}
private boolean valited(String name, String password){
if(name.equals(Username) && password.equals(Password)){
return true;
}
return false;
}
}
public MainActivity(Button eLogin) {
this.eLogin = eLogin;
}
make this constructor empty, and initialize eLogin button using findViewById as you are doing for eName.
you should initialize all of your views in/after onCreate(). can not initialize view in class constructor.
Why constructor Activity you passing Param?
Edit:
public class MainActivity extends AppcompatActivity
And
Button button = findViewById(R.id....)
The structure should like that
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

the mediaPlayer in my timer keeps crushing the app

when i run this code :
package com.example.eggtimer;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView timeLft;
SeekBar timer;
public void start(View view) {
CountDownTimer countDownTimer = new CountDownTimer(timer.getProgress() * 1000 + 100, 1000) {
#Override
public void onTick(long l) {
updateTimer((int) l / 1000);
}
#Override
public void onFinish() {
Log.i("state", "done");
MediaPlayer hi = MediaPlayer.create(getApplicationContext(),R.raw.sound);
hi.start();
}
}.start();
}
public void updateTimer(int secLft) {
int min = secLft/60;
int sec = secLft - (min*60);
String secS = Integer.toString(sec);
if (sec <= 9) {
secS = "0" + sec;
}
timeLft.setText(Integer.toString(min) + ":" + secS);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timer = findViewById(R.id.timer);
timeLft = findViewById(R.id.timeLft);
timer.setMax(600);
timer.setProgress(30);
timer.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
updateTimer(i);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
}
without the mediaPlayer the code runs ok, but when i run it with the mediaPlayer it crushs, and these errors appear in the run section :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.eggtimer, PID: 10017
android.content.res.Resources$NotFoundException: File res/raw/sound.MP3 from drawable resource ID #0x7f0c0000
at android.content.res.ResourcesImpl.openRawResourceFd(ResourcesImpl.java:296)
at android.content.res.Resources.openRawResourceFd(Resources.java:1292)
at android.media.MediaPlayer.create(MediaPlayer.java:965)
at android.media.MediaPlayer.create(MediaPlayer.java:948)
at com.example.eggtimer.MainActivity$1.onFinish(MainActivity.java:27)
at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:127)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.io.FileNotFoundException: This file can not be opened as a file descriptor; it is probably compressed
at android.content.res.AssetManager.openNonAssetFdNative(Native Method)
at android.content.res.AssetManager.openNonAssetFd(AssetManager.java:487)
at android.content.res.ResourcesImpl.openRawResourceFd(ResourcesImpl.java:294)
at android.content.res.Resources.openRawResourceFd(Resources.java:1292) 
at android.media.MediaPlayer.create(MediaPlayer.java:965) 
at android.media.MediaPlayer.create(MediaPlayer.java:948) 
at com.example.eggtimer.MainActivity$1.onFinish(MainActivity.java:27) 
at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:127) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6541) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
what does this mean?

java.lang.NullPointerException: Attempt to invoke virtual method '.getPackageName()' on a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I'm trying to get lists from a db and suddenly this error appear.
Errors are from here:
TinyDB tinydb = new TinyDB(MyApp.getContext());
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
Here's the MyApp's class
public class MyApp extends Application {
private static MyApp instance;
public static MyApp getInstance() {
return instance;
}
public static Context getContext(){
return instance;
// or return instance.getApplicationContext();
}
#Override
public void onCreate() {
instance = this;
super.onCreate();
}
}
I have no idea how to fix this right now.
EDIT:
Process: com.example.pangelyn, PID: 7750
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.pangelyn/com.example.pangelyn.SwipeLeft}:
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String android.content.Context.getPackageName()' on a null
object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2679)
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 'java.lang.String
android.content.Context.getPackageName()' on a null object reference
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:135)
at android.app.Activity.getLocalClassName(Activity.java:5854)
at android.app.Activity.getPreferences(Activity.java:5897)
at com.example.pangelyn.SwipeLeft.(SwipeLeft.java:28)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1174)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2669)
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)
EDIT 2:
public class SwipeLeft extends AppCompatActivity {
float x1,x2,y1,y2;
List<GroupModel> lisSiswaModel = new ArrayList<>();
TinyDB tinydb = new TinyDB(MyApp.getContext());
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_groups);
RecyclerView recyclerView = findViewById(R.id.recyclerView_group);
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
GroupModel groupModel1 = new GroupModel();
groupModel1.setName("School");
String json1 = gson.toJson(groupModel1);
prefsEditor.putString("groups", json1);
prefsEditor.commit();
List<String> json2 = tinydb.getListString("groups");
for (String string : json2) {
GroupModel groupModel2 = gson.fromJson(string, GroupModel.class);
lisSiswaModel.add(groupModel2);
}
recyclerView.setLayoutManager(new LinearLayoutManager(this));
GroupAdapter adapter = new GroupAdapter(this, lisSiswaModel);
recyclerView.setAdapter(adapter);
}
public boolean onTouchEvent(MotionEvent touchEvent){
switch(touchEvent.getAction()){
case MotionEvent.ACTION_DOWN:
x1 = touchEvent.getX();
y1 = touchEvent.getY();
break;
case MotionEvent.ACTION_UP:
x2 = touchEvent.getX();
y2 = touchEvent.getY();
if(x1 > x2 + 250){
Intent i = new Intent(SwipeLeft.this, MainActivity.class);
startActivity(i);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
break;
}
return false;
}
}
The fix is to move this inside the onCreate of the activity(as it says, context is null):
public class SwipeLeft extends AppCompatActivity {
float x1,x2,y1,y2;
List<GroupModel> lisSiswaModel = new ArrayList<>();
TinyDB tinydb = new TinyDB(MyApp.getContext());
SharedPreferences mPrefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_groups);
mPrefs = getPreferences(MODE_PRIVATE);
...more code
}
...more code
}
I guess is crashing because of this TinyDB tinydb = new TinyDB(MyApp.getContext()); initialize your objects inside of your onCreate()?
public class SwipeLeft extends AppCompatActivity {
float x1,x2,y1,y2;
List<GroupModel> lisSiswaModel = new ArrayList<>();
TinyDB tinydb;
SharedPreferences mPrefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_groups);
tinydb = new TinyDB(MyApp.getContext());
mPrefs = getPreferences(MODE_PRIVATE);
Also I'd change your MyApp class to this one :
public class MyApp extends Application {
private static MyApp mContext;
#Override
public void onCreate() {
super.onCreate();
mContext = this;
}
public static MyApp getContext() {
return mContext;
}
}
Do not put the mContext = instance before super.onCreate()

Error I cant Solve:Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference

Whenever I open the activity Testme in the emulator, it encounters a RuntimeException. The logcat has been posted below:
FATAL EXCEPTION: main
Process: com.learn.earn.earnlearnapp, PID: 6622
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.learn.earn.earnlearnapp/com.learn.earn.earnlearnapp.Testme}: 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:2679)
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 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
Nothing seems anything wrong with the code. I have spent hours trying to fix this problem. It would be great if you could help me solve this problem. Part of my activity code has been attached below:
public class Testme extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testme);
readQuestions();
}
int qnum = 0;
private List<TopicQuestion> questionsList = new ArrayList<>();
private TextView txtquestion = findViewById(R.id.txtquestion);
private Button answer1 = findViewById(R.id.btnans1);
private Button answer2 = findViewById(R.id.btnans2);
private Button answer3 = findViewById(R.id.btnans3);
private Button answer4 = findViewById(R.id.btnans4);
private boolean correct = false;
private void readQuestions() {
InputStream is = getResources().openRawResource(R.raw.questions);
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, Charset.forName("UTF-8"))
);
String line = "";
try {
while (
(line = reader.readLine()) != null) {
//Split the data
String[] tokens = line.split(",");
//Read the data
TopicQuestion question = new TopicQuestion();
question.setTopic(tokens[0]);
question.setQuestion(tokens[1]);
question.setAns1(tokens[2]);
question.setAns2(tokens[3]);
question.setAns3(tokens[4]);
question.setAns4(tokens[5]);
questionsList.add(question);
}
} catch (IOException e) {
Log.wtf("MyActivity","Error reading question file on line" + line, e);
e.printStackTrace();
}
{
}
txtquestion.setText(questionsList.get(qnum).getQuestion());
answer1.setText(questionsList.get(qnum).getAns1());
answer2.setText(questionsList.get(qnum).getAns3());
answer3.setText(questionsList.get(qnum).getAns2());
answer4.setText(questionsList.get(qnum).getAns4());
answer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
correct = (questionsList.get(qnum).getAns1()).equals(answer1.getText().toString());
}
});
answer2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
correct = (questionsList.get(qnum).getAns2()).equals(answer2.getText().toString());
}
});
answer3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
correct = (questionsList.get(qnum).getAns1()).equals(answer3.getText().toString());
}
});
answer4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
correct = (questionsList.get(qnum).getAns1()).equals(answer4.getText().toString());
}
});
if (correct)
{
qnum +=1;
txtquestion.setText(questionsList.get(qnum).getQuestion());
answer1.setText(questionsList.get(qnum).getAns1());
answer2.setText(questionsList.get(qnum).getAns3());
answer3.setText(questionsList.get(qnum).getAns2());
answer4.setText(questionsList.get(qnum).getAns4());
}
else
{
txtquestion.setText(questionsList.get(qnum).getQuestion());
answer1.setText(questionsList.get(qnum).getAns1());
answer2.setText(questionsList.get(qnum).getAns3());
answer3.setText(questionsList.get(qnum).getAns2());
answer4.setText(questionsList.get(qnum).getAns4());
}
}
}
You have to assign the values of the view in OnCreate after the setContentView.
Declare the fields outside:
private TextView ;
private Button; etc..
Place the below lines in OnCreate
txtquestion = findViewById(R.id.txtquestion);
answer1 = findViewById(R.id.btnans1);
answer2 = findViewById(R.id.btnans2);
answer3 = findViewById(R.id.btnans3);
answer4 = findViewById(R.id.btnans4);
Hope it helps!

GLSurfaceView in main.xml null pointer exception

I am trying to make glsurfaceview a part of my layout. It returns an error at a line I am sure about and I don't understand why.
My GLGame class:
public abstract class GLGame extends Activity implements Game, Renderer {
enum GLGameState {
Initialized,
Running,
Paused,
Finished,
Idle
}
GLSurfaceView glView;
GLGraphics glGraphics;
Audio audio;
Input input;
FileIO fileIO;
Screen screen;
GLGameState state = GLGameState.Initialized;
Object stateChanged = new Object();
long startTime = System.nanoTime();
WakeLock wakeLock;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
glView =(GLSurfaceView) this.findViewById (R.id.glSurface);
glView.setRenderer(this); //Failing line
setContentView(R.layout.main);
glGraphics = new GLGraphics(glView);
fileIO = new AndroidFileIO(getAssets());
audio = new AndroidAudio(this);
input = new AndroidInput(this, glView, 1, 1);
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "GLGame");
}
public void onResume() {
super.onResume();
glView.onResume();
wakeLock.acquire();
}
#Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
glGraphics.setGL(gl);
synchronized(stateChanged) {
if(state == GLGameState.Initialized)
screen = getStartScreen();
state = GLGameState.Running;
screen.resume();
startTime = System.nanoTime();
}
}
#Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
}
#Override
public void onDrawFrame(GL10 gl) {
GLGameState state = null;
synchronized(stateChanged) {
state = this.state;
}
if(state == GLGameState.Running) {
float deltaTime = (System.nanoTime()-startTime) / 1000000000.0f;
startTime = System.nanoTime();
screen.update(deltaTime);
screen.present(deltaTime);
}
if(state == GLGameState.Paused) {
screen.pause();
synchronized(stateChanged) {
this.state = GLGameState.Idle;
stateChanged.notifyAll();
}
}
if(state == GLGameState.Finished) {
screen.pause();
screen.dispose();
synchronized(stateChanged) {
this.state = GLGameState.Idle;
stateChanged.notifyAll();
}
}
}
#Override
public void onPause() {
synchronized(stateChanged) {
if(isFinishing())
state = GLGameState.Finished;
else
state = GLGameState.Paused;
while(true) {
try {
stateChanged.wait();
break;
} catch(InterruptedException e) {
}
}
}
wakeLock.release();
glView.onPause();
super.onPause();
}
public GLGraphics getGLGraphics() {
return glGraphics;
}
#Override
public Input getInput() {
return input;
}
#Override
public FileIO getFileIO() {
return fileIO;
}
#Override
public Graphics getGraphics() {
throw new IllegalStateException("We are using OpenGL!");
}
#Override
public Audio getAudio() {
return audio;
}
#Override
public void setScreen(Screen screen) {
if (screen == null)
throw new IllegalArgumentException("Screen must not be null");
this.screen.pause();
this.screen.dispose();
screen.resume();
screen.update(0);
this.screen = screen;
}
#Override
public Screen getCurrentScreen() {
return screen;
}
}
Logcat:
03-25 16:44:51.683 4919-4919/com.badlogic.androidgames.glbasics E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.badlogic.androidgames.glbasics, PID: 4919
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.badlogic.androidgames.glbasics/com.badlogic.androidgames.glbasics.GLGameTest}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.opengl.GLSurfaceView.setRenderer(android.opengl.GLSurfaceView$Renderer)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2329)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
at android.app.ActivityThread.access$900(ActivityThread.java:147)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1296)
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:898)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.opengl.GLSurfaceView.setRenderer(android.opengl.GLSurfaceView$Renderer)' on a null object reference
at com.badlogic.androidgames.framework.impl.GLGame.onCreate(GLGame.java:51)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2282)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
            at android.app.ActivityThread.access$900(ActivityThread.java:147)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1296)
            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:898)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
Everything worked fine until I decided I want other things than just glsurfaceview.
I think I am just making a silly mistake, but since the time presses I would be glad if you helped.
Thanks
EDIT: the issue turned out to be that I am unable to findviewbyid from here for some reason. I also tried this:
GLGame.glView = (GLSurfaceView) ((Activity)getApplicationContext()).findViewById (R.id.glSurface);
As it turned out, I am incredibly dumb for writing in in the wrong order. It is supposed to be like this:
setContentView(R.layout.main);
GLGame.glView = (GLSurfaceView) this.findViewById(R.id.glSurface);
glView.setRenderer(this);

Categories