android WebView cant render my native language - java

Hello I am trying to load HTML (From String)
Here is the RSS feed (I am getting a link from there and after that HTML string from specific class ):
http://www.naec.ge/index.php?option=com_rsssyndicator&feed_id=1&format=raw
As you can see it is encoded in utf-8, but still I can't render it, it gives me this result: android web view result
Here are the code fragments :
class parseText extends AsyncTask<String,Void,String>
{
protected String doInBackground(String... params)
{
try {
org.jsoup.nodes.Document doc = Jsoup.connect(url).get();
System.out.println("hey kurwo "+doc.getElementsByClass("article-content"));
data = doc.getElementsByClass("article-content").toString();
} catch (IOException e) {
e.printStackTrace(); System.out.println("jeban!!");
}
return null;
}
#Override
protected void onPostExecute(String s) {
System.out.println("chiken boneZZZ");
view.loadData(data,"text/html","UTF-8");
super.onPostExecute(s);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
}
}
Also this, I don't think there is any problem :
public class NewsDetails extends Activity
{
static String url;
WebView view;
TextView info;
static String data;
String address;
Bundle bundle;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detailed_news_layout);
bundle = getIntent().getExtras();
url = bundle.getString("Link");
view = (WebView) findViewById(R.id.webview);
new parseText().execute();
}

here is a deal you have to use loaddatawithbaseurl instead of loadData(), here is example : this will not work view.loadData(data,"text/html","utf-8");
this will work :
view.loadDataWithBaseURL(null, data, "text/html", "UTF-8", null);

Related

How to do tasks like HttpURLConnection in the background of a app using Java in Android Studio?

I am basically following a tutorial for learing Android Studio that uses AsyncTask class for doing background tasks like HttpURLConnection. But the thing is that it created a lot of error and later I found out that class was deprecated. So what is the alternative?
(Please provide an example code if you can)
CODE:
public class MainActivity extends AppCompatActivity {
public class DownloadingTask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urls)
{
String result="";
HttpURLConnection urlConnection=null;
URL url;
try{
url=new URL(urls[0]);
urlConnection=(HttpURLConnection)url.openConnection();
InputStream in;
in = urlConnection.getInputStream();
InputStreamReader reader=new InputStreamReader(in);
int data=reader.read();
while (data!=-1)
{
char current=(char) data;
result = result + current;
data=reader.read();
}
return result;
}
catch (Exception e)
{
e.printStackTrace();
return "Failed";
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadingTask task= new DownloadingTask();
String s=null;
try {
s = task.execute("http://www.android.com/").get();
}
catch (Exception e)
{
e.printStackTrace();
}
Log.i("Msg",s);
}
}
This is an example that shows how to download an image using AsynkTask.
private class DownLoadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView imageView;
DownLoadImageTask(ImageView imageView) {
this.imageView = imageView;
}
protected Bitmap doInBackground(String... urls) {
String urlOfImage = urls[0];
Bitmap logo = null;
try {
InputStream is = new URL(urlOfImage).openStream();
logo = BitmapFactory.decodeStream(is);
} catch (Exception e) { // Catch the download exception
Log.v("download", e.getMessage());
}
return logo;
}
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
}
This is how to run it
new DownLoadImageTask(img).execute(imageUrl);
Any update is done in this method onPostExecute as it runs on the UI Thread.
Yes, You are right. AsynkTask is deprecated. You can use LoderManager and Java Executor
Or Volley, Retrofit libraries
For downloading images, You can use Picasso and Gilde Libraries.

Cannot use asyncTask.cancel ()

