I am new to Android and I want to play online radio (example link http://www.bbc.co.uk/radio/listen/live/r1_aaclca.pls) using ParsePls. I have PlsParse code but after this I don't know how to play using the player in Android.
PlsParser.java
public PlsParser(File file) throws FileNotFoundException {
this.reader = new BufferedReader(new FileReader(file), 1024);
}
#Override
public List<String> getUrls() {
LinkedList<String> urls = new LinkedList<String>();
while (true) {
try {
String line = reader.readLine();
if (line == null) {
break;
}
String url = parseLine(line);
if (url != null && !url.equals("")) {
urls.add(url);
}
} catch (IOException e) {
e.printStackTrace();
}
}
return urls;
}
private String parseLine(String line) {
if (line == null) {
return null;
}
String trimmed = line.trim();
if (trimmed.indexOf("http") >= 0) {
return trimmed.substring(trimmed.indexOf("http"));
}
return "";
}
}
and
PlaylistParser.java
public interface PlaylistParser {
public List<String> getUrls();
}
Basically I need to play online fm in Android. How can I do this?
I got some solution without Parse pls,
Just Enter URL of pls file in browser(example link yp.shoutcast.com/sbin/tunein-station.pls?id=213352),
you will get download "tunein-station.pls",
Just open the downloaded file with notepad,
you can see
[playlist]
numberofentries=2
File1=http://208.115.222.205:9938
Title1=(#1 - 1/100) RADIO CITY TAMIL
Length1=-1
File2=http://208.115.222.205:9948
Title2=(#2 - 67/300) RADIO CITY TAMIL
Length2=-1
Version=2
Here File1 URL(shoutcast online radio url)
Now using this URL i coded with mediaplayer.
Related
I have this account creation program I'm working on, and would love to save the persons name, last name, email and password to a text file. The following snippet should do just that, but the error message I'm getting when I put a String variable in the .write method is, "no suitable method found for write(JTextFeild)".
private void signupActionPerformed(java.awt.event.ActionEvent evt) {
fname.getText();
lname.getText();
email.getText();
reemail.getText();
password.getText();
repassword.getText();
if(male.equals(true)) {
males = true;
}
if(female.equals(true)) {
females = true;
}
BufferedWriter writer = null;
try {
writer = new BufferedWriter( new FileWriter("UserPass.txt"));
writer.write(fname);
}
catch ( IOException e) {
}
finally {
try {
if ( writer != null) {
writer.close( );
}
}
catch ( IOException e) {
}
}
}
Any ideas on how to fix this?
From the documentation of getText() in javax.swing.text.JTextComponent:
public String getText()
JTextField is just the GUI element, getText() doesn't change it.
You should store the result in a String variable and then use it to write().
I'm working on a homework assignment and have run into an odd "ArrayOutOfBoundsException" error - I know what the error means (essentially I'm trying to reference a location in an array that isn't there) but I'm not sure why it's throwing that error? I'm not sure what I'm missing, but obviously there must be some logic error somewhere that I'm not seeing.
PhoneDirectory.java
import java.util.HashMap;
import java.io.*;
class PhoneDirectory {
private HashMap<String, String> directoryMap;
File directory;
public PhoneDirectory() { //create file for phone-directory
directory = new File("phone-directory.txt");
directoryMap = new HashMap<String, String>();
try(BufferedReader buffer = new BufferedReader(new FileReader(directory))) {
String currentLine;
while((currentLine = buffer.readLine()) != null) { //set currentLine = buffer.readLine() and check if not null
String[] fileData = currentLine.split(","); //create array of values in text file - split by comma
directoryMap.put(fileData[0], fileData[1]); //add item to directoryMap
}
}
catch(IOException err) {
err.printStackTrace();
}
}
public PhoneDirectory(String phoneDirectoryFile) {
directory = new File(phoneDirectoryFile);
directoryMap = new HashMap<String, String>();
try(BufferedReader buffer = new BufferedReader(new FileReader(directory))) {
String currentLine;
while((currentLine = buffer.readLine()) != null) { //set currentLine = buffer.readLine() and check if not null
String[] fileData = currentLine.split(","); //create array of values in text file - split by comma
directoryMap.put(fileData[0], fileData[1]); //add item to directoryMap
}
}
catch(IOException err) {
err.printStackTrace();
}
}
public String Lookup(String personName) {
if(directoryMap.containsKey(personName))
return directoryMap.get(personName);
else
return "This person is not in the directory.";
}
public void AddOrChangeEntry(String name, String phoneNumber) {
//ASK IF "IF-ELSE" CHECK IS NECESSARY
if(directoryMap.containsKey(name))
directoryMap.put(name,phoneNumber); //if name is a key, update listing
else
directoryMap.put(name, phoneNumber); //otherwise - create new entry with name
}
public void DeleteEntry(String name) {
if(directoryMap.containsKey(name))
directoryMap.remove(name);
else
System.out.println("The person you are looking for is not in this directory.");
}
public void Write() {
try(BufferedWriter writeDestination = new BufferedWriter(new FileWriter(directory)))
{
for(String key : directoryMap.keySet())
{
writeDestination.write(key + ", " + directoryMap.get(key) + '\n');
writeDestination.newLine();
}
}
catch(IOException err) {
err.printStackTrace();
}
}
}
Driver.java
public class Driver {
PhoneDirectory list1;
public static void main(String[] args) {
PhoneDirectory list1 = new PhoneDirectory("test.txt");
list1.AddOrChangeEntry("Disney World","123-456-7890");
list1.Write();
}
}
Essentially I'm creating a file called "test.txt" and adding the line "Disney World, 123-456-7890" - what's weird is that the code still works - but it throws me that error anyway, so what's really happening? (For the record, I'm referring to the line(s): directoryMap.put(fileData[0], fileData[1]) - which would be line 14 and 28 respectively.)
I had problems with jsoup, because I have written the code for parsing some information from the web site in Java and working perfectly.
But I copy the code in Android (encapsulate it in the asyncTask) but the document is different from the doc Java parsing with jsoup.connect().
Why?
Some code lines are:
Document doc = null;
try {
doc=Jsoup.connect("myurl").timeout(10000).get();
} catch (IOException e) {
e.printStackTrace();
}
Element body = doc.body();
Element figlio = body.child(0);
Elements span_elements = figlio.getElementsByTag("span");
I posted here complete code in java and android.
JAVA
public class MainClass {
public static void main(String[] args){
String ProductName = "";
String Description = "";
String LongDescription = "";
String Category = "";
Document doc = null;
try {
doc=Jsoup.connect("http://eandata.com/lookup/9788820333584/").timeout(10000).get();
} catch (IOException e) {
e.printStackTrace();
}
Element body = doc.body();
Element figlio = body.child(0);
Elements span_elements = figlio.getElementsByTag("span");
for(Element p : span_elements) {
if((p.id().compareTo("")) == 0 || p.id() == null) {
continue;
}
else if(p.id().compareTo("upc_prod_product_o") == 0) {
ProductName = p.text();
continue;
}
else if(p.id().compareTo("upc_prod_description_o") == 0) {
Description = p.text();
continue;
}
else if(p.id().compareTo("upc_prod_cat_path_o") == 0) {
Category = p.text();
continue;
}
else if(p.id().compareTo("upc_prod_url_o") == 0) {
continue;
}
else if(p.id().compareTo("upc_prod_long_desc_o") == 0) {
LongDescription = p.text();
continue;
}
}
System.out.println(ProductName);
System.out.println(Description);
System.out.println(Category);
System.out.println(LongDescription);
This is instead code ANDROID (i have included the INTERNET PERMISSION in AndroidManifest)
ANDROID
public class MainActivity extends Activity {
//Campi necessari per il Parser HTML
String ProductName = "";
String Description = "";
String LongDescription = "";
String Category = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HttpHTML task3 = new HttpHTML();
task3.execute();
}
public class HttpHTML extends AsyncTask<Void,Void,Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void...params) {
Document doc = null;
try {
doc=Jsoup.connect("http://eandata.com/lookup/9788820333584/").timeout(10000).get();
} catch (IOException e) {
e.printStackTrace();
}
//Accedo all'elemento <body> del documento
Element body = doc.body();
System.out.println(body.text());
//Prendo l'elemento figlio del body
Element figlio = body.child(0);
System.out.println(figlio.text());
Elements span_elements = figlio.getElementsByTag("span");
for(Element p : span_elements) {
if((p.id().compareTo("")) == 0 || p.id() == null) {
continue;
}
else if(p.id().compareTo("upc_prod_product_o") == 0) {
ProductName = p.text();
continue;
}
else if(p.id().compareTo("upc_prod_description_o") == 0) {
Description = p.text();
continue;
}
else if(p.id().compareTo("upc_prod_cat_path_o") == 0) {
Category = p.text();
continue;
}
else if(p.id().compareTo("upc_prod_url_o") == 0) {
continue;
}
else if(p.id().compareTo("upc_prod_long_desc_o") == 0) {
LongDescription = p.text();
continue;
}
}
System.out.println(ProductName);
System.out.println(Description);
System.out.println(Category);
System.out.println(LongDescription);
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
}
#Override
protected void onPostExecute(Void result) {
}
}
}
Without knowing the URL you're hitting, this is just a guess, but I would bet $5 I'm right: the server is sending back different HTML based on your user-agent string, and because you're not explicitly setting it, it's defaulting. And the default between Android and Java is different. The server is trying to be helpful and is giving you mobile optimized HTML for Android.
Make sure you specify a user-agent when building your request. See the Connection.userAgent() docs for details. I normally set it to my current browser.
Very interesting problem. If you look at the website the interesting part of the information is loaded dynamically. Jsoup is not supposed to parse this part. I don't understand why it is work differently on android. But it is not important. I found the url where the interesting information loaded from.
Try parsing this one. The added benefit is that it is returned with smaller dataset, it use smaller memory and could be quicker on android.
http://eandata.com/lookup.php?extra=x&code=9788820333584&mode=prod&show=&force_amazon=&ajax=1
I want the simplest logger there is to simply log errors, mostly exceptions, to a Log file in the android file system. for exemple, the easiest and most convinient (in my opinion at least) way that i used to log to a file on PC java was by simply printing all exceptions to console and redirecting system out to both console and my file, this doesnt really suffice on android as far as i know i guess its because of how Android OS is designed, so what is the simplest way of doing it in Android?
Note that the project has already lot of code in it and i really wouldnt like to go over it and add log calls on catch blocks or whatever to log my exceptions, as little i need to do for logging those exceptions is best for my use case...
Thanks ahead!
It's not finished but works quite stable. It saves human readable json array with exception name, time, stack trace and additional data. Also you can save logcat's logs.
Using:
ExceptionWriter ew = new ExceptionWriter(new File(Environment.getExternalStorageDirectory(), "debug.txt"));
ew.w(new IllegalArgumentException("some msg"), "additional message");
Source:
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* User: elevenetc
* Date: 10/9/13
* Time: 12:52 PM
*/
public class ExceptionWriter {
private final StringBuilder sb;
private final ExceptionWriter.WriteExceptionTask writeExceptionTask;
private final SimpleDateFormat dataFormat;
private int totalExceptions;
private StringBuilder stackBuilder = new StringBuilder();
public int getTotalExceptions(){return totalExceptions;}
public ExceptionWriter(File file) throws IOException {
if(file != null){
writeExceptionTask = new WriteExceptionTask(file);
sb = new StringBuilder();
dataFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
new Thread(writeExceptionTask).start();
}else{
sb = null;
writeExceptionTask = null;
dataFormat = null;
}
}
public synchronized int wLogcat(){
try {
writeExceptionTask.addStreamToRead(Runtime.getRuntime().exec("logcat -d -v time").getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
public int w(Exception debugException, String caughtMessage){
return w(debugException, caughtMessage, null);
}
public synchronized int w(Exception debugException, String caughtMessage, String additionalData){
if(writeExceptionTask == null) return -1;
sb.setLength(0);
StackTraceElement[] stackTrace = debugException == null ? null : debugException.getStackTrace();
sb.append("{\"date\":\"");sb.append(getTime());
sb.append("\",\"exceptionClassName\":\"");sb.append(debugException == null ? null : debugException.getClass());
sb.append("\",\"exceptionMessage:\":\"");sb.append(debugException == null ? null : debugException.getMessage());
sb.append("\",\"caughtMessage:\":\"");sb.append(caughtMessage);
if(additionalData != null) {sb.append("\",\"data:\":\"");sb.append(additionalData);}
sb.append("\",\"stack\":");sb.append(stackToString(stackTrace));
sb.append("},");
writeExceptionTask.stringQueue.add(sb.toString());
totalExceptions++;
return 0;
}
public void destroy() {
if(writeExceptionTask != null) {
writeExceptionTask.stop();
}
}
private String getTime(){
return dataFormat.format(System.currentTimeMillis());
}
private String stackToString(StackTraceElement[] stackTrace){
if(stackTrace == null) return null;
stackBuilder.setLength(0);
stackBuilder.append("[");
for (int i = 0; i < stackTrace.length; i++) {
StackTraceElement e = stackTrace[i];
stackBuilder.append("{\"");
stackBuilder.append(e.getLineNumber());
stackBuilder.append("\":\"");
stackBuilder.append(e.getClassName());
stackBuilder.append(".");
stackBuilder.append(e.getMethodName());
stackBuilder.append("\"}");
if(i != stackTrace.length -1) stackBuilder.append(",");
}
stackBuilder.append("]");
return stackBuilder.toString();
}
///////////////////////////////////////////////
/// Static classes
///////////////////////////////////////////////
private class WriteExceptionTask implements Runnable {
private final File file;
private boolean running;
private final ConcurrentLinkedQueue<String> stringQueue;
private final ConcurrentLinkedQueue<InputStream> isQueue;
private final FileWriter writer;
private WriteExceptionTask(File file) throws IOException {
this.file = file;
writer = new FileWriter(this.file, true);
stringQueue = new ConcurrentLinkedQueue<String>();
isQueue = new ConcurrentLinkedQueue<InputStream>();
running = true;
}
public void addStreamToRead(InputStream is){
if(is != null){
isQueue.add(is);
}
}
#Override
public void run() {
while(running){
if(!stringQueue.isEmpty()){
//TODO check file existence
try {
writer.append(stringQueue.poll());
writer.flush();
} catch (IOException e) {
e.printStackTrace();
running = false;
}
}
if(!isQueue.isEmpty()){
InputStream is = isQueue.poll();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder("{\"catLog\":\"");
String aux;
try {
while ((aux = reader.readLine()) != null) {
//TODO view like array or \n
builder.append(aux);
}
} catch (IOException e) {
e.printStackTrace();
}
builder.append("\"},");
stringQueue.add(builder.toString());
}
}
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void stop() {
running = false;
}
}
}
I am developing one Application which show Gold rate and create graph for this.
I find one website which provide me this gold rate regularly.My question is how to extract this specific value from html page.
Here is link which i need to extract = http://www.todaysgoldrate.co.in/todays-gold-rate-in-pune/ and this html page have following tag and content.
<p><em>10 gram gold Rate in pune = Rs.31150.00</em></p>
Here is my code which i use for extracting but i didn't find way to extract specific content.
public class URLExtractor {
private static class HTMLPaserCallBack extends HTMLEditorKit.ParserCallback {
private Set<String> urls;
public HTMLPaserCallBack() {
urls = new LinkedHashSet<String>();
}
public Set<String> getUrls() {
return urls;
}
#Override
public void handleSimpleTag(Tag t, MutableAttributeSet a, int pos) {
handleTag(t, a, pos);
}
#Override
public void handleStartTag(Tag t, MutableAttributeSet a, int pos) {
handleTag(t, a, pos);
}
private void handleTag(Tag t, MutableAttributeSet a, int pos) {
if (t == Tag.A) {
Object href = a.getAttribute(HTML.Attribute.HREF);
if (href != null) {
String url = href.toString();
if (!urls.contains(url)) {
urls.add(url);
}
}
}
}
}
public static void main(String[] args) throws IOException {
InputStream is = null;
try {
String u = "http://www.todaysgoldrate.co.in/todays-gold-rate-in-pune/";
//Here i need to extract this content by tag wise or content wise....
Thanks in Advance.......
You can use library like Jsoup
You can get it from here --> Download Jsoup
Here is its API reference --> Jsoup API Reference
Its really very easy to parse HTML content using Jsoup.
Below is a sample code which might be helpful to you..
public class GetPTags {
public static void main(String[] args){
Document doc = Jsoup.parse(readURL("http://www.todaysgoldrate.co.intodays-gold-rate-in-pune/"));
Elements p_tags = doc.select("p");
for(Element p : p_tags)
{
System.out.println("P tag is "+p.text());
}
}
public static String readURL(String url) {
String fileContents = "";
String currentLine = "";
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream()));
fileContents = reader.readLine();
while (currentLine != null) {
currentLine = reader.readLine();
fileContents += "\n" + currentLine;
}
reader.close();
reader = null;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Error Message", JOptionPane.OK_OPTION);
e.printStackTrace();
}
return fileContents;
}
}
http://java-source.net/open-source/crawlers
You can use any of that's apis, but don't parse the HTML with the pure JDK, because it's too painfull.