unable to convert string resource name into resource [duplicate] - java

This question already has an answer here:
How to find resource id of a file located in /res/raw folder by its filename?
(1 answer)
Closed 2 years ago.
I have an array of strings (for sound file names) , and i have the exact files attached to the projects as resources (raw), i am trying to fetch the ID of these resources via code in order to change which file (resource) to be playing from within the code.
String[] phrasesDesc = {"doyouspeakenglish.m4a",
"goodevening.m4a",
"hello.m4a",
"howareyou.m4a",
"ilivein.m4a",
"mynameis.m4a",
"please.m4a",
"welcome.m4a"
};
int index = 0;
for (String str : phrasesDesc) {
String res_name =phrasesDesc[index] ;
resourceID[index] = this.getResources().getIdentifier(res_name, "raw", this.getPackageName());
System.out.println(res_name +" "+ resourceID[index]);
index++;
}
please help.
enter image description here

You need to query them without the file-type extension:
String[] phrasesDesc = {"doyouspeakenglish", "goodevening", "hello", "howareyou", "ilivein", "mynameis", "please", "welcome"};
or somehow strip the file-type extension, eg: res_name.replace(".m4a", "").

Related

Best way to validate and read files from a date wise folder in Java

I have to validate and read .txt files from a date wise folder. Need suggestions on best possible ways to achieve this
I will have a property file which will have following information
value active channel
5092 Y 11
5092 Y 12
5092 Y 13
5093 N 10
5093 N 11
from this property file first i need get active value(i.e. 5092) and their channel information i.e 11,12,13
based on the above information need to iterate files from a date wise folder.
Input(folder)
10JUN2017
HW_5092_ABC_11.txt
HW_5092_ABC_12.txt
HW_5092_ABC_13.txt
11JUN2017
HW_5092_ABC_11.txt
HW_5092_ABC_12.txt
Based on the property file information (i.e. 5092 is active file and it has channel 11,12,13) look for the current date folder i.e. 11JUN2017 then look for files of 5092. If 11JUN2017 has files related to 5092 (i.e. all 3 files 11,12 and 13) then need to read files from 11JUN2017 folder and process the files. Else need to go back to previous date then look for the files.
In the above example, 11JUN2017 does not have all the files so, i need to go back to previous date i.e. 10JUN2017 and look for the files if found then process it. If 10JUN2017 also does not have all files then go back to previous date (max no of days to traverse back is 43 days).
Update
There is some change in my requirement. There will not be date wise folder instead file name itself contains date in YYYYMMdd format and all files will be in single folder, for example, filename will be like as follows BIG_ABCHINE_MATERIAL_2092_11_20170614-150136-243.txt.
So below is what I am trying
public void fileLoadingProcess() {
//Reading text file which contains all the information
in = new BufferedReader(new FileReader("C:\\OrgDetails.txt"));
in.readLine();
String str;
while ((str = in.readLine()) != null) {
values = str.split("\t");
//Adding config property values to Map
if (values[5].equalsIgnoreCase("Y")) {
System.out.println("Active sales org " + values[0]);
if (distChannelMap.containsKey(values[0])) {
list = distChannelMap.get(values[0]);
list.add(Integer.parseInt(values[6]));
} else {
list = new ArrayList<Integer>();
list.add(Integer.parseInt(values[6]));
distChannelMap.put(values[0], list);
}
} else {
System.out.println("Inactive Sales org " + values[0]);
}
}
Set set = distChannelMap.entrySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
Map.Entry mentry = (Map.Entry) iterator.next();
System.out.println("Key --> " + mentry.getKey() + " Value(s) -->" + mentry.getValue());
//Calling this method to check file needs to be processed based on active and inactive states
isFileNeedsToBeProcessed(mentry.getKey().toString(), (ArrayList<Integer>) mentry.getValue());
}
//Check whether this file is exists or not
//
}
public void isFileNeedsToBeProcessed(String salesOrg, ArrayList<Integer> distChannel) {
System.out.println("Previous Day " + new TxtToXMLCommon().previousDate(1));
//String previousDate = new TxtToXMLCommon().getCurrentDate();
for (int i = 0; i < distChannel.size(); i++) {
int x =1;
previousDate = new TxtToXMLCommon().previousDate(x);
System.out.println("Distribution channel " + distChannel.get(i));
File folder = new File(Constants.INPUT_FOLDER);
File[] files = folder.listFiles();
if (files.length == 0) {
_logger.info("***No files present to process***");
return;
} else {
for (int k = 0; k < files.length; k++) {
if (files[k].getName().contains("MATERIAL")) {
if (salesOrg.equalsIgnoreCase(files[k].getName().substring(21, 25))
&& (distChannel.get(i) == Integer.parseInt(files[k].getName().substring(26, 28)))&&
previousDate.equalsIgnoreCase(files[k].getName().substring(29, 37))) {
System.out.println("File present to process " + files[k].getName());
break;
// if () {
// //processingFilesMap.put("MATERIAL", files[k].getName());
// System.out.println("File present to process " + files[k].getName());
// }else{
//
// }
}else{
//previousDate = new TxtToXMLCommon().previousDate(x+1);
}
//previousDate = new TxtToXMLCommon().previousDate(2);
}//end of if(MATERIAL)
}// end of files length
}
}
}
But I am little bit stuck here while finding for the file in a folder(single source folder). Say, as you see, I have put the property file information in the distChannelMap and then for each value I am iterating source folder and trying to find the file which contains org value values[0] and key values[6] which I have stored in arraylist. because for one value 5092 there are 3 channel.
Now if I do not find file matching org value (5092), channel (11) and date (20170615), I need to iterate the folder again with date-1 means value 5092, channel 11 and date 20170614 like this till 43 days. once i found the file I am thinking to put it into map so that I have all files which are ready to process. But I am little bit stuck in going to previous date when i do not the file for particular channel. once this channel is find, I need to do the same process for other channels like 12 and 13 for the org 5092.
I think it’s simplest to take one channel at a time.
Construct the file name from active value and channel number, for example
String.format("HW_%d_ABC_%d.txt", activeValue, channel)
Use LocalDate for the folder names.
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("ddMMMuuuu", Locale.ENGLISH);
LocalDate date = LocalDate.now(ZoneId.systemDefault());
String folderName = date.format(dateFormatter).toUpperCase(Locale.ROOT);
Think twice about the time zone to use. ZoneId.systemDefault() will give you the JVM’s current setting, it may not be what you need. I am typing this on June 10th and understand that in your time zone it’s already June 11th. Would be a pity to miss today’s files because of incorrect time zone.
In a loop, look for the file in the folder. If found, exit the loop. If not found, do
date = date.minusDays(1);
folderName = date.format(dateFormatter).toUpperCase(Locale.ROOT);
This will give you the folder name of the previous day’s folder. Then look there.
This will work across the beginning of the month and the beginning of the year. For the limit of looking 43 days back, either use a counter or set
LocalDate limit = date.minusDays(43);
and then give up when date.isBefore(limit).
Edit If you want to start from the folders and files, look into Files.newDirectoryStream(Path, String). You may use it first to find the folders of this month and the previous two months (that should cover 43 days and more), maybe filter and sort them. Next for each folder you can use the same method to determine which files are present. You will have a challenge keeping track of which files are present in more than one folder and which one is the newest, it can be solved. I am not immediately convinced about the advantage of this approach, but I trust you to make a good decision for yourself.

