I have code,which can extract text value of the class. But in this class, exist attribute "title", which I should get. While I can extract only class ".day__description". Below part my code.
try {
Document document = Jsoup.connect(URL).get();
Elements nodeDay = document.select(".day__description");
if(nodeDay.size() > 0) {
day = nodeDay.get(0).text();
}
} catch (IOException e) {
day = "Not found";
}
return null;
protected void onPostExecute(Void result) {
TextView txttitle = (TextView) findViewById(R.id.tv);
txttitle.setText(day);
}
I need to get "title" from this part of the site:
<div class="day__description" title="SomeText">...</div>
As a result in variable "day", should be text "Some Text". Sorry for my English))
I hope all understand. Thanks for advance.
Try:
Document doc = Jsoup.connect(url).get();
Elements div=doc.select("div.day__description");
System.out.println(div.attr("title"));
Related
I am working on an app in Android Studio that downloads a json file from a php query, however when I have managed to read the contents of the json file from android, this contents does not behave as text, because when comparing a text entered from the app against the read from the json file, it never matches despite being the same text. (Example: password text from app and the password from the json file).
Php Code:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
include('functions.php');
$col=$_GET["col"];
$colbus=$_GET["colbus"];
$tabla=$_GET["nomtable"];
$todfilas=$_GET["todasf"];
$dbuser =$_GET["username"];
$dbpass=$_GET["password"];
$dbbase=$_GET["dbname"];
//echo "$todfilas <br>";
if($todfilas == 1){
$sqlt="SELECT * FROM $tabla";
}else{
$sqlt="SELECT * FROM $tabla WHERE $col='$colbus'";
}
//echo "$sqlt <br>";
if($resultset=getSQLResultSet($sqlt,$dbuser,$dbpass,$dbbase)){
while ($row = $resultset->mysqli_fetch_array(MYSQLI_NUM)){
echo json_encode($row);
}
}
?>
Code from Android Studio:
private class ConsultData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "No es posible cargar pagina web o la direccion es invalida!";
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
JSONArray ja = null;
try {
ja = new JSONArray(result);
Log.d("Password:",ja.getString(7)+"="+logPass.getText().toString().trim());
logPass2.setText(ja.getString(7).trim());
String pass1 =logPass2.toString();
String pass0 = logPass.toString().trim();
if(pass0==pass1){
showAlertDialog("Session:","login is valid!");
} else{
showAlertDialog("Session:","password does not match!");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I'm not sure if the way to create the json file in the php query is the problem? because I can see the contents of the json array in Android Studio, but when I compare text from json array, they do not match even if they are the same ("123" = "123").
As seeing your code you doing so many mistakes like you are getting textview value thats not right way
change code like this
String pass1 =logPass2.getText().toString();
String pass0 = logPass.getText().toString().trim();
Also comparsion of string
if(pass0.equals(pass1)){
showAlertDialog("Session:","login is valid!");
} else{
showAlertDialog("Session:","password does not match!");
}
instead of this
if(pass0==pass1){
showAlertDialog("Session:","login is valid!");
} else{
showAlertDialog("Session:","password does not match!");
}
I have an image in JPG in a sit (I suppose it is HTML format but I am not sure about it). I open the source of the page and I see there the image I need written this way.
If I take the link it show me the image.
But i don't know how can I get from the URL page to get this link. It is not look like written in JSON format.
How can I get it?
Thanks
Bar.
After some play I get to this:
The meta is the elements, and og.image and content are one of there meta data attribute.
So I do as follow to get the image URL string
String imageLink=null;
try {
Log.d(TAG, "Connecting to [" + strings[0] + "]");
Document doc = Jsoup.connect(strings[0]).get(); // put all the HTML page in Document
// Get meta info
Elements metaElems = doc.select("meta");
for (Element metaElem : metaElems) {
String property = metaElem.attr("property");
if(property.equals("og:image"))// if find the line with the image
{
imageLink = metaElem.attr("content");
Log.d(TAG, "Image URL" + imageLink );
}
}
} catch (Exception e) {
e.printStackTrace();
exception =e;
return null;
}
Here I am posting the small code snippet for ingrate this kind of functionality may this help you.
Step 1: Add below gradle
compile 'org.jsoup:jsoup:1.10.2'
Step 2:
Use below async task for get all meta information from any Url.
public class MainActivity extends AppCompatActivity {
private ImageView imgOgImage;
private TextView text;
String URL = "https://www.youtube.com/watch?v=ufaK_Hd6BpI";
String UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text);
imgOgImage = (ImageView) findViewById(R.id.imgOgImage);
new FetchMetadataFromURL().execute();
}
private class FetchMetadataFromURL extends AsyncTask<Void, Void, Void> {
String websiteTitle, websiteDescription, imgurl;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
// Connect to website
Document document = Jsoup.connect(URL).get();
// Get the html document title
websiteTitle = document.title();
//Here It's just print whole property of URL
Elements metaElems = document.select("meta");
for (Element metaElem : metaElems) {
String property = metaElem.attr("property");
Log.e("Property", "Property =" + property + " \n Value =" + metaElem.attr("content"));
}
// Locate the content attribute
websiteDescription = metaElems.attr("content");
String ogImage = null;
Elements metaOgImage = document.select("meta[property=og:image]");
if (metaOgImage != null) {
imgurl = metaOgImage.first().attr("content");
System.out.println("src :<<<------>>> " + ogImage);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
text.setText("Title : " + websiteTitle + "\n\nImage Url :: " + imgurl);
//t2.setText(websiteDescription);
Picasso.with(getApplicationContext()).load(imgurl).into(imgOgImage);
}
}
}
Note : Here I have just roughly making this demo.no any coding standard will user so please take care this while you ingrate this code in your application.I am just making this demo for learning purpose only.
Here I am just used youtube url for display meta data.you can used any url based on your requirement.
I hope you are clear with my logic.
Good Luck
I want to display in a TextView the Snow in the past 24 hours of a ski resort. I used the CSS path and tried other ways but nothing happens the TextView doesn't display nothing.
The web page: http://www.arizonasnowbowl.com/resort/snow_report.php
The CSS path: #container > div.right > table.interior > tbody > tr:nth-child(2) > td.infoalt
private class Description extends AsyncTask<Void, Void, Void> {
String desc;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(Snowreport.this);
mProgressDialog.setTitle("Snow Report");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
// Connect to the web site
Document document = Jsoup.connect(url).get();
Elements elms = document.select("td.infoalt");
for(Element e:elms)
if(e.className().trim().equals("infoalt"))
//^^^<--trim is required as,
// their can be leading and trailing space
{
TextView txtdesc = (TextView) findViewById(R.id.snowp24);
txtdesc.setText((CharSequence) e);
}
mProgressDialog.dismiss();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
The code:
Element div = doc.getElementById("contentinterior");
Elements tables = div.getElementsByTag("table");
Element table = tables.get(1);
String mSnow = table.getElementsByTag("tr").get(1).getElementsByTag("td").get(1).text();
You may have the incorrect String for the selection parameter. The correct selection to use as a parameter for Document.select() can be found by 'Inspecting the element' of a webpage most easily done by right clicking in the Chrome browser.
The following code may produce a better result for you:
final Elements tableElements = response.parse()
.getElementsByClass("info")
.select("td");
for (Element element : tableElements) {
String string = element.getElementsByClass("infoalt").text().trim()
Log.d("Jsoup", string);
}
Good luck and happy coding!
In my JSON response I am get nothing in value and at that I want to print message using textview I am trying but its not showing nothing,can any one help?the response is looks like this
{"name":"Patel Monali","age":24,"location":"","mother_tounge":"","occupation":"","income":"","height":"","cast":"","marital_status":"","religion":"","gotra":"","manglik":"","rashi":"","education":"","eating":"","drink":"","smoke":"","about_me":"","profile_pic":"Imaege","user_status":"Accept","interest_id":1288}
and here is the code:
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String user_name = jsonObj.getString(USER_NAME);
String user_age = jsonObj.getString(USER_AGE);
...............
final TextView uname = (TextView)findViewById(R.id.namedetail);
final TextView fdetail = (TextView)findViewById(R.id.firstdetail);
..............
uname.setText(user_name);
fdetail.setText(user_age+" years");
androidAQuery.id(ucover).image(user_pro, true, true);
}catch (JSONException e)
{
e.printStackTrace();
}
If I understand your question correctly here is what you need
if(user_name==null)
{
uname.setText("not willing to specify");
}
else
{
uname.setText(user_name);
}
If you need something more please update your question or tell me in comments.
.
Hope it help
All you have to do is check if the received string is null.
for example:
String user_occupation = jsonObj.getString(USER_OCCU);
if(user_occupation.length==0){
user_occupation="not willing to specify";//set your message here
}
OR
String user_occupation = jsonObj.getString(USER_OCCU);
if(user_occupation==null){
user_occupation="not willing to specify";//set your message here
}
I'm parse site http://animecalendar.net with Jsoup. Аll is well parsed fine, but i have one problem. I get a mixed list of urls, but they are parsed correctly (see logs)
Code:
#Override
protected ArrayList<Order> doInBackground(String... urls) {
listItems.clear();
myAdapter.notifyDataSetChanged();
String dates = null;
String url = null;
try {
Document doc = Jsoup.connect(URL).get();
Elements main = doc.select("div.day");
for (Element m : main) {
titles = m.select("div.tooltip");
for (Element tts : titles) {
title = tts.select("td.tooltip_title h4").text();
time = tts.select("td.tooltip_info h4").text();
img = tts.select("td.tooltip_desc img[src]");
Order o = new Order();
o.setLink(URL + img.attr("src"));
o.setTextName(title);
o.setTextTime(time);
o.setTextDate(dates);
o.setDetailsUrl(URL + url); // incorrect (mixed) displayed urls list in device
listItems.add(o);
}
Elements date = m.select("h2");
for (Element m1 : date) {
dates = m1.select("a").attr("href");
}
Elements links = m.select("h3");
for (Element link : links) {
url = link.select("a").attr("href"); // parse urls from site
System.out.println(url); // in LogCat displayed correct urls list
}
}
} catch (IOException e) {
e.printStackTrace();
}
return listItems;
}
LogCat:
01-21 12:55:55.429: I/System.out(8036): /show/596/Cardfight%21%21_Vanguard%3A_Asia_Circuit_Hen
01-21 12:55:55.429: I/System.out(8036): /show/583/Inazuma_Eleven_GO_2%3A_Chrono_Stone
01-21 12:55:55.445: I/System.out(8036): /show/671/Ai_Mai_Mi_
01-21 12:55:55.445: I/System.out(8036): /show/697/Mangirl%21
etc...
As a result, I get a mixed list of urls.
Screen:
How to resolve it?
Thanks.
Problem resolved like this
Elements epBox = doc.select("div.ep_box h3");
int urlcount = 0;
for (Element ep : epBox) {
url = ep.select("a").attr("href");
if (urlcount < listItems.size()) {
Order o = (Order) listItems.get(urlcount);
o.setDetailsUrl(URL + url);
newarraylist.add(o);
}
urlcount++;
}