I have a problem with getting website with jsoup on Android.
public class Parser
{
Parser()
{
new Parser1().execute();
}
class Parser1 extends AsyncTask<Void, Void, Void>
{
String website1 = "http://google.com";
Document doc;
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
This code is not execute doInBackground method.
#Override
protected Void doInBackground(Void... params)
{
try
{
doc = Jsoup.connect(website1).get();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
And the rest of code.
#Override
protected void onProgressUpdate(Void... values)
{
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result)
{
Log.d ("OK",doc.toString());
super.onPostExecute(result);
}
#Override
protected void onCancelled()
{
super.onCancelled();
}
}
}
I tried to write code without class AsyncTask, but always on Json.connect the program was exception.
Thanks for all replies.
Try this:
#Override
protected Void doInBackground(Void... params) {
try {
doc = GetDocument(website1);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Click the following link to get the full implementation of GetDocument.
References
How to use Jsoup with Volley?
you can use a httpURLconnections as an alternative and see if that works.
are you getting anything as the debug output for this code?
Log.d ("OK",doc.toString());
Related
I am using AsyncTask for loading data, data comes from server, but due to so much data I want to load data on a background thread.
Here is my code
private void loadData() {
new AsyncTask<Void, ArrayList<DataModel>, ArrayList<DataModel>>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
DialogHelper.showProgress(MyActivity.this);
}
#Override
protected ArrayList<DataModel> doInBackground(Void... voids) {
try {
return MyParser.parseData(jsonDataAsResultFromServer);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<DataModel> list) {
super.onPostExecute(list);
DialogHelper.hideProgress();
if (list.size() > 0) {
myAdapter = new MyAdapter(MyActivity.this);
myAdapter.addAll(list);
recyclerview.setAdapter(myAdapter);
}
}
}.execute();
}
So I am having issues with my AsyncTask. I need postExecute to display an alert dialog if a certain error throwable is caught in doInBackground. The problem is that postExecute is never called. I have tried adding #Override but Android Studio says that it isn't overriding a method in its super class. I have also tried changing the return type. I looked around this site and couldn't find an answer. Thanks in advance.
AsyncTask Class
public class AsyncTaskActivity extends AsyncTask<Void, Void, Void> {
String exception;
#Override
protected void onPreExecute() {
}
protected void onPostExecute() {
if (exception.contains("java.net.UnknownHostException")) {
MainActivity.showDialog();
Log.i("Error Message", "ERROR MESSAGE SHOWN");
}
}
#Override
protected Void doInBackground(Void... params) {
try {
Log.i("AsyncTask", "Loading...");
// Make a URL to the web page. This takes the string representation of the URL
// and changes it into a URL object
URL url = new URL("http://api.wunderground.com/api/0c0fcc3bf62ab910/conditions/q/IN/Fort_Wayne.json");
// Get the input stream through URL Connection
URLConnection con = url.openConnection();
InputStream is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
// read each line and write to text file
while ((line = br.readLine()) != null) {
Log.i("AsyncTask", line);
TextEditor.file = new File(MainActivity.path, "siteInfo.txt");
TextEditor.writeString(line);
}
TextEditor.saveAndClose();
} catch (Exception e) {
e.printStackTrace();
exception = e.toString();
}
Log.i("AsyncTask", "DONE");
return null;
}
}
showDialog method
public static void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.context);
builder.setView(R.layout.dialog_layout);
builder.setPositiveButton(
R.string.dialog_close,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
System.exit(1);
}
});
builder.show();
}
look like you're missing something
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (exception.contains("java.net.UnknownHostException")) {
MainActivity.showDialog();
Log.i("Error Message", "ERROR MESSAGE SHOWN");
}
}
First please refer this documentation. you have missed parameters on onPostExecute().
https://developer.android.com/reference/android/os/AsyncTask.html
What you would have to do is,
#Override
protected void onPostExecute(Params) {
// your logics
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (exception.contains("java.net.UnknownHostException")) {
MainActivity.showDialog();
Log.i("Error Message", "ERROR MESSAGE SHOWN");
}
}
Please note that you need to initialize exception, otherwise it may cause a NullPointerException
I am following the documentation given by IBM (https://developer.ibm.com/mobilefirstplatform/documentation/getting-started-7-0/hello-world/creating-first-native-android-mobilefirst-application/)
After calling request.send(new MyInvokeListener()); there is no sucess or failure call back. Receiving an error message "Android Prototype stopped working."
Adapter is working fine when i right click on the adapter --> Run As --> Call Mobile First Adapter
Below is my android native code.
public class TaskFeed extends AsyncTask<Void, Void, String> {
ProgressDialog Dialog = new ProgressDialog(TaskActivity.this);
#Override
protected void onPreExecute() {
Dialog.setMessage("Establishing connection...");
Dialog.show();
}
#Override
protected String doInBackground(Void... params) {
try {
final WLClient client = WLClient.createInstance(TaskActivity.this);
client.connect(new MyConnectListener());
URI adapterPath = new URI("/adapters/TaskAdapter/getAllTasks");
WLResourceRequest request = new WLResourceRequest(adapterPath,WLResourceRequest.GET);
request.send(new MyInvokeListener());
} catch (Exception e) {
e.printStackTrace();
}
// Dialog.setMessage("Loading Tasks..");
return "test";
}
#Override
protected void onPostExecute(String r) {
Dialog.dismiss();
ArrayList<ListViewModel> result = AssignAndGetCurrentTaskResults();
tvListCount.setText(GetActionBarString());
adapter = new ArrayDataAdapter(taContext, R.layout.task_row_item, result);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
My InvokeListner Class
public class MyInvokeListener implements WLResponseListener {
public void onSuccess(WLResponse response) {
try {
allTaskResults= ParseData(response.getResponseJSON().getJSONArray("array"));
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public void onFailure(WLFailResponse response) {
}
}
Taking out the code which creates and call to mobile first adapter from async task solved my problem.
There is a window leakage in android doing so.
I'm trying to display a result in a textview but i get an error. The code is:
private class ContentView extends AsyncTask<String,String,String> {
#Override
protected void onPreExecute()
{
mProgressDialog = new ProgressDialog(SingleActivity.this);
mProgressDialog.setTitle("Multiplayer.it");
mProgressDialog.setMessage("Caricamento articoli...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
content = new ArrayList<String>();
}
#Override
protected String doInBackground(String... params) {
try {
//String BLOG_URL_LINKS = links;
Document doc = Jsoup.connect(links).get();
String info = doc.select("div.col-1-1 article p").text();
System.out.println(info);
//info.toString();
} catch (Exception e) {
// In caso di errore
Log.e("ESEMPIO", "ERRORE NEL PARSING");
}
return null;
}
#Override
protected void onPostExecute(String result)
{
articololink = (TextView)findViewById(R.id.content);
articololink.setText(info);
mProgressDialog.dismiss();
}
}
And the problem is : info cannot be resolved to a variable. How can i do?
Info is declared and initialized in doInbackground is local to doInbackground.
So Return info in doInbackground
#Override
protected String doInBackground(String... params) {
String info=null;
try {
Document doc = Jsoup.connect(links).get();
info = doc.select("div.col-1-1 article p").text();
} catch (Exception e) {
e.printStacktrace();
}
return info;
}
and then in onPostExecute
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
articololink = (TextView)findViewById(R.id.content);
articololink.setText(result);
mProgressDialog.dismiss();
}
Do read the topic The 4 Steps #
http://developer.android.com/reference/android/os/AsyncTask.html
I have AsyncTask class and I call it in my main class. I need to override the onPostExecute function and call inside ftpDisconnect(). But it does not work properly.
TempClass dj = new TempClass(serialnum) {
#Override
protected void onProgressUpdate(Integer... values) {
pr_bar.setProgress(values[0]);
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
//dj.ftpDisconnect(); //need to make this happen
super.onPostExecute(result);
}
};
dj.execute();
My TempClass:
public class TempClass extends AsyncTask<String, Integer, String> {
public TempClass(String serialnum) {
this.serialnum = serialnum;
}
#Override
protected String doInBackground(String... params) {
//do stuff
return null;
}
public boolean ftpDisconnect() {
try {
mFTPClient.disconnect();
return true;
} catch (Exception e) {
}
return false;
}
}
You can't access that instance of dj without making it final. You should be able to call ftpDisconnect from inside the class:
#Override
protected void onPostExecute(String result) {
ftpDisconnect();
super.onPostExecute(result);
}