How to get the name of the currently used Layout(s) file name(s) ?
for example it could be res/layout/main.xml or something like that.
Also, the code which require this information is not part of the app that contains this layout, it's kind of a testing code.
You don't. Internally Android doesn't refer to them by filenames, it refers to them by id- an integer. You can see the integer it uses in your generated R file. And that information isn't stored, it inflates the proper file then forgets about it.
i assume, you can go with reflection and lots of iteration.
First you want all your statics in the R.layout class - then you obtain their values and compare them to the View.getId() and in a last step you retrieve the fields name.
but: the name will only contain layout-files name (in your example main) and not the full path to it, even though you could have duplicate layouts with the same name, e.g. for landscape/portrait mode etc
I never tried something like that and I'm not sure if this works out, because i don't know if your testenvironment can access your R file without errors, but that's the way you could go
edit: just adding some sample code that should do the job, works from within the app - as said i'm unsure about your framework and the way you access r
R.layout layout = new R.layout();
Map<Integer, String> id2name = new HashMap<Integer, String>();
for (Field f : layout.getClass().getDeclaredFields()) {
try {
id2name.put(f.getInt(layout), f.getName());
Log.i("Layout", f.getInt(layout) + "," + f.getName());
}
catch (IllegalArgumentException e) {
//oops
Log.e("Layout", "", e);
}
catch (IllegalAccessException e) {
//oops
Log.e("Layout", "", e);
}
}
for (Entry<Integer, String> e:id2name.entrySet()) {
if (findViewById(e.getKey()) != null) {
Log.i("Layout:", "found: " + e.getValue() + ";" + e.getKey());
}else {
Log.i("Layout:", "not found: " + e.getValue()+ ";" + e.getKey());
}
}
note that there will be no view found unless layouting is done (findViewById() is null if you call to early)
of course you can go the other way around and search down the view tree by checking if a layout is instance of a ViewGroup and iterate over its childviews and compare each's id to the ids in the map
Related
I have a large Android codebase and I am writing a custom lint rule that checks whether the values of certain attributes fall within a given range.
For example, I have this component:
<MyCustomComponent
my:animation_factor="0.7"
...>
</MyCustomComponent>
and I want to write a lint rule that alerts developers that values of my:animation_factor >= 1 should be used with caution.
I followed the instructions at http://tools.android.com/tips/lint-custom-rules and managed to retrieve the value of my:animation_factor using this code:
import com.android.tools.lint.detector.api.*;
public class XmlInterpolatorFactorTooHighDetector {
....
#Override
public Collection<String> getApplicableElements() {
return ImmutableList.of("MyCustomComponent");
}
#Override
public void visitElement(XmlContext context, Element element) {
String factor = element.getAttribute("my:animation_factor");
...
if (value.startsWith("#dimen/")) {
// How do I resolve #dimen/xyz to 1.85?
} else {
String value = Float.parseFloat(factor);
}
}
}
This code works fine when attributes such as my:animation_factor have literal values (e.g. 0.7).
However, when the attribute value is a resources (e.g. #dimen/standard_anim_factor) then element.getAttribute(...) returns the string value of the attribute instead of the actual resolved value.
For example, when I have a MyCustomComponent that looks like this:
<MyCustomComponent
my:animation_factor="#dimen/standard_anim_factory"
...>
</MyCustomComponent>
and #dimen/standard_anim_factor is defined elsewhere:
<dimen name="standard_anim_factor">1.85</dimen>
then the string factor becomes "#dimen/standard_anim_factor" instead of "1.85".
Is there a way to resolve "#dimen/standard_anim_factor" to the actual value of resource (i.e. "1.85") while processing the MyCustomComponent element?
The general problem with the resolution of values is, that they depend on the Android runtime context you are in. There might be several values folders with different concrete values for your key #dimen/standard_anim_factory, so just that you are aware of.
Nevertheless, AFAIK there exist two options:
Perform a two phase detection:
Phase 1: Scan your resources
Scan for your attribute and put it in a list (instead of evaluating it immediately)
Scan your dimension values and put them in a list as well
Phase 2:
override Detector.afterProjectCheck and resolve your attributes by iterating over the two lists filled within phase 1
usually the LintUtils class [1] is a perfect spot for that stuff but unfortunately there is no method which resolves dimensions values. However, there is a method called getStyleAttributes which demonstrates how to resolve resource values. So you could write your own convenient method to resolve dimension values:
private int resolveDimensionValue(String name, Context context){
LintClient client = context.getDriver().getClient();
LintProject project = context.getDriver().getProject();
AbstractResourceRepository resources = client.getProjectResources(project, true);
return Integer.valueOf(resources.getResourceItem(ResourceType.DIMEN, name).get(0).getResourceValue(false).getValue());
}
Note: I haven't tested the above code yet. So please see it as theoretical advice :-)
https://android.googlesource.com/platform/tools/base/+/master/lint/libs/lint-api/src/main/java/com/android/tools/lint/detector/api/LintUtils.java
Just one more slight advice for your custom Lint rule code, since you are only interested in the attribute:
Instead of doing something like this in visitElement:
String factor = element.getAttribute("my:animation_factor");
...you may want to do something like this:
#Override
public Collection<String> getApplicableAttributes() {
return ImmutableList.of("my:animation_factor");
}
#Override
void visitAttribute(#NonNull XmlContext context, #NonNull Attr attribute){
...
}
But it's just a matter of preference :-)
I believe you're looking looking for getResources().getDimension().
Source: http://developer.android.com/reference/android/content/res/Resources.html#getDimension%28int%29
Assuming xml node after parsing your data, try the following
Element element = null; //It is your root node.
NamedNodeMap attrib = (NamedNodeMap) element;
int numAttrs = attrib.getLength ();
for (int i = 0; i < numAttrs; i++) {
Attr attr = (Attr) attrib.item (i);
String attrName = attr.getNodeName ();
String attrValue = attr.getNodeValue ();
System.out.println ("Found attribute: " + attrName + " with value: " + attrValue);
}
I'm trying to finish the 'backbone' of my app in the next 3 weeks, however, one of the few obstacles I stutter at is saving data. I've had a look at saving data internally, but there is limited tutorials from what I can find of reading and writing multiple lines to files in the apps cache directory.
Basically what I'm trying to do is save the values stored inside a fragment. This fragment resets all its values when the user clicks a button and changes text to match a page number. (A number of duplicates that contain various values.) I would do multiple fragments, however, thought it would be beneficial to use just one fragment to minimize storage space needed.
I've only got round to writing to the files, and created two methods to manage this which are then called on the click of a button. One creates these files and the other writes to them. Unfortunately I'm inexperienced using adb and could only find that the files are created, but don't know if they are being correctly written to. Is there any chance someone could review this and possibly assist with re-reading the files? Help is much appreciated.
The two methods (Warning: A great number of lines ahead):
public void createEmptyFiles() {
try {
outputTempExerciseFileE1 = File.createTempFile("temp_exercise_1",
".txt", outputTempExerciseDir);
outputTempExerciseFileE2 = File.createTempFile("temp_exercise_2",
".txt", outputTempExerciseDir);
outputTempExerciseFileE3 = File.createTempFile("temp_exercise_3",
".txt", outputTempExerciseDir);
} catch (IOException e) {
e.printStackTrace();
Log.w("rscReporter", "Encountered an error when creating empty files!");
}
}
public void writeTemporaryFiles() {
try {
if (counterAnotherExercise == 1) {
writerTemp = new FileWriter(outputTempExerciseFileE1);
writerTemp
.write(editTextExerciseName.getText().toString() + "\n"
+ counterNoSets + "\n" + counterRepsPerSet
+ "\n" + counterMeanRepTime + "\n"
+ counterMeanRepTimeRefined + "\n"
+ counterSetInterval);
writerTemp.close();
} else if (counterAnotherExercise == 2) {
writerTemp = new FileWriter(outputTempExerciseFileE2);
writerTemp
.write(editTextExerciseName.getText().toString() + "\n"
+ counterNoSets + "\n" + counterRepsPerSet
+ "\n" + counterMeanRepTime + "\n"
+ counterMeanRepTimeRefined + "\n"
+ counterSetInterval);
writerTemp.close();
} else if (counterAnotherExercise == 3) {
writerTemp = new FileWriter(outputTempExerciseFileE3);
writerTemp
.write(editTextExerciseName.getText().toString() + "\n"
+ counterNoSets + "\n" + counterRepsPerSet
+ "\n" + counterMeanRepTime + "\n"
+ counterMeanRepTimeRefined + "\n"
+ counterSetInterval);
writerTemp.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Any of the text files should look like:
editTextExerciseName
counterNoSets
counterRepsPerSet
counterMeanRepTime
counterMeanRepTimeRefined
counterSetInterval
Where the two methods are called:
// In a switch statement as there are around 15 buttons
case R.id.button_another_exercise_foreground:
// Increases page number in fragment
counterAnotherExercise++;
// This then checks the page number and changes text
checkPageNo();
// Writing to files is called, files were created in onCreateView()
writeTemporaryFiles();
// Resets all the counters, giving the imitation it is a completely new fragment
counterReset();
// default array exercise is then set to the page number which is then displayed as title
// For example: Exercise 1, Exercise 2, Exercise 3...
textViewExerciseTitle.setText(defaultArrayExercise);
break;
I only know the basics of Java and Android, for myself this is ambitious, however, you gotta learn somewhere! Additional suggestion for saving values are welcomed.
You don't really need files as you are only writing and then reading a handful of fixed data. Use SharedPreferences like this:
to write:
PreferenceManager.getDefaultSharedPreferences(YourActivity.this).edit().putString("editTextExerciseName", "my exercise").commit();
to read:|
PreferenceManager.getDefaultSharedPreferences(YourActivity.this).getString("editTextExerciseName");
I need help with this function.
I know that the if statement recognizes my input because it affects the program elsewhere, but I'm not sure what's going on because this particular Log doesn't display anything even in adb logcat.
Other Log statements in the same class file that this function is from display just fine, and the value update does seem to be changing ("show all" blanks it for some reason but I can figure that out after I get the log to work.)
I am unsure how to search for this problem because it is very specific and I have no idea what causes it (probably something simple that I didn't think of, though.)
void command(String input)
{
//do stuff here
//update = whatever
if(input.equalsIgnoreCase("show all"))
{
update=printAllRooms();
Log.i(input, update);
}
else update=input; //just for testing, will delete later
}
the printAllRooms function:
public String printAllRooms() //for debug purposes
{
String result = "";
for (Iterator<Room> iterator = rooms.iterator(); iterator.hasNext();) {
Room current = iterator.next();
result = result + current.toString()+"\n";
Log.i("printallrooms", current.toString());
}
return result;
}
A note on using Log.
The first argument sent to Log is typically a fixed string indicating the name of the class you are in.
So at the top of your class you might define:
private static final String TAG = "MyClassName";
Then you would use TAG for your log statements in that class.
Log.i(TAG, "My input was: " + input + " Update was: " + update;
To put it mildly, your function looks quite odd. Set a breakpoint at your Log statement, run the debugger and then inspect the variable value contained in update. Most likely, printAllRooms() is not doing what you think.
If the iterator doesn't work for you, try using the For-Each loop:
for (Room r : rooms) {
result = result + r.toString()+"\n";
Log.i("printallrooms", r.toString());
}
My app reads in large amounts of data from text files assets and displays them on-screen in a TextView. (The largest is ~450k.) I read the file in, line-by-line into a SpannableStringBuffer (since there is some metadata I remove, such as section names). This approach has worked without complaints in the two years that I've had the app on the market (over 7k active device installs), so I know that the code is reasonably correct.
However, I got a recent report from a user on a LG Lucid (LGE VS840 4G, Android 2.3.6) that the text is truncated. From log entries, my app only got 9,999 characters in the buffer. Is this a known issue with a SpannableStringBuffer? Are there other recommended ways to build a large Spannable buffer? Any suggested workarounds?
Other than keeping a separate expected length that I update each time I append to the SpannableStringBuilder, I don't even have a good way to detect the error, since the append interface returns the object, not an error!
My code that reads in the data is:
currentOffset = 0;
try {
InputStream is = getAssets().open(filename);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
ssb.clear();
jumpOffsets.clear();
ArrayList<String> sectionNamesList = new ArrayList<String>();
sectionOffsets.clear();
int offset = 0;
while (br.ready()) {
String s = br.readLine();
if (s.length() == 0) {
ssb.append("\n");
++offset;
} else if (s.charAt(0) == '\013') {
jumpOffsets.add(offset);
String name = s.substring(1);
if (name.length() > 0) {
sectionNamesList.add(name);
sectionOffsets.add(offset);
if (showSectionNames) {
ssb.append(name);
ssb.append("\n");
offset += name.length() + 1;
}
}
} else {
if (!showNikud) {
// Remove nikud based on Unicode character ranges
// Does not replace combined characters (\ufb20-\ufb4f)
// See
// http://en.wikipedia.org/wiki/Unicode_and_HTML_for_the_Hebrew_alphabet
s = s. replaceAll("[\u05b0-\u05c7]", "");
}
if (!showMeteg) {
// Remove meteg based on Unicode character ranges
// Does not replace combined characters (\ufb20-\ufb4f)
// See
// http://en.wikipedia.org/wiki/Unicode_and_HTML_for_the_Hebrew_alphabet
s = s.replaceAll("\u05bd", "");
}
ssb.append(s);
ssb.append("\n");
offset += s.length() + 1;
}
}
sectionNames = sectionNamesList.toArray(new String[0]);
currentFilename = filename;
Log.v(TAG, "ssb.length()=" + ssb.length() +
", daavenText.getText().length()=" +
daavenText.getText().length() +
", showNikud=" + showNikud +
", showMeteg=" + showMeteg +
", showSectionNames=" + showSectionNames +
", currentFilename=" + currentFilename
);
After looking over the interface, I plan to replace the showNikud and showMeteg cases with InputFilters.
Is this a known issue with a SpannableStringBuffer?
I see nothing in the source code to suggest a hard limit on the size of a SpannableStringBuffer. Given your experiences, my guess is that this is a problem particular to that device, due to a stupid decision by an engineer at the device manufacturer.
Any suggested workarounds?
If you are distributing through the Google Play Store, block this device in your console.
Or, don't use one massive TextView, but instead use several smaller TextView widgets in a ListView (so they can be recycled), perhaps one per paragraph. This should have the added benefit of reducing your memory footprint.
Or, generate HTML and display the content in a WebView.
After writing (and having the user run) a test app, it appears that his device has this arbitrary limit for SpannableStringBuilder, but not StringBuilder or StringBuffer. I tested a quick change to read into a StringBuilder and then create a SpannableString from the result. Unfortunately, that means that I can't create the spans until it is fully read in.
I have to consider using multiple TextView objects in a ListView, as well as using Html.FromHtml to see if that works better for my app's long term plans.
I am on the project RichTextEditor and completed almost all functionality. I can insert image and can save the file with image and also getting the image and all styles while opening the file again.I am stuck at one point ie. when copying all the content of the Edittext, while pasting except Image all things got paste, but in image area i got like this
any idea or workaround to copy and paste the image.
Thanks.
I have the same problem. After get the editText field's string, I find the "obj" character, and then replace it with image's link. I created a ArrayList to store the images' links. And moreover, I think I need to catch the delete action. If an image is deleted, I deleted its link in the image list. Below is the code I use to replace the "obj" character.
private String replaceSpecialCharactorFromNote(){
String noteString = edt_note.getText().toString();
char[] noteCharacters = noteString.toCharArray();
for(int i=0; i<noteCharacters.length; i++){
if((int)noteCharacters[i] <1 || (int)noteCharacters[i]>254 ){//compare the ascii code
Log.i("the first abnormal charactor is ", "" + noteCharacters[i]);
if(imageIndex < imgsList.size()){
Log.i("replace triggered", "special char index is "+i);
Log.i("replace triggered", "replaced image index is "+imageIndex);
Log.i("replace triggered", "image is "+imgsList.get(imageIndex));
String beforeString = noteString.substring(0, i);
String afterString = noteString.substring(i+1);
noteString = beforeString + imgsList.get(imageIndex) + afterString;
Log.i("replace triggered", "note is "+noteString);
}
imageIndex++;
}
}
return noteString;
}
Overall, I do not think the way I did is the best way to solve the problem. The best way probably will be to create a custom field to handle it.
Did you check the content on the clipboard? How is the image handled in the clipboard? You will have to make your RichTextView handle the paste operation (is the image copied as a bimap / are you referencing a path to the bitmap) from the clipboard.