Music Plays and Stops with messages on ImageButtons' Clicks - android-mediaplayer

Trying to code a simple programme. Four ImageButtons, any once clicked, a particular music plays with a message display; again any button clicked, the music stopped along with a message display again. The problem is that the first click to start and second click to stop performs perfectly; the problem arises when I press any button, this message displays: “Unfortunately the programme has stopped” or something like that and the program crashes.
package com.example.appliedexperimentz;
import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
private MediaPlayer mp;
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = new MediaPlayer();
iv = (ImageView) findViewById(R.id.spaceForAnimation);
iv.setBackgroundResource(R.drawable.animestore);
}
public void imageButton1(View v) {
if(mp.isPlaying()){
mp.release();
Toast.makeText(MainActivity.this, "Music Stopped!", Toast.LENGTH_LONG).show();
}else{
mp = MediaPlayer.create(this, R.raw.firstmusik);
mp.start();
Toast.makeText(MainActivity.this, "First Music!", Toast.LENGTH_LONG).show();
}
}
public void imageButton2(View v) {
if(mp.isPlaying()){
mp.release();
Toast.makeText(MainActivity.this, "Music Stopped!", Toast.LENGTH_LONG).show();
}else{
mp = MediaPlayer.create(this, R.raw.secondmusik);
mp.start();
Toast.makeText(MainActivity.this, "Second Music!", Toast.LENGTH_LONG).show();
}
}
public void imageButton3(View v) {
if(mp.isPlaying()){
mp.release();
Toast.makeText(MainActivity.this, "Music Stopped!", Toast.LENGTH_LONG).show();
}else{
mp = MediaPlayer.create(this, R.raw.thirdmusik);
mp.start();
Toast.makeText(MainActivity.this, "Third Music!", Toast.LENGTH_LONG).show();
}
}
public void imageButton4(View v) {
if(mp.isPlaying()){
mp.release();
Toast.makeText(MainActivity.this, "Music Stopped!", Toast.LENGTH_LONG).show();
}else{
mp = MediaPlayer.create(this, R.raw.fourthmusik);
mp.start();
Toast.makeText(MainActivity.this, "Fourth Music!", Toast.LENGTH_LONG).show();
}
}
#Override
public void onDestroy() {
mp.release();
}
}
Here go the Logcat errors:
11-14 23:23:31.943: E/AndroidRuntime(659): FATAL EXCEPTION: main
11-14 23:23:31.943: E/AndroidRuntime(659): java.lang.IllegalStateException: Could not execute method of the activity
11-14 23:23:31.943: E/AndroidRuntime(659): at android.view.View$1.onClick(View.java:3044)
11-14 23:23:31.943: E/AndroidRuntime(659): at android.view.View.performClick(View.java:3511)
11-14 23:23:31.943: E/AndroidRuntime(659): at android.view.View$PerformClick.run(View.java:14105)
11-14 23:23:31.943: E/AndroidRuntime(659): at android.os.Handler.handleCallback(Handler.java:605)
11-14 23:23:31.943: E/AndroidRuntime(659): at android.os.Handler.dispatchMessage(Handler.java:92)
11-14 23:23:31.943: E/AndroidRuntime(659): at android.os.Looper.loop(Looper.java:137)
11-14 23:23:31.943: E/AndroidRuntime(659): at android.app.ActivityThread.main(ActivityThread.java:4424)
11-14 23:23:31.943: E/AndroidRuntime(659): at java.lang.reflect.Method.invokeNative(Native Method)
11-14 23:23:31.943: E/AndroidRuntime(659): at java.lang.reflect.Method.invoke(Method.java:511)
11-14 23:23:31.943: E/AndroidRuntime(659): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
11-14 23:23:31.943: E/AndroidRuntime(659): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
11-14 23:23:31.943: E/AndroidRuntime(659): at dalvik.system.NativeStart.main(Native Method)
11-14 23:23:31.943: E/AndroidRuntime(659): Caused by: java.lang.reflect.InvocationTargetException
11-14 23:23:31.943: E/AndroidRuntime(659): at java.lang.reflect.Method.invokeNative(Native Method)
11-14 23:23:31.943: E/AndroidRuntime(659): at java.lang.reflect.Method.invoke(Method.java:511)
11-14 23:23:31.943: E/AndroidRuntime(659): at android.view.View$1.onClick(View.java:3039)
11-14 23:23:31.943: E/AndroidRuntime(659): ... 11 more
11-14 23:23:31.943: E/AndroidRuntime(659): Caused by: java.lang.IllegalStateException
11-14 23:23:31.943: E/AndroidRuntime(659): at android.media.MediaPlayer.isPlaying(Native Method)
11-14 23:23:31.943: E/AndroidRuntime(659): at com.example.appliedexperimentz.MainActivity.imageButton3(MainActivity.java:59)
11-14 23:23:31.943: E/AndroidRuntime(659): ... 14 more

