Parse an <div> of an website to web view - java

Hey Im trying to take a specific part of an website and then display it on my web view but the problem is when I do that , on smaller screens the letters got all bugged whit accents and stuff , is there any way that I can transfer just a specific div of the website to my web view that is not this bugged one ?
The part that I need in this website is called : "inside2"
This is the website: http://www.dges.gov.pt/guias/detcursopi.asp?codc=8184&code=0400
Code that I load the info :
private class MyTask extends AsyncTask<String, Integer, String> {
// Runs in UI before background thread is called
#Override
protected void onPreExecute() {
super.onPreExecute();
}
// This is run in a background thread
#Override
protected String doInBackground(String... params) {
// get the string from params, which is an array
Bundle CursoInfoData = getIntent().getExtras();
site = CursoInfoData.getString("site");
Document doc = null;
try {
doc = Jsoup.connect(site).get();
} catch (IOException e) {
e.printStackTrace();
}
ele = doc.select(".inside2");
return "start";
}
// This is called from background thread but runs in UI
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
// Do things like update the progress bar
}
// This runs in UI when background thread finishes
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
String text = "<html><head>"
+ "<style type=\"text/css\">body{color: #01A9DB; background-color: #FFFFFF;}"
+ "</style></head>"
+ "<body>"
+ ele.toString()
+ "</body></html>";
cursoInfoWeb.loadData(text, "text/html", "utf-8");
}
bugged form that I told you

You have utf-8 problem I guess. Use this:
cursoInfoWeb.loadDataWithBaseURL(null, text, "text/html", "UTF-8", null);
Reference: SO answer

Related

How to read .txt file line by line from assets folder efficiently & in a fast way in Android Studio?

I've a text file in my assets folder, where it has around 15000 lines, I wanna loop through each line, I've applied the logic using BufferedReader, but it takes too long to loop through each line(1min+).
Now I need to reduce the time of reading each line to maximize the UX.
AsyncTask<Void, String, Void> asyncTask = new AsyncTask<Void, String, Void>() {
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
appBarLayout.setVisibility(View.VISIBLE);
viewpager.setVisibility(View.VISIBLE);
splashScreen.setVisibility(View.GONE);
gamesLoaded = true;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
makeRandomText(gameRandomText, "Random Text" + new Random().nextInt(1000));
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
gamePercentage.setText(values[0]);
}
#Override
protected Void doInBackground(Void... voids) {
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("games.txt"), "UTF-8"));
int startingCount = 0;
// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
Game gameAdded = new Game(mLine);
addGame(database, gameAdded);
startingCount++;
String percentage = startingCount * 100 / Constants.GAMES_COUNT + "%";
publishProgress(percentage);
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
return null;
}
};
Without knowing how long it takes to execute addGame it is hard to say for sure, but I suspect the issue lies with your use of runOnUiThread. You said your file contains 15000 lines so it will create and schedule an update that the UI handler HAS to run for each item with the way you have it set up.
What you are not aware of is that AsyncTask has a built-in way to handle progress which handles request debouncing for you. Look into the publishProgress and onProgressUpdate methods to handle to UI updates.

jSoup method closes android App

I'm trying to use jsoup to display temperature of Boston from a website as a toast message in an android app. My Java program looks like this:
public static void showWeather() throws IOException
{
Document doc = Jsoup.connect("http://www.wunderground.com/US/ma/boston.html?MR=1").get();
Elements languages = doc.select("#tempActual span.b ");
for(Element langElement: languages)
{
//System.out.println(" The temperature in Boston: "+langElement.text()+ " F");
}
}
The Java program works Okay and prints the temperature of Boston to the screen. I want to use this method to try to display the temperature as a toast in a simple android app, but when I try to run to method (without the print statement of course) in the onCreate method in my android activity, the program closes automatically. Here's my onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addKeyListener();
try {
showWeather();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Can anybody please tell how to run this java program in my android activity? I don't know how to treat the try/catch clause properly. I tried put toast in the catch clause but to no avail. Please help.
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
Reference:
http://developer.android.com/reference/android/os/AsyncTask.html
Usage
AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground(Params...)), and most often will override a second one (onPostExecute(Result).)
Here is an example of subclassing:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
Once created, a task is executed very simply:
new DownloadFilesTask().execute(url1, url2, url3);

MetaIO progressDialog freezes when loading SDK