How can I get parameters from URL in Android? [duplicate]

This question already has answers here:
How to parse or split URL Address in Java?
(4 answers)
Closed 6 years ago.
I have a URL like this:
http://www.chalklit.in/post.html?chapter=V-Maths-Addition%20&%20Subtraction&post=394
How to get the value of parameter of chapter and post?
My URL contains '&' in the value of chapter parameter.
You can use the Uri class in Android to do this; https://developer.android.com/reference/android/net/Uri.html
Uri uri = Uri.parse("http://www.chalklit.in/post.html?chapter=V-Maths-Addition%20&%20Subtraction&post=394");
String server = uri.getAuthority();
String path = uri.getPath();
String protocol = uri.getScheme();
Set<String> args = uri.getQueryParameterNames();
Then you can even get a specific element from the query parameters as such;
String chapter = uri.getQueryParameter("chapter"); //will return "V-Maths-Addition "

Extract project name from URL

I have URL
../p/xmlProj/bugs/...
I'm looking for a way to extract the project name into single variable using java code
I tried this
String url = "/p/xmlProject/bugs/";
final String[] projName = url.split("/",3);
But i didn't work for me !!
You don't need this 3 there. Simply write:
final String[] projName = url.split("/");
And the project name will be projName[3].

How to get domain of example.co.ir in java [duplicate]

This question already has answers here:
Parsing result of URL.getHost()
(2 answers)
Closed 8 years ago.
I need to parse url in my java code and get the domain. I wrote the following code:
static String domain(URL url) {
String host = url.getHost();
int i = host.lastIndexOf('.');
if(i == -1){
return "Not domain";
}
if (i ==0 ){
return "Not domain";
}
String domain;
i = host.lastIndexOf('.', i - 1);
if (i == -1) {
domain = host;
}
else {
domain = host.substring(i + 1, host.length());
}
}
This code parses domains like example.com
But how can my code parse domains like exmaple.co.ir , subdomains.example.co.ir and the others extensions like co.uk, org.ir and so on.
EDIT
my url is http//blog.example.co.ir/index.php or http//blog.example.co.uk/something.html
my goal is to print:
example.co.ir and example.co.uk
The problem is that your parsing code is limited to domains with just one dot. You can use regular expressions or recursive parsing to solve this problem. This is one way of approaching this problem.
I believe this work for any kind of URL(in correct URL format)
domain= host.split("/")[2];
Note:
split("/") will create an array from the String, for example:
String host="http//blog.example.co.ir/index.php";
host.split("/") will give you array of String: [http, ,blog.example.co.ir, index.php]
And your desired output is at index 2

Convert an int-value to a resource uri

i have implemented an android-project which plays a random song. So i have an int-array like this:
int [] playlist_stadt = {R.raw.black_a, R.raw.black_b, R.raw.black_c};
for the random play i wrote:
Random r = new Random();
int i = playlist_stadt[r.nextInt(playlist_stadt.length)];
PlayMusic(i);
what i dont understand is following:
textView.setText(i);
textview shows: res/raw/black_c.mp3
Log.e("Output: ", "" + i);
String uriPath = "android.resource://" + getPackageName() + i;
in the log is i an number and not the same string how in the textview:
Output: 2130968577
203-06 13:09:23.680: E/Output:(31456): android.resource://com.example.testproject2130968577
can s.o. explain me this and how to convert the int-value, that i use it as an resource uri path?
thanks in advance and sry for my english
getResources().getResourceEntryName(i) should get you the mp3 name you are looking for.
i is the resource ID generated by aapt in gen/R.java
Android Accessing Resources Doc
The reason textView.setText(i) returns the mp3 resource name is because you are actually calling setText(int resId)
setText(int resId) JavaDoc
You are passing an int parameter which Android interprets as a resource ID and does the getResourceEntryName conversion for you.
Try using "valueOf(i)", otherwise it will try to look up the location of i and not use the value of i.

Categories

Resources