I have a dataGetter class in which I load the necessary data (part of the url address, email, ...) and then call AsyncTask.
I use a drawer menu where every single fragment calls, when creating, a dataGetter from a new thread. If I quickly switch between fragments (before AsyncTask completes), the data will mix (in the new fragment I will release the data from the previous one).
I've tried using AsyncTask.cancel, but I always get an error.
public class dataGetter {
#SuppressLint("StaticFieldLeak")
public static Context context;
private static String siteURL;
private static String domain;
private static boolean login;
private static String email;
private static String password;
private static AsyncRetrieve asyncRetrieve;
public static String getData(Context context, String url, String domain, boolean login, String email, String password) {
dataGetter.context = context;
dataGetter.siteURL = url;
dataGetter.domain = domain;
dataGetter.login = login;
dataGetter.email = email;
dataGetter.password = password;
String result = "";
try {
if (asyncRetrieve != null)
asyncRetrieve.cancel(true);
asyncRetrieve = new AsyncRetrieve();
result = asyncRetrieve.execute().get();
}
catch (ExecutionException | InterruptedException e) {
Sentry.capture(e);
e.printStackTrace();
}
return result;
}
public static class AsyncRetrieve extends AsyncTask<String, Void, String> {
HttpsURLConnection conn;
URL url = null;
// This method does not interact with UI, You need to pass result to onPostExecute to display
#Override
protected String doInBackground(String... params) {
.....
}
}
}
Any call to asyncRetrieve.cancel () returns the following error
E/AndroidRuntime: FATAL EXCEPTION: Thread-9
Process: com.example.wedos, PID: 6709
java.util.concurrent.CancellationException
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:193)
at android.os.AsyncTask.get(AsyncTask.java:542)
at com.example.xyz.dataGetter.getData(dataGetter.java:45)
at com.example.xyz.ui.domains.DomainsFragment.getDetails(DomainsFragment.java:195)
at com.example.xyz.ui.domains.DomainsFragment.access$100(DomainsFragment.java:36)
at com.example.xyz.ui.domains.DomainsFragment$1.run(DomainsFragment.java:74)
at java.lang.Thread.run(Thread.java:764)
I tried to search the internet, but unfortunately nothing.
Would anyone advise me how to cancel the asynctask so that the data from the previous fragment does not appear in the new?
Thank you very much in advance
EDIT
First fragment "domains"
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
//new ViewModelProvider(this).get(DomainsViewModel.class);
root = inflater.inflate(R.layout.fragment_domains, container, false);
context = root.getContext();
setHasOptionsMenu(true);
models = new ArrayList<>();
result = new ArrayList<>();
progressBar = root.findViewById(R.id.loading);
viewPager2 = root.findViewById(R.id.viewPager);
tabLayout = root.findViewById(R.id.tabs);
linearLayout = root.findViewById(R.id.DomainsLinearLayout);
thread = new Thread(new Runnable() {
#Override public void run() {
try {
getData();
} catch (JSONException e) {
Sentry.capture(e);
e.printStackTrace();
}
for (String domena : result) {
try {
getDetails(domena);
} catch (JSONException e) {
Sentry.capture(e);
e.printStackTrace();
}
}
}
});
thread.start();
check();
return root;
}
#Override
public void onDestroy() {
super.onDestroy();
asyncRetrieve.cancel(true);
System.out.println("On Destroy");
if (thread.isAlive())
thread.interrupt();
}
Second fragment "cash"
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
//new ViewModelProvider(this).get(CashViewModel.class);
View root = inflater.inflate(R.layout.fragment_cash, container, false);
context = root.getContext();
setHasOptionsMenu(true);
textView = root.findViewById(R.id.cash_amount);
progressBar = root.findViewById(R.id.loading);
linearLayout = root.findViewById(R.id.CashLinearLayout);
Button cashHistory = root.findViewById(R.id.showHistory);
cashHistory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int index = result.indexOf(' ');
Intent i = new Intent(context, CashHistoryActivity.class);
i.putExtra("CURRENCY", result.substring(index));
startActivity(i);
}
});
thread = new Thread(new Runnable() {
#Override
public void run() {
getData();
}
});
thread.start();
return root;
}
getData() method
result = dataGetter.getData(context, "cashCheck", "", false, "", "");
Latest error
I/System.out: On Destroy
E/AndroidRuntime: FATAL EXCEPTION: Thread-12
Process: com.example.wedos, PID: 9115
java.util.concurrent.CancellationException
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:193)
at android.os.AsyncTask.get(AsyncTask.java:542)
at com.example.wedos.dataGetter.getData(dataGetter.java:45)
at com.example.wedos.ui.cash.CashFragment.getData(CashFragment.java:90)
at com.example.wedos.ui.cash.CashFragment.access$200(CashFragment.java:25)
at com.example.wedos.ui.cash.CashFragment$2.run(CashFragment.java:59)
at java.lang.Thread.run(Thread.java:764)
D/io.sentry.android.event.helper.AndroidEventBuilderHelper: Proguard UUIDs file not found.
W/System.err: SLF4J: Failed to load class "org.slf4j.impl.StaticMDCBinder".
SLF4J: Defaulting to no-operation MDCAdapter implementation.
SLF4J: See http://www.slf4j.org/codes.html#no_static_mdc_binder for further details.
W/System.err: java.lang.InterruptedException
at java.util.concurrent.FutureTask.awaitDone(FutureTask.java:420)
at java.util.concurrent.FutureTask.get(FutureTask.java:192)
at android.os.AsyncTask.get(AsyncTask.java:542)
at com.example.wedos.dataGetter.getData(dataGetter.java:45)
at com.example.wedos.ui.domains.DomainsFragment.getDetails(DomainsFragment.java:198)
at com.example.wedos.ui.domains.DomainsFragment.access$100(DomainsFragment.java:38)
at com.example.wedos.ui.domains.DomainsFragment$1.run(DomainsFragment.java:76)
at java.lang.Thread.run(Thread.java:764)
I/Process: Sending signal. PID: 9115 SIG: 9
I recommend dropping the dataGetter class and removing the extra Thread that runs the AsyncTask. As the way you handle the API response depends on the fragment, you should create a public base class, e.g. AsyncReceiver in a seperate file.
public class AsyncRetrieve extends AsyncTask<String, Void, String> {
private Context context;
private Domain domain;
// etc.
public AsyncRetrieve(Context context, String domain, boolean login, String email, String password) {
this.context = context;
this.url = url;
this.domain = domain;
// etc.
}
#Override
public String doInBackground(String... params) {
return fetchData("domainList");
}
private String fetchData(String url) {
// do what you originally did in the old doInBackground
// of the old AsyncRetriever class, but use the url argument
// passed to this method
return result;
}
}
Then, in your fragments add a private extended subclass of AsyncReceiver that implements the onPostExecute method. That's where you handle the API response and update your views accordingly.
For example:
public class DomainsFragment extends Fragment {
private DomainsAsyncReceiver receiver;
// example text view that is updated on results
private TextView tv_results;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// instantiate your views
// e.g.
tv_results = findViewById(R.id.tv_results);
// etc.
// instantiate the async task
receiver = new DomainsAsyncReceiver(domain, url, etc.);
receiver.execute();
}
#Override
public void onDestroy() {
super.onDestroy();
// cancel the async task
receiver.cancel(true);
}
private class DomainsAsyncReceiver extends AsyncRetrieve {
#Override
protected String doInBackground(String... params) {
String result = fetchData("domainList");
// do something with the result, e.g.
String details = fetchData("domainDetails");
return details;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tv_results.setText(result);
}
}
}

