How to sort files in assets folder? - java

Here are faced with the problem of sorting files. Choose the files from the folder Asset. How to sort files in ascending?
Here is my code:
//fillGrid
private void fillGridAdapter(int cat) {
ASSETS_IMAGE_DIR = imagePath[cat];
addImages(getImages(imagePath[cat]));
}
//Adds the files
private void addImages(String[] temp){
imBitmap = new Bitmap[temp.length];
if(temp != null) {
for(int i = 0; i < temp.length; i++){
try {
imBitmap[i] = getBitmapFromAsset(imagePath[g.getImageCat()]+"/"+temp[i]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private String[] getImages(String f){
try {
AssetManager assetManager = getResources().getAssets();
String[] temp = assetManager.list(f);
Arrays.sort(temp);
return temp;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
After assetManager.list(f) String[] temp - (1.jpg, 10.jpg, 12.jpg ... 9.jpg). After Arrays.sort(temp) - (1.jpg, 10.jpg, 12.jpg ... 9.jpg). And I need to - 1.jpg, 2.jpg, 3.jpg... n.jpg.

Use Arrays.sort(T[] a, Comparator c)
Here's an example http://www.coderanch.com/t/378718/java/java/sort-array-files-directories

It sounds like you want to sort the files into numeric order ... not lexical order.
To achieve this, you will need to split the pathnames into a numeric and non-numeric segments. For the numeric segment(s) you need to parse the segment as an integer and sort based on the integer values.
It looks like your files are of the form <number>.<suffix>, so the splitting should be simple.
This logic needs to be implemented in the compare method of a Comparator which you provides a parameter to sort.

Related

Hbase Long Comparison Filter using Java Api

I am unable to compare a Long value in one of the column values of my HBase table. I am using java api. Below is the code snippet.I clearly have a value in the table which satisfies the filter.
I would also like to know what is lexicographical comparison and how would I perform long comparison.
Any direction on this greatly helpful.
Thanks in advance
FilterList list = new FilterList(FilterList.Operator.MUST_PASS_ALL);
SingleColumnValueFilter fil = new SingleColumnValueFilter(CF1_BYTE, VALUE_BYTE, CompareOp.LESS,new BinaryComparator(Bytes.toBytes(50)));
Scan scan = new Scan();
scan.addColumn(Bytes.toBytes("C1"),Bytes.toBytes("VALUE"));
list.addFilter(fil);
scan.setFilter(list);
try {
ResultScanner scanner = table.getScanner(scan);
for(Result r : scanner){
String VAL = Bytes.toString(r.getValue(Bytes.toBytes("C1"),Bytes.toBytes("VALUE")));
count ++;
if(count == 1000){
break;
}
System.out.println(count +" "+Bytes.toString(r.getRow()) + " "+VAL );
}
scanner.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
table.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
According to doc, you have to provide your own comparator which will deserialize Long values from Byte arrays. As I know default comparison is lexicographical. Regarding lexicographical comparison, you can find this post useful. And this post provide a clue how you can write the corresponding comparator.
Update:
import java.util.Comparator
import org.apache.hadoop.hbase.util.Bytes
class LongComparator implements Comparator<byte[]> {
public int compare(byte[] left, byte[] right) {
long leftLong = Bytes.toLong(left);
long rightLong = Bytes.toLong(right);
return Long.compare(leftLong, rightLong);
}
}
I suggest using HBase utils instead of guava since it may conflict with HBase guava dependencies.

How get path to file from List<File> and put to the another list

EDIT
It's my list with values from List listQuestion now i need to add pathFile like extra value to this list.
My code look like this
private static List<String> listQuestionE(Scanner sc, List<File> listQuestion){
//List with value from List<File> listQuestion ( its some value from .log files it doesn't matter
List<String> question = new ArrayList<String>();
//I think that I need to do something with File input1 but i try several things and it doesnt work for me.
for(File input1 : listaQuestion){
try {
sc = new Scanner(input1);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while(sc.hasNextLine()){
s = new Scanner(sc.nextLine());
while(s.hasNext()){
String words = s.nextLine();
if(!getTagValues(words).isEmpty() ){
try {
question.add(getTagValues(words).toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
return question;
}
And i don't know where i need to add code to get path and alse if i use .getAbsolutePath befor i got list like this
[value from log],[Path] or worst [],[Path] because sometimes log haven't error so answer is empty.
If you are trying to determine the file path from File object, using Java 7 nio you can do that.
file.getAbsolutePath() // where file is a reference to File object
Returns the absolute pathname string of this abstract pathname.
private static List<String> listQuestionE(Scanner sc, List<File> listQuestion){
List<String> question = new ArrayList<String>();
for(File input1 : listQuestion){
try {
String fPath = input1.getAbsolutePath();
sc = new Scanner(input1);
question.add(fPath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
return question;
}

ComboBox adds all the values together as one value

I'm making an application at the moment and now I need to fill a comboBox with all the values that I get from another class in an arrayList type.
This is the code that I use to fill my combobox:
public void setComboBox(){
MessageConsole mc = new MessageConsole(textArea);
//The redirectOut will redirect the text from the System.out.prtnln to the text area.
mc.redirectOut();
List<String> arrayList = new ArrayList<String>();
if(gf.loadCombo("config") != null){
arrayList.addAll(gf.loadCombo("config"));
for (int i = 0; i < arrayList.size(); i++) {
String s = arrayList.get(i);
configName.removeItem(s);
configName.addItem(s);
}
}
}
This is the code from the other class:
public Collection<String> loadCombo(String property) {
//Check if the property file is present in the given directory.
if(cf.checkProperty()==true){
//Check is there are any properties saved in the property file.
if(cf.getProperty() != null){
Properties prop = new Properties();
FileInputStream fis;
try {
fis = new FileInputStream("config.properties");
prop.load(fis);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Check if the properties match with the entered configuration.
List<String> arrayList = new ArrayList<String>();
arrayList.addAll(cf.getProperty());
Collection<String> propertyList = new ArrayList<String>();
for (int i = 0; i < arrayList.size(); i++) {
String s = arrayList.get(i);
if(s.startsWith(property)){
System.out.println("This value has been added to the arrayList from the other class: "+s);
propertyList.add(cf.getPropertyValue(s));
}
}
return propertyList;
}
//The system prints a message of the missing properties.
else{
System.out.println("You need to save a configuration first.");
}
}
//The system prints a message of the missing property file.
else{
System.out.println("The property file is either missing or could not be found. in de Load class");
}
return null;
}
Following is a screenshot of the result:
As you can see all the values are added as 1 long String"[3, 2, 1]" in the comboBox. Could anyone tell me why this happens?
Thanks in advance,
Lordarnoud
P.S. I hope this is the correct way to ask my question and I hope my question is clear enough for everyone to understand.
At a first look it appears the problem could be one of two things:
The value "[3 2 1]" is returned from the loadCombo method. More specifically from the cf.getProperty(). It is not clear from the context provided what cf is.
The value "[3 2 1]" was added to your combobox at some other point in you code. If this might be case, try using configName.removeAllItems() instead of removing then adding each item in your collection.
Additionally in your loadCombo method you load the config.properties file into a Properties object and then do nothing with it. It seems your intentions were to load the config properties from that file instead of the cf object.

String comparison issue

I'm trying to do something reallllly simple that apparently is extremely difficult in android.
I just want to compare two strings to see if they are equal.
I have a temp variable with the value "Location"
I have debugged this and it does indeed contain Location...
So I tried this at first
if(temp == "Location") { //do something }
But I already know that doesn't work. I then tried all the possible functions for a string such as:
.equals
.contains
.ignoreCaseEquals
etc...
If anyone has any idea what to do please help. This is really getting annoying.
EDIT:
Here is the function where I'm comparing the strings for those of you who want to see.
public String[] getData(){
try {
int tempGroupCount = 0;
URL food_url = new URL (Constants.SERVER_DINING);
BufferedReader my_buffer = new BufferedReader(new InputStreamReader(food_url.openStream()));
temp = my_buffer.readLine();
// prime read
while (temp != null ){
// check to see if readline equals Location
Log.w("HERasdfsafdsafdsafE", temp);
// start a new location
if (temp.equals("Location")
{
groups[tempGroupCount] = temp;
tempGroupCount++;
}
Log.w("HERasdfsafdsafdsafE", temp);
//start for-loop to test to get child info
//for(temp = my_buffer.readLine(); temp != "Location" && temp != null; groupCount++, childrenCount++){
//children[groupCount][childrenCount] = temp;
//}
temp = my_buffer.readLine();
}
my_buffer.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("IO EXCEPTION", "Exception occured in MyExpandableListAdapter:" + e.toString());
}
return groups;
}
equals does work. If temp.equals("Location") returns false, then your temp variable does not refer to a string with the value "Location".
There may be unprintable characters or other oddities about the string - I suggest you look at the length of the string to check. Alternatively, there can be other characters which look like the ASCII characters, but aren't. In the debugger, try examining the array and get at the underlying char array - check the Unicode value of each character.
if(temp.equals("Location"))
{
//your code here
}
does not work
try this
if(temp.contains("Location"))
{
//your code here
}
try like
if(temp.equals("Location")) { //do something }
and
while (!temp.equals("")){
if your variable temp is a String, you can also used the method compareTo(String).
if (temp.compareTo("Location") == 0)
{
//do something
}
I am doing same scenario , its working fine.
String result = responsePrimitiveData.toString();
if(!result.equals("0")){
}
Try doing this:
if (temp.toLowerCase().compareTo("location") == 0)
public String[] getData(){
try {
int tempGroupCount = 0;
URL food_url = new URL (Constants.SERVER_DINING);
BufferedReader my_buffer = new BufferedReader(new InputStreamReader(food_url.openStream()));
temp = my_buffer.readLine();
// prime read
while (temp != null ){
// check to see if readline equals Location
Log.w("HERasdfsafdsafdsafE", temp);
// start a new location
if (temp.toString().equalsIgnoreCase("Location")
{
groups[tempGroupCount] = temp;
tempGroupCount++;
}
Log.w("HERasdfsafdsafdsafE", temp);
//start for-loop to test to get child info
//for(temp = my_buffer.readLine(); temp != "Location" && temp != null; groupCount++, childrenCount++){
//children[groupCount][childrenCount] = temp;
//}
temp = my_buffer.readLine();
}
my_buffer.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("IO EXCEPTION", "Exception occured in MyExpandableListAdapter:" + e.toString());
}
return groups;
}
first try to convert "temp" into string then compare it, apply this may helps you
you may try the following to find out where your problem is.
final String LOCATION = "Location"; // just to make sure we use the very same character sequence
if (temp.equals(LOCATION)
{
/* your code here */
}
else
{
System.out.println("Location : " + Arrays.toString(LOCATION.getBytes(Charset.forName("UTF-8"))));
System.out.println("temp : " + Arrays.toString(temp.getBytes(Charset.forName("UTF-8"))));
}
This should print the byte representation of both Strings to standard out. If equals() returns false, the strings differ. Because of unprintable characters or similar looking characters it's sometimes difficult to find the difference. But the byte representation should show you.
(I'm not an android programmer, so I hope the functions exist on android JVM. And sorry for any typos and missing brackets - if any ;-)

Java: Try-Catch-Continue?

Let's say I can a set of statements:
try {
String a = getProperty("a");
String b = getProperty("b");
String c = getProperty("c");
} catch(Exception e) {
}
Now, lets say property b was not found and the function throws an exception. In this case, how would I just continue or perhaps set b to null without having to write a try-catch block for each property? I mean, a,b,c exist but sometime they might not be found at all during which an exception is thrown.
Assuming you can't change the function so that it returns null when the property isn't found, you are kind of stuck wrapping everything in its own try catch block -- especially if you want for every value that can be retrieved to be retrieved (as opposed to letting the first value that fails cancel the whole operation.)
If you have a lot of these properties to retrieve, perhaps it would be cleaner to write a helper method to use:
String getPropertySafely(String key) {
try {
return getProperty(key);
} catch (Exception e) {
return null;
}
}
You have to put a try-catch around each statement. There is no continue (like there is in ON ERROR ... RESUME blocks in VB). Instead of:
String a = null;
try {
a = getProperty("a");
} catch(Exception e) {
...
}
String b = null;
try {
b = getProperty("b");
} catch(Exception e) {
...
}
String c = null;
try {
c = getProperty("c");
} catch(Exception e) {
...
}
you could write:
public String getPropertyNoException(String name) {
try {
return getProperty(name);
} catch (Exception e) {
return null;
}
}
Personally I think a getProperty() is a poor candidate for throwing exceptions just for all this extra boilerplate required
Since you are using the same function each time you might be able to put this in a loop:
String[] abc = new String[3];
String[] param = {"a", "b", "c"};
for (int i = 0; i < 3; i++) {
try {
abc[i] = getProperty(param[i]);
} catch(Exception e) {
}
}
but this is rather contrived and would only be useful for a large number of properties. I suspect you will have to simple write 3 try-catch.
You should reconsider how getProperty is handled if you plan to use many of them because there isn't a plain way to do it.
You can exploit finally statement but you still need a try-catch for every call.

Categories

Resources