Change your button click function as follows
public void releasePlayer() {
mp.release();
mp = null;
}
public void imageButton1(View v) {
if (mp != null && mp.isPlaying()) {
releasePlayer();
Toast.makeText(MainActivity.this, "Music Stopped!",
Toast.LENGTH_LONG).show();
} else {
mp = MediaPlayer.create(this, R.raw.muzika);
mp.start();
Toast.makeText(MainActivity.this, "First Music!", Toast.LENGTH_LONG)
.show();
}
}
Do the above changes to all the button click events. Hope this helps :)

Related

Don't understand why I'm getting this error. Any suggestions/guidance would be great

package com.example.myapplication
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.myapplication.MainModel
import com.example.myapplication.MovieAdapter
import com.example.myapplication.R
import com.example.myapplication.retrofit.ApiService
import kotlinx.android.synthetic.main.activity_detail.*
import kotlinx.android.synthetic.main.activity_main.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class MainActivity : AppCompatActivity() {
private val TAG: String = "MainActivity"
private lateinit var movieAdapter: MovieAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
supportActionBar!!.title = "Avengers"
setupRecyclerView()
getDataFromApi()
}
private fun getDataFromApi() {
showLoading(true)
ApiService.endpoint.data()
.enqueue(object : Callback<MainModel> {
override fun onFailure(call: Call<MainModel>, t: Throwable) {
printLog(t.toString())
showLoading(false)
}
override fun onResponse(
call: Call<MainModel>,
response: Response<MainModel>
) {
showLoading(false)
if (response.isSuccessful) {
showResult(response.body()!!)
}
}
})
}
private fun printLog(message: String) {
Log.d(TAG, message)
}
private fun showLoading(loading: Boolean) {
when (loading) {
true -> progressBar.visibility = View.VISIBLE
false -> progressBar.visibility = View.GONE
}
}
private fun showResult(results: MainModel) {
for (result in results.result) printLog("title: ${result.artistId}")
movieAdapter.setData(results.result)
}
private fun setupRecyclerView(){
movieAdapter = MovieAdapter(arrayListOf(), object : MovieAdapter.OnAdapterListener {
override fun onClick(result: MainModel.Result) {
recyclerView.apply {
layoutManager = LinearLayoutManager(context)
adapter = movieAdapter
}
}
})
}
}
This is the error:
2022-08-13 22:41:43.360 14628-14628/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 14628
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Iterator java.util.ArrayList.iterator()' on a null object reference
at com.example.myapplication.MainActivity.showResult(MainActivity.kt:64)
at com.example.myapplication.MainActivity.access$showResult(MainActivity.kt:18)
at com.example.myapplication.MainActivity$getDataFromApi$1.onResponse(MainActivity.kt:46)
at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1.lambda$onResponse$0$retrofit2-DefaultCallAdapterFactory$ExecutorCallbackCall$1(DefaultCallAdapterFactory.java:89)
at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1$$ExternalSyntheticLambda1.run(Unknown Source:6)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

Loading an image into a RecyclerView cell