Pass-parameter when calling a function in Java

in java, i'm calling a function which reads a text file's content from the web into a variable, but my problem is that the file's url is hardcoded in the functio. I would like to use this function several times for different files. So how can i manage, to add the file's url when i call the function?
The function is;
public class readtextfile extends AsyncTask<String, Integer, String>{
private TextView description;
public readtextfile(TextView descriptiontext){
this.description = descriptiontext;
}
#Override
protected String doInBackground(String... params) {
URL url = null;
String result ="";
try {
url = new URL("http://example.com/description1.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line = null;
while ((line = in.readLine()) != null) {
result+=line;
}
in.close();
}
catch (MalformedURLException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
return result;
}
protected void onProgressUpdate() {
//called when the background task makes any progress
}
protected void onPreExecute() {
//called before doInBackground() is started
}
#Override
protected void onPostExecute(String result) {
this.description.setText(result);
}
}
Where i'm calling the function:
public class PhotosActivity extends Activity {
TextView description;
String descriptiontext;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photos_layout);
description = ((TextView)findViewById(R.id.description1));
new readtextfile(description).execute();
}
}
Using AsyncTask for a single task is not a good solution, you should better look to Threads.
But if you want to use AsyncTask, anyway, you can add a constructor like this :
public readtextfile(TextView descriptiontext, String url){
this.description = descriptiontext;
this.url = url;
}
And use this.url in your doInBackground.

Parsing Xml with Sax on Android

