-1

I'm making a batch renamer and when i click on rename button after selecting files it should call a background service to rename it while showing notification but the app crashes upon click. Im testing on android 5.0 i tried putting a toast message at the start but it crashed before that as well im thinking it crashes before executing buttons click event

Stack Trace from crash

04-09 20:19:00.077 834-1027/? E/ConnectivityService: RemoteException caught trying to send a callback msg for NetworkRequest [ id=143, legacyType=-1, [ Capabilities: INTERNET&NOT_RESTRICTED&TRUSTED] ]
04-09 20:25:47.388 834-1024/? E/WifiStateMachine: setSuspendOptimizationsNative: 4 false -want true stack:setSuspendOptimizationsNative - access$16400 - processMessage - processMsg
04-09 20:25:53.743 18486-18506/com.pride.msgshareapp E/[DRVB][EXT][UTIL]: disp_only_chk: DRVB CHECK0 PROCESS DONE ! STATUS (0x2000)
04-09 20:25:53.748 18486-18506/com.pride.msgshareapp E/GED: Failed to get GED Log Buf, err(0)
04-09 20:26:59.738 18486-18486/com.pride.msgshareapp E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.pride.msgshareapp, PID: 18486
    java.lang.IndexOutOfBoundsException: Invalid index 2, size is 2
        at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:260)
        at java.util.ArrayList.get(ArrayList.java:313)
        at com.pride.msgshareapp.RenameOption$onCreate$5.onClick(RenameOption.kt:80)
        at android.view.View.performClick(View.java:4848)
        at android.view.View$PerformClick.run(View.java:20262)
        at android.os.Handler.handleCallback(Handler.java:815)
        at android.os.Handler.dispatchMessage(Handler.java:104)
        at android.os.Looper.loop(Looper.java:194)
        at android.app.ActivityThread.main(ActivityThread.java:5643)
        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:960)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

renamebtn.setOnClickListener {
        val paramtxt = paratxt.text.toString().trim()
        var reptxt = paramtxt
        for(i in 0..cc)
        {
            reptxt = reptxt.replace("%title",seltitle[i],true)
            reptxt = reptxt.replace("%album",selalbum[i],true)
            reptxt = reptxt.replace("%artist",selartist[i],true)
            resultt.add(reptxt)
        }
        val inte = Intent(this,RenameService::class.java)
        inte.putExtra("path",selpath.toTypedArray())
        inte.putExtra("newname",resultt.toTypedArray())
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        {
            startForegroundService(inte)
        }
        else{
            startService(inte)
        }
    }

Service Code

class RenameService : Service() {

override fun onBind(intent: Intent): IBinder? {
    return null
}

override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
    val bundle: Bundle?=intent.extras
    val pathss = bundle!!.getStringArray("path")
    val namess = bundle!!.getStringArray("newname")
    val resultt:MutableList<String> = mutableListOf()
    val notifID = 595
    val maxProgress = pathss.size
    var currentProgress = 0

    val inten = Intent(this, HobbiesActivity::class.java)
    inten.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK

    val pendingIntent : PendingIntent = PendingIntent.getActivity(this,0,inten,0)

    val builderr = NotificationCompat.Builder(this, "Renamer")
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentTitle("Renaming " + pathss.size.toString() + " files")
            .setContentText("Renaming....")
            .setStyle(NotificationCompat.BigTextStyle()
                    .bigText("Renaming..."))
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setVisibility(1)

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val name = "ChannelMain"
        val descText = "Renaming Progress"
        val imp = NotificationManager.IMPORTANCE_HIGH
        val channel = NotificationChannel("Renamer", name, imp).apply {
            description = descText
            enableVibration(true)
        }
        val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(channel)
    }
    Toast.makeText(this,"Renaming",Toast.LENGTH_SHORT).show()
    startForeground(notifID,builderr.build())

    with(NotificationManagerCompat.from(this)){
        builderr.setProgress(maxProgress, currentProgress, false)
        notify(notifID, builderr.build())

        for(i in 0..pathss.size)
        {
            if(renameTarget(pathss[i],namess[i])!=0)
            {
                resultt.add("Failed")
            }
            else
            {
                resultt.add("Success")
            }
            currentProgress = i
            builderr.setContentText("Renaming " + i.toString() + " of " + pathss.size.toString())
            builderr.setProgress(maxProgress,currentProgress,false)
            notify(notifID,builderr.build())
        }

        builderr.setContentText("Rename Complete")
                .setProgress(0,0,false)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true)
        notify(notifID,builderr.build())
    }
    return Service.START_REDELIVER_INTENT
}

override fun onDestroy() {
    super.onDestroy()
    Toast.makeText(this,"Renaming completed",Toast.LENGTH_SHORT).show()
    stopForeground(true)
}

override fun onTaskRemoved(rootIntent: Intent?) {
    super.onTaskRemoved(rootIntent)
    stopSelf()
}
}

fun renameTarget(filePath:String, newName:String):Int{
val src= File(filePath)
var ext=""
val dest: File
if(src.isFile)
{
    ext=filePath.substring(filePath.lastIndexOf("."),filePath.length)
}
if(newName.isEmpty())
{
    return -1
}
val temp=filePath.substring(0,filePath.lastIndexOf("/"))
dest= File("$temp/$newName$ext")
return if(src.renameTo(dest)) {
    0
} else {
    1
}
}
Zoe
  • 27,060
  • 21
  • 118
  • 148
Grim
  • 41
  • 6
  • 2
    Please [edit] your question to provide the complete [stack trace from the crash](https://stackoverflow.com/a/23353174). – Mike M. Apr 09 '19 at 14:36
  • Possible duplicate of [Unfortunately MyApp has stopped. How can I solve this?](https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this) – Zoe Apr 09 '19 at 14:52
  • I would go for some missing permission. Your app is probably throwing a SecurityException ? – MajorShepard Apr 09 '19 at 14:55
  • 1
    Duplicate of https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it – Zoe Apr 09 '19 at 15:04

2 Answers2

0

The issue is most likely caused by this line: for(i in 0..cc). The reason is that the operator .. creates an closed range, where cc is included, so if cc is equal to the size of your list/array then you'll get the IndexOutOfBoundsException. To fix that you can simply change your line to for (i in 0 until cc), since the until function creates a range that doesn't include the end element.

user2340612
  • 10,053
  • 4
  • 41
  • 66
-1

Without the stack trace requested by Mike in the comments the only thing I can think about is that u forgot to link your button with the ID of the xml button

findViewById(R.id.button);

something like this

Gerard E
  • 27
  • 9
  • Don't know why downvoting, I can't post a comment so I'm posting what I think can help in this answer, of course once I can see the error output I will edit this answer – Gerard E Apr 09 '19 at 14:57
  • the problem is with the index of the arrayList java.lang.IndexOutOfBoundsException: Invalid index 2, size is 2 you are accessing outside your array in some point of your code – Gerard E Apr 09 '19 at 15:17