override fun onBindViewHolder(holder: CustomViewHolder, position: Int) {
val itunesStoreItemTitle = itunes.results.get(position)
val imageURL = itunesStoreItemTitle.artworkUrl100
//val inputStream = URL(imageURL).openStream()
//val posterImage = BitmapFactory.decodeStream(inputStream)
holder?.view?.textView_iTunes_title?.text = itunesStoreItemTitle.collectionName
//holder?.view?.imageView_itunes?.setImageBitmap(posterImage)
holder?.view?.textView_iTunes_Description?.text = itunesStoreItemTitle.longDescription
}
from my MainActivity class
fun fetchJSON() {
println("Attempting to fetch JSON")
val url = URL(BASE_URL).addParameters(iTunesMap)
val request = Request.Builder().url(url).build()
val client = OkHttpClient()
client.newCall(request).enqueue(object: Callback {
override fun onResponse(call: Call, response: Response) {
val body = response?.body?.string()
val gson = GsonBuilder().create()
val iTunesFeed = gson.fromJson(body, iTunesFeed::class.java)
runOnUiThread {
recyclerView_main.adapter = MoshiAdapter(iTunesFeed)
}
println(body)
}
override fun onFailure(call: Call, e: IOException) {
println("Failed to fetch data")
}
})
}
I am trying to load images into my RecyclerView cell but it crashes on the first commented line.
CRASH LOG
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.oneorangetree.itunessearch, PID: 17091
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1605)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:115)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:103)
at java.net.InetAddress.getAllByName(InetAddress.java:1152)
at com.android.okhttp.Dns$1.lookup(Dns.java:41)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:178)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:144)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:86)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:176)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:128)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:97)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:289)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:232)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:465)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:411)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:248)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:211)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:30)
at java.net.URL.openStream(URL.java:1072)
at com.oneorangetree.itunessearch.adapters.MoshiAdapter.onBindViewHolder(MoshiAdapter.kt:30)
at com.oneorangetree.itunessearch.adapters.MoshiAdapter.onBindViewHolder(MoshiAdapter.kt:14)
at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7065)
at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7107)
at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6012)
at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6279)
at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:665)
at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3851)
at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4404)
at android.view.View.layout(View.java:22844)
at android.view.ViewGroup.layout(ViewGroup.java:6389)
at androidx.constraintlayout.widget.ConstraintLayout.onLayout(ConstraintLayout.java:1843)
at android.view.View.layout(View.java:22844)
at android.view.ViewGroup.layout(ViewGroup.java:6389)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
at android.view.View.layout(View.java:22844)
at android.view.ViewGroup.layout(ViewGroup.java:6389)
at androidx.appcompat.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:530)
at android.view.View.layout(View.java:22844)
at android.view.ViewGroup.layout(ViewGroup.java:6389)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
E/AndroidRuntime: at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
at android.view.View.layout(View.java:22844)
at android.view.ViewGroup.layout(ViewGroup.java:6389)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1829)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1673)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1582)
at android.view.View.layout(View.java:22844)
at android.view.ViewGroup.layout(ViewGroup.java:6389)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
at com.android.internal.policy.DecorView.onLayout(DecorView.java:784)
at android.view.View.layout(View.java:22844)
at android.view.ViewGroup.layout(ViewGroup.java:6389)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:3470)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2938)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1952)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8171)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:972)
at android.view.Choreographer.doCallbacks(Choreographer.java:796)
at android.view.Choreographer.doFrame(Choreographer.java:731)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:957)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
your issue is very clear, android.os.NetworkOnMainThreadException occurs when you try to access network on your main thread, please use Rx or AsyncTask to handle network request, refer RxAndroid

Kotlin null pointer exception when trying to get context from Registar in Flutter

