Convert Array list to Sparse Array - android

I have copied some code from a project and want to reuse a small part of it in my private app.
The class contains a Sparse Array
public class GolfResult {
String hcpAfter;
String hcpBefore;
SparseArray roundResults;
public GolfResult() {
hcpAfter = "";
hcpBefore = "";
roundResults = new SparseArray();
}
}
I have created an ArrayList for roundResults that is filled with the necessary data.
Then I am trying to fill the instance with content.
GolfResult golferRes = new GolfResult();
SparseArray<RoundResults> hu= new SparseArray<>();
hu = roundresults; // *
golferRes.setHcpAfter("33");
golferRes.setHcpBefore("kk");
golferRes.setRoundResults(hu);
But the problem is that hu = roudresults is not possible, because of the error message:
required: Android.util.SparseArray found: java.util.Array List
Any help will be welcome.
After receiving two helpful answers I got a step further, but now I am facing the problem that my SparseArray hu is empty {}.
The content of hu should be the class roundresults that has the following structure:
public class RoundResults {
boolean actualRound;
private List<HoleResult> holeResults;
Integer roundId;
Integer roundNumber;
String unfinishedReason;
The arrayList roundresults has the size of 1 and has data in the objects.
unfinishedReason =""
holeResults = ArrayLIST size= 18
roundID = "1"
roundNumber = "1"
actualRound = true
hu ={}
mValues = All elements are null
mSize = 0
Does anybody have an idea why?

SparseArray is different than ArrayList, from the documentation:
SparseArrays map integers to Objects. Unlike a normal array of
Objects, there can be gaps in the indices. It is intended to be more
memory efficient than using a HashMap to map Integers to Objects, both
because it avoids auto-boxing keys and its data structure doesn't rely
on an extra entry object for each mapping.
It's using a key value pair principle where the key is an integer and the value which the key mapping is the object. You need to use put [(int key, E value)](https://developer.android.com/reference/android/util/SparseArray.html#put(int, E)) where the E is your object. Remember that:
Adds a mapping from the specified key to the specified value,
replacing the previous mapping from the specified key if there was
one.
So you need to use a loop to add each object in your ArrayList as #valentino-s says:
SparseArray<RoundResults> hu= new SparseArray<>();
for( int i = 0; i < roundresults.size(); i++) {
// i as the key for the object.
hu.put(i, roundresults.get(i));
}

If I understand well your problem, maybe you can try with this:
for ( int i=0; i<roundresults.size(); i++ ) {
hu.put(i,roundresults.get(i));
}

After some trial and error I found a solution for the empty hu:
Instead of put I used append and it is working now.
hu.append(i, roundresults.get(i));
Time for a beer.

Related

Firebase Database change node ID

How can I change the naming of the nodes of my children in the image below?
questions_stats is a List<Integer>, I'm aware that I get integers as nodes Id because this is a List. I create each of the children randomly with a number between 0 and 1000. I set this ID as part of the object and to find it I loop trough the list. What I want is to set the "0671" as the Key of the Object at the moment I create it.
How should I define my object in order to access each child with an Id that I define as a String.
Each of the questions_stats is an object.
This is my UserProfile Class definition.
public class UserProfile implements Parcelable {
private List<Integer> questions_list;
private List<QuestionsStats> questions_stats;
private String country_name, share_code, user_name;
private int token_count;
private Boolean is_guest;
public UserProfile() {
}
public UserProfile(List<Integer> questions_list, List<QuestionsStats> questions_stats, String country_name, String share_code, String user_name, int token_count, Boolean is_guest) {
this.questions_list = questions_list;
this.questions_stats = questions_stats;
this.country_name = country_name;
this.share_code = share_code;
this.user_name = user_name;
this.token_count = token_count;
this.is_guest = is_guest;
}
}
I know I can set them using the child("0159").setValue(QuestionStats) individually.
But for my purpose I need to retrieve the data of the "user" as a whole and then iterate whithin questions_stats like it is a List.
How should I define my UserProfile class in order to achieve what I want?
Anybody could give me a hint?
How can I change the node names of my children in the image below?
Answer: There is no way in which you can change the names of the nodes from your Firebase database. There is no API for doing that. What can you do instead is to attach a listener on that node and get the dataSnapshot object. Having that data, you can write it in another place using other names. You cannot simply rename them from 0 to 0000, 1 to 0001 and so on.
Perhaps I should have asked for How to "Set" the node Id instead of "Change"
What I have is an List<QuestionsStats>, but when using an List<QuestionsStats> you get indexes as Keys, What I want is to have the same List<QuestionsStats> but instead of indexes, String Keys for each of my items.
So I changed my List for a Map<String, QuestionsStats>. Now the tricky part is when parceling the Object. You can use readMap() or writeMap() to parcel as shown here in this answer by #David Wasser, but it gives a warning:
Please use writeBundle(Bundle) instead. Flattens a Map into the parcel
at the current dataPosition(), growing dataCapacity() if needed. The
Map keys must be String objects. The Map values are written using
writeValue(Object) and must follow the specification there. It is
strongly recommended to use writeBundle(Bundle) instead of this
method, since the Bundle class provides a type-safe API that allows
you to avoid mysterious type errors at the point of marshalling.
So with the help of the comments in This Question I parceled using this code, note that I'm leaving the "easy" way commented in case somebody find it useful or have any comment on that :
protected UserProfile(Parcel in) {
// in.readMap(myMap, Object.class.getClassLoader());
myMap = new HashMap<>();
String[] array = in.createStringArray();
Bundle bundle = in.readBundle(Object.class.getClassLoader());
for (String s : array) {
myMap.put(s, (Object) bundle.getParcelable(s));
}
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// dest.writeMap(myMap);
Bundle bundle = new Bundle();
for (Map.Entry<String, Object> entry : myMap.entrySet()) {
bundle.putParcelable(entry.getKey(), entry.getValue());
}
Set<String> keySet = myMap.keySet();
String[] array = keySet.toArray(new String[keySet.size()]);
dest.writeStringArray(array);
dest.writeBundle(bundle);
}
Why I want this, well at the moment my list contains less than 100 items but it could grow up to a 1000, I'm no Pro, but I believe that if I already know the key of the item I'm interested in will be always better than having to iterate over the list to find it. In the end my main problem was the usage of a Map, I did not know howto.

Looping out JSON Array using ArrayList

I am trying to learn retrofit and I have made successful attempts at posting data and now I am trying to retrieve JSON array which looks as follows:
{
"result": "success",
"message": "All Questions Have Been Selected",
"question": {
"all_question_ids": ["1","2","3"]
}
}
I am using the following getter
public ArrayList getAll_question_ids(){
return all_question_ids;
}
I am retrieving using Retrofit as follows
if (resp.getResult().equals(Constants.SUCCESS)) {
SharedPreferences.Editor editor = pref.edit();
Log.d("Question_IDs", "getAllQuestionID() = " + response.body().getQuestion().getAll_question_ids() );
editor.putString(Constants.All_QUESTION_IDS,((resp.getQuestion().getAll_question_ids().toString())));
editor.apply();
}
progress.setVisibility(View.INVISIBLE);
It is here that I am stuck, as I am retrieving the array ok but I am unsure how to loop out the Array which is now stored in Shared Preferences.
When I place a toast to show me how the IDs are coming across, my toast confirms the data as [1,2,3]
The goal is to add a dynamic button and the individual ID, i.e button 1, button 2 etc every-time the loop is iterated.
I have tried the following:
String questionNumber = pref.getString(Constants.All_QUESTION_IDS, "");
for (int i =0; i < questionNumber.length(); i++) {
try {
/*Dynamically create new Button which includes the question name
*/
AppCompatButton btn_question = new AppCompatButton(getActivity());
/*LayoutParams (int width, int height,float weight)
As LayoutParams is defaulted in px, I have called a method called dpToPX to make sure
the dynamically added EditText is the same size on all devices.
*/
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(dpToPx(280), dpToPx(45), 1);
btn_question.setBackgroundColor(Color.parseColor("#3B5998"));
btn_question.setTextColor(Color.WHITE);
// btn_question.setText(String.valueOf(x));
btn_question.setText("Question "+ pref.getString(Constants.All_QUESTION_IDS,""));
btn_question.setGravity(Gravity.CENTER);
//generate unique ID for each new EditText dynamically created
View.generateViewId();
//Log.d("TEST VALUE", "Question1 generated ID = " + btn_question.generateViewId());
params.setMargins(0, dpToPx(10), 0, dpToPx(10));
btn_question.setPadding(0, 0, 0, 0);
btn_question.setLayoutParams(params);
allEds.add(btn_question);
mLayout.addView(btn_question);
} catch (Exception e) {
Log.d(TAG, "Failed to create new edit text");
}
}
However the above is adding the value as it appears in the array e.g [1,2,3] which is obviously not what I want.
I have added a photo in case my explanation isn't clear. I want a button with 1 number added to it each time the loop iterates but I am unable to figure this out.
I have looked through lots of resource but cannot find an answer that is relevant to my problem, although, if there is, I am not familiar enough to recognise a similar issue.
If someone can offer some assistance, I would appreciate it!
When you call editor.putString(Constants.All_QUESTION_IDS,((SOMETHING.toString())));, what is actually stored depends on the implementation of the toString method in the type of SOMETHING (in this case String[]). So avoid doing that. Instead, since you're already using Gson or Jackson (or others), store the question_idsas JSON:
final String jsonIds = gson.toJson (resp.getQuestion().getAll_question_ids());
editor.putString(Constants.All_QUESTION_IDS, jsonIds);
Your actual stored value no longer depends on the implementation of something that you don't control (String[].toString). It is a valid JSON array and regardless of what tool/library you use to read it back, it's valid.
Now, to read back the stored data:
final String storedJson = pref.getString(Constants.All_QUESTION_IDS, null);
if (null == storedJson) {
// TODO: No question ids found
}
final String[] ids = gson.fromJson (storedJson, String[].class);
for (int i = 0; i < ids.length; i++) {
// make your buttons
}
This is a problem of saving and then reading out a List of items (in this case, String instances).
You've chosen to save the list by calling editor.putString() with a value of getAll_question_ids().toString(). That toString() call is going to return a string representation of your list, or, in other words, a String instance with the value [1, 2, 3]. At this point, you no longer have a List proper, but a String that looks like a list.
This is all technically fine, but it means you have to take this into account when you're trying to read out that list.
You've written this to read the list back out:
String questionNumber = pref.getString(Constants.All_QUESTION_IDS, "");
Once this line executes, questionNumber will be a String instance with the value [1, 2, 3]. Again, this is fine, but now we come to the key point: we have to convert this String back into a List.
If you know for sure that the values in this list won't have commas in them, you can do it easily:
Trim the braces off the string using substring()
Create a String[] using split()
Convert your array to a list using Arrays.asList() (you could even skip this step since iterating over an array is just as easy as iterating over a list)
Put that together and you get:
String questionNumber = pref.getString(Constants.All_QUESTION_IDS, "");
questionNumber = questionNumber.substring(1, questionNumber.length() - 1);
String[] array = questionNumber.split(", ");
List list = Arrays.asList(array);
At this point, you can iterate over your array or list:
for (String value : list) {
...
btn_question.setText("Question " + value);
...
}

Android setter of String array

now i've got simple setter and getter of string array. I want to use setter to put some retrevied json info + same text to array. When i use belowe code:
met.setPlacepic(new String[]{"http://dfsdfsdfsf/" + json.getString("source")});
it looks like setter put only one string to array, despite there is many more data.
Declaration is simple
public String[] placepic
and the setter is also simple:
public void setPlacepic(String[] placepic) {
this.placepic = placepic;
}
Anybody knows reason of this?
If the number of strings is fixed (you know exactly how many element you would have in the array), then you could use String Arrays:
String[] placepic = new String[20]; //20 strings
//Then, in your loop:
placepic[i] = yourData;
If you do NOT know how many strings in your data, You should use List:
List<String> placepicList= new ArrayList<String>();
//Then, in your loop:
placepicList.add(yourData);
//Then after the loop, you get the array
String[] placepic = placepicList.toArray(new String[placepicList.size()]);

Ormlite RawRowMapper truncated double

I am using RawRowMapper to load relevant columns from ormlite. RawRowMapper returns all data as String.
The observation is that it truncates the double value.
Example:
Data inserted -> 57.1117146374
Data type used to store the data -> Double
Data from Ormlite when directly queried: -> 57.1117146374 (This is correct and essentially means that ormlite is actually storing the data correctly)
Data from Ormlite when using mapper -> 57.1117 (Truncated data coming as part of String[] resultColumns
Any idea how do I avoid it getting truncated?
EDIT:
#DatabaseField(columnName = "LAT")
private Double lat;
Object Field:
private double lat;
The key here is that the string in resultcolumns[], I get is already truncated.
Data from Ormlite when using mapper -> 57.1117 (Truncated data coming as part of String[] resultColumns
The problem seems to be that getting a double value out as a String is truncated by Android's cursor.getString(...) method. Not sure why but if the result is extracted by using cursor.getDouble(columnIndex); on the same column-index, the full precision is preserved.
The solution here I believe is to map the rows differently. If you use dao.queryRaw(String, DataType[], ...) method, the double field seems to be extracted appropriately. Here's a sample from my test class.
GenericRawResults<Object[]> results =
dao.queryRaw(dao.queryBuilder().selectColumns("lat")
.prepareStatementString(), new DataType[] { DataType.DOUBLE });
CloseableIterator<Object[]> iterator = results.closeableIterator();
try {
assertTrue(iterator.hasNext());
Object[] objs = iterator.next();
assertEquals(foo.doubleField, objs[0]);
} finally {
iterator.close();
}
You could also use a custom row mapper and the dao.queryRaw(String, RawRowMapper, ...) method to convert and return a custom object with a double field.

How to retrieve data from ArrayList<ModelObject> not from ArrayList<String>?

Hi I'm still new to java data management.
I have a model object class named Computer which has 3 fields: processor, ram, hddSize.
I created a ArrayList
ArrayList<Computer> myCompList = new ArrayList<Computer>();
Computer comp1 = new Computer();
comp1.setProcessor("1.5 GHZ");
comp1.setRam("512 MB");
comp1.setHddSize("100 GB");
Computer comp2 = new Computer();
comp2.setProcessor("2.5 GHZ");
comp2.setRam("512 MB");
comp2.setHddSize("50 GB");
myCompList.add(comp1);
myCompList.add(comp2);
Now How can I retrieve data at index1 of the ArrayList above?
PS: I know how to do it if its a ArrayList< String> by convert it to String[] and then String[index].
Look at the Javadocs for ArrayList
This is where you should check for simple questions like this. The answer can be found in the "Method Summary" section.
Assuming that you have created getters and setters in your Computer class:
String processor = myCompList.get(1).getProcessor();
String ram = myCompList.get(1).getRam();
String hddSize = myCompList.get(1).getHddSize();
Can't you just go myCompList.get(0); ?
An arraylist of objects is essentially the same as an arraylist of strings. The .get() method returns the specific object at the given index. Here is the documentation for ArrayList.
myCompList.get(index) will return you data on the given index, make sure index number wouldn't be greater than array size, it will give you index out of bounds exception.

Categories

Resources