Situation: I have been attempting to parse a URL and retrieve the information between the body tags and setting it in the Android Text View.
Problem: Something is wrong and/or missing..
Code:
package jsouptutorial.androidbegin.com.jsouptutorial;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import java.io.File;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textOut = (TextView)findViewById(R.id.rootTxtView);
//------------------Something went wrong here-------------------------------
Document doc;
try {
//doc = Jsoup.connect("https://stackoverflow.com/questions/45311629/android-jsoup-parsing-url-for-all-body-text").get();
doc = Jsoup.parse(new File("https://stackoverflow.com/questions/45311629/android-jsoup-parsing-url-for-all-body-text"), "UTF-8");
Elements desc = doc.select("a.body");
textOut.setText((CharSequence) desc); //Setting textView to a String
} catch (IOException e) {
e.printStackTrace();
}
//--------------------------------------------------------------------
}
}
You have a couple of problems here:
First you are trying to create a File object from a URL, this will throw an IOException. You instead want to use the JSoup method to retrieve the document from the URL
Document doc = Jsoup.connect("https://stackoverflow.com/questions/45311629/android-jsoup-parsing-url-for-all-body-text").get();
The next problem is your elements selection doc.select("a.body"). This is trying to select all anchor tags <a> with a class of body - and there is none. To get the body just use doc.body()
Also as mentioned by cricket_007 you are attempting a network request from the Main thread so it will throw a NetworkOnMainThreadException the easiest way around this will be to run it in an AsyncTask, see this question for details.
Related
I started to use Socketio, and I got a problem. I can't send a simple message to my flask session. My Java code:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URISyntaxException;
import io.socket.client.IO;
import io.socket.client.Socket;
public class MainActivity extends AppCompatActivity {
Socket socket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
socket = IO.socket("http://192.168.8.101:8080/send");
} catch (URISyntaxException e) {
}
}
public void TestButton(View v){
Log.d("send","before send");
JSONObject obj = new JSONObject();
try {
obj.put("message", "hi");
obj.put("binary", new byte[42]);
socket.emit("mes", obj);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
My Python code:
from flask import Flask
from flask_socketio import SocketIO
app = Flask(__name__)
socketio = SocketIO(app)
#socketio.on("mes", namespace="/send")
def chat_message(message):
print("message:")
if __name__ == "__main__":
print("start")
socketio.run(app, host="0.0.0.0", port=8080)
The error:
TypeError: a bytes-like object is required, not 'str' <Greenlet at 0x24118773178: _handle_and_close_when_done(<bound method WSGIServer.handle of <WSGIServer at , <bound method StreamServer.do_close of <WSGIServer, (<gevent._socket3.socket [closed] object, fd=-1, )> failed with TypeError
I hope someone is able to help me with this problem. I've searched everywhere and i can't find my answer.
I think you use python3 with the gevent and gevent-websocket plugin.
gevent-websocket does not support python3 yet.
You have to options here:
Uninstall gevent and gevent-websocket and use eventlet.
Fix the code geventwebsocket/handler.py at line 236.
if b'101' not in self.status:
I hope I could help you.
I searched this error and tried all available solutions but still getting this error. I am new to android so please help to rectify and remove this error.
I am fully aware that this error is somewhat associated with .R file of android.
I am using eclipse and getting 2 error
1- "activity_main cannot be resolved or is not a field"
2- List is a raw type. Reference to generic type.
Following is MainActivity code. This code is written to calculate nearest located Latlong distance..
package com.example.latlong;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import android.R;
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.os.Environment;
import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
public class MainActivity extends Activity {
Double latToCompare=0.0, longToCompare=0.0;
float shortestDistance = 0.0f;
Boolean isDistanceComparedFirstTime = true;
Boolean isFirstRowInCSV1 = true, isFirstRowInCSV2 = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); /////// Error1 Line
createDirIfNotExists("/windows/Pictures/LatLongFiles");
String csvFilename1 = Environment.getExternalStorageDirectory()+"/windows/Pictures/LatLongFiles/Data.csv";
String csvFilename2 = Environment.getExternalStorageDirectory()+"/windows/Pictures/LatLongFiles/SourceFile.csv";
String csvFilename3 = Environment.getExternalStorageDirectory()+"/windows/Pictures/LatLongFiles/OutputFile.csv";
CSVReader csvReader1 = null;
CSVReader csvReader2 = null;
CSVWriter csvWriter3 = null;
List csvFile2List = null; ///////////// Error2 Line
I know this error is not new to you android guys but i tried everything and still stuck on this error.. Thanks in advance..
Removed import android.R; And clean and rebuild your project
import your_application_package_name.R;
Error 1 indicates that the build system cannot find a layout file called "activity_main.xml". Verify that you have such a layout file.
Error 2 is simply a warning that informs you that you are using a raw type rather than a generic type. Add a type parameter that indicates the type of objects that are to reside in your list, e.g.:
List<YourTypeHere> csvFile2List = null;
Delete import.android.R; and in place of it, add import com.example.latlong.R; if com.example.latlong is your package name.
Or if this is not your package name, see your manifest file for the package name. And add import YourPackageName.R; instead of import.android.R; where YourPackageName is the name of your package.
I'm coding an app which:
- load a URL in a Webview;
- extract the HTML thorugh a javascript code;
- show the extracted HTML code in the LOG.
As i need to load the page without Javascript enabled (to avoid some behaviors of the page), i tried the code below where:
- i load the page in the webview with the Javascript disabled;
- when the page is loaded, i enable the Javascript;
- then, the app execute the Javascript required to extract the HTML code.
Unfortunately, when the code is executed in debug mode on Android 4.0.4, it gives an error:
01-22 22:37:56.575: E/Web Console(7605): Uncaught TypeError: Cannot call method 'processHTML' of undefined at null:1
If i remove the myBrowserSettings.setJavaScriptEnabled(false); declaration, after the loadurl call, everything works correctly.
What i can do to let the code below works?
package com.stefano.formfiller;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.PluginState;
public class MainActivity extends Activity {
WebView myBrowser;
String urlToBrowse = "http://www.mywebsite.com";
String htmlCode = null;
StringBuffer buffer = new StringBuffer();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myBrowser = (WebView)findViewById(R.id.webView1);
//Browser settings
WebSettings myBrowserSettings = myBrowser.getSettings();
//Prevent cache to be used
myBrowserSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
myBrowserSettings.setAppCacheEnabled(false);
//General settings
myBrowserSettings.setJavaScriptEnabled(true);
Log.d("Stefano", "JS enabled");
//FIREFOX user agent
myBrowserSettings.setUserAgentString("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
myBrowser.setWebChromeClient(new WebChromeClient());
myBrowser.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url)
{
WebSettings myBrowserSettings = myBrowser.getSettings();
myBrowserSettings.setJavaScriptEnabled(true);
Log.d("Stefano", "JS enabled");
Log.d("Stefano", "OnPageFinished running");
} });
//Start the delayed HTML code extraction
delayedStartHtmlExtractor(16000);
Log.d("Stefano", "DelayedStart HTML Extractor launched");
//Prepare Javascript to extract the HTML code from the webview
myBrowser.addJavascriptInterface(new LoadListener(), "HTMLOUT");
myBrowser.loadUrl(urlToBrowse);
Log.d("Stefano", "Main URL requested");
myBrowserSettings.setJavaScriptEnabled(false);
Log.d("Stefano", "JS disabled");
}
//Delayed HTML extraction
public void delayedStartHtmlExtractor(final int delay){
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
myBrowser.loadUrl("javascript:window.HTMLOUT.processHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
Log.d("Stefano", "HTML extraction launched");
}
}, delay);
}
//Insert the HTML code in the log information
class LoadListener{
public void processHTML(String html)
{
Log.d("Stefano", "HTML Extraction in progress...");
Log.e("HTML CODE",html);
}
}
Update:
I have a doubt: the code instantiate the Javascript interface while the Javascript is enabled (trough myBrowser.addJavascriptInterface(new LoadListener(), "HTMLOUT");); then, i disable the javascript after the URL call, to re-enable the Javascript when the page is fully loaded.
Could it be that when i disable the Javascript with the instantiated Interface, i "cut-off the communication channel" between the Javascipt and the Java code?
add myBrowser.loadData(...) after the interface setting, like this
myBrowser.addJavascriptInterface(new LoadListener(), "HTMLOUT");
myBrowser.loadData("", "text/html", null);
myBrowser.loadUrl(urlToBrowse);
Also since you will disable js by the end of oncreate method there is no need to enable it on its debut :)
Hope this help
First of all, you should attach the proper annotation #JavascriptInterface to the methods that will be called through the Javascript interface; in your case:
//..
#JavascriptInterface
public void processHTML(String html) {
Log.d("Stefano", "HTML Extraction in progress...");
Log.e("HTML CODE",html);
}
//..
"Note that injected objects will not appear in JavaScript until the page is loaded"
I suppose that loading a page with setJavaScriptEnabled(false) will not inject any Javascript object at all, and this is way you are experiencing this problem.
A possible workaround (untested) could be this:
always load the page using setJavaScriptEnabled(true)
load the webpage passing through http://www.google.com/gwt/n (will load the page without JS or Flash)
do your processing
When you instantiate your LoadListener object, try the following:
this.new LoadListener();
I am trying to create a code which will convert images into video. I have surfed a lot and find some method to do it using javacv. now i am getting variable not found error in these lines.
recorder.setCodecID( CODEC_ID_MPEG1VIDEO);
recorder.setPixelFormat( PIX_FMT_YUV420P);
I have imported all the jar files into my library as well but still getting this error. Some quick help would be appreciated. I have gone through the below link for the importing the javacv into my workspace.
How to Import JavaCV libraries to Android Project
package com.example.photoaday;
import static com.googlecode.javacv.cpp.opencv_core.cvReleaseImage;
import static com.googlecode.javacv.cpp.opencv_highgui.cvLoadImage;
import static com.googlecode.javacv.cpp.opencv_highgui.cvShowImage;
import static com.googlecode.javacv.cpp.opencv_highgui.cvWaitKey;
import static com.googlecode.javacv.cpp.opencv_imgproc.CV_GAUSSIAN;
import static com.googlecode.javacv.cpp.opencv_imgproc.cvSmooth;
import com.googlecode.javacv.FFmpegFrameRecorder;
import com.googlecode.javacv.cpp.opencv_core;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class Recordvideo extends Activity {
// #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create);
opencv_core.IplImage img = cvLoadImage("/sdcard/folder/img1.jpg");
FFmpegFrameRecorder recorder = new FFmpegFrameRecorder("/sdcard/folder/test.mpeg",200,150);
try {
recorder.setCodecID( CODEC_ID_MPEG1VIDEO);
recorder.setFrameRate(30);
recorder.setPixelFormat( PIX_FMT_YUV420P);
recorder.start();
for (int i=0;i<100;i++)
{
recorder.record(img);
}
recorder.stop();
}
catch (Exception e){
e.printStackTrace();
}
}
}
I assume that your compiler gives error as follows
error: ‘CODEC_ID_MPEG1VIDEO’ was not declared in this scope
error: ‘PIX_FMT_YUV420P’ was not declared in this scope
then solution for error is
change : ‘CODEC_ID_MPEG1VIDEO’ to 'AV_CODEC_ID_MPEG1VIDEO'
change : ‘PIX_FMT_YUV420P’ to 'AV_PIX_FMT_YUV420P'
So, I just wanted to use properties-files again, but currently I am just not able to load them! I've already wasted 1h of work just to get this working, but somehow I couldnt. My problem is similar to this one, but Java just doesn't get the file!
Here's my code:
package fast.ProfileManager;
import java.io.FileInputStream;
import java.util.Properties;
import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.Toast;
public class PMMain extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String defaultProfileProperties = "defaultProfile.properties";
Properties properties = new Properties();
properties.load(new FileInputStream(defaultProfileProperties));
...
I've already tried to put an "/" infront of the filename, but it didnt work either.
Here's my Project-Directory:
I'm getting an IOException on the line "properties.load ... "
Check out this introduction to using/accessing properties files in Android.
Based on that link, put the properties file in the /assets folder and use the following code:
// Read from the /assets directory
try {
InputStream inputStream = assetManager.open("defaultProfile.properties"");
Properties properties = new Properties();
properties.load(inputStream);
System.out.println("The properties are now loaded");
System.out.println("properties: " + properties);
} catch (IOException e) {
System.err.println("Failed to open microlog property file");
e.printStackTrace();
}