I have to develop an app for an internship and I'm using AndroidStudio.
For now I'm just trying things and I'm developping a Spank counters app (yeah yeah I know).
I know that there is already a response there :
What is a NullPointerException, and how do I fix it?
and many other questions similar to mine.
The fact is I understant the error but I can't find it in my code.
(I havn't put the xml file because I don't think it's usefull bet let me konw if you want to see it.)
Sorry if it's hard to read this post. It's the first time I ask something on a forum.
Thanks in advance for those who will be brave enough to read it and help me.
So here is errors :
--------- beginning of crash
06-02 18:05:31.515 2680-2680/com.example.florian.fessee E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.florian.fessee, PID: 2680
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.florian.fessee/com.example.florian.fessee.MainActivity}: 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:2236)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:132)
at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:374)
at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:369)
at com.example.florian.fessee.MainActivity.<init>(MainActivity.java:23)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)Â
at android.app.ActivityThread.access$800(ActivityThread.java:151)Â
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)Â
at android.os.Handler.dispatchMessage(Handler.java:102)Â
at android.os.Looper.loop(Looper.java:135)Â
at android.app.ActivityThread.main(ActivityThread.java:5254)Â
at java.lang.reflect.Method.invoke(Native Method)Â
at java.lang.reflect.Method.invoke(Method.java:372)Â
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)Â
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)Â
06-02 18:11:28.569 3101-3101/com.example.florian.fessee D/AndroidRuntime: Shutting down VM
06-02 18:11:28.570 3101-3101/com.example.florian.fessee E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.florian.fessee, PID: 3101
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.florian.fessee/com.example.florian.fessee.MainActivity}: 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:2236)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:132)
at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:374)
at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:369)
at com.example.florian.fessee.MainActivity.<init>(MainActivity.java:23)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)Â
at android.app.ActivityThread.access$800(ActivityThread.java:151)Â
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)Â
at android.os.Handler.dispatchMessage(Handler.java:102)Â
at android.os.Looper.loop(Looper.java:135)Â
at android.app.ActivityThread.main(ActivityThread.java:5254)Â
at java.lang.reflect.Method.invoke(Native Method)Â
at java.lang.reflect.Method.invoke(Method.java:372)Â
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)Â
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)Â
06-02 18:16:53.409 3339-3339/com.example.florian.fessee D/AndroidRuntime: Shutting down VM
06-02 18:16:53.435 3339-3339/com.example.florian.fessee E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.florian.fessee, PID: 3339
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.florian.fessee/com.example.florian.fessee.MainActivity}: 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:2236)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:132)
at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:374)
at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:369)
at com.example.florian.fessee.MainActivity.<init>(MainActivity.java:23)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)Â
at android.app.ActivityThread.access$800(ActivityThread.java:151)Â
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)Â
at android.os.Handler.dispatchMessage(Handler.java:102)Â
at android.os.Looper.loop(Looper.java:135)Â
at android.app.ActivityThread.main(ActivityThread.java:5254)Â
at java.lang.reflect.Method.invoke(Native Method)Â
at java.lang.reflect.Method.invoke(Method.java:372)Â
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)Â
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)Â
06-02 18:19:42.932 3515-3515/com.example.florian.fessee D/AndroidRuntime: Shutting down VM
06-02 18:19:42.935 3515-3515/com.example.florian.fessee E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.florian.fessee, PID: 3515
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.florian.fessee/com.example.florian.fessee.MainActivity}: 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:2236)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:132)
at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:374)
at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:369)
at com.example.florian.fessee.MainActivity.<init>(MainActivity.java:23)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)Â
at android.app.ActivityThread.access$800(ActivityThread.java:151)Â
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)Â
at android.os.Handler.dispatchMessage(Handler.java:102)Â
at android.os.Looper.loop(Looper.java:135)Â
at android.app.ActivityThread.main(ActivityThread.java:5254)Â
at java.lang.reflect.Method.invoke(Native Method)Â
at java.lang.reflect.Method.invoke(Method.java:372)Â
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)Â
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)Â
And here is my code :
package com.example.florian.fessee;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private int compt = 0;
private Button b1 = null;
private Button b5 = null;
private Button b01 = null;
private Button b05 = null;
private Button braz = null;
private TextView t = null;
private String COMPT = "comptfess";
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button1);
b5 = (Button) findViewById(R.id.button5);
b01 = (Button) findViewById(R.id.button01);
b05 = (Button) findViewById(R.id.button05);
braz = (Button) findViewById(R.id.buttonraz);
t = (TextView) findViewById(R.id.textView);
compt = preferences.getInt(COMPT, 0);
b1.setOnClickListener(b1Listener);
b5.setOnClickListener(b5Listener);
b01.setOnClickListener(b01Listener);
b05.setOnClickListener(b05Listener);
braz.setOnClickListener(brazListener);
if (compt == 1) {
t.setText("Je dois 1 fessée à Sophie.");
}
else if (compt!=0){
t.setText("Je dois " + compt + "fessées à Sophie.");
}
}
private View.OnClickListener b1Listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
compt +=1;
editor.putInt(COMPT,compt);
editor.commit();
if (compt == 1) {
t.setText("Je dois 1 fessée à Sophie.");
}
else if (compt!=0){
t.setText("Je dois " + compt + "fessées à Sophie.");
}
}
};
private View.OnClickListener b5Listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
compt +=5;
editor.putInt(COMPT,compt);
editor.commit();
if (compt == 1) {
t.setText("Je dois 1 fessée à Sophie.");
}
else if (compt!=0){
t.setText("Je dois " + compt + "fessées à Sophie.");
}
}
};
private View.OnClickListener b01Listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(compt!=0){
compt -=1;
editor.putInt(COMPT,compt);
editor.commit();
if (compt==0){
t.setText("Je ne dois plus de fessées å Sophie");
}
else if (compt == 1) {
t.setText("Je dois 1 fessée à Sophie.");
}
else{
t.setText("Je dois " + compt + "fessées à Sophie.");
}
}
else {
Toast.makeText(MainActivity.this, "Un nombre de fessées doit être positif.", Toast.LENGTH_SHORT).show();
}
}
};
private View.OnClickListener b05Listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(compt>4){
compt -=5;
editor.putInt(COMPT,compt);
editor.commit();
if (compt==0){
t.setText("Je ne dois plus de fessées å Sophie.");
}
else if (compt == 1) {
t.setText("Je dois 1 fessée à Sophie.");
}
else{
t.setText("Je dois " + compt + "fessées à Sophie.");
}
}
else {
Toast.makeText(MainActivity.this, "Un nombre de fessées doit être positif.", Toast.LENGTH_SHORT).show();
}
}
};
private View.OnClickListener brazListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
compt = 0;
editor.putInt(COMPT,compt);
editor.commit();
t.setText("Je ne dois plus de fessées à Sophie.");
}
};
}
This is your problem:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
You can't initialize SharedPreferences before the Activity has been created. Separate your declaration and instantiation like this:
...
SharedPreferences preferences;
SharedPreferences.Editor editor;
...
#Override
public void onCreate(Bundle savedInstanceState){
...
preferences = PreferenceManager.getDefaultSharedPreferences(this);
editor = preferences.edit();
...
}
It seems your argument boils down to the idea that passing an Activity Context to getDefaultSharedPreferences() should be valid.
And normally it should - but only after the Activity's Context is fully initialized. I believe that is only true during or after the call to onCreate().
You can declare your preferences related variables where you are, but don't attempt to initialize them until during or after onCreate().
Related
The below code gives null pointer exception in android studio
please help me to solve that
02-10 22:42:11.702 30997-30997/? I/art: Late-enabling -Xcheck:jni
02-10 22:42:11.749 30997-30997/? D/TidaProvider: TidaProvider()
02-10 22:42:11.757 30997-30997/? W/ReflectionUtils: java.lang.NoSuchMethodException: android.os.MessageQueue#enableMonitor()#bestmatch
at miui.util.ReflectionUtils.findMethodBestMatch(ReflectionUtils.java:338)
at miui.util.ReflectionUtils.findMethodBestMatch(ReflectionUtils.java:375)
at miui.util.ReflectionUtils.callMethod(ReflectionUtils.java:800)
at miui.util.ReflectionUtils.tryCallMethod(ReflectionUtils.java:818)
at android.os.BaseLooper.enableMonitor(BaseLooper.java:47)
at android.os.Looper.prepareMainLooper(Looper.java:111)
at android.app.ActivityThread.main(ActivityThread.java:5584)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
02-10 22:42:11.789 30997-30997/com.androidexample.courtcounter W/ResourceType: No package identifier when getting name for resource number 0x00000000
02-10 22:42:11.803 30997-30997/com.androidexample.courtcounter W/System: ClassLoader referenced unknown path: /data/app/com.androidexample.courtcounter-1/lib/arm64
02-10 22:42:11.826 30997-30997/com.androidexample.courtcounter D/AndroidRuntime: Shutting down VM
02-10 22:42:11.827 30997-30997/com.androidexample.courtcounter E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.androidexample.courtcounter, PID: 30997
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.androidexample.courtcounter/com.androidexample.courtcounter.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2396)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2545)
at android.app.ActivityThread.access$1100(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1396)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5601)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:160)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:109)
at android.content.Context.obtainStyledAttributes(Context.java:517)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:839)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:806)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:630)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:223)
at com.androidexample.courtcounter.MainActivity.(MainActivity.java:19)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2386)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2545)
at android.app.ActivityThread.access$1100(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1396)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5601)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
public class MainActivity extends AppCompatActivity {
int team_a_Score=0;
int team_b_Score=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
final Button button1=(Button)findViewById(R.id.score2);
final Button button_teamB1=(Button)findViewById(R.id.TeamB_score1);
final Button buttonScore3A=(Button)findViewById(R.id.score3);
final Button buttonScore3B=(Button)findViewById(R.id.TeamB_score3);
final Button buttonScore_freeshotA=(Button)findViewById(R.id.freeshot);
final Button buttonScore_freeshotB=(Button)findViewById(R.id.TeamB_freeshot);
public void onClick(View v) {
if (v.equals(button1)) {
team_a_Score = team_a_Score + 1;
TextView text = (TextView) findViewById(R.id.score_team_a);
text.setText(team_a_Score);
} else if (v.equals(button_teamB1)) {
team_b_Score = team_b_Score + 1;
TextView text = (TextView) findViewById(R.id.score_teamB);
text.setText(team_b_Score);
} else if (v.equals(buttonScore3A)) {
team_a_Score = team_a_Score + 3;
TextView text = (TextView) findViewById(R.id.score_team_a);
text.setText(team_b_Score);
} else if (v.equals(buttonScore3B)) {
team_b_Score = team_b_Score + 3;
TextView text = (TextView) findViewById(R.id.score_teamB);
text.setText(team_b_Score);
} else if (v.equals(buttonScore_freeshotA)) {
team_a_Score = team_a_Score + 4;
TextView text = (TextView) findViewById(R.id.score_team_a);
text.setText(team_a_Score);
} else if (v.equals(buttonScore_freeshotB)) {
team_b_Score = team_b_Score + 4;
TextView text = (TextView) findViewById(R.id.score_teamB);
text.setText(team_b_Score);
}
}
}
List item
It looks like this code:
final Button button1=(Button)findViewById(R.id.score2);
final Button button_teamB1=(Button)findViewById(R.id.TeamB_score1);
final Button buttonScore3A=(Button)findViewById(R.id.score3);
final Button buttonScore3B=(Button)findViewById(R.id.TeamB_score3);
final Button buttonScore_freeshotA=(Button)findViewById(R.id.freeshot);
is member variable definitions outside of a method. That doesn't work on Android, because this code executes at object instantiation time and you cannot call findViewById() before setContentView() is called. You are calling setContentView() in onCreate() which is correct, but onCreate() is called after the object is instantiated.
You need to split the member variable definitions from the initialization. To do that, declare the member variables without initialization outside of a method:
final Button button1;
final Button button_teamB1;
final Button buttonScore3A;
final Button buttonScore3B;
final Button buttonScore_freeshotA;
Then, in onCreate(), after calling setContentView(), you can initialize the member variables like this:
button1=(Button)findViewById(R.id.score2);
button_teamB1=(Button)findViewById(R.id.TeamB_score1);
buttonScore3A=(Button)findViewById(R.id.score3);
buttonScore3B=(Button)findViewById(R.id.TeamB_score3);
buttonScore_freeshotA=(Button)findViewById(R.id.freeshot);
I theoretically have 2 related questions.
1) I tried to make a night mode for my app. That works so far pretty good. Then I wanted to put the setting the User chooses to SharedPreferences. In my first try, It just didn't work. All I did was getting red and causing errors. After a lot of research on the Internet, I found another idea. Now the app is starting but crashing immediately again. The error has to be in the SharedPreferences because as soon as I delete this part it is working again. I just can't find the error and it doesn't show me a red area or so either.
2) Just to check if my research are right. Is it true that it is not possible anymore to make a time-related Night mode? Means dark at night, light at day? I found out that MODE_NIGHT_AUTO_TIME was supposed to do that but is deprecated and they suggest to use MODE_NIGHT_AUTO_BATTERY which is kinda something really different.
btw. here is my code if it helps from the Setting:
public class Settings extends AppCompatActivity {
private static final String TAG = "SettingsActivity";
private RelativeLayout layout;
private SharedPreferences preferences;
private Bundle savedInstanceState;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Spinner spinner = findViewById(DarkMode);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.e(TAG, "onItemSelected: " + position);
handleNightMode(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Log.e(TAG, "onNothingSelected: ");
}
});
}
private void handleNightMode(int position) {
switch (position) {
case 0:
Log.e(TAG, "Nothing Selected");
break;
case 1:
Log.e(TAG, "FOLLLOW_SYSTEM");
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
getDelegate().applyDayNight();
break;
case 2:
Log.e(TAG, "YES");
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
getDelegate().applyDayNight();
break;
case 3:
Log.e(TAG, "NO");
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
getDelegate().applyDayNight();
break;
case 4:
Log.e(TAG, "AUTO");
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
getDelegate().applyDayNight();
break;
default:
Log.e(TAG, "FOLLLOW_SYSTEM");
break;
}
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String NightMode = preferences.getString("prefTheme", "NO");
if (NightMode.equals("YES"))
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
if (NightMode.equals("NO"))
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
else if (NightMode.equals("AUTO"))
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
the MainActivity:
public class MainActivity extends AppCompatActivity {
int currentDayNight;
private Button settings;
private RelativeLayout layout;
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
layout = findViewById(R.id.layout);
settings = findViewById(R.id.btn_settings);
currentDayNight = AppCompatDelegate.getDefaultNightMode();
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openSettings();
}
});
}
private void openSettings() {
Intent intent = new Intent(this, Settings.class);
startActivity(intent);
}
}
logcat:
04-16 21:31:59.861 11136-11136/? I/art: Not late-enabling -Xcheck:jni (already on)
04-16 21:32:00.033 11136-11136/com.goldenegg.darkmode W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
04-16 21:32:00.086 11136-11136/com.goldenegg.darkmode I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
04-16 21:32:00.087 11136-11136/com.goldenegg.darkmode I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
04-16 21:32:00.168 11136-11149/com.goldenegg.darkmode I/art: Background partial concurrent mark sweep GC freed 523(79KB) AllocSpace objects, 0(0B) LOS objects, 50% free, 1007KB/2031KB, paused 6.320ms total 27.683ms
04-16 21:32:00.204 11136-11136/com.goldenegg.darkmode D/AndroidRuntime: Shutting down VM
--------- beginning of crash
04-16 21:32:00.205 11136-11136/com.goldenegg.darkmode E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.goldenegg.darkmode, PID: 11136
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.goldenegg.darkmode/com.goldenegg.darkmode.MainActivity}: 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: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.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.goldenegg.darkmode.MainActivity.onCreate(MainActivity.java:34)
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)
Thanks for your Help.
have a great day
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
What is false in my program that gives "App keeps stopping" while opening that activity?
(2 answers)
Closed 5 years ago.
//I'm new to programming and android studio
package com.example.calc;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import static com.example.calc.R.id.editText;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText editTexts = (EditText) findViewById(editText);
double a = 0.0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Buttons to take input and display
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
Button button3 = (Button) findViewById(R.id.button3);
Button button4 = (Button) findViewById(R.id.button4);
Button button5 = (Button) findViewById(R.id.button5);
Button button6 = (Button) findViewById(R.id.button6);
//using to make the buttons react
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
button4.setOnClickListener(this);
button5.setOnClickListener(this);
button6.setOnClickListener(this);
}
#Override
public void onClick (View v){
double res; //Display and taking input from same textfield
if (TextUtils.isEmpty(editTexts.getText().toString())) {
return;
}
res = Double.parseDouble(editTexts.getText().toString());
switch (v.getId()) {
case R.id.button1:
a += res;
editTexts.setText(" ");
break;
case R.id.button2:
a -= res;
editTexts.setText(" ");
break;
case R.id.button3:
a *= res;
editTexts.setText(" ");
break;
case R.id.button4:
a /= res;
editTexts.setText(" ");
break;
case R.id.button5:
editTexts.setText((int) a);
break;
case R.id.button6:
a = 0.0;
editTexts.setText(" ");
break;
}
}
}
Unfortunately, App crashed.
Gradle is building but crashing as soon as opening.
How to resolve this error??
logCat:
06-24 22:36:42.926 4983-4983/? E/libprocessgroup: failed to make and chown
/acct/uid_10058: Read-only file system
06-24 22:36:42.926 4983-4983/? W/Zygote: createProcessGroup failed, kernel
missing CONFIG_CGROUP_CPUACCT?
06-24 22:36:42.930 4983-4983/? I/art: Not late-enabling -Xcheck:jni (already
on)
06-24 22:36:43.400 4983-4983/com.example.calc I/InstantRun: starting instant
run server: is main process
06-24 22:36:43.626 4983-4983/com.example.calc W/art: Verification of boolean
android.support.v7.app.AppCompatDelegateImplV9.initializePanelContent(android.support.v7.app.AppCompatDelegateImplV9$PanelFeatureState) took 139.729ms
06-24 22:36:43.741 4983-4983/com.example.calc W/art: Verification of
android.support.v7.view.ActionMode
android.support.v7.app.AppCompatDelegateImplV9.startSupportActionModeFromWindow(android.support.v7.view.ActionMode$Callback) took 109.701ms
06-24 22:36:43.743 4983-4983/com.example.calc D/AndroidRuntime: Shutting down VM
--------- beginning of crash
06-24 22:36:43.746 4983-4983/com.example.calc E/AndroidRuntime: FATAL
EXCEPTION: main
Process:
com.example.calc, PID: 4983
java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.example.calc/com.example.calc.MainActivity}:
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:2236)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at
android.app.ActivityThread.access$800(ActivityThread.java:151)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at
android.os.Handler.dispatchMessage(Handler.java:102)
at
android.os.Looper.loop(Looper.java:135)
at
android.app.ActivityThread.main(ActivityThread.java:5254)
at
java.lang.reflect.Method.invoke(Native Method)
at
java.lang.reflect.Method.invoke(Method.java:372)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by:
java.lang.NullPointerException: Attempt to invoke virtual method
'android.view.Window$Callback android.view.Window.getCallback()' on a null
object reference
at
android.support.v7.app.AppCompatDelegateImplBase.<init>
(AppCompatDelegateImplBase.java:118)
at
android.support.v7.app.AppCompatDelegateImplV9.<init>
(AppCompatDelegateImplV9.java:152)
at
android.support.v7.app.AppCompatDelegateImplV11.<init>
(AppCompatDelegateImplV11.java:29)
at
android.support.v7.app.AppCompatDelegateImplV14.<init>
(AppCompatDelegateImplV14.java:53)
at
android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:204)
at
android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:184)
at
android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:518
)
at
android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:189
)
at
com.example.calc.MainActivity.<init>(MainActivity.java:15)
at
java.lang.reflect.Constructor.newInstance(Native Method)
at
java.lang.Class.newInstance(Class.java:1606)
at
android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at
android.app.ActivityThread.access$800(ActivityThread.java:151)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at
android.os.Handler.dispatchMessage(Handler.java:102)
at
android.os.Looper.loop(Looper.java:135)
at
android.app.ActivityThread.main(ActivityThread.java:5254)
at
java.lang.reflect.Method.invoke(Native Method)
at
java.lang.reflect.Method.invoke(Method.java:372)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I am trying to create an android app on android studio which scans WIFI signals, and passes all the WIFI signal SSIDs containing "WDT_" to another intent.
When I run the app, it crashes due to a NPE.
I debugged the app, and it says that intent.getStringArrayExtra() in MultipleWifi.java is null.
Am I doing something wrong with passing the string array?
MainActivity.java:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
WifiConfiguration conf = new WifiConfiguration();
int WDTWifiCount = 0;
List<ScanResult> results = wifiManager.getScanResults();
for (ScanResult scanResult : results) {
if (scanResult.SSID.contains("WDT_")) {
SSIDString[0] = (scanResult.SSID);
WDTWifiCount++;
}
}
WDTWifiCount = 2;
SSIDString[0] = "WDT_12345";
SSIDString[1] = "WDT_14445";
if (WDTWifiCount < 1) {
startActivity(new Intent(this, NoWifi.class));
} else if (WDTWifiCount > 1) {
Intent intent = new Intent(this, MultipleWifi.class);
intent.putExtra("SSIDList", SSIDString);
startActivityForResult(intent, 1);
}
conf.SSID = "\"" + networkSSID + "\"";
conf.preSharedKey = "\"" + networkPass + "\"";
WDTWifiCount = 0;
wifiManager.addNetwork(conf);
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for (WifiConfiguration i : list) {
if (i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"") && WDTWifiCount != 0) {
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
break;
}
}
myWebView = new WebView(this);
myWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);
webSettings.setSupportZoom(true);
webSettings.setBuiltInZoomControls(true);
myWebView.setWebChromeClient(new WebChromeClient());
myWebView.loadUrl("http://192.168.1.1/index.html");
}
MultipleWifi.java:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.multiplewifi);
Intent intent = getIntent();
final String[] StringSSID = intent.getStringArrayExtra("SSIDstring");
List<String> SSIDList = new ArrayList<String>(Arrays.asList(StringSSID));
final Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, SSIDList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String SSID = spinner.getSelectedItem().toString();
Intent intent = new Intent();
intent.putExtra("SSID", SSID);
setResult(RESULT_OK, intent);
finish();
}
});
}
Debug:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.wdt, PID: 9031
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.wdt/com.example.wdt.MultipleWifi}: java.lang.NullPointerException: storage == null
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2200)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5105)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException: storage == null
at java.util.Arrays$ArrayList.<init>(Arrays.java:38)
at java.util.Arrays.asList(Arrays.java:155)
at com.example.wdt.MultipleWifi.onCreate(MultipleWifi.java:23)
at android.app.Activity.performCreate(Activity.java:5275)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2164)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5105)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608)
at dalvik.system.NativeStart.main(Native Method)
EDIT: After editing the key in "intent.putExtra" to SSIDString it still returns null.
Debug:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.wdt, PID: 31443
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.wdt/com.example.wdt.MultipleWifi}: java.lang.NullPointerException: storage == null
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2200)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5105)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException: storage == null
at java.util.Arrays$ArrayList.<init>(Arrays.java:38)
at java.util.Arrays.asList(Arrays.java:155)
at com.example.wdt.MultipleWifi.onCreate(MultipleWifi.java:23)
at android.app.Activity.performCreate(Activity.java:5275)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2164)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5105)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608)
at dalvik.system.NativeStart.main(Native Method)
You are using wrong key
Intent intent = new Intent(this, MultipleWifi.class);
intent.putExtra("SSIDList", SSIDString);
there is key that you are passing
startActivityForResult(intent, 1);
//change key you are using wrong key here
final String[] StringSSID = intent.getStringArrayExtra("SSIDList");
First take the user permisison!
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
PERMISSIONS_REQUEST_CODE_ACCESS_COARSE_LOCATION);
//After this point you wait for callback in onRequestPermissionsResult(int, String[], int[]) overriden method
}else{
getScanningResults();
//do something, permission was previously granted; or legacy device
}
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();
}
});
}