Playing audio WITHOUT raw folder in Android (JAVA) - java

Trying to add a song to the MediaPlayer without R.raw.audiofilename. Making a music player and I obviously don't have the audio file being packaged with the app.
More detail: I am creating buttons to add to a scroll view, and on click, play the song.
The on click method seems to be where the error happening.
private void addSongs() {
Toast.makeText(this, "Searching", Toast.LENGTH_SHORT).show();
ContentResolver cr = this.getContentResolver();
Cursor cursor = cr.query(BASE_URI, BASE_PROJECTION, BASE_SELECTION, null, BASE_SORTORDER);
int count;
if (cursor != null) {
count = cursor.getCount();
if (count > 0) while (cursor.moveToNext()) createButton(cursor);
}
}
private void createButton(final Cursor cursor) {
final String TITLE = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
final String PATH = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
Button button = new Button(this);
button.setText(TITLE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MediaPlayer mediaPlayer = MediaPlayer.create(
MainActivity.this, Uri.parse(Environment.getExternalStorageDirectory().getPath()
+ "Music/" + TITLE + ".m4a")
);
mediaPlayer.start();
}
});
songList.addView(button);
}
This is pretty much all the code so far in the program, I am worried that my logic is the error here.
Exception thrown:
D/MediaPlayer: create failed:
java.io.IOException: setDataSource failed.
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1168)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1141)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1059)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1001)
at android.media.MediaPlayer.create(MediaPlayer.java:908)
at android.media.MediaPlayer.create(MediaPlayer.java:885)
at android.media.MediaPlayer.create(MediaPlayer.java:864)
at theredspy15.fosyplayer.MainActivity$1.onClick(MainActivity.java:80)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
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)
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: theredspy15.fosyplayer, PID: 24561
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at theredspy15.fosyplayer.MainActivity$1.onClick(MainActivity.java:84)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
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)
EDIT: I am using the .m4a as the audio files I am using to test the app in the emulator are .m4a. Will change that later

Related

Why can't I call this method from a class?

I've created a class that contains a method to play a sound.
import android.content.Context;
import android.media.MediaPlayer;
public class Sounds {
private Context context;
public void Sound(Context context) {
this.context = context;
}
void hydrogen() {
final MediaPlayer mp = MediaPlayer.create(context, R.raw.hydrogen);
mp.start();
}
}
I want to play the sound upon a button click using this code:
public void onClick(View view){
Sounds s = new Sounds();
s.hydrogen();
}
When I click the button, the program crashes.
The sound plays fine when I use code in MainActivity rather than calling a method from a separate class.
I suspect the issue has something to do with retrieving the sound file from the res folder, but I don't know how to fix it.
I created a separate class with a method that just defines variables and I was able to call that method without any problems.
Logcat makes reference to this line with purple highlighting on the word "create"
final MediaPlayer mp = MediaPlayer.create(context, R.raw.hydrogen);
Does anyone know what the problem is?
This is the stacktrace
E FATAL EXCEPTION: main
Process: com.xxmassdeveloper.soundtest, PID: 14132
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:473)
at android.view.View.performClick(View.java:7870)
at android.widget.TextView.performClick(TextView.java:14970)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1219)
at android.view.View.performClickInternal(View.java:7839)
at android.view.View.access$3600(View.java:886)
at android.view.View$PerformClick.run(View.java:29363)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
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.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:468)
at android.view.View.performClick(View.java:7870) 
at android.widget.TextView.performClick(TextView.java:14970) 
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1219) 
at android.view.View.performClickInternal(View.java:7839) 
at android.view.View.access$3600(View.java:886) 
at android.view.View$PerformClick.run(View.java:29363) 
at android.os.Handler.handleCallback(Handler.java:883) 
at android.os.Handler.dispatchMessage(Handler.java:100) 
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.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.media.MediaPlayer.create(MediaPlayer.java:1002)
at android.media.MediaPlayer.create(MediaPlayer.java:981)
at com.xxmassdeveloper.soundtest.Sounds.hydrogen(Sounds.java:15)
at com.xxmassdeveloper.soundtest.MainActivity.onClick(MainActivity.java:48)
at java.lang.reflect.Method.invoke(Native Method) 
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:468) 
at android.view.View.performClick(View.java:7870) 
at android.widget.TextView.performClick(TextView.java:14970) 
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1219) 
at android.view.View.performClickInternal(View.java:7839) 
at android.view.View.access$3600(View.java:886) 
at android.view.View$PerformClick.run(View.java:29363) 
at android.os.Handler.handleCallback(Handler.java:883) 
at android.os.Handler.dispatchMessage(Handler.java:100) 
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) 
2023-01-27 10:29:00.836 14132-14132 Process com.xxmassdeveloper.soundtest I Sending signal. PID: 14132 SIG: 9
2023-01-27 10:29:00.912 3675-4184 WindowManager pid-3675 E win=Window{57fa696 u0 com.xxmassdeveloper.soundtest/com.xxmassdeveloper.soundtest.MainActivity EXITING} destroySurfaces: appStopped=false win.mWindowRemovalAllowed=true win.mRemoveOnExit=true win.mViewVisibility=0 caller=com.android.server.wm.AppWindowToken.destroySurfaces:1200 com.android.server.wm.AppWindowToken.destroySurfaces:1181 com.android.server.wm.WindowState.onExitAnimationDone:5030 com.android.server.wm.-$$Lambda$01bPtngJg5AqEoOWfW3rWfV7MH4.accept:2 java.util.ArrayList.forEach:1262 com.android.server.wm.AppWindowToken.onAnimationFinished:3549 com.android.server.wm.AppWindowToken.commitVisibility:860
Thanks
The constructor of your Sounds class is not correct.
public class Sounds {
private Context context;
// You should have a constructor here, not a function
// So, void should be removed. And you should have name same as the class name
public Sounds(Context context) {
this.context = context;
}
// Better to make is public so that you can call it in other packages
public void hydrogen() {
final MediaPlayer mp = MediaPlayer.create(context, R.raw.hydrogen);
mp.start();
}
}
And therefore when you try to call this Sounds class, you should do something like this:
public void onClick(View view) {
// As you are inside an Activity, you can pass this
Sounds s = new Sounds(this);
s.hydrogen();
}
You don't need to pass the context as part of the Sounds constructor. Instead I would pass the context to hydrogen. You should also make the hydrogen method public so it can be accessed from elsewhere:
public void hydrogen(Context context)
{
final MediaPlayer mp = MediaPlayer.create(context, R.raw.hydrogen);
mp.start();
}

