I have a website which only shows one line of text which I need to extract the text form in android studio, I would prefer to get it as a string. How do I do this?
Something such as webView.getTitle() would work but than for the content of the site, is there such a quick way to get this or how should I else do it?
specific info
the site I need to get the information form is:
"<html> <head></head> <body> #4d636f </body> </html> "
from this I only need the text in the body, in this case a color as text.
You can use any Web Scraper/Crawler API to fetch data from web site.
For example:
JSOUP API For Java And Android
Update
Step By Step guide to solve the mentioned problem
Add Jsoup dependency to the app level of your build.gradle.
implementation 'org.jsoup:jsoup:1.11.1'
Add Internet permission to the Android Manifest file for internet access.
<uses-permission android:name="android.permission.INTERNET" />
Add button and text view in your app to get data from website on button click and display the result on text view.
Below is the sample code:
public class MainActivity extends AppCompatActivity {
private TextView result;
private Button fetch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
fetch = (Button) findViewById(R.id.fetch);
fetch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getBodyText();
}
});
}
private void getBodyText() {
new Thread(new Runnable() {
#Override
public void run() {
final StringBuilder builder = new StringBuilder();
try {
String url="http://www.example.com";//your website url
Document doc = Jsoup.connect(url).get();
Element body = doc.body();
builder.append(body.text());
} catch (Exception e) {
builder.append("Error : ").append(e.getMessage()).append("\n");
}
runOnUiThread(new Runnable() {
#Override
public void run() {
result.setText(builder.toString());
}
});
}
}).start();
}
}
This type of process is known as web scrubbing. And you could do more research to see different methods. One methd I would suggest is getting the HTML from source and searching the DOM for any tags unique to the text you want.
By getting the HTML you avoid rendering the whole page (images, javascript, ect..)
Do you have a snippet of the source code you want to scrub from?
Sure here is an example. P.S. I'm not familiar with javascript, correct him for your case.
webView.evaluateJavascript("return document.getElementById(your_id)", new ValueCallback<String>() {
#Override
public void onReceiveValue(String value) {
// value is your result
}
});
Related
I have a problem that I want to use jsoup to grab news but always fail.
this is news website.
https://www3.nhk.or.jp/news/
this is my picture . which I circle is I wanted data.
https://drive.google.com/open?id=1KJAyOSdHO8APPD6_A9MjxkoFjekcQLXt
but no matter what I do. it always get wrong data or empty.
this is my program.
public class News extends AppCompatActivity {
Button ok;
private static final String url ="https://www3.nhk.or.jp/news/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news);
ok=(Button)findViewById(R.id.ok);
ok.setOnClickListener(okbtn);
}
private Button.OnClickListener okbtn=new Button.OnClickListener(){
public void onClick(View v){
try{
Connection.Response response = Jsoup.connect(url).execute();
String body = response.body();
Document data = Jsoup.parse(body);//visible-phone print_hide
Elements country=data.select("main");
Elements main=data.select("div[id=module module--news-main index-main]");
for(Element e1: country)
{
mytoast(e1+"");
}
}
catch(Exception ex){ex.printStackTrace() ;}
}
};
private void mytoast(String str)
{
Toast toast=Toast.makeText(this, str, Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
please help me
thanks
You can try to see it's HTML first.
If you can't see it, you don't use jsoup.
There's a small hint in its comment:
このページではJavaScriptを使用しています
=>This is generated by JavaScript
If it's generated, you can't find it from Jsoup.
In this case, I'll use Chrome's tool to monitor the XHR tab
Look into each XHR request, and find the most possible one,
for example, I see this
https://www3.nhk.or.jp/news/json16/syuyo.json?_=1559183885640
A part of the response:
"id":"193411",
"title":"三菱UFJ銀行 新規口座は原則デジタル通帳に",
"pubDate":"Thu, 30 May 2019 04:03:11 +0900",
"cate":"5",
...
"id":"193437",
"title":"エアレース世界選手権 今季限りで終了",
"pubDate":"Thu, 30 May 2019 09:40:37 +0900",
So this is exactly what you want. It comes from another link!
You don't need Jsoup, just HttpGet the link
https://www3.nhk.or.jp/news/json16/syuyo.json?_=1559183885640
And I think the numbers looks like UnixTime,
So I check the current time is : 1559184830782, that's it.
Just use that link as API and time as parameter.
I want to send a String message to database when user presses a specific button in the LibGDX game I am designing for android. How do I go about doing that? Following is the code I tried. But it does not work.
Net.HttpRequest httpRequest = new Net.HttpRequest();
httpRequest.setMethod("POST");
httpRequest.setUrl("URL is here");
httpRequest.setContent("INSERT INTO `game_table` (`Button`) VALUES ('Button 1 Pressed')");
Net.HttpResponseListener httpResponseListener = new Net.HttpResponseListener() {
#Override
public void handleHttpResponse(Net.HttpResponse httpResponse) {
Gdx.app.log("Log httpResponse", httpResponse.getResultAsString());
}
#Override
public void failed(Throwable t) {
}
#Override
public void cancelled() {
}
};
Gdx.net.sendHttpRequest(httpRequest,httpResponseListener);
Log does not provide anything in android monitor. I also tried using AsyncTask and without AsyncTask to implement this code. But neither works.
Am I missing something? If so could you give me small code snippet that will work?
You don't need to use an AsyncTask, libGDX' HTTPRequest is async out of the box.
You did not log anything if the request fails or is cancelled so probably that's the case.
i have a sales summary print out and has a QR Code ,
i want to develop an app (IOS and android) that reads the QR code , extract all information,do some calculations,and display in specific form , i tried zxing library but it did not extract all information from the receipt.any tip?
You can use google vision API to achieve this. I personally used this and found it great. The below code snippets should help you.
Put this below line in the gradle.
compile 'com.google.android.gms:play-services:9.4.0'
Use BarcodeDetector and CameraSource classes to capture the QR code on real time and decode it.
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> barcodes = detections.getDetectedItems();
if (barcodes.size() != 0) {
barcodeInfo.post(new Runnable() { // Use the post method of the TextView
public void run() {
barcodeInfo.setText( // Update the TextView
barcodes.valueAt(0).displayValue
);
}
});
}
}
});
Use a SparseArray to fetch the detections and the displayValue of the elements of this sparse array returns the deocded string.
After extracting the string one can do anything, be it displaying the string or make some calculation out of it etc.
This library is the most popular and easiest of reading QR codes in your Android application.
You should also have a look at the Wiki section of this library for learning about how to integrate this library into your Android Application and how to use this library.
This is how you can use this library.
1. Add this library to your project by adding following line into your dependencies inside build.gradle(Module: app) file
compile 'com.github.nisrulz:qreader:2.0.0'
2. Then, after syncing project files, add the SurfaceView element provided by this library into your XML layout file.
<SurfaceView
android:id="#+id/camera_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
3. Declare the SurfaceView & QREader inside your Activity's Java file & then initialize it inside onCreate() method.
class MainActivity extends AppCompatActivity{
private SurfaceView mySurfaceView;
private QREader qrEader;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Setup SurfaceView
// -----------------
mySurfaceView = (SurfaceView) findViewById(R.id.camera_view);
// Init QREader
// ------------
qrEader = new QREader.Builder(this, mySurfaceView, new QRDataListener() {
#Override
public void onDetected(final String data) {
Log.d("QREader", "Value : " + data);
text.post(new Runnable() {
#Override
public void run() {
text.setText(data);
}
});
}
}).facing(QREader.BACK_CAM)
.enableAutofocus(true)
.height(mySurfaceView.getHeight())
.width(mySurfaceView.getWidth())
.build();
}
4. Initialize it inside onResume()
#Override
protected void onResume() {
super.onResume();
// Init and Start with SurfaceView
// -------------------------------
qrEader.initAndStart(mySurfaceView);
}
There are many more possibilities you can do with this library, so I recommend you to visit the GitHub repository and check it out. It's worth a shot!
I want to have a simple gauge view where i will define the start value and the end value and have a pointer to show given variable value.
So i can show a given value like speedmeter. For example if my the value of a textView is 1300, then next to the textview i want to have this custom meter view animation like this!
It is possible? Any existing example code?
Another one i found at Evelina Vrabie's blog, used it and worked perfect!
Look at Evelina Vrabie's GitHub.
It has a gauge library and some samples to interact with.
Big thanks to the owner Evelina Vrabie!
However it is not working on XHDPI/Few versions of android devices (above 4). Problem is the text in gauge view.
For anyone looking for simple gauge view I made a library that you can clone and use/modify for your needs.
CustomGauge
All other gauges you recommended have bugs and don't run fine on Kitkat and Lollipop. Also there is no Android Studio and gradle friendly library here.
Here's git repo for the more recent one updated for Lollipop you can use with Gradle:
https://github.com/Sulejman/GaugeView
After you include library in your project add gaugelibrary to xml layout of your activity:
<io.sule.gaugelibrary.GaugeView
android:id="#+id/gauge_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
gauge:showOuterShadow="false"
gauge:showOuterRim="false"
gauge:showInnerRim="false"
gauge:needleWidth="0.010"
gauge:needleHeight="0.40"
gauge:scaleStartValue="0"
gauge:scaleEndValue="100"
/>
This will show static gauge without needle. To instantiate needle with random animation you need to do that in activity class file. See how it's done here:
package io.sule.testapplication;
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.Menu;
import android.view.MenuItem;
import java.util.Random;
import io.sule.gaugelibrary.GaugeView;
public class MainActivity extends Activity {
private GaugeView mGaugeView;
private final Random RAND = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGaugeView = (GaugeView) findViewById(R.id.gauge_view);
mTimer.start();
}
private final CountDownTimer mTimer = new CountDownTimer(30000, 1000) {
#Override
public void onTick(final long millisUntilFinished) {
mGaugeView.setTargetValue(RAND.nextInt(101));
}
#Override
public void onFinish() {}
};
}
This will instantiate needle and make it animate moving to random values.
I made this one a while ago. Feel free to clone and modify. (It takes some ideas from the old Vintage Thermometer.)
github.com/Pygmalion69/Gauge
It can easily be added to your Gradle project:
repositories {
maven {
url 'https://www.jitpack.io'
}
}
dependencies {
compile 'com.github.Pygmalion69:Gauge:1.1'
}
The views are declared in XML:
<de.nitri.gauge.Gauge
android:id="#+id/gauge1"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:layout_weight="0.75"
gauge:labelTextSize="42"
gauge:maxValue="1000"
gauge:minValue="0"
gauge:totalNicks="120"
gauge:valuePerNick="10"
gauge:upperText="Qty"
gauge:lowerText="#string/per_minute" />
Here's an example of setting the values programmatically:
final Gauge gauge1 = (Gauge) findViewById(R.id.gauge1);
final Gauge gauge2 = (Gauge) findViewById(R.id.gauge2);
final Gauge gauge3 = (Gauge) findViewById(R.id.gauge3);
final Gauge gauge4 = (Gauge) findViewById(R.id.gauge4);
gauge1.moveToValue(800);
HandlerThread thread = new HandlerThread("GaugeDemoThread");
thread.start();
Handler handler = new Handler(thread.getLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
gauge1.moveToValue(300);
}
}, 2800);
handler.postDelayed(new Runnable() {
#Override
public void run() {
gauge1.moveToValue(550);
}
}, 5600);
HandlerThread gauge3Thread = new HandlerThread("Gauge3DemoThread");
gauge3Thread.start();
Handler gauge3Handler = new Handler(gauge3Thread.getLooper());
gauge3Handler.post(new Runnable() {
#Override
public void run() {
for (float x = 0; x <= 6; x += .1) {
float value = (float) Math.atan(x) * 20;
gauge3.moveToValue(value);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
gauge4.setValue(333);
On this site you will find some free customizable gauges.
ScComponents
Very easy to install and well documented.
For example you can have for free something like this in 5 minutes following the instruction below.
Go on the above linked website. Click the GR004 and after the popup appear click on "Download for FREE".
The library will downloaded, unzip and follow the instruction to install the library (aar file) inside your Android project.
Write this code in your XML layout and your gauge will done:
<com.sccomponents.gauges.gr004.GR004
android:layout_width="match_parent"
android:layout_height="match_parent" />
You have many XML options to customize it:
sccAnimDuration
sccEnableTouch
sccInverted
sccFontName
sccLabelsSizeAdjust
sccMajorTicks
sccMaxValue
sccMinorTicks
sccMinValue
sccShowContour
sccShowLabels
sccText
sccValue
And the related function by coding.
I don't know whether the late answer is going to help or not. I also came to the same situation where i want to use a gauge to visualize data, since gauge is not given as widget in android, as a enthusiast i went for libraries like above which can be found through various links in the Internet, although it was quite helpful(thanks to the wonderful authors of it..) i find myself difficult to visualize the during certain situations, so another solution what i have done is for my app is i integreated the JavaScript gauges into my android application.
You can do that by the following steps
Create an asset folder in our project-look this link and you will see how to create an asset folder if someone don't knows about it.
Next one is you have design an html page on how your page sholud look like, for eg- header,no.of guages etc... and place it in the folder asset.
There are many sites which provide the guages like This is one site or you can browse other sites and take whatever you feel cool...!!
take it all including .js files and place it in the asset folder.
Android provides a class for handling webiview called "WebViewClient" you can browse more to know more about it in internet
This is sample code for viewing the webview content..
web = (WebView) findViewById(R.id.webview01);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
web.setWebViewClient(new myWebClient());
web.getSettings().setJavaScriptEnabled(true);
web.post(new Runnable() {
#Override
public void run() {
web.loadUrl("file:///android_asset/fonts/guage.html");
}
});
The above for loading the html & javscript.
public class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
progressBar.setVisibility(View.VISIBLE);
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
}
This the webview class
You can also send data from activity to html page.. Refer This link
Kindly read through all, corrections are welcomed..!!
Use this : Sample Project
It can easily be added to your Gradle project:
repositories {
maven {
url 'https://www.jitpack.io'
}
}
dependencies {
implementation 'com.jignesh13.speedometer:speedometer:1.0.0'
}
The views are declared in XML:
<com.jignesh13.speedometer.SpeedoMeterView
android:id="#+id/speedometerview"
android:layout_width="250dp"
android:layout_height="250dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.453"
app:layout_constraintStart_toStartOf="parent"
app:backimage="#android:color/black"
app:needlecolor="#fff"
app:removeborder="false"
app:linecolor="#fff"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.079" />
I try to select text in webview, after I select text,I need to decide what to do next.not just copy the selected text.I have more choice for user to choose from.I mean, after user selected text in webview,could I prompt out a some button for further? I tried use emulateshiftheld to solve my problem.but google's docs said " This method is deprecated".
also,I can't prompt out some choice button.
you can clck the link to see what I mean. link: https://public.blu.livefilestore.com/y1pHhMR2iyIbQN7uJ2C-9CLLJBosWAZw2r4MvD0qyyTG-QWUM-06i6HFu4Fn4oaWnHMbDyTBOa-CPwN6PwoZNifSQ/select.jpg?download&psid=1
Pasting relevant code from WebView emulateShiftHeld() on Android Newer SDK's
/**
* Select Text in the webview and automatically sends the selected text to the clipboard
*/
public void selectAndCopyText() {
try {
KeyEvent shiftPressEvent = new KeyEvent(0,0,KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_SHIFT_LEFT,0,0);
shiftPressEvent.dispatch(mWebView);
} catch (Exception e) {
throw new AssertionError(e);
}
}
The question is very old, but for other people here is a solution with javascript for API 19+. Just add this to your WebView:
public void getSelectedText(final SelectedTextInterface selectedTextInterface) {
evaluateJavascript("(function(){return window.getSelection().toString()})()", new ValueCallback<String>() {
#Override
public void onReceiveValue(final String selectedText) {
if (selectedText != null && !selectedText.equals("")) {
//If you don't have a context, just call
//selectedTextInterface.onTextSelected(selectedText);
if (context instanceof Activity) {
((Activity) context).runOnUiThread(new Runnable() {
#Override
public void run() {
selectedTextInterface.onTextSelected(selectedText);
}
});
} else selectedTextInterface.onTextSelected(selectedText);
}
}
});
}
public interface SelectedTextInterface {
void onTextSelected(String selectedText);
}
When you are done with selecting text, just call it with:
webView.getSelectedText(new YourWebView.SelectedTextInterface() {
#Override
public void onTextSelected(String selectedText) {
//Your code here
}
});
I hope this may be useful for some people :-)