I'm trying to create a Flutter Plugin that uses a native Android sdk
I'm able to compile the .aar libraries of the sdk and use them in the project but the sdk requires me to get the context of the main activity
here is the error im getting
E/MethodChannel#mychart_plugin(16277): Failed to handle method call
E/MethodChannel#mychart_plugin(16277): kotlin.KotlinNullPointerException
E/MethodChannel#mychart_plugin(16277): at org.ccf.flutter.plugin.mychart_plugin.MychartPlugin.getContext(MychartPlugin.kt:79)
E/MethodChannel#mychart_plugin(16277): at epic.mychart.android.library.api.authentication.WPAPIAuthentication$1.getContext(WPAPIAuthentication.java:564)
E/MethodChannel#mychart_plugin(16277): at epic.mychart.android.library.prelogin.AuthenticationService.libraryLogin(AuthenticationService.java:461)
E/MethodChannel#mychart_plugin(16277): at epic.mychart.android.library.api.authentication.WPAPIAuthentication.login(WPAPIAuthentication.java:411)
E/MethodChannel#mychart_plugin(16277): at org.ccf.flutter.plugin.mychart_plugin.MychartPlugin.onMethodCall(MychartPlugin.kt:42)
E/MethodChannel#mychart_plugin(16277): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:201)
E/MethodChannel#mychart_plugin(16277): at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:88)
E/MethodChannel#mychart_plugin(16277): at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:219)
E/MethodChannel#mychart_plugin(16277): at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#mychart_plugin(16277): at android.os.MessageQueue.next(MessageQueue.java:325)
E/MethodChannel#mychart_plugin(16277): at android.os.Looper.loop(Looper.java:142)
E/MethodChannel#mychart_plugin(16277): at android.app.ActivityThread.main(ActivityThread.java:6541)
E/MethodChannel#mychart_plugin(16277): at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#mychart_plugin(16277): at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
E/MethodChannel#mychart_plugin(16277): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
here is my code for getting the context
class MychartPlugin: MethodCallHandler, WPAPIAuthentication.IWPOnLoginListener {
private var registrar: PluginRegistry.Registrar? = null
private val LOGIN_REQUEST_CODE = 9876
fun MychartPlugin(registrar: PluginRegistry.Registrar) {
this.registrar = registrar
}
companion object {
#JvmStatic
fun registerWith(registrar: Registrar) {
val channel = MethodChannel(registrar.messenger(), "mychart_plugin")
channel.setMethodCallHandler(MychartPlugin())
}
}
override fun onMethodCall(call: MethodCall, result: Result) {
if (call.method == "getPlatformVersion") {
result.success("Android ${android.os.Build.VERSION.RELEASE}")
} else if (call.method == "MyChartSdkLogin") {
WPAPIAuthentication.login(this, "TURKJ123", "TurkJ123", LOGIN_REQUEST_CODE)
result.success("called MyChartSdkLogin")
} else {
result.notImplemented()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
// super.onActivityResult(requestCode, resultCode, data)
if (requestCode == LOGIN_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
// login successful
Log.i("LoginFragment", "OK")
} else {
// login failed
val result = WPAPIAuthentication.getLoginResult(data)
Log.i("LoginFragment", result.toString())
val errorMessage = result.getErrorMessage(getContext())
if (!errorMessage.isEmpty()) {
Toast.makeText(getContext(), errorMessage, Toast.LENGTH_LONG).show()
}
}
}
}
override fun startActivityForResult(p0: Intent, p1: Int) {
// super.startActivityForResult(p0, p1)
}
override fun getSupportFragmentManager(): FragmentManager {
val act = registrar!!.activity() as FragmentActivity
return act.getSupportFragmentManager()
}
override fun getContext(): Context {
val cxt = registrar!!.context()
return cxt
}
}
notice the override getContext() method that im overriding from the sdk, I think this context call to the registar is where my KotlinNullPointerException is coming from
In getContext you have registrar!!. And registrar is a nullable field which you initialize to null and can only set in a method which you never call. Note that fun MychartPlugin isn't a constructor, you'd call it as e.g.
val plugin = MychartPlugin()
plugin.MychartPlugin(registrar)
But it doesn't seem like there is any reason to make registrar nullable or mutable in the first place. You can change to
class MychartPlugin(private val registrar: Registrar): ...
and
fun registerWith(registrar: Registrar) {
val channel = MethodChannel(registrar.messenger(), "mychart_plugin")
channel.setMethodCallHandler(MychartPlugin(registrar))
}

Vert.x Test halts with TimeoutException: The test execution timed out