I am getting null pointer exception in android

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);

App crashes when file is shared in Fragment

I have a Fragment which is attached to MainActivity. It displays an image. User has to share the image but the app crashes when clicking the share button.
This is the Fragment code:
Context mcontext = getActivity();
case R.id.item_share: {
final Uri uri = FileProvider.getUriForFile(mcontext, "com.whats.insta", file);
final Intent intent = ShareCompat.IntentBuilder
.from((Activity)mcontext)
.setType("image/jpg")
.setStream(uri)
.createChooserIntent()
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET)
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
mcontext.startActivity(intent);*/
break;
}
Crash log
09-05 10:41:05.410 26011-26011/com.whats.insta E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.whats.insta, PID: 26011
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.app.Activity.getPackageName()' on a null object reference
at android.support.v4.app.ShareCompat$IntentBuilder.<init>(ShareCompat.java:216)
at android.support.v4.app.ShareCompat$IntentBuilder.from(ShareCompat.java:210)
at com.whats.insta.ui.imageslider.imagedetails.ImageDetailsFragment.onOptionsItemSelected(ImageDetailsFragment.java:267)
at android.support.v4.app.Fragment.performOptionsItemSelected(Fragment.java:2476)
at android.support.v4.app.FragmentManagerImpl.dispatchOptionsItemSelected(FragmentManager.java:3343)
at android.support.v4.app.FragmentController.dispatchOptionsItemSelected(FragmentController.java:347)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:413)
at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)
at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
at android.support.v7.app.ToolbarActionBar$2.onMenuItemClick(ToolbarActionBar.java:63)
at android.support.v7.widget.Toolbar$1.onMenuItemClick(Toolbar.java:203)
at android.support.v7.widget.ActionMenuView$MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:780)
at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:171)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:973)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:963)
at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:624)
at android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:150)
at android.view.View.performClick(View.java:6261)
at android.widget.TextView.performClick(TextView.java:11185)
at android.view.View$PerformClick.run(View.java:23752)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
You must check if the implicit intent resolves to at least one activity otherwise application crashes.
// Verify the intent will resolve to at least one activity
if (mContext != null && intent.resolveActivity(getPackageManager()) != null) {
startActivity(chooser);
}

SimpleCursorAdapter issue - "java.lang.IllegalStateException: trying to requery an already closed cursor"