I'm trying to parse an XML from a url page. To do so I have used the SAX implementation explained in this IBM example with the Adapter and other changes I got from this article. I've also tried to implement an AsyncTask to do the parsing and show a ProgressDialog but I think this is where my application starts to break down.
I don't really know exactly how to implement the AsyncTask into my code, and I believe my poor implementation is causing my app to force close.
MainActivity:
public class MainActivity extends Activity {
/** Called when the activity is first created. */
ListView lv1;
ProgressDialog ShowProgress;
public static ArrayList<MangaItem> MangaItemList = new ArrayList<MangaItem>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv1 = (ListView) findViewById(R.id.listView1);
ShowProgress = ProgressDialog.show(MainActivity.this, "",
"Loading. Please wait...", true);
//new loadingTask().execute("http://www.mangapanda.com/alphabetical");
new loadFeedTask().execute();
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri
.parse(MangaItemList.get(position).getMangaLink()));
startActivity(intent);
}
});
}
class loadFeedTask extends AsyncTask<String, Void, ArrayList<MangaItem>> {
private String feedUrl;
protected void onPostExecute(String s) {
lv1.setAdapter(new EfficientAdapter(MainActivity.this, MangaItemList));
//new MangaParserTask().execute();
ShowProgress.dismiss();
}
protected ArrayList<MangaItem> doInBackground(String... params) {
ArrayList<MangaItem> ParsedMangaItemList = new ArrayList<MangaItem>();
feedUrl = "http://www.mangapanda.com/alphabetical";
FeedParser parser = new SaxFeedParser(feedUrl);
ParsedMangaItemList = parser.parse();
for (MangaItem mitem : ParsedMangaItemList) {
MangaItemList.add(mitem);
}
return MangaItemList;
}
}
}
How can I properly use AsyncTask so that my parser will return an ArrayList that I can then put into an ArrayAdapter
Improper use of type parameters in subclass (AsyncTask<Params, Progress, Result>). Re-write the AsyncTask sub-class.
class loadFeedTask extends AsyncTask<String, Void, ArrayList<MangaItem>> {
protected void onPostExecute(ArrayList<MangaItem> list) {
lv1.setAdapter(new EfficientAdapter(MainActivity.this, list));
ShowProgress.dismiss();
}
protected ArrayList<MangaItem> doInBackground(String... params) {
ArrayList<MangaItem> list=null;
String feedUrl = "http://www.mangapanda.com/alphabetical";
FeedParser parser = new SaxFeedParser(feedUrl);
list = parser.parse();
MangaItemList=list;
return list;
}
}
use this code
try {
items = new ArrayList<String>();
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new InputStreamReader(
getUrlData(" url")));
while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {
Log.i(TAG, "doc started");
if (xpp.getEventType() == XmlPullParser.START_TAG) {
if (xpp.getName().equals("entry")) {
items.add(xpp.getAttributeValue(0));
}
}
xpp.next();
}
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
get url data method
public InputStream getUrlData(String url) throws URISyntaxException,
ClientProtocolException, IOException {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(new URI(url));
HttpResponse res = client.execute(method);
return res.getEntity().getContent();
}

Android debugger and JSOUP: Source not found

I am trying to retrieve a website's html code and parse it to get the site's text. For some reason the class I have below runs fine when I comment out the jsoup library part of the code, but otherwise I get this weird error "source code not found", and the debug section does not hit any of the breakpoints. Not even those before any jsoup code. It jumps right to the error as soon as I hit the button on the emulator. I have the jsoup jar file added to my eclipse project as an external JAR in my java build path. What am I doing wrong?
BTW: I have jsoup 1.6.2
public class AndroidActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText eText = (EditText) findViewById(R.id.address);
final TextView tView = (TextView) findViewById(R.id.pagetext);
// TODO Auto-generated method stub
class TareaAsincrona extends AsyncTask<String, Void ,String>
{
#Override
protected void onPreExecute()
{
}
#Override
protected void onPostExecute(String X)
{
}
#Override
protected String doInBackground(String... urls)
{
try
{
// Perform action on click
URL url = new URL(eText.getText().toString());
URLConnection conn = url.openConnection();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
String Codigo_Fuente ="";
while ((line = rd.readLine()) != null)
{
Codigo_Fuente= Codigo_Fuente + line;
//Codigo_Fuente.add(line);//android.text.Html.fromHtml(line).toString());
}
Document doc = Jsoup.parse(Codigo_Fuente);
return doc.body().text();
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
}
final Button button = (Button) findViewById(R.id.ButtonGo);
button.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View arg0)
{
new TareaAsincrona().execute();
}
});
}
}
Did you add the library to the "libs" folder too?

Categories

Resources