无法实例化活动 ComponentInfo{com.example.dip.tuneai/com.example.dip



使用 Kotlin 构建音乐 android 应用程序。创建了两个 .kt 文件作为主活动和实用程序。但是在Android清单文件中面临以下错误

错误:-

at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2977)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3182)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1916)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6898)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.dip.tuneai.MainActivity" on path: DexPathList[[zip file "/data/app/com.example.dip.tuneai-B8jZb4mao-TDK8fFECTmAQ==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.dip.tuneai-B8jZb4mao-TDK8fFECTmAQ==/lib/arm64, /system/lib64]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
at android.support.v4.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:43)
at android.app.Instrumentation.newActivity(Instrumentation.java:1232)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2965)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3182) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1916) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:6898) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 

安卓清单.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.dip.tuneai">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"
tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@drawable/mp"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

MainActivity.kt

package com.example.dip.songm
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.database.Cursor
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.media.MediaMetadataRetriever
import android.media.MediaPlayer
import android.os.Handler
import android.provider.MediaStore
import android.support.annotation.NonNull
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.TextView
import android.widget.Toast
import com.example.dip.tuneai.R
import com.example.dip.tuneai.Utilities
import java.io.File
import java.io.IOException
import java.util.ArrayList
import java.util.HashMap
open class MainActivity:AppCompatActivity(), MediaPlayer.OnCompletionListener, SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
// ImageButton playBtn, prevBtn, nextBtn;
private lateinit var mdTv1:TextView
private lateinit var mdTv2:TextView
private lateinit var mdTv3:TextView
private lateinit var elapsedTime:TextView
private lateinit var totalTime:TextView
private lateinit var seekBar:SeekBar
private lateinit var songIcon:ImageView
private lateinit var playBtn:ImageButton
private lateinit var nextBtn:ImageButton
private lateinit var prevBtn:ImageButton
private lateinit var mCurrentArtUrl:String
internal lateinit var metaRetriver:MediaMetadataRetriever
internal lateinit var art:ByteArray
private lateinit var mp:MediaPlayer
private lateinit var utils: Utilities
private var startTime = 0.0
private var finalTime = 0.0
private var forwardTime = 500
private var backwardTime = 500
private var currentSongIndex = 0
private var mHandler = Handler()
private var songsList = ArrayList<HashMap<String, String>>()
private var mUpdateTimeTask = object:Runnable {
public override fun run() {
var totalDuration = mp.getDuration()
var currentDuration = mp.getCurrentPosition()
// Displaying Total Duration time
totalTime.setText("" + utils.milliSecondsToTimer(totalDuration.toLong()))
// Displaying time completed playing
elapsedTime.setText("" + utils.milliSecondsToTimer(currentDuration.toLong()))
// Updating progress bar
var progress = (utils.getProgressPercentage(currentDuration.toLong(), totalDuration.toLong())) as Int
//Log.d("Progress", ""+progress);
seekBar.setProgress(progress)
// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100)
}
}
val playList:ArrayList<HashMap<String, String>>
get() {
val mCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
arrayOf<String>(MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM), null, null,
"LOWER(" + MediaStore.Audio.Media.TITLE + ") ASC")
val count = mCursor.getCount()
if (mCursor.moveToFirst())
{
do
{
val song = HashMap<String, String>()
song.put("songTitle", mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME)))
song.put("songArtist", mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)))
song.put("songAlbum", mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM)))
song.put("songPath", mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)))
songsList.add(song)
}
while (mCursor.moveToNext())
}
mCursor.close()
return songsList
}
protected override fun onCreate(savedInstanceState:Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
metaRetriver = MediaMetadataRetriever()
intiViews()
seekBar.setOnSeekBarChangeListener(this) // Important
mp.setOnCompletionListener(this) // Important
songsList = playList
playSong(0)
nextBtn.setOnLongClickListener(object:View.OnLongClickListener {
override fun onLongClick(view:View):Boolean {
var temp = startTime.toInt()
if ((temp + forwardTime) <= finalTime)
{
startTime = startTime + forwardTime
mp.seekTo(startTime.toInt())
Toast.makeText(getApplicationContext(), "You have Jumped forward 5 seconds", Toast.LENGTH_SHORT).show()
}
else
{
Toast.makeText(getApplicationContext(), "Cannot jump forward 5 seconds", Toast.LENGTH_SHORT).show()
}
return false
}
})
prevBtn.setOnLongClickListener(object: View.OnLongClickListener {
override fun onLongClick(view:View):Boolean {
var temp = startTime.toInt()
if ((temp - backwardTime) > 0)
{
startTime = startTime - backwardTime
mp.seekTo(startTime.toInt())
Toast.makeText(getApplicationContext(), "You have Jumped backward 5 seconds", Toast.LENGTH_SHORT).show()
}
else
{
Toast.makeText(getApplicationContext(), "Cannot jump backward 5 seconds", Toast.LENGTH_SHORT).show()
}
return false
}
})
}
private fun intiViews() {
// playBtn = (ImageButton) findViewById(R.id.btnPlay);
// prevBtn = (ImageButton) findViewById(R.id.btnPrevious);
// nextBtn = (ImageButton) findViewById(R.id.btnNext);
seekBar = findViewById(R.id.seekBar) as SeekBar
seekBar.setClickable(false)
mdTv1 = findViewById(R.id.metadata_1) as TextView
mdTv2 = findViewById(R.id.metadata_2) as TextView
mdTv3 = findViewById(R.id.metadata_3) as TextView
elapsedTime = findViewById(R.id.elapsed_time) as TextView
totalTime = findViewById(R.id.total_time) as TextView
playBtn = findViewById(R.id.btnPlay) as ImageButton
nextBtn = findViewById(R.id.btnNext) as ImageButton
prevBtn = findViewById(R.id.btnPrevious) as ImageButton
mp = MediaPlayer()
utils = Utilities()
}
fun playPause(view:View) {
if (mp.isPlaying())
{
if (mp != null)
{
mp.pause()
// Changing button image to play button
playBtn.setImageResource(R.drawable.play_button)
}
}
else
{
// Resume song
if (mp != null)
{
mp.start()
// Changing button image to pause button
playBtn.setImageResource(R.drawable.pause)
}
}
}
fun playPrevious(view:View) {
if (currentSongIndex > 0)
{
playSong(currentSongIndex - 1)
currentSongIndex = currentSongIndex - 1
}
else
{
// play last song
playSong(songsList.size - 1)
currentSongIndex = songsList.size - 1
}
}
fun playNext(view:View) {
if (currentSongIndex < (songsList.size - 1))
{
playSong(currentSongIndex + 1)
currentSongIndex = currentSongIndex + 1
}
else
{
// play first song
playSong(0)
currentSongIndex = 0
}
}
override fun onCompletion(mediaPlayer:MediaPlayer) {
if (currentSongIndex < (songsList.size - 1))
{
playSong(currentSongIndex + 1)
currentSongIndex = currentSongIndex + 1
}
else
{
// play first song
playSong(0)
currentSongIndex = 0
}
}
override fun onStartTrackingTouch(seekBar:SeekBar) {
mHandler.removeCallbacks(mUpdateTimeTask)
}
override fun onStopTrackingTouch(seekBar:SeekBar) {
mHandler.removeCallbacks(mUpdateTimeTask)
var totalDuration = mp.getDuration()
var currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration)
// forward or backward to certain seconds
mp.seekTo(currentPosition)
// update timer progress again
updateProgressBar()
}
protected override fun onActivityResult(requestCode:Int,
resultCode:Int, data:Intent?){
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == 100)
{
if (data != null) {
currentSongIndex = data.getExtras().getInt("songIndex")
}
// play selected song
playSong(currentSongIndex)
}
}
protected override fun onDestroy() {
super.onDestroy()
mp.release()
}
fun playSong(songIndex:Int) {
// Play song
try
{
mp.reset()
mp.setDataSource(songsList.get(songIndex).get("songPath"))
mp.prepare()
mp.start()
// Displaying Song title
var songTitle = songsList.get(songIndex).get("songTitle")
var songArtist = songsList.get(songIndex).get("songArtist")
var songAlbum = songsList.get(songIndex).get("songAlbum")
mdTv1.setText(songTitle)
mdTv2.setText(songArtist)
mdTv3.setText(songAlbum)
/* art = metaRetriver.getEmbeddedPicture();
Bitmap songImage = BitmapFactory .decodeByteArray(art, 0, art.length);
songIcon.setImageBitmap(songImage);
*/
// Changing Button Image to pause image
playBtn.setImageResource(R.drawable.pause)
// set Progress bar values
seekBar.setProgress(0)
seekBar.setMax(100)
// Updating progress bar
updateProgressBar()
}
catch (e:IllegalArgumentException) {
e.printStackTrace()
}
catch (e:IllegalStateException) {
e.printStackTrace()
}
catch (e:IOException) {
e.printStackTrace()
}
/* catch (Exception e) {
songIcon.setBackgroundColor(Color.GRAY);
}*/
}
fun updateProgressBar() {
mHandler.postDelayed(mUpdateTimeTask, 100)
}
}