I've read similar topics and didn't find any answer that I could apply to my situation.
Long story short, I have an AutoCompleteTextView with SimpleCursorAdapter. It queries my SQLiteDatabase for the matching drop down list of options.
Everything works fine, but when I press the "Home" button (onPause() -> onStop()) if I've shortly before that used the AutoCompleteTextView, upon re-entering the app (onRestart() -> onStart() -> onResume()), I get this error:
03-05 19:17:42.186 13847-13847/com.ardovic.weatherappprototype
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ardovic.weatherappprototype, PID: 13847
java.lang.RuntimeException: Unable to resume activity
{com.ardovic.weatherappprototype/com.ardovic.weatherappprototype.MainActivity}:
java.lang.IllegalStateException: trying to requery an already closed
cursor android.database.sqlite.SQLiteCursor#2cae0855
at
android.app.ActivityThread.performResumeActivity(ActivityThread.java:4053)
at
android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4084)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1749)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6918)
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:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.IllegalStateException: trying to requery an
already closed cursor android.database.sqlite.SQLiteCursor#2cae0855
at android.app.Activity.performRestart(Activity.java:6660)
at android.app.Activity.performResume(Activity.java:6688)
at
android.app.ActivityThread.performResumeActivity(ActivityThread.java:4042)
at
android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4084) 
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1749) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:6918) 
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:1404) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
It doesn't point to any of my code lines, so I suppose that it's the SimpleCursorAdapter problem. Here is the code for it (I've commented out unrelated parts, but they are still there):
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.dropdown_text,
null,
new String[]{CITY_COUNTRY_NAME},
new int[]{R.id.text});
actvCityCountryName.setAdapter(adapter);
actvCityCountryName.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
cursor = (Cursor) listView.getItemAtPosition(position);
// cityCountryName = cursor.getString(cursor.getColumnIndexOrThrow(CITY_COUNTRY_NAME));
// actvCityCountryName.setText(cityCountryName);
// JSONWeatherTask task = new JSONWeatherTask();
// task.execute(new String[]{cityCountryName});
}
});
adapter.setCursorToStringConverter(new SimpleCursorAdapter.CursorToStringConverter() {
#Override
public CharSequence convertToString(Cursor cursor) {
final int columnIndex = cursor.getColumnIndexOrThrow(CITY_COUNTRY_NAME);
final String cityCountryName = cursor.getString(columnIndex);
return (cityCountryName);
}
});
adapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
// cursor = getMatchingStates((constraint != null ? constraint.toString() : null));
return cursor;
}
});
I've already tried various suggestions, like calling stopManagingCursor(cursor), cursor.requery(), actvCityCountryName.dismissDropDown(), actvCityCountryName.clearListSelection(), or actvCityCountryName.clearFocus() in various places and lifecycle methods.
Looking forward for any suggestions that would solve this problem, thanx in advance!

New Activity crashes on startup [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
When clicking a Button to switch from the main Activity to my "ColoursGame" Activity the app crashes.
I'm still a beginner so not an expert at debugging.
The main activity code
Button colorsGame = (Button) findViewById(R.id.colours);
colorsGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, ColoursGame.class));
}
});
Manifest new activity
<activity android:name=".ColoursGame"
android:label="ColourGame"
android:theme="#style/AppTheme.NoActionBar"></activity>
ColoursGame Activity OnCreate code
public class ColoursGame extends Activity {
int livesCount = 3;
String x;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_colours_game);
Button start = (Button) findViewById(R.id.startColors);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
vSwitch.showNext();
x = String.valueOf(livesCount);
lives.setText(x);
text();
textColor();
backgroundColor();
start();
}
});
}
The Error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.aynaar.numbersgameforkids, PID: 3278
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.aynaar.numbersgameforkids/com.aynaar.numbersgameforkids.ColoursGame}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.Activity.findViewById(Activity.java:2323)
at com.aynaar.numbersgameforkids.ColoursGame.<init>(ColoursGame.java:42)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2538)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
at com.aynaar.numbersgameforkids.ColoursGame.<init>(ColoursGame.java:42)
Don't call findViewById outside of onCreate, there's no Window to call findViewById at that point.
If you still get a NullPointer, then you must have #+id/startColors in activity_colours_game.xml
Answer explanation here
Button start = (Button) findViewById(R.id.startColors);
According to the error you are trying to reach a button that doesnt exist in your activity layout file (whatever it is). Check the id of your button and make sure it is placed on the layout page that related with your "ColoursGame" Activity.

Categories