I am quite new to Android/Java, and my first app is using MetaIO SDK.
I am trying to implement "Loading" progress bar, while app (MetaIO SDK) is loading.
Overlay background is shown
Loading dialog is appeared and "loading image" starts spinning
Overlay background disappears and loading image stops spinning <- the problem
After 2-3 seconds it unfreezes and ARELViewActivity is executed.
The code:
public void onScanButtonClick(View v)
{
new ScanLoadingDialog().execute(0);
}
private class ScanLoadingDialog extends AsyncTask<Integer, Integer, Boolean>
{
//Before running code in separate thread
#Override
protected void onPreExecute()
{
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(false);
progressDialog.show();
}
#Override
protected Boolean doInBackground(Integer... params)
{
try
{
synchronized (this) {
AssetsManager.extractAllAssets(getApplicationContext(), true);
startActivity( new Intent(getApplicationContext(), ARELViewActivity.class));
}
}
catch (IOException e)
{
MetaioDebug.log(Log.ERROR, "Error extracting assets: "+e.getMessage());
MetaioDebug.printStackTrace(Log.ERROR, e);
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean result)
{
progressDialog.dismiss();
finish();
}
}
Am I doing something wrong?
P.S. Full source code can be found here: link text
P.S.S. Related to this question, but I am using technique suggested there, and it still doesn't want to work
I had a similar problem and i solved it by running the UI handling code on the UI thread like so
runOnUiThread(new Runnable() {
#Override
public void run() {
if (imgvExampleOverlay != null)
imgvExampleOverlay.setVisibility(View.VISIBLE);
}
});
imgvExampleOverlay is an image like the one the user has to capture.
Hope this helps

Java/Android Asynchronous work in the background

in the past few days I have been trying to figure something but had no luck, I am developing an android game, I have 3 packages for now each with its own purpose:
1 - package for GUI classes.
2 - package that has classes communicates with my wcf service (login/pass DB)
3 - package that holds my asynchronous classes/workers (like a bridge between GUI and SERVICE)
I am not sure if this is even the right approach when it comes to android/java game development, but what I want to achieve is a simple registeration/login in the GUI and when the user is done registering or logining, while the gui talks to the service through the "bridge", a message is displayed for the user like a dialog saying "registering" or "loging in".
Now I would like to hear tips/feedback from more experienced programmers, on how to acomplish this, and if this is the right aproach, and most importantly some examples for this specific case would be really helpfull, I tried to work with the asynctask but I couldn't figure out how to communicate between these 3 seperate packages and return the result from the service back to the gui through the async task.
Take a look at this
public class FindEventsActivity extends Activity {
ProgressDialog pd;
// lots of other code up here
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.clickete);
pd = new ProgressDialog(this);
pd.setMessage("loading");
findViewById(R.id.clickLayout).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
new LongOperation().execute("");
pd.show();
}
});
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
for (int i = 0; i < 15; i++) {
try {
Thread.sleep(1000); // Simulates your intensive work
// Update your progress if you want
this.publishProgress();
} catch (InterruptedException e) {
return "Failed";
}
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
// Handle fail or success accordingly
pd.dismiss();
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
// Update UI according to your progress
}
}
}
Hope this helps and enjoy your work

Show ProgressDialog, Retrieve Data, and WAIT FOR IT

I'm writing an app that at many points will attempt to retrieve account information from a website. I'd like to write a single function ("getAccount()") to do the following:
Show a ProgressDialog
Make the call to the website
Wait for a response
Clear the ProgressDialog
Return control to the calling function after the first four steps are done
I'm not having a problem with getting the data from the page; the problem I have is with the whole "show dialog / wait for completion / return control to the calling function" portion. Either the ProgressDialog doesn't show at all, or the function returns to the caller immediately after making the data request from the site, without giving it enough time to retrieve the data.
Any help would be most appreciated.
EDIT: I'm adding a bit of code below for what I have with AsyncTask. Notice that I have the line MsgBox("done") inside grabURL(); this is simply a Toast call. When I run this code, "done" pops up while the HTTP request is still being made. This MsgBox line only exists so I can see if grabURL is properly waiting for GrabURL to finish (which it isn't).
public void grabURL() {
new GrabURL().execute();
MsgBox("done");
}
private class GrabURL extends AsyncTask<String, Void, Void> {
private ProgressDialog Dialog = new ProgressDialog(MyContext);
protected void onPreExecute() {
Dialog.setTitle("Retrieving Account");
Dialog.setMessage("We're retrieving your account information. Please wait...");
Dialog.show();
}
protected Void doInBackground(String... urls) {
try {
// Get account info from the website
String resp = GetPage(ThePage); // I have this classed out elsewhere
// Some other code that massages the data
AccountRetrievalSuccess = true;
} catch (Exception e) {
AccountRetrievalSuccess = false;
}
return null;
}
protected void onPostExecute(Void unused) {
Dialog.dismiss();
}
}
The message box done appears because AsyncTask is using a separate thread(s) to run doInBackground. The call to execute does NOT block. You could move message box done to onPostExecute following the call to dismiss. Tip. You may want to call progress.cancel in onPause or you may get unwanted behaviour on orientation change. Finally, if you are retrieving info in doInBackground, consider returning the info in doInBackground. The info will be passed to onPostExecute. So if the info is object MyInfo consider:
private class GrabURL extends AsyncTask<String, Void, MyInfo> {
Can't say for sure without seeing some code but sounds like you are making a asynchronous call to the website when you want to make a synchronous call (which will block and wait for return data) to the website instead.
You want to use an AsyncTask, generate a non-user-cancellable ProgressDialog in the onPreExecute, do your work in doInBackground, and dismiss it in onPostExecute.
Something like this:
public class MyApp extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// blah blah blah
URL url;
try
{
url = new URL("http://example.com");
new MyTask().execute(url);
}
catch (MalformedURLException e)
{
}
}
protected void doSomeStuff()
{
// stuff to do after the asynctask is done
}
protected void throwAWobbly()
{
// stuff to do if you didn't get the data
}
// inner class to do the data getting off the UI thread,
// so android doesn't "not responding" kill you
private class MyTask extends AsyncTask<URL, Void, Boolean>
{
private ProgressDialog dialog;
private boolean gotData = false;
protected void onPreExecute()
{
// create a progress dialog
dialog = ProgressDialog.show(MyApp.this, "",
"Doing stuff. Please wait...", false, false);
}
protected Boolean doInBackground(URL... urls)
{
// get your data in here!
return gotData;
}
protected void onPostExecute(Boolean result)
{
// get rid of the progress dialog
dialog.dismiss();
if (true == result)
{
// got all data!
doSomeStuff();
}
else
{
// oops!
throwAWobbly();
}
}
}
}

Categories

Resources