I'm using Vert.x 3.5.3. I have this (simple) Verticle:
class DialPadVerticle : AbstractVerticle() {
private companion object : KLogging()
override fun start(future: Future<Void>) {
vertx.eventBus().consumer(Address.DIALPAD_COMBINATIONS) { message: Message<Int> ->
val input = message.body()
logger.info { "Received: $input" }
message.reply(JsonObject().put("result", DialPad().combinations(input)))
}
future.complete()
}
override fun stop(future: Future<Void>) {
logger.debug { "Stopping ${this.javaClass.simpleName} (${deploymentID()})...DONE" }
future.complete()
}
}
...and I'm trying to build a unit test skeleton for it using the experimental (yet) vertx-junit5. So far, I have this:
#ExtendWith(VertxExtension::class)
#DisplayName("Dial pad verticle should...")
internal class DialPadVerticleTest {
#BeforeEach
fun prepare(vertx: Vertx, testContext: VertxTestContext) {
vertx.deployVerticle(DialPadVerticle(), testContext.succeeding())
}
#Test
#Throws(Exception::class)
#DisplayName("Consume Message<Int> correctly")
fun `consume message correctly`(vertx: Vertx, testContext: VertxTestContext) {
vertx.eventBus().send<JsonObject>(Address.DIALPAD_COMBINATIONS, 5) {
// Assertions.assertThat(it.succeeded()).isTrue()
testContext.verify {
testContext.completeNow()
}
}
}
}
But every time I try to run that from within IntelliJ, I'm getting:
java.util.concurrent.TimeoutException: The test execution timed out
at io.vertx.junit5.VertxExtension.joinActiveTestContexts(VertxExtension.java:213)
at io.vertx.junit5.VertxExtension.beforeTestExecution(VertxExtension.java:171)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeBeforeTestExecutionCallbacks$4(TestMethodTestDescriptor.java:141)
at org.junit.jupiter.engine.execution.ThrowableCollector.execute(ThrowableCollector.java:40)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeBeforeMethodsOrCallbacksUntilExceptionOccurs(TestMethodTestDescriptor.java:155)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeBeforeTestExecutionCallbacks(TestMethodTestDescriptor.java:140)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:111)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:58)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:113)
at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:121)
at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:121)
at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:121)
at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:121)
at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:55)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:43)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:170)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:154)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:90)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:74)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Is this somehow a bug on the vertx-junit5 library? I've noticed also that, if the Verticles relies on some external config, even though I pass the correct DeploymentOptions().setConfig(JsonObject().put(...)) as second parameter to deployVerticle, it doesn't read those.
I ran your code and noticed that the execution never reached the test method.
You need to also close your context in #BeforeEach methods:
#BeforeEach
fun prepare(vertx: Vertx, testContext: VertxTestContext) {
vertx.deployVerticle(DialPadVerticle(), testContext.succeeding {
testContext.completeNow()
})
}
testContext.succeeding only provides a AsyncResult handler that checks that the result succeeded, but it does not mark the whole test context as having completed. It simplifies checking intermediary steps.
Now the test passes just fine!
Would you have a minimal reproducer project somewhere?

A prompt for user input makes the app crashes

I coded a demo for prompt user input, and it always crashes when i click the Ok button on the prompt dialog, giving me this error log:
08-24 06:24:11.669 3275-3275/com.sano.tamer.prompuserinputdialog W/IInputConnectionWrapper: beginBatchEdit on inactive InputConnection
08-24 06:24:11.669 3275-3275/com.sano.tamer.prompuserinputdialog W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
08-24 06:24:19.019 3275-3275/com.sano.tamer.prompuserinputdialog D/AndroidRuntime: Shutting down VM
08-24 06:24:19.019 3275-3275/com.sano.tamer.prompuserinputdialog W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x5c8d4160)
08-24 06:24:19.039 3275-3275/com.sano.tamer.prompuserinputdialog E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.sano.tamer.prompuserinputdialog, PID: 3275
java.lang.NullPointerException
at com.sano.tamer.prompuserinputdialog.MainActivity$1$2.onClick(MainActivity.java:48)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:157)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5252)
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:794)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:610)
at dalvik.system.NativeStart.main(Native Method)
I am using a physical device running KitKat.
Here are the files:
prompts.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="#+id/tvUserInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tv_message" />
<EditText
android:id="#+id/etUserInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text">
<requestFocus/>
</EditText>
</LinearLayout>
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.sano.tamer.prompuserinputdialog.MainActivity">
<Button
android:id="#+id/btnShowPrompt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_label"/>
<EditText
android:id="#+id/etResult"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity.java:
package com.sano.tamer.prompuserinputdialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button btnShowPrompt;
private EditText etResult;
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnShowPrompt = (Button) findViewById(R.id.btnShowPrompt);
etResult = (EditText) findViewById(R.id.etResult);
btnShowPrompt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// get prompts.xml view
LayoutInflater inflater = LayoutInflater.from(context);
View vUserPrompt = inflater.inflate(R.layout.prompts,null);
AlertDialog.Builder adBuilder = new AlertDialog.Builder(context);
// set prompts.xml to be the layout file of the alertdialog builder
adBuilder.setView(vUserPrompt);
final EditText etUserInput = (EditText) findViewById(R.id.etUserInput);
// setup a dialog window
adBuilder
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// get user input and set it to result
etResult.setText(etUserInput.getText());
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
// create an alert dialog
AlertDialog alertDialog = adBuilder.create();
alertDialog.show();
}
});
}
}