As an aviation lover, I'm trying to build up an Android App to get METAR/TAF. The main goal of one of the project activities is to go to https://www.aviationweather.gov/adds/metars/, and read the METAR/TAF (METHEOROLOGICAL REPORTS) of the airport the user chooses.
As a draft project I have the following xml (read the info from webpage and pasting it into a textViwe):
TextView tv = (TextView) findViewById(R.id.textview1);
try{
HttpClient cliente = new DefaultHttpClient();
HttpPost poste = new HttpPost("https://www.aviationweather.gov/adds/metars/?station_ids=LELL&std_trans=standard&chk_metars=on&hoursStr=most+recent+only&chk_tafs=on&submitmet=Submit");
HttpResponse respuesta = cliente.execute(poste);
HttpEntity entidad=respuesta.getEntity();
InputStream mensaje=entidad.getContent();
StringBuffer sb=new StringBuffer();
String linea;
BufferedReader br=new BufferedReader(new InputStreamReader(mensaje,"UTF-8"));
while((linea=br.readLine())!=null){
sb.append(linea);
sb.append("\n");
}
tv.setText(sb.toString());
mensaje.close();
The main thing is, I read the whole information and get the following text*, but I just want to display the lines (METAR in red , TAF in blue):
Any Idea?
I've tried many codes in this website, even tried to get to the webpage with a WebView , but I'd rather display the metheorological information as a text in TextView.
Thanks in advance,
SERGI
You can use Jsoup with the following to access the text you want
Document doc = Jsoup.connect("https://www.aviationweather.gov/adds/metars/?station_ids=LELL&std_trans=standard&chk_metars=on&hoursStr=most+recent+only&chk_tafs=on&submitmet=Submit").get();
Elements fontTags = content.getElementsByTag("font");
for (Element fontTag : fontTags) {
String fontTagText = fontTag.text();
}
Final code:
Document doc = Jsoup.connect("https://www.aviationweather.gov/adds/metars/?station_ids=LELL&std_trans=standard&chk_metars=on&hoursStr=most+recent+only&chk_tafs=on&submitmet=Submit").get();
Elements fontTags = doc.getElementsByTag("font");
for (org.jsoup.nodes.Element fontTag : fontTags){
String frase =fontTags.text();
TextView hola=(TextView)findViewById(R.id.hello);
hola.setText(frase);
}
Related
I'm trying to parse some HTML in my Android app and I need to get the text:
Pan Artesano Elaborado por Panadería La Constancia. ¡Esta Buenísimo!
in
Is there any easy way to get only the text and remove all html tags?
The behavior that I need is exactly the one shown in this PHP code http://php.net/manual/es/function.strip-tags.php
Document doc = Jsoup.parse(html);
Element content = doc.getElementById("someid");
Elements p= content.getElementsByTag("p");
String pConcatenated="";
for (Element x: p) {
pConcatenated+= x.text();
}
System.out.println(pConcatenated);//sometext another p tag
Well when you want just to show it, then webview would help you, just set that string to webview and you got it.
When you would to use it elsewhere then i am to stupid for that :D.
String data = "your html here";
WebView webview= (WebView)this.findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadDataWithBaseURL("", data, "text/html", "UTF-8", "");
also you can pass just web URL webview.loadDataWithBaseURL("url","","text/html", "UTF-8", "");
Firstly get HTML code with
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
html = str.toString();
then I recommend to create custom tag in HTML such as <toAndroid></toAndroid> and then you can get text with
String result = html.substring(html.indexOf("<toAndroid>", html.indexOf("</toAndroid>")));
your html for example
<toAndroid>Hello world!</toAndroid>
will result
Hello world!
Note that you can place <p> into <toAndroid> tags and then remove it in Java from result.
I'm writing an app that downloads youtube videos and I got a lttle problem.
As you might know, each video link in youtuube contains direct links to the video.
When the page uses the flash flayer (and not html5 or so), it is stored in the flash object (in it's flashvar attr).
My app parses that flash object and extract from it those direct links (one link for each available video quality).
I get the flash object's html code by downloading the video's html code (e.g http://www.youtube.com/watch?v=VIDEOID) and parsing it.
I use asynctask to dowload the html code (the non mobile version), and here is my downloading code :
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0.1)");
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
html = str.toString();
return html;
Now I got a little problem:
The code above doesn't download the whloe html code. The downloaded html string gets cut somewhere in the middle and I don't get the flash object part. This function works fine with other sites!
Am I doing something wrong?
Thanks :)
Check out BasicResponseHandler.
String html = client.execute(request, new BasicResponseHandler());
I'm getting back names of (Foursquare) venues from a server call where the names of the venues returned can be in English or non-English.
Assume the venue name is in a JSON object as follows:
{...
"name":"venue name which can be in any language"
...}
I'm creating a JSONObject from this response and then pulling out the name of the venue as follows:
String name = jsonObject.getString("name");
Lastly, I'm setting the TextView's text to show the name of the venue as follows:
myTextView.setText(name);
I'm finding however for Arabic names that where the Arabic characters are joined in the original JSON object (as they should be), the characters that show in the app (i.e. in the TextView) are disjoint. (I'm not too familiar with other languages so can't really tell if they're showing incorrectly too.)
Is there something additional I should be doing to pull out non-English names correctly from the JSON object and setting it as the text of a TextView, or is it down to the phone to decide how the text will be displayed?
Edit: I've tried parsing the server response (as suggested by #bbedward) explicitly specifying the content encoding as UTF-8 as follows...
HttpEntity httpEntity = httpResponse.getEntity();
String responseMessage = EntityUtils.toString(myHttpEntity, "UTF-8");
JSONObject jsonObject = new JSONObject(responseMessage);
... but still no joy. (Arabic characters appear, as before, disjoint in words where they should be joint up.) Could it be a phone thing or is there something extra needing to be done myself to get the words/characters to show proper in non-English languages? Perhaps the server needs to explicitly specify a "Content-Type" header with value "UTF-8"?
I'm going to answer anyway, I'm guessing you aren't getting your json in UTF-8 as i had a similar problem, I believe json won't come any other way.
Complete Example
The only things to concern yourself with this is setting the encoding for the InputStreamReader and creating the JSONObject
private DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://myjsonurl.com/search?type=json");
// Depending on your web service
httppost.setHeader("Content-type", "application/json");
try
{
String result = null;
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
JSONObject myJObject = new JSONObject(sb.toString();
}
catch (Exception e)
{
}
finally
{
try{if(inputStream != null)inputStream.close();}catch(Exception none){}
}
add this line when you connect to mysql:
mysql_set_charset('utf8', $con);
ex:
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysql_set_charset('utf8', $con);
mysql_select_db(DB_DATABASE);
I want to format the content I get from a specific website to show it on my device . For example , from this page I need only the program titles and the description of each one . I get the html code for this page with this function :
private String getPage() {
String str = "***";
try
{
HttpClient hc = new DefaultHttpClient();
HttpPost post = new HttpPost("http://golfnews.no/golfpaatv.php");
HttpResponse rp = hc.execute(post);
if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
str = EntityUtils.toString(rp.getEntity());
}
}catch(IOException e){
e.printStackTrace();
}
return str;
}
It returns a string which contains the html code. Now I want to have some strings containing the titles and other strings containing the description . I tried a few methods but I can't figure out what to do ! I am a beginner and I don't know much in android . Could you please help me ? Thanks.
Instead of that URL, you just fetch RSS by using this link, and now parse the RSS either by using SAX Parser, DOM Parser or Pull Parser.
I am trying to be able to view the source code of a webpage after being given a URL in order to parse the text for a certain string which represents and image url.
I found this post which is pretty much what I am after trying to do but can't get it working:
Post
This is my code below.
public String fetchImage() throws ClientProtocolException, IOException {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("www.google.co.uk/images?q=songbird+oasis");
HttpResponse response = client.execute(request);
String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
html = str.toString();
return html;
}
but for some reason it just does not work. It forces me to use a try catch statement in calling the method. Once this works I think it will simple from here using regex to find the string "href="/imgres?imgurl=........jpg" to find the url of a jpg image to then be shown in an image view.
Please tell me if i'm going at this all wrong.
First, Google has a search API, which will be a better solution than the scraping you are going through, since the API will be reliable, and your solution will not be.
Second, use the BasicResponseHandler pattern for string responses, as it is much simpler.
Third, saying something "just does not work" is a pretty useless description for a support site like this one. If it crashes, as kgiannakakis pointed out, you will have an exception. Use adb logcat, DDMS, or the DDMS perspective in Eclipse to examine the stack trace and find out what the exception is. That will give you some clues for how to solve whatever problem you have.