ArrayIndexOutOfBoundsException: length=2; index=2 (Kotlin)
Writing a small program on Android using Kotlin and sometimes getting ArrayIndexOutOfBoundsException: length=2; index=2
java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
at java.util.Arrays$ArrayList.get(Arrays.java:3769)
at com.example.MainActivity.Q(:271)
at com.example.MainActivity.K(:44)
at com.example.MainActivity$e.b(:173)
at com.example.MainActivity$e.a(:44)
at androidx.lifecycle.LiveData.b(:131)
at androidx.lifecycle.LiveData.c(:149)
at androidx.lifecycle.LiveData.i(:307)
at b.o.o.i(:50)
at c.a.b$d.f(:185)
at d.e.a.a.a0$c$a.run(:187)
at android.os.Handler.handleCallback(Handler.java:794)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:6662)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
I can't reproduce the issue, but a team member experienced this bug and shared with me to resolve, so may I know the exact line number causes this exception
Line number: 173
viewModel.peers.observe(this, {
if (it != null) {
handlePeers(it) // 173
}
})
Line number: 271
for (i in peers.indices) if (peers[i] != curPeers.getOrNull(i)) when (val peer = peers[i]) {
is LocalPeer -> {
peer.getVideoTracks()["camera"]?.addRenderer(viewRenderers[i]) // 271
peerViews[i].setMirror(true)
}
is RemotePeer -> {
peer.getVideoTracks()["camera"]?.addRenderer(viewRenderers[i])
peerViews[i].setMirror(false)
}
else -> {
}
}
Line number: 307
for (i in peerViews.indices) {
if (i < peerViews.size) { // peers
peerViews[i].visibility = VISIBLE
} else {
peerViews[i].visibility = GONE
}
} // 307
Line number: 149
if (it != null) {
binding.mainView.apply {
init(null)
setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FIT)
setEnableHardwareScaler(false)
}
try {
initSubView(it, binding.subView1)
initSubView(it, binding.subView2)
} catch (e: Exception) {
}
// 149
}
See also questions close to this topic
-
How to remove semicolon from ${} placeholder?
Using Spring Boot I'm trying to set @PropertySource dynamically like this:
@PropertySource(value="classpath:application-${spring.profiles.active}.properties")
which gives an error.Error:
class path resource [application-test;.properties] cannot be opened because it does not exist
${spring.profiles.active}
works fine but it adds semicolon at the end which makes it unusable. Is there any workaround for this? -
How to create an interceptor that deletes old record (LIFO) on insert after reaching predefined record limit?
I would like to save only X records for each uid.
After reaching the limit of X records, I want hibernate to delete the "last in" record before/after insert the new one.
Table example: Messages
uid | id | message YY 1 "1" YY 2 "2"
If I set limit of 2 messages for the same UID then when message "3" will arrive message "1" will be deleted and the table remains with 2 messages for same UID.
-
Lottie animation return this Error: Lottie doesn't support 3D layers
Every time I run my app, this error is given: Error: Lottie doesn't support 3D layers. In the same app there are more LottieAnimationView and no error is given, only this one return it. LottieAnimationView declare like this:
LottieAnimationView bookAnimation = findViewById(R.id.backToSchoolAnimation); bookAnimation.setVisibility(View.VISIBLE);
layout declare like this:
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <com.airbnb.lottie.LottieAnimationView android:id="@+id/backToSchoolAnimation" android:layout_width="match_parent" android:layout_height="450dp" app:lottie_autoPlay="true" android:visibility="gone" app:lottie_rawRes="@raw/back_to_school" /> </LinearLayout>
It would be of great help is someone could point out the mistake in my code. Thanks! Cheers!
-
onQueryTextSubmit ..no result appear
public boolean onQueryTextChange(String newText) {
db.open(); ArrayList<Car> c=db.Search(newText); db.close(); adapter.setCars(c); adapter.notifyDataSetChanged(); return false; }
public boolean onQueryTextChange(String newText) {
db.open(); ArrayList<Car> c=db.Search(newText); db.close(); adapter.setCars(c); adapter.notifyDataSetChanged(); return false; }
public ArrayList Search(String modelsearch){
ArrayList<Car> cars=new ArrayList<>(); Cursor cursor = dataBase.rawQuery("SELECT * FROM " + MyDataBase.Tabel_name+" WHERE " + MyDataBase.CarModel+"=?",new String[]{modelsearch}); if(cursor!=null && cursor.moveToFirst()){ do { int id=cursor.getInt(cursor.getColumnIndex(MyDataBase.CarId)); String model=cursor.getString(cursor.getColumnIndex(MyDataBase.CarModel)); String color=cursor.getString(cursor.getColumnIndex(MyDataBase.Carcolor)); double DPL=cursor.getDouble(cursor.getColumnIndex(MyDataBase.CarDPL)); String desc=cursor.getString(cursor.getColumnIndex(MyDataBase.CarDiscription)); String img=cursor.getString(cursor.getColumnIndex(MyDataBase.CarImage)); Car c=new Car(id,model,color,DPL,img,desc); cars.add(c); }while (cursor.moveToNext()); cursor.close(); } return cars; }
-
incomplete data retrieved from web service
I have an android application which retrieves data in JSON format from the REST web service of my site, since I changed the web host, the data that I retrieve is not complete however when I invoke the web-service via the browser i can see the complete JSON file.
I send a GET request to the web service, I get the InputStream in a BufferedReader from an HttpURLConnection, and I put the response in a String. I searched a lot but no solution could work, I hope to find some help here !!
String response = null; BufferedReader bufferedReader = null; try { URL url = new URL(Config.URL_API_ALL); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(10000); con.setReadTimeout(10000); con.setRequestMethod("GET"); bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream())); response = bufferedReader.readLine(); ...
-
How to root Huawei P9
there. I cannot root/remount my phone. I am going to root my Huawei P9 phone now. I can find my device with
adb devices
But I cannot rootadb root
. I tried to root with KingRoot, but it is not working. Please let me know how to root Huawei P9. -
Tableview not updating with updated datamodel values ios
I am trying to update tableview with updated datasource. As I debugged the code, i could see that the model class has updated data but, it is not being imprinted on the view. I have even initialized the cell labels as empty strings before adding the new values. But stil, its failing.
// MARK: - Override Methods override func viewDidLoad() { super.viewDidLoad() setupTableView() initViewModel() title = Language.getLocalizedString(byKey: "Settings") } override func viewDidAppear(_ animated: Bool) { initNotifications() DispatchQueue.main.async { self.assignedEquipments?.removeAll() self.assignedEquipments = Repository.fetchAssignedEquipment() self.tableView.reloadData() } super.viewDidAppear(true) } // MARK: - Functions private func setupTableView() -> Void { tableView.estimatedRowHeight = 88.0 tableView.allowsSelection = false tableView.rowHeight = UITableViewAutomaticDimension tableView.delegate = self tableView.dataSource = self registerCells() } func reloadData() { self.assignedEquipments?.removeAll() self.assignedEquipments = Repository.fetchAssignedEquipment() print(self.assignedEquipments) DispatchQueue.main.async { self.tableView.layoutIfNeeded() self.tableView.reloadData() } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = UITableViewCell() if indexPath.section == 0 { cell = self.viewModel?.listData![indexPath.row] as! UITableViewCell if let cell1 = cell as? GenericTableViewCell006 { cell1.delegate = self return cell1 } } else { if let cell = (tableView.dequeueReusableCell(withIdentifier: GenericTableViewCell007.cellIdentifier, for: indexPath) as? GenericTableViewCell007) { cell.delegate = self cell.indexPath = indexPath var equipData = GenericTableViewCell007Model() equipData.deviceNameTitle = APP.CONSTANTS.STRING.EQUIPMENT_NAME equipData.deviceTypeTitle = APP.CONSTANTS.STRING.EQUIPMENT_TYPE if let count = self.assignedEquipments?.count, count > 0, self.shouldDisplayEquipmentDetails(assignedEquipmentTypeCode: (self.assignedEquipments?[indexPath.row].equipmentTypeCode ?? "") as String) == true { //n debugging, I could see assignedEquipments has updated values, but tableview still shows older values. equipData.deviceNameValue = self.assignedEquipments?[indexPath.row].equipmentName as String? equipData.deviceTypeValue = self.assignedEquipments?[indexPath.row].equipmentTypeCode as String? } else { equipData.deviceNameValue = APP.CONSTANTS.STRING.LBL_SELECT as String? equipData.deviceTypeValue = APP.CONSTANTS.STRING.LBL_SELECT as String? } equipData.btnModifyTitle = APP.CONSTANTS.STRING.MODIFY cell.initData(model: equipData) } } return cell }
Tableview Cell Class :
struct GenericTableViewCell007Model { // MARK: - Properties var deviceTypeTitle: String? = "" var deviceNameTitle: String? = "" var deviceTypeValue: String? = "" var deviceNameValue: String? = "" var btnModifyTitle : String? = "" var cellName: String? = "" var object : Any? } class GenericTableViewCell007 : UITableViewCell { //MARK: - Outlets @IBOutlet weak var lblDeviceType: UILabel! @IBOutlet weak var lblDeviceName: UILabel! @IBOutlet weak var lblDeviceTypeValue: UILabel! @IBOutlet weak var lblDeviceNameValue: UILabel! @IBOutlet weak var btnModify: UIButton! //MARK: - Properties static let cellIdentifier = "GenericTableViewCell007" var delegate : GenericTableViewCell007Delegate? var indexPath : IndexPath? var cellName : String = "" // MARK: - Functions func initData(model: GenericTableViewCell007Model) -> Void { self.resetUI() // object = model.object lblDeviceName.text = model.deviceNameTitle lblDeviceType.text = model.deviceTypeTitle lblDeviceNameValue.text = model.deviceNameValue lblDeviceTypeValue.text = model.deviceTypeValue cellName = model.cellName ?? "" btnModify.setTitle(model.btnModifyTitle, for: .normal) } func resetUI(){ lblDeviceName.text = "" lblDeviceType.text = "" lblDeviceNameValue.text = "" lblDeviceTypeValue.text = "" } }
I am failing to understanding : Why its behaving this way? and, how to make this work? I want to reload tableview on viewwillappear.
-
javascript check the data from the array and what the user entered
my script checks what the user has entered with what we have in a particular array. How to make it so that if the user is mistaken, the script suggested what information he needs to display at the user's request?
-
Is there a way to make this lines of code simpler with only one join()-method?
The code itself looks like this:
phrase="Don't panic!" plist=list(phrase) print(phrase) print(plist) phrase_1=''.join(plist[1:3]) phrase_2=''.join(plist[5:3:-1]) phrase_3=''.join(plist[7:5:-1]) phrase=phrase_1+phrase_2+phrase_3 plist=list(phrase) print(phrase) print(plist)
The result displays as follow:
Don't panic! ['D', 'o', 'n', "'", 't', ' ', 'p', 'a', 'n', 'i', 'c', '!'] on tap ['o', 'n', ' ', 't', 'a', 'p']
The main goal is to execute the program with the same result as above with the less lines of code using list slices.
I tried to insert the list slices onto the single variable
phrase=''.join()
phrase=''.join(plist[[1:3],[5:3:-1],[7:5:-1]]) plist=list(phrase)
but then it returns a syntax error:
phrase=''.join(plist[[1:3],[5:3:-1],[7:5:-1]]) ^ SyntaxError: invalid syntax
Is there any solution to shrink this lines of code?
-
How slow is using reflection for an event bus in a Kotlin application and why?
I'm creating an event system for my Kotlin application. I imagined it like the one in the SpigotAPI, so I have created an @EventHandler annotation, an EventBus and Event classes, and a Listener interface. So basically I implement the Listener interface and I create as many methods as I want and I tag them using the @EventHandler annotation. These methods must accept one parameter that extends the Event class. When I register that Listener implementation in the EventBus, I look for every annotated method and store them (as KFunctions) in a map using as key the event that they are listening for. When an event is called I access the map using it as key and dispatch the event to the relative KFunction.
The question is: how much slower is that solution compared to a "interface event" model and why? I wanted to use that method because the idea of having one class with differents listener seemed good. The SpigotAPI seems to have no speed problems but a friend of mine is absolutely sure that I couldn't find any slower alternative.
Here's the code for the EventBus class:
import java.util.* import kotlin.collections.HashMap import kotlin.reflect.KFunction import kotlin.reflect.jvm.kotlinFunction typealias EventFunction = (Event)->Unit class EventBus { private val map = HashMap<Class<Event>, LinkedList<KFunction<EventFunction>>>() fun dispatchEvent(event: Event){ var list = map[event::class.java] if(!list.isNullOrEmpty()){ list.forEach { it.call(event) } } } fun registerListener(eventListener: Listener){ eventListener::class.java.methods.forEach { if(it.isAnnotationPresent(EventHandler::class.java)){ val parameterTypes = it.parameterTypes val methodName = it.name if(parameterTypes.isNotEmpty()){ val eventClass = parameterTypes[0] var list = map[eventClass as Class<Event>] if(list.isNullOrEmpty()){ list = LinkedList<KFunction<EventFunction>>() } list.add(eventListener::class.java.getDeclaredMethod(methodName,Event::class.java).kotlinFunction as KFunction<EventFunction>); } } } } }
-
How to make a slide up in android studio (kotlin)
I don't know how to write code like this in kotlin https://www.youtube.com/watch?v=ES_kgC0M0s4
-
Duplicate code due to different list objects
So I got a function in each of my classes which does the same but with diffrent objects in the list, for example I got the methode for Streets and HouseNumbers.
Here the example of the two nearly identical functions, first for Streets:
fun batchInsert(import: List<ImportStreet>, source: String) { var part : MutableList<ImportStreet> = mutableListOf() for(i in import) { part.add(i) if(part.size % 25000 == 0) { batchUpdate(part, source) part = mutableListOf() } } if (part.size < 25000) { batchUpdate(part, source) } }
Nearly the same but now for HouseNumbers:
fun batchInsert(import: List<ImportHouseNumber>, source: String) { var part : MutableList<ImportHouseNumber> = mutableListOf() for(i in import) { part.add(i) if(part.size % 25000 == 0) { batchUpdate(part, source) part = mutableListOf() } } if (part.size < 25000) { batchUpdate(part, source) } }
Is there a easy or efficent way to get rid of the duplicate code?
-
IndexOutOfBoundsException when trying to getDownloadUrl after image upload from android to Firebase Storage
as you can see below I'd like to get the download URL for each image whose (android storage) URI is in mArrayUri:
StorageReference storeRef = FirebaseStorage.getInstance().getReference(user.getUid()+"/events/"+eventName); while (up < mArrayUri.size()){ Log.w("while1", Integer.toString(up)); storeRef.child(mArrayUri.get(k).getLastPathSegment()).putFile(mArrayUri.get(k)).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { Log.i("img", "image successfully uploaded"); Log.i("up", Integer.toString(up)); Log.i("k", Integer.toString(k)); storeRef.child(mArrayUri.get(k).getLastPathSegment()).getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri uri) { Log.i("URI", uri.toString()); } }); } }); up++; k++; }
The problem is that "up" and "k" are always equal to mArrayUri.size() when printed through Log.i(), and I have no idea on how to make them consistent with the outer addOnSuccessListener. I also tried to add another while cycle soon after this, only to get the download URLs, but it executes before images are uploaded, causing several 404 errors.
-
Visual Basic: Vertical bar chart using two-dimensional arrays, index out of bounds
I have recently started out with Visual Basic and have encountered a problem with two-dimensional arrays. My program is designed to take 5 integers from a user and then output 5 vertical bars of heights correspondent to the numbers. The bar starts from the bottom, which means in the case of numbers lower than the highest entered number, the top part of the column consists of spaces, rather than asterisks. When iterating through the array of numbers and putting an asterisk into the relevant position in the multi-dimensional array, I recieve a "index out of bounds" error.
Sub Main() Dim Numbers(4) As Integer WriteLine("Enter 5 numbers:") For i = 0 To 4 Numbers(i) = ReadLine() Next Dim ChartLimit As Integer = Numbers.Max Dim Chart(4, ChartLimit - 1) As String Dim Filled_bar As Integer Dim Bar_counter As Integer = 0 For Each Number In Numbers Filled_bar = ChartLimit - Number For i = Filled_bar - 1 To ChartLimit - 1 Chart(Bar_counter, i) = "*" Next Bar_counter += 1 Next For i = 0 To 4 For k = 0 To ChartLimit - 1 Write(Chart(i, k)) Next WriteLine() Next ReadKey() End Sub
-
How to fix Array Index out of bounds exception in java?
I am very new to java and I would like some help. I've tried searched everywhere and there are so many of the same question but I don't understand the answers given.
The code I want to run is simple:
Take two names as command-line arguments and print "Hello, name1 and name2." but I get the message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
I understand that my array must be the incorrect length, but what do I need to do to fix this? How do I get the code to accept more than one argument?
My code:
public class HelloGoodbye { public static void main( String [] args ){ System.out.print( "Hello " ); System.out.print( args[0] ); System.out.print( " and " ); System.out.println( args[1] + "." ); } }
Thank you