hay everyone;
I'm having problem displaying image url from java file (Connection), that use Jsoup library to extract the urls and assign them to ArrayList of type String.
public class Connection {
ArrayList<String> StringArray = new ArrayList<String>();
private String fileExtension = "jpg";
private String html = "http://mcs.une.edu.au/~salmutai/cameras";
private int count = 0;
public void UrlExtract() throws Exception {
Document doc = Jsoup.connect(html).get();
Elements castURL = doc.select("a");
for (Element el : castURL) {
String src = el.absUrl("href");
String extension = src.substring(src.lastIndexOf(".") + 1,
src.length());
if (extension.equalsIgnoreCase(fileExtension)) {
StringArray.add(src);
count++;
}
}
}
public int getCount() throws Exception {
return count;
}
public String ImgArray(int i) throws Exception {
String[] StrArray = new String[count];
StrArray = (String[]) StringArray.toArray(StrArray);
return StrArray[i];
}
}
how can I use Toast to show exact url and the count of images.
also, i'm using GridView to display all the images in order.
the pervious code is working in Java Application, but it doesn't work in Android app
Regarding the problem as to why your parsing code doesn't work when running from android, I can only assume that the html retrieved might be different, but that is only a guess. You need to debug the code when running it from you android. A solution might be to output the retrieved html to a log file and see if there is a difference.
Regarding showing your message using Toast:
String text = "Found " + StringArray.size() + " images at the url: " + html;
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
NOTE: you don't need to increment the count variable, you can just see how big the StringArray list is, by calling StringArray.size()
the main problem now is when I call this code in Activity 2:
try {
Connection co = new Connection();
co.UrlExtract();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
the app is crashing :(.
Related
I am trying to get a value from the first line of a csv file ( header excluded) store in Firebase Storage
Here is the code :
private String readFromCsv() {
StorageReference refCompteActifs = FirebaseStorage.getInstance().getReference().child("my_file").child("my_file.csv");
StorageReference gsReference = refCompteActifs.getStorage().getReferenceFromUrl("gs://test-8095e.appspot.com/my_file/my_filer.csv");
File localFile = null;
try {
localFile = File.createTempFile("my_file", ".csv");
} catch (IOException e) {
e.printStackTrace();
}
File finalLocalFile = localFile;
final String[] result = {null};
List<String> rows = new ArrayList<>();
gsReference.getFile(Objects.requireNonNull(localFile)).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
try {
CSVReader reader = new CSVReader(new FileReader("./data/user/0/com.example.test/cache/" + finalLocalFile.getName()), ',', '\'', 1);
String[] nextLine = null;
while ((nextLine = reader.readNext()) != null) {
System.out.println(nextLine[4] + "\n");
rows.add(nextLine[4]);
}
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 0; i < rows.size(); i++) {
result[0] = rows.get(i);
}
}
}
System.out.println(result[0] + "\n");
return result[0];
}
The console never write "System.out.println(result[0] + "\n");" result[0] is affected inside the onlistener but I can't access it outside of it.
Thank you for your Help
That is the expected behavior. The getFile API is an asynchronous operation, which means that it executes in the background while the rest of your code continues to run. Then when the operation is complete, your onSuccess is called with the result.
This is easiest to see if you add some logging:
Log.i("File", "1. Starting to load file");
gsReference.getFile(Objects.requireNonNull(localFile)).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Log.i("File", "2. Loaded file");
}
}
Log.i("File", "3. Started to load file");
If you run this code it outputs:
Starting to load file
Started to load file
Loaded file
This is probably not what you expected, but it is working by design - and it does completely explain why your System.out.println(result[0] + "\n"); doesn't show the file contents: the file hasn't been loaded yet.
This is an incredibly common problem, as most I/O and network APIs are asynchronous these days. The solution is always the same: any code that needs the data that is asynchronously loaded has to be inside the onSuccess handler, be called from there, or otherwise synchronized.
This means for example that you can't return the value from the file, as the return runs before the load has completed, and you'll instead want to pass a callback to your readFromCsv function, very similar to the OnSuccessListener.
For more on this, I recommend reading:
getContactsFromFirebase() method return an empty list
Setting Singleton property value in Firebase Listener
more questions on losing the asynchronous value outside of a callback
I am trying to read a text file which contains strings (separated by commas) of airport information. However, when I try to read the file, it throws and IOException. Here is the code:
public ArrayList<ArrayList<String>> createAirportLibrary() {
ArrayList<ArrayList<String>> airportLibrary = new ArrayList<>();
String[] line;
BufferedReader reader = null;
try {
// import the text file
File airportsFile = new File("C:\\Users\\cjkei\\AndroidStudioProjects\\TravelTime\\app\\libs\\airports.txt");
// read the first line of the file
reader = new BufferedReader(new FileReader(airportsFile));
line = reader.readLine().split(",");
// loop through each line of file and add each airport to the library
while (line != null) {
int i = 0;
ArrayList<String> thisAirport = new ArrayList<>();
while (i < line.length){
if (line[i] instanceof String){
thisAirport.add(line[i]);
}
else {
airportLibrary.add(thisAirport);
thisAirport.clear();
}
i++;
}
line = reader.readLine().split(",");
}
}
catch (IOException e) {
Context context = this;
String text = "error reading file";
int duration = Toast.LENGTH_SHORT;
Toast.makeText(context, text, duration).show();
}
finally {
try {
if (reader != null) {
reader.close();
}
}
catch (IOException e) {
Context context = this;
String text = "could not close reader";
int duration = Toast.LENGTH_SHORT;
Toast.makeText(context, text, duration).show();
}
}
return airportLibrary;
}
I tried to debug step by step, but right after the onCreate call, it shows
this.
You might want to try the function Files.lines. It returns a Stream<String> you can then iterate over the stream.
Stream<String> stream = Files.lines(Paths.get(fileName))
stream.forEach(this::doSomethingWithLine);
private void doSomethingWithLine(String line) {
// actually do something
}
The picture you added does not show any exception information, but it does make clear where the error is coming from:
You are confusing two environments, and trying to open a file that does not exist.
The code in your example is for an Android app, but the file path is for a file on a Windows PC.
There is no "C drive" on Android devices, and you can not have Android code read a file from your PC, even if you run it on an emulator running on said PC.
If you look carefully at the full exception message, you will see that the problem is "File not found".
To do this, you can do something like this:
Toast.makeText(context, "Exception: " + e.toString(), Toast.LENGTH_SHORT).show();
or batter yet, since you are on Android, use the logging utility:
Log.e("MY_APP", "Exception: " + e.toString());
e.printStackTrace();
If you want the file to be part of your app and read it on the Android device, put it under assets folder in your project and use:
context.getAssets().open("MyFile.txt");
https://developer.android.com/reference/android/content/res/Resources
i need a library to extract file's full name from it's URL(Direct Download Link). I want a powerful library. I use FileNameUtils from Apache commons, But this class does not support a lot of URLs.
I want a library which supports these Urls:
https://example.cdn.com/mp4/7/9/5/file_795f32460d111df334849ee8336e56ca.mp4?e=1535545105&h=4772d27a70cd9b1c665b712f62592c47&download=1
name : file_795f32460d111df334849ee8336e56ca.mp4
http://example.cdn.comr/post/93/3/Jozve-Kamele-arbi.abp.zip
name : Jozve-Kamele-arbi.abp.zip
http://cdl.example.com/?b=dl-software&f=Windows.8.1.Enterprise.x86.Aug.2018_n.part1.rar
name : dl-software&f=Windows.8.1.Enterprise.x86.Aug.2018_n.part1.rar
https://www.google.com/url?sa=t&source=web&rct=j&url=http://www.pdf995.com/samples/pdf.pdf&ved=2ahUKEwjV096X-ZHdAhVQzlkKHTpUBV4QFjAAegQIARAB&usg=AOvVaw3HFvAQ7GNf5QjsUo05ot-j
name: pdf.pdf
Can anyone help me? Thanks.
I apologize in advance if the grammar of my sentence is not correct. because I can't speak English well.
You could actually also try to solve this problem with regular expressions (like e.g (?i)([^=/&?]+\\.(" + EXTENSIONS + "))\\b), if you have a list of the files extensions you are interested in.
Here is an example of such a method which extracts a file from a URL:
private static final String EXTENSIONS = "ez|aw|atom|atomcat|atomsvc|ccxml|cdmia|cdmic|cdmid|cdmio|cdmiq|cu|davmount|dbk|dssc|xdssc|ecma|emma|epub|exi|pfr|gml|gpx|gxf|stk|ipfix|jar|ser|class|js|json|jsonml|lostxml|hqx|cpt|mads|mrc|mrcx|mathml|mbox|mscml|metalink|meta4|mets|mods|mp4s|mp4|mxf|oda|opf|ogx|omdoc|oxps|xer|pdf|pgp|prf|p10|p7s|p8|ac|cer|crl|pkipath|pki|pls|cww|pskcxml|rdf|rif|rnc|rl|rld|rs|gbr|mft|roa|rsd|rss|rtf|sbml|scq|scs|spq|spp|sdp|setpay|setreg|shf|rq|srx|gram|grxml|sru|ssdl|ssml|tfi|tsd|plb|psb|pvb|tcap|pwn|aso|imp|acu|air|fcdt|xdp|xfdf|ahead|azf|azs|azw|acc|ami|apk|cii|fti|atx|mpkg|m3u8|swi|iota|aep|mpm|bmi|rep|cdxml|mmd|cdy|cla|rp9|c11amc|c11amz|csp|cdbcmsg|cmc|clkx|clkk|clkp|clkt|clkw|wbs|pml|ppd|car|pcurl|dart|rdz|fe_launch|dna|mlp|dpg|dfac|kpxx|ait|svc|geo|mag|nml|esf|msf|qam|slt|ssf|ez2|ez3|fdf|mseed|gph|ftc|fnc|ltf|fsc|oas|oa2|oa3|fg5|bh2|ddd|xdw|xbd|fzs|txd|ggb|ggt|gxt|g2w|g3w|gmx|kml|kmz|gac|ghf|gim|grv|gtm|tpl|vcg|hal|zmm|hbci|les|hpgl|hpid|hps|jlt|pcl|pclxl|sfd-hdstx|mpy|irm|sc|igl|ivp|ivu|igm|i2g|qbo|qfx|rcprofile|irp|xpr|fcs|jam|rms|jisp|joda|karbon|chrt|kfo|flw|kon|ksp|htke|kia|sse|lasxml|lbd|lbe|123|apr|pre|nsf|org|scm|lwp|portpkg|mcd|mc1|cdkey|mwf|mfm|flo|igx|mif|daf|dis|mbk|mqy|msl|plc|txf|mpn|mpc|xul|cil|cab|xlam|xlsb|xlsm|xltm|eot|chm|ims|lrm|thmx|cat|stl|ppam|pptm|sldm|ppsm|potm|docm|dotm|wpl|xps|mseq|mus|msty|taglet|nlu|nnd|nns|nnw|ngdat|n-gage|rpst|rpss|edm|edx|ext|odc|otc|odb|odf|odft|odg|otg|odi|oti|odp|otp|ods|ots|odt|odm|ott|oth|xo|dd2|oxt|pptx|sldx|ppsx|potx|xlsx|xltx|docx|dotx|mgp|dp|esa|paw|str|ei6|efif|wg|plf|pbd|box|mgz|qps|ptid|bed|mxl|musicxml|cryptonote|cod|rm|rmvb|link66|st|see|sema|semd|semf|ifm|itp|iif|ipk|mmf|teacher|dxp|sfs|sdc|sda|sdd|smf|sgl|smzip|sm|sxc|stc|sxd|std|sxi|sti|sxm|sxw|sxg|stw|svd|xsm|bdm|xdm|tao|tmo|tpt|mxs|tra|utz|umj|unityweb|uoml|vcx|vis|vsf|wbxml|wmlc|wmlsc|wtb|nbp|wpd|wqd|stf|xar|xfdl|hvd|hvs|hvp|osf|osfpvg|saf|spf|cmp|zaz|vxml|wgt|hlp|wsdl|wspolicy|7z|abw|ace|dmg|aam|aas|bcpio|torrent|bz|vcd|cfs|chat|pgn|nsc|cpio|csh|dgc|wad|ncx|dtb|res|dvi|evy|eva|bdf|gsf|psf|pcf|snf|arc|spl|gca|ulx|gnumeric|gramps|gtar|hdf|install|iso|jnlp|latex|mie|application|lnk|wmd|wmz|xbap|mdb|obd|crd|clp|mny|pub|scd|trm|wri|nzb|p7r|rar|ris|sh|shar|swf|xap|sql|sit|sitx|srt|sv4cpio|sv4crc|t3|gam|tar|tcl|tex|tfm|obj|ustar|src|fig|xlf|xpi|xz|xaml|xdf|xenc|dtd|xop|xpl|xslt|xspf|yang|yin|zip|adp|s3m|sil|eol|dra|dts|dtshd|lvp|pya|ecelp4800|ecelp7470|ecelp9600|rip|weba|aac|caf|flac|mka|m3u|wax|wma|rmp|wav|xm|cdx|cif|cmdf|cml|csml|xyz|ttc|otf|ttf|woff|woff2|bmp|cgm|g3|gif|ief|ktx|png|btif|sgi|psd|sub|dwg|dxf|fbs|fpx|fst|mmr|rlc|mdi|wdp|npx|wbmp|xif|webp|3ds|ras|cmx|ico|sid|pcx|pnm|pbm|pgm|ppm|rgb|tga|xbm|xpm|xwd|dae|dwf|gdl|gtw|mts|vtu|appcache|css|csv|n3|dsc|rtx|tsv|ttl|vcard|curl|dcurl|mcurl|scurl|sub|fly|flx|gv|3dml|spot|jad|wml|wmls|java|nfo|opml|etx|sfv|uu|vcs|vcf|3gp|3g2|h261|h263|h264|jpgv|ogv|dvb|fvt|pyv|viv|webm|f4v|fli|flv|m4v|mng|vob|wm|wmv|wmx|wvx|avi|movie|smv|ice";
private static final Pattern FILE_DETECT = Pattern.compile("(?i)([^=/&?]+\\.(" + EXTENSIONS + "))\\b");
public static Optional<String> extractFileFrom(String url) {
Matcher matcher = FILE_DETECT.matcher(url);
return (matcher.find()) ? Optional.of(matcher.group(1)) : Optional.empty();
}
And here is a test which demonstrates how to use the method above:
public static void main(String[] args) throws ParseException {
List<String> strings = Arrays.asList(
"https://example.cdn.com/mp4/7/9/5/file_795f32460d111df334849ee8336e56ca.mp4?e=1535545105&h=4772d27a70cd9b1c665b712f62592c47&download=1",
"http://example.cdn.comr/post/93/3/Jozve-Kamele-arbi.abp.zip",
"http://cdl.example.com/?b=dl-software&f=Windows.8.1.Enterprise.x86.Aug.2018_n.part1.rar",
"https://www.google.com/url?sa=t&source=web&rct=j&url=http://www.pdf995.com/samples/pdf.pdf&ved=2ahUKEwjV096X-ZHdAhVQzlkKHTpUBV4QFjAAegQIARAB&usg=AOvVaw3HFvAQ7GNf5QjsUo05ot-j",
"https://www.google.com/url?sa=t&source=web&rct=j&url=http://www.pdf995.com/samples/pdf.PDF&ved=2ahUKEwjV096X-ZHdAhVQzlkKHTpUBV4QFjAAegQIARAB&usg=AOvVaw3HFvAQ7GNf5QjsUo05ot-j");
strings.stream().map(s -> extractFileFrom(s)).collect(Collectors.toList())
.forEach(System.out::println);
}
If you execute the main method you will see this on the console:
Optional[file_795f32460d111df334849ee8336e56ca.mp4]
Optional[Jozve-Kamele-arbi.abp.zip]
Optional[Windows.8.1.Enterprise.x86.Aug.2018_n.part1.rar]
Optional[pdf.pdf]
Optional[pdf.PDF]
I use this method, hope it helps you too. It will parse from question marks, hash too.
public static String parseFileNameFromUrl(String url) {
if (url == null) {
return "";
}
try {
URL res = new URL(url);
String resHost = res.getHost();
if (resHost.length() > 0 && url.endsWith(resHost)) {
// handle ...example.com
return "";
}
} catch (MalformedURLException e) {
e.printStackTrace();
return "";
}
int startIndex = url.lastIndexOf('/') + 1;
int length = url.length();
// find end index for ?
int lastQuestionMarkPos = url.lastIndexOf('?');
if (lastQuestionMarkPos == -1) {
lastQuestionMarkPos = length;
}
// find end index for #
int lastHashPos = url.lastIndexOf('#');
if (lastHashPos == -1) {
lastHashPos = length;
}
// calculate the end index
int endIndex = Math.min(lastQuestionMarkPos, lastHashPos);
return url.substring(startIndex, endIndex);
}
I am using Java Eclipse to create an event management system which will write and read JSON files. Here I have code which creates a new JSON file...
public void actionPerformed(ActionEvent arg0) {
//Declaration of variables
String title = txtTitle.getText();
String month = (String) cboMonth.getSelectedItem();
String day = (String) cboDate.getSelectedItem();
String year = (String) cboYear.getSelectedItem();
String location = txtLocation.getText();
String description = txtDescription.getText();
String URL = txtURL.getText();
// Combine multiple variables together to make a single variable
String date = month + "" + day + "" + year;
// Create a new instance of the class called 'Event'
Event event = new Event();
// Assign values to the getter/setter methods of this instance
event.setName(title);
event.setDate(date);
event.setLocation(location);
event.setDesc(description);
event.setURL(URL);
// Add this new instance to the 'eventList' array list
MainMenu.eventList.add(event);
// Create a new instance of the class called 'Event'
JSONObject JSONEvent = new JSONObject();
// Add data to the JSON file
JSONEvent.put("Title", title);
JSONEvent.put("Date", date);
JSONEvent.put("Location", location);
JSONEvent.put("Description", description);
JSONEvent.put("URL", URL);
// Create a new JSON file called 'Events.json' that has elements added to it
try (FileWriter file = new FileWriter("Events.json", true)) {
file.write("\n");
file.write(JSONEvent.toJSONString());
file.flush();
// Error Handling
} catch (IOException e) {
e.printStackTrace();
}
}
This code works perfectly fine by creating a JSON file and populating it with JSONObjects. Here is an image of what a single entry in the JSON file looks like... Single JSON Element
I then have a separate class with the following code which attempts to read the JSON file and output its contents to the console...
public static void main(String[] args) {
JSONObject JSONEvent;
String line = null;
try {
FileReader fileReader = new FileReader("Events.json");
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
JSONEvent = (JSONObject) new JSONParser().parse(line);
String title = (String) JSONEvent.get("Title");
System.out.println(title);
String date = (String) JSONEvent.get("Date");
System.out.println(date);
String location = (String) JSONEvent.get("Location");
System.out.println(location);
String description = (String) JSONEvent.get("Description");
System.out.println(description);
String URL = (String) JSONEvent.get("URL");
System.out.println(URL);
Event event = new Event();
event.setName(title);
event.setDate(date);
event.setLocation(location);
event.setDesc(description);
event.setURL(URL);
MainMenu.eventList.add(event);
}
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
When I run this code, I get the following errors in the console...
Unexpected token END OF FILE at position 0
Does anyone have any idea what this error means?
The very first thing you write to the file is an empty line:
file.write("\n");
So, when reading the file, you're trying to parse an empty string to JSON, hence the exception: the parser finds the end of its input before even having a chance to parse anything.
Instead of relying on the internal format of the generated JSON, and to write several distinct JSON objects to the file, it would be simpler, and safer, to write a single array of objects all at once in the file (replacing its previous content), and to read the whole array at once in memory.
Faced a similar issue. Was trying to write a JSON data record from a file on a Kafka topic. Was getting Unexpected token END OF FILE at position . As a fix, I cleared all the \n characters from the file and tried sending it to the kafka topic. It worked.
I want to extract data such as name of page, likes,talking_about_count and page information from any page using FQL in Java. I have written code like below:
public static void main(String[] args) {
// TODO Auto-generated method stub
String STR_FACEBOOK_FQL_URL = "https://api.facebook.com/method/fql.query?query=";
String STR_FACEBOOK_RETURN_FORMAT = "&format=json";
String STR_FACEBOOK_ACCESS_TOKEN = "&access_token=";
String FQL_GET_QUERY= "SELECT name,likes,about FROM page WHERE id={page-id}";
String encodedQuery;
try
{
encodedQuery = URLEncoder.encode(FQL_GET_QUERY, "UTF-8");
String faceBookURL = STR_FACEBOOK_FQL_URL + encodedQuery +
STR_FACEBOOK_RETURN_FORMAT
+ STR_FACEBOOK_ACCESS_TOKEN ;
URL url = new URL(faceBookURL);
InputStream is = url.openStream();
JSONTokener tok = new JSONTokener(is);
JSONObject result = new JSONObject(tok);
System.out.println(result.toString());
is.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
But this is shownig error like:
{"request_args":[{"value":"fql.query","key":"method"},{"value":"SELECT likes,name,about FROM page WHERE uid=me()","key":"query"},{"value":"json","key":"format"},{"value":"id|secret","key":"access_token"}],"error_code":602,"error_msg":"likes is not a member of the page table."}
Can anybody tell me, what is the wrong in this code?
First of all, please don't use the deprecated endpoint:
String STR_FACEBOOK_FQL_URL = "https://graph.facebook.com/fql?q=";
is the way to go now. You're using non-existing fields for the page table (see https://developers.facebook.com/docs/reference/fql/page/). likes needs to be replaced by fan_count:
String FQL_GET_QUERY= "SELECT name,fan_count,about FROM page WHERE id={page-id}";