How to dynamically add to double[]? - android

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);
}

Related

Display name and value (sum of all the value with same name) in pie chart android

I am having problem in displaying the items and their value in pie chart. My output is as follows
As we can see the there is food slice three times. I want only one food slice along with the sum of value in those three slices. I have stored these values in arraylist. The code can be seen below:
Realm realm;
ArrayList<String> items = new ArrayList<String>();
ArrayList<Integer> expense = new ArrayList<Integer>();
RealmResults<Credit> result = realm.where(Credit.class).equalTo("regId", userId).findAll();
result.load();
for (Credit p : result) {
items.add(p.getItem());
expense.add(p.getExpense());
}
setPieChart();
}
private void setPieChart() {
List<PieEntry> pieEntries = new ArrayList<>();
for(int i = 0; i<items.size();i++){
pieEntries.add(new PieEntry(expense.get(i), items.get(i)));
PieDataSet dataSet = new PieDataSet(pieEntries,"Spending of User");
PieData data = new PieData(dataSet);
dataSet.setColors(ColorTemplate.COLORFUL_COLORS);
data.setValueTextSize(20f);
chart = (PieChart) findViewById(R.id.pieChart);
chart.animateY(1500);
chart.setData(data);
chart.invalidate();
}
}
Can somebody please help me to solve this problem? I had used nested loop to compare the data within the array list and add it to piechart but it didnot work..
There is no groupBy feature in realm implemented so far. So you should do it by yourself. I recommend you to use streams API, for that you can use this library (since Java 8 native Stream API is not supported for all API levels in Android)
https://github.com/aNNiMON/Lightweight-Stream-API
In documentation you can see this part
groupBy - groups by extractor function
stream.groupBy(Credit::getExpense)
It will group by expenses, also this lib will help you to get sum of each group.

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());
}

Store multiple dynamic EditText value

I have a code adding multiple EditText. How can i store them into a array. This number 10 is just example, the number may bigger than that. How can i store it after click a button
for(int i=0; i<10; i++) {
String store[] = new String[10];
EditText addAnsMCQ = new EditText(this);
AnswerRG.addView(addAnsMCQ, 1);
addAnsMCQ.setWidth(200);
addAnsMCQ.setId(1000);
}
In your example the store variable isn't actually being used, did you intend do use it for storing the EditTexts?
Instead of using an array of String, just use an array of EditText and store a reference to them:
EditText store[] = new EditText[10];
for(int i=0; i<10; i++) {
EditText addAnsMCQ = new EditText(this);
AnswerRG.addView(addAnsMCQ, 1);
addAnsMCQ.setWidth(200);
addAnsMCQ.setId(1000);
store[i] = addAnsMCQ; //store a reference in the array to the EditText created
}
Then outside of the for loop, you can access the reference to each EditText, e.g.
store[0].setWidth(300);
You need to keep/get a reference to each of your EditText's then you can look up its value with .getText().toString() which you can store in whatever manner you like.
However if as you say
This number 10 is just example, the number may bigger than that.
If the number is going to be larger you should be using an Adapter and a ListView or something to hold your View objects. That will make it easier to get everything on to the screen. And will give you the benefit of view recycling.

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>();

ListView with Array Issue

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.

Categories

Resources