Iteration Through R class - android

is there any possible way to iterate throught R.raw or R.drawable or any R class? I want to get every id on that folder dynamically.
ArrayList resArray = new ArrayList();
foreach(int id : R.raw) {
resArray.add(id);
}
or is there any other way?

You can do this using java reflection:
Class raw = R.raw.class;
Field[] fields = raw.getFields();
for (Field field : fields) {
try {
Log.i("REFLECTION",
String.format("%s is %d", field.getName(), field.getInt(null)));
} catch(IllegalAccessException e) {
Log.e("REFLECTION", String.format("%s threw IllegalAccessException.",
field.getName()));
}
}

Related

Convert Google Place Types into String

I'm working on my code to check the types of the place base on place details following this document (https://developers.google.com/android/reference/com/google/android/gms/location/places/Place).
I manage the value from List, the question is how I can display the string for example place a is restaurant, place be is bank from the class. Or should I create an array based on the document? Please advise.
final Place place = PlacePicker.getPlace(this, data);
final List<Integer> types = place.getPlaceTypes();
Toast.makeText(getApplicationContext(), types.get(0).toString(), Toast.LENGTH_SHORT).show();
Regards, -sea-
You could do something as crazy as:
int myPlaceType = 1;
Field[] fields = Place.class.getDeclaredFields();
for (Field field : fields) {
Class<?> type = field.getType();
if(type == int.class) {
try {
if(myPlaceType == field.getInt(null)) {
Log.i("Testing", "onCreate: " + field.getName());
break;
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
This will print TYPE_ACCOUNTING to your Android console.
Where myPlaceType is the int place type...
Not perfect, and I hope someone has a better suggestion!
Gav

Compare Two JSON object

I am having JSON object like
{
key1:value1,
key2:value2
key3:value3
}
and i will write this JSON content to file.(Done)
For next interval of time i am getting JSON Object as
{
key1:newValue1,
key2:value2
key3:newValue3
}
I need to find out difference between each values. and need to write new json into file
{
key1:(value1- newValue1),
key2:(value2 - value2)
key3:(value3- newValue3)
}
How can i achieve it.? Please help.
The code below just iterates through the keys of your testObject, subtracts the value of the object from file and puts the result of this subtraction back to the testObject... Than you can save, or do whatever you want to do with the values in testObject
for(Iterator<String> iterator = testObject.keys(); iterator.hasNext();) {
String key = iterator.next();
try {
int testValue = testObject.getInt(key);
int fileValue = fileObject.getInt(key);
int differenceValue = testValue - fileValue;
testObject.put(key, differenceValue);
} catch (JSONException e) {e.printStackTrace();}
}

Parse get multiple objects using their objectIds

I have a ArrayList<String> -named listObjectId below- of objectIds. I'm trying to get all the objects that have an objectId contained in the ArrayList.
The solution I have right now, I think, is very bad from a performance point of view:
for (int i = 0; i < listObjectId.size(); i++) {
ItemModel mItemModelRetrieved = null;
ParseQuery<ItemModel > query = ParseQuery.getQuery(ItemModel .class);
try {
mItemModelRetrieved = query.get(listObjectId.get(i));
subscriber.onNext(mItemModelRetrieved ); //-- I'm using RxJava
} catch (ParseException e) {
Log.e(TAG, "Error Local " + e.getMessage());
}
}
You're using the wrong method. You have the object ids, so create a ParseObject with them using ParseObject.createWithoutData and then fetch the object. Try the following:
List<ParseObject> parseObjects = new ArrayList<>();
for (String objectId : listObjectId) {
parseObjects.add(ParseObject.createWithoutData(ItemModel.class, objectId));
}
ParseObject.fetchAll(parseObjects);
// parseObjects will now contain all data retrieved from Parse.
The error you're getting tells you that the data type of the column you query must be of type Array, not the value you pass into the method.

Show string keys instead of values

Is it possible to show the keys of my strings in strings.xml instead of the value, would be cool to check which key is it directly in the UI.
for example
<string name="jobs_key">Jobs</string>
i would like to show in the UI jobs_key instead of Jobs
use Resources.getResourcesName(int),
Return the full name for a given resource identifier
here you can find the documentation. You can also use reflection:
private ArrayList<String> getKeysName(Context context, String className) {
Class c;
ArrayList<String> fieldsName = new ArrayList<String>();
try {
c = Class.forName(context.getPackageName() + ".R$" + className);
Field[] fields = c.getDeclaredFields();
for (Field f : fields) {
Log.e("LOG_TAG", " " + f.getName());
fieldsName.add(f.getName());
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return fieldsName;
}
and call it like getKeysName(context, "string");, to get, for instance all the keys declared inside string.xml.

android XML parse into Hash map not working

I am getting the most bizzarre behavior with trying to parse an XML, I run through it step by step and all values are assigned and retrieved in order and then the object I create is added to a HashMap for easy look up, the problem is when I am done retrieving it all the HashMap has null values and the ones that aren't null are the value of the very last node that was read, I have walked through it over and over and it all seems correct, but when it's done loading the values in the HasMap look like:
[0] null
[1] NarrationItem#44e9d170
[2] null
[3] null
[4] NarrationItem#44e9d170
etc, etc.
The format of my XML files is:
<narrations>
<narration id="0" name="A" alias="a" >
<line text="This is a test."></line>
</narration>
<narration id="1" name="B" alias="b" >
<line text="This another a test."></line>
</narration>
<narration id="2" name="C" alias="c" >
<line text="This is STILL a test."></line>
</narration>
</narrations>
And my XML parsing method is follows:
public HashMap<String, NarrationItem> NarrationMap = new HashMap<String, NarrationItem>();
private void LoadNarrationsXML() {
NarrationItem i = new NarrationItem();
String line;
String s;
try {
// Get the Android-specific compiled XML parser.
XmlResourceParser xmlParser = this.getResources().getXml(R.xml.narrations);
while (xmlParser.getEventType() != XmlResourceParser.END_DOCUMENT) {
if (xmlParser.getEventType() == XmlResourceParser.START_TAG) {
s = xmlParser.getName();
if (s.equals("narration")) {
i.Clear();
i.ID = xmlParser.getAttributeIntValue(null, "id", 0);
i.Name = xmlParser.getAttributeValue(null, "name");
i.Alias = xmlParser.getAttributeValue(null, "alias");
} else if (s.equals("line")) {
line = xmlParser.getAttributeValue(null, "text");
i.Narration.add(line);
}
} else if (xmlParser.getEventType() == XmlResourceParser.END_TAG) {
s = xmlParser.getName();
if (s.equals("narration")) {
NarrationMap.put(i.Alias, i);
}
}
xmlParser.next();
}
xmlParser.close();
} catch (XmlPullParserException xppe) {
Log.e(TAG, "Failure of .getEventType or .next, probably bad file format");
xppe.toString();
} catch (IOException ioe) {
Log.e(TAG, "Unable to read resource file");
ioe.printStackTrace();
}
}
The NarrationItem object is a custom object defined as:
public class NarrationItem {
int ID;
String Name;
String Alias;
ArrayList<String> Narration = new ArrayList<String>();
public NarrationItem() { }
public void LoadNarration(int id, String name, String alias, ArrayList<String> narration) {
ID = id;
Name = name;
Alias = alias;
Narration.addAll(narration);// = narration;
}
public void Clear() {
ID = 0;
Name = "";
Alias = "";
Narration.clear();
}
}//End Narration
If someone could point out the problem I'd be very thankful I have sat here staring at this issue for hours.
You're only ever creating one NarrationItem object - you're then using a reference to that object as the value for multiple entries in the map. Don't do that. You need to understand that the map doesn't contain an object as the value - it contains a reference to an object.
You can probably fix this just by creating a new NarrationItem each time instead of calling Clear.
It's not clear how you're looking at the map to see those null values, but if you're using the debugger and looking at the internal data structure, you probably shouldn't really be doing that either - instead, step through the keys, values or entries, i.e. stick within the abstraction that HashMap is meant to support.

Categories

Resources