Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing an element from String array in android

Am doing a simple android application.In that I am deleting an element from array using the following code.

 arr_fav = {"1","2","3"};
 for(int i= 0;i<arr_fav.length;i++)
 {
     if(current_id == Integer.parseInt(arr_fav[i]))
     {
        arr_fav[1] = null;
     } }

By doing this am getting the array like arr_fav = {"1",null,"3"}.But I want like arr_fav = {"1","3"}.How to delete an element.Am new to this android development.Please help me to solve this.

like image 391
Madhumitha Avatar asked Dec 06 '12 08:12

Madhumitha


People also ask

How do you remove an element from an array array?

You can remove the element at any index by using the splice method. If you have an array named arr it can be used in this way to remove an element at any index: arr. splice(n, 1) , with n being the index of the element to remove.

Can you remove an element from an array?

If you want to remove an item from an array, you can use the pop() method to remove the last element or the shift() method to remove the first element.

How do I remove an element from an array in Kotlin?

How do you remove the first element from an array in Kotlin? Using removeAt() function. The removeAt() function removes an element at the specified index from a mutable list. Using clear() function.


2 Answers

its better to use arraylist

arr_fav = {"1","2","3"};
List<String> numlist = new ArrayList<String>();
for(int i= 0;i<arr_fav.length;i++)
{
 if(current_id == Integer.parseInt(arr_fav[i]))
 {
   // No operation here 
 }
 else
 {
     numlist.add(arr_fav[i]);
 }
}
 arr_fav = numlist .toArray(new String[numlist .size()]);
like image 135
Ram kiran Pachigolla Avatar answered Oct 04 '22 21:10

Ram kiran Pachigolla


You don't.

Arrays can not be resized.

You would need to create a new (smaller) array, and copy the elements you wished to preserve into it.

A better Idea would be to use a List implementation that was dynamic. An ArrayList<Integer> for example.

like image 42
Brian Roach Avatar answered Oct 04 '22 21:10

Brian Roach