ListView with Array Issue - android

What I'm doing is wanting to start off my ListView with 0 rows, download a list from the Internet, then populate the ListView with the downloaded contents. Seems easy enough, but arrays are proving to be an issue.
What's happening is that I'm declaring my array in the only way ListView seems to want it
static String[] CONTENTS = new String[]{};
so that it populates with no rows. After downloading the contents through a thread, I then go to fill the array with what I've downloaded. The problem is that it doesn't want to fill the array; if I initiate the array with one empty string, it will only let me fill it with exactly one row (so if I give it an array with more than one object, it doesn't do anything). How can I expand on the array the ListView is taking data from, so I can fill it with more than the number of objects I've declared it with?
The closest I've been able to come was through the code
private String[] expand(String[] array, int size) {
String[] temp = new String[size];
System.arraycopy(array, 0, temp, 0, array.length);
for(int j = array.length; j < size; j++)
temp[j] = "";
return temp;
}
to expand the array and giving it the number of objects downloaded, but that still doesn't seem to work.
Thanks in advance!

Don't use arrays, use some implementation of List. (ArrayList will do the work). Collections are far superior than old-school arrays.
//List
list = new ArrayList();
//BaseAdapter
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
//ListView
listView = (ListView) findViewByID(R.id.listview);
listView.setAdapter(adapter);
And when you add/remove elements to/from the list, you must invoke
adapter.notifyDataSetChanged();

How can I expand on the array ...
I assume you are using an ArrayAdapter. Instead of using a fixed-size array, use a dynamically-resizable ArrayList to back it using one of the ArrayAdapter constructors that take a List argument.

Related

How to dynamically add to double[]?

How to dynamically add to double[]?
Should I create a List...
List<double[]> y = new ArrayList<double[]>();
y.add(new double[15]);
y.add(new double[20]);
and convert List to double[]?
use a List<Double> such as List<Doulble> list = new ArrayList<Double>();
add whatever the numbers to the list and then convert the list to array:
Double[] asArray = list.toArray(new Double[list.size()]);
I'm unsure of what exactly you're trying to accomplish, but let's see if I can shed some light on things.
An ArrayList works like an array that will automatically grow in size as you add items to it. So ArrayList<Double> is very similar to a double[], with the exception that you cannot alter the size of the double[] after it's been created.
For example, double[] list = new double[10]; creates an array that holds doubles, but it can never hold more than 10 items. On the other hand, List<Double> list = new ArrayList<>(); can hold 10 items, it can hold 100 items, and it can hold millions of items, all without recreating the list.
Lets look at dynamically expanding an array of doubles:
// Create the array
double[] list = new double[2];
list[0] = 1.1;
list[1] = 2.2;
// Copy the array with space for another entry
list = Arrays.copyOf(list, 3);
// Add another entry to the newly expanded array
list[3] = 3.3;
Every time you want to hold more values than the array has the capacity for, you will need to create a new array, and copy the values from one to the other (Which is what Arrays.copyOf(...) does).
Using an ArrayList<Double> simplifies things by handling all of this nonsense internally, so you don't have to worry about maintaining an array of the proper size.
List<Double> list = new ArrayList<Double>();
list.add(1.1);
list.add(2.2);
list.add(3.3);
You can keep adding without worrying about what size your ArrayList actually is.
With this, you can replace double[] with ArrayList<Double>. If you need to turn your ArrayList<Double> into a double[] for whatever reason, that is reasonably simple to do:
double[] array = new double[list.size()];
for (int i = 0; i < array.length; i++) {
array[i] = list.get(i);
}

Check if ArrayList of Strings contains 50 different Strings one by one

How to check if ArrayList of strings contains every of 50 different strings from string array one by one and for every identical string in ArrayList to do something?
You can use this function to check if all Strings in your array are also in the ArrayList. If you want to add additional logic, like doSomething() each time a match is found, you should be able to adapt the code easily.
ArrayList myList; // let's assume its initialized and filled with Strings
String[] strArray; // let's assume its initialized and filled with Strings
//this function returns true if all Strings in the array are also in your arraylist
public boolean containsAll(myList, strArray){
//iterate your String array
for(int i = 0; i < strArray.length; i++){
if(!myList.contains(strArray[i])){
//String is not in arraylist, no need to check the rest of the Strings
return false;
}
}
return true;
}
Why not use LINQ?
List<String> duplicates = YourList.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(g => g.Key)
.ToList();
Note that this will return all duplicates in a new List<string> , so if you want only want to know which items are duplicated in the source list, you could apply Distinct to the resulting sequence or use the solution given above

Split TreeMap<List<>,List<>> into two ArrayList

i have two ArrayLists:
List<String> names = new ArrayList<String>(10);
List<Drawable> drawables = new ArrayList<Drawable>(10);
which i want to sort alphabetically.
For this i created a TreeMap:
Map<List<String>, List<Drawable>> myMapToSort = new TreeMap<List<String>, List<Drawable>>();
myMapToSort.put(names, drawables);
First two Question
Is the map now sorted in lexicographical order? Or do i Need to do something additional?
After i have sorted them, if they are yet, i want to split them back again to List<String> and List<Drawable>. And i tried like this:
List<String> sortedNames = new ArrayList<String>(myMapToSort.keySet());
Of course it doesn't work because myMapToSort.keySet() Returns a Set and not List.
And List doesn't have an Constructor for a Set.
So how can i accomplish that and what i'm misunderstanding?
Any help is appreciated. Thanks in advance!
I figured it out by my own.
The key was to create a TreeMap with not two list but two single Objects:
Map<String, Drawable> myTreeMap = new TreeMap<String, Drawable>;
Then add the Items from the Arraylists one by one to the Map:
for(int i = 0; i<names.size(); i++) {
myTreeMap.put(names.get(i), drawables.get(i));
}
Now the Map is automatically sorted Lexicographical in relation with the Drawables.
That means Names and Drawables are sorted in lexicographical order.
If you want to retrieve the keys and the values and put them back in seperate ArrayLists simply type:
List <String> mySortedNames = new ArrayList<String>(myTreeMap.keySet());
List <Drawables> mySortedDrawables = new ArrayList<Drawables>(myTreeMap.values());
That's it. ;)
You can use SortedSet (or SortedList) to have sorted elements. The elements are ordered using their natural ordering, or by a Comparator typically provided at sorted set creation time.
For splitting a Map in two lists :
List<String> sortedNames = new ArrayList<String>();
List<Drawable> drawables = new ArrayList<Drawable>();
for (Map.Entry<String, Drawable> entry : map.entrySet())
{
sortedNames.add(entry.getKey()
drawables.add(entry.getValue());
}

How to display images stored in database as a blob, in the Listview in Android?

My question here is that, I am creating a small quiz such that I want an image at the top and its answer right below it. This is all done in a new activity where I want to show the answers for the quiz. There are about 40 questions each with an image. Hence, I tried using HashMap as follows:-
ListView lv = (ListView)findViewById(R.id.list1);
String[] from = new String[] {"ques","ans"};
int[] to = new int[] {R.id.ques, R.id.ans};
// prepare the list of all records
List<HashMap<String,Bitmap>> fillMaps = new ArrayList<HashMap<String,Bitmap>>();
Cursor c1 = db.getQues(4);
byte[] bb = c1.getBlob(0);
Bitmap image = BitmapFactory.decodeByteArray(bb, 0, bb.length);
//Cursor c2 = db.getAns(4);
// String ans1 ="Ans"+") "+c2.getString(0);
HashMap<String,Bitmap> map = new HashMap<String, Bitmap>();
// HashMap<String,String> map1 = new HashMap<String, String>();
map.put("ques",image);
// map1.put("ans",ans1);
fillMaps.add(map);
SimpleAdapter adapter = new SimpleAdapter(this, fillMaps, R.layout.itemsign, from, to);
lv.setAdapter(adapter);
But I couldn't find a way to correctly implement it. This code does not work. It just shows a blank page. So, any help will greatly be appreciated. As I am new to android so please be more detailed while explaining.
Well, I don't think that the blob is your problem. Here is the javadoc for the SimpleAdapter constructor:
public SimpleAdapter (Context context, List> data, int resource, String[] from, int[] to)
Since: API Level 1
Constructor
Parameters
context The context where the View associated with this SimpleAdapter is running
data A List of Maps. Each entry in the List corresponds to one row in the list. The Maps contain the data for each row, and should include all the entries specified in "from"
resource Resource identifier of a view layout that defines the views for this list item. The layout file should include at least those named views defined in "to"
from A list of column names that will be added to the Map associated with each item.
to The views that should display column in the "from" parameter. These should all be TextViews. The first N views in this list are given the values of the first N columns in the from parameter.
You can't use Bitmaps in a SimpleAdapter, it's too simple for that :)

trying to use ArrayList to hold image resources

In my app, I have a bunch of images in my drawable folder which I select at random and display using imageView. I've been told about ArrayList's which can add/remove objects from the list...in order to prevent image repeats, some sample code I used below:
// create an array list
ArrayList imageHolder = new ArrayList();
int remaining = 10;
public void initArrayList(){
// add elements to the array list
imageHolder.add((int)R.drawable.child0);
imageHolder.add((int)R.drawable.child1);
imageHolder.add((int)R.drawable.child2);
imageHolder.add((int)R.drawable.child3);
imageHolder.add((int)R.drawable.child4);
imageHolder.add((int)R.drawable.child5);
imageHolder.add((int)R.drawable.child6);
imageHolder.add((int)R.drawable.child7);
imageHolder.add((int)R.drawable.child8);
imageHolder.add((int)R.drawable.child9);
}
//get random number within the current range
int randInt = new Random().nextInt((remaining-1));
//update the imageView config
ImageView image = (ImageView) findViewById(R.id.shuffleImageView);
image.setImageResource(imageHolder.get(randInt));
Eclipse reports that image.setImageResource cannot use an object argument, which is what is provided by arrayList. The actual argument should be int. Any clue how to get around this??
Thanks in advance!
Use List<Integer> imageHolder = new ArrayList<Integer>();
ArrayList contains Objects, always, never primitive types. When you set ints into it, they are autoboxed to Integer objects, when you get them back, you get Integer objects as well. A short fix will be:
image.setImageResource((int)imageHolder.get(randInt));
Be careful though, unboxing a null pointer will cause a NullPointerException, So make sure your randInt is in the range of the arraylist.
EDIT:
I totally missed that, but You initialize your ArrayList like that:
ArrayList imageHolder = new ArrayList();
Which creates ArrayList of Objects. instead, initialize the ArrayList like the following to create ArrayList of integers:
List<Integer> imageHolder = new ArrayList<Integer>();

Categories

Resources