Utilities.kt

package com.example.dip.tuneai
class Utilities {
fun milliSecondsToTimer(milliseconds: Long): String {
var finalTimerString = ""
var secondsString = ""
// Convert total duration into time
val hours = (milliseconds / (1000 * 60 * 60)).toInt()
val minutes = (milliseconds % (1000 * 60 * 60)).toInt() / (1000 * 60)
val seconds = (milliseconds % (1000 * 60 * 60) % (1000 * 60) / 1000).toInt()
// Add hours if there
if (hours > 0) {
finalTimerString = hours.toString() + ":"
}
// Prepending 0 to seconds if it is one digit
if (seconds < 10) {
secondsString = "0$seconds"
} else {
secondsString = "" + seconds
}
finalTimerString = "$finalTimerString$minutes:$secondsString"
// return timer string
return finalTimerString
}
/**
* Function to get Progress percentage
* @param currentDuration
* @param totalDuration
*/
fun getProgressPercentage(currentDuration: Long, totalDuration: Long): Int {
var percentage: Double? = 0.toDouble()
val currentSeconds = (currentDuration / 1000).toInt().toLong()
val totalSeconds = (totalDuration / 1000).toInt().toLong()
// calculating percentage
percentage = currentSeconds.toDouble() / totalSeconds * 100
// return percentage
return percentage.toInt()
}
/**
* Function to change progress to timer
* @param progress -
* @param totalDuration
* returns current duration in milliseconds
*/
fun progressToTimer(progress: Int, totalDuration: Int): Int {
var totalDuration = totalDuration
var currentDuration = 0
totalDuration = totalDuration / 1000
currentDuration = (progress.toDouble() / 100 * totalDuration).toInt()
// return current duration in milliseconds
return currentDuration * 1000
}
}

当我在AndroidManifest中创建MainActivity.kt时.xml它表明MainActivity类不存在。克服错误的解决方案是什么?

在清单中,我看到package="com.example.dip.tuneai"

在您的 Kotlin 文件中:package com.example.dip.songm'

您必须修复包名称

相关内容

最新更新