Async class not passing the argument - java

My async class is throwing some errors. The line with AsyncLoadData says that I should create local variable url
public void getData() {
new AsyncLoadData(this,this).execute(url);
}
My AsyncLoadData class
package com.example.hay;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.EditText;
public class AsyncLoadData extends AsyncTask<String, Void, String> {
private Context mContext;
private ILoadDataListener mListener;
public AsyncLoadData(Context context, ILoadDataListener listener) {
this.mContext = context;
this.mListener = listener;
}
#Override
protected String doInBackground(String... params) {
try {
EditText tf = (EditText) this.findViewById(R.id.editText1);
String url = params[0];
url = tf.getText().toString();
Document doc;
doc = Jsoup.connect(url).get();
String title = doc.text();
return title;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private EditText findViewById(int edittext1) {
return null;
}
#Override
protected void onPostExecute(String result) {
mListener.complete(result);
}
#Override
protected void onPreExecute() {
mListener.loading();
}
public interface ILoadDataListener {
void loading();
void complete(String result);
}
}
As you can see the AsyncLoadData should pass the url variable.

Have you declared url somewhere else in the code before calling this line : new AsyncLoadData(this,this).execute(url); ?
If not, you should add line String url = "the value of the url you are trying to call"; just before it, otherwise the variable url does not exist in the getData method...

Related

JSON IOException error No value for Daily Forecast

I am building a weather module for my app I am using accuweather api to get 5days forecast details. I have added internet permission in manifest.xml.I tried to get a log to get the weather URL and when I click the url it opens in the browser and shows the json file. This means that link is correct. But when I create a jsonobject and try to fetch data as JSON array It shows that there is no data:
Here are my codes:
MyWeatherActivity.java
public class MyWeather extends AppCompatActivity {
private final String TAG = "hello";
// TODO : If following are not used in activity then move the declaration to asynch task
private ArrayList<Weather> weatherArrayList = new ArrayList<>();
private ArrayList<String> dateArray = new ArrayList<>();
private ArrayList<String> minTempArray = new ArrayList<>();
private ArrayList<String>maxTempArray= new ArrayList<>();
private ArrayList<String> backgroundDayArray= new ArrayList<>();
private ArrayList<String>backgroundNightArray= new ArrayList<>();
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_weather);
findViews();
}
protected void findViews()
{
listView = findViewById(R.id.list_item1);
startFetchWeatherDetailsAsyncTask();
}
protected void startFetchWeatherDetailsAsyncTask()
{
URL weatherUrl= NetworkUtils.buildURLForWeather();
new FetchWeatherDetails().execute(weatherUrl);
Log.d(TAG,"oncreate:weatherURL : " + weatherUrl);
}
// TODO : Please make below class static and pass all the list in execute parameters
// TODO : Not doing it will cause the memory leak and you should not access activity objects directly.
private class FetchWeatherDetails extends AsyncTask<URL,Void,String>{
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected String doInBackground(URL... urls) {
URL weatherUrl =urls[0];
String weatherSearchResults=null;
try {
weatherSearchResults=NetworkUtils.getResponseFromHttpUrl(weatherUrl);
} catch (IOException e) {
e.printStackTrace();
}
return weatherSearchResults;
}
#Override
protected void onPostExecute(String weatherSearchResults) {
if(weatherSearchResults !=null && !weatherSearchResults.equals("")){
weatherArrayList =parseJSON(weatherSearchResults );
}
super.onPostExecute(weatherSearchResults);
}
private ArrayList<Weather> parseJSON(String weatherSearchResults) {
if(weatherArrayList!=null){
weatherArrayList.clear();
}
if(weatherSearchResults!=null){
try {
JSONObject rootObject= new JSONObject(weatherSearchResults);
**JSONArray results= rootObject.getJSONArray("Daily Forecasts");**
// TODO : pass the context in constructor and use weakreference
Toast.makeText(getApplicationContext(),"toast:"+results,Toast.LENGTH_LONG).show();
for(int i= 0;i<results.length();i++){
Weather weather= new Weather();
JSONObject resultObj = results.getJSONObject(i);
String date = resultObj.getString("date");
dateArray.add(date);
weather.setDate(date);
JSONObject temperatureObj = resultObj.getJSONObject("Temperature");
String minTemp=temperatureObj.getJSONObject("Minimum").getString("Value");
minTempArray.add(minTemp);
weather.setMinTemp(minTemp);
String maxTemp=temperatureObj.getJSONObject("Maximum").getString("Value");
maxTempArray.add(maxTemp);
weather.setMaxTemp(maxTemp);
JSONObject backDayObj= resultObj.getJSONObject("Day");
String backday=backDayObj.getJSONObject("IconPhrase").getString("");
backgroundDayArray.add(backday);
weather.setBackgroundDay(backday);
JSONObject backNightObj =resultObj.getJSONObject("Night");
String backnight =backNightObj.getJSONObject("IconPhrase").getString("");
backgroundNightArray.add(backnight);
weather.setBackgroundNight(backnight);
weatherArrayList.add(weather);
}
if(weatherArrayList !=null){
WeatherAdapter weatherAdapter = new WeatherAdapter(MyWeather.this,weatherArrayList);
listView.setAdapter(weatherAdapter);
}else {
Toast.makeText(getApplicationContext(),"Data invalid",Toast.LENGTH_LONG).show();
}
return weatherArrayList;
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
}
}
A class for getter setter
public class Weather
{
private String date;
private String minTemp;
private String maxTemp;
private String backgroundDay;
private String backgroundNight;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getMinTemp() {
return minTemp;
}
public void setMinTemp(String minTemp) {
this.minTemp = minTemp;
}
public String getMaxTemp() {
return maxTemp;
}
public void setMaxTemp(String maxTemp) {
this.maxTemp = maxTemp;
}
public String getBackgroundDay() {
return backgroundDay;
}
public void setBackgroundDay(String background) {
this.backgroundDay = background;
}
public String getBackgroundNight() {
return backgroundNight;
}
public void setBackgroundNight(String backgroundNight) {
this.backgroundNight = backgroundNight;
}
}
For connection:
package com.example.a49ersense;
import android.net.Uri;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
public class NetworkUtils {
private final static String WeatherDB_Base_URL=
"https://dataservice.accuweather.com/forecasts/v1/daily/5day/location key which I have deleted";
private final static String API_KEY="my api key which i have deleted";
private final static String PARAM_API_KEY="apikey";
private static final String TAG="hello";
public static URL buildURLForWeather(){
Uri builtUri = Uri.parse(WeatherDB_Base_URL).buildUpon()
.appendQueryParameter(PARAM_API_KEY,API_KEY)
.build();
URL url = null;
try {
url= new URL(builtUri.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
Log.d(TAG,"buildUrlForWeather:url:"+url);
return url;
}
public static String getResponseFromHttpUrl(URL url)throws IOException{
HttpURLConnection httpURLConnection =(HttpURLConnection) url.openConnection();
try {
InputStream in= httpURLConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if(hasInput){
return scanner.next();
}else {
return null;
}
}finally {
httpURLConnection.disconnect();
}
}
}
error is:
W/System.err: org.json.JSONException: No value for Daily Forecasts
You are using Daily Forecasts which is wrong key. You should use DailyForecasts
Use
JSONArray results = rootObject.getJSONArray("DailyForecasts");
Instead of
JSONArray results = rootObject.getJSONArray("Daily Forecasts");

Get variable from onResponse

I want to get the variable "response" from the BDDRequest class for using it in a ListView in my MainActivity class, how i can do ?
public class BDDRequest implements Serializable {
private final long serialVersionUID = 1L;
static private Activity activity;
public String req;
public BDDRequest(){}
public static void GetRequest(final Context t, UserEmployeeInfo User) {
activity = (Activity) t;
RequestQueue queue = Volley.newRequestQueue(t);
ParamsSend params = new ParamsSend();
params.setUser(User);
ParserJson<ParamsSend> pj = new ParserJson<>(params);
String strJson;
try {
strJson = pj.writeJSON();
} catch (JsonProcessingException e) {
strJson = "null";
}
final String data = strJson;
String REST_API_URL = "http://212.227.53.116:8080/WSmartgroom/rest/perso/request";
Log.d("lol", strJson);
StringRequest myReq = new StringRequest(Request.Method.PUT,
REST_API_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("reponse:", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("That didn't work!", "Error");
}
}) {
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public byte[] getBody() throws AuthFailureError {
return data.getBytes();
}
};
queue.add(myReq);
}
}
Use an interface for it,
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.io.Serializable;
public class BDDRequest implements Serializable {
private final long serialVersionUID = 1L;
static private Activity activity;
public String req;
public BDDRequest() {
}
public static void GetRequest(final Context t, UserEmployeeInfo User, final Callback callback) {
activity = (Activity) t;
RequestQueue queue = Volley.newRequestQueue(t);
ParamsSend params = new ParamsSend();
params.setUser(User);
ParserJson<ParamsSend> pj = new ParserJson<>(params);
String strJson;
try {
strJson = pj.writeJSON();
} catch (JsonProcessingException e) {
strJson = "null";
}
final String data = strJson;
String REST_API_URL = "http://212.227.53.116:8080/WSmartgroom/rest/perso/request";
Log.d("lol", strJson);
StringRequest myReq = new StringRequest(Request.Method.PUT,
REST_API_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("reponse:", response);
callback.onSuccess(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("That didn't work!", "Error");
callback.onError();
}
}) {
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public byte[] getBody() throws AuthFailureError {
return data.getBytes();
}
};
queue.add(myReq);
}
public interface Callback {
void onSuccess(String response);
void onError();
}
}
And implement the interface on your class .
Use like this,
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.TextView;
import com.example.BDDRequest.Callback;
public class MainActivity extends FragmentActivity implements Callback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BDDRequest.GetRequest(this, new UserEmployeeInfo(), this);
}
#Override
public void onSuccess(String response) {
// Bind the data to the listview
}
#Override
public void onError() {
//Show fallback message here
}
}
You're declaring onResponse method. Inside it, response is a parameter. Why do you want to get a parameter which you're putting into? The question is not clear.

Android: How can I know CSS injection is complete?

I am trying to show my webview only after I inject the CSS file to the HTML.
I have tried to put it on onPageCommitVisible function, but it works only 23 apis andd above. Someone knows how can I show the webview only after the CSS has fininshed to load? Now it "jumps" and I see the original CSS for the first one second, before the new one is replaced.
#Override
public void onPageFinished(WebView view, String url) {
Utils.logDebug(this, "Page finished");
if (android.os.Build.VERSION.SDK_INT < 23) {
injectCSS(view);
}
super.onPageFinished(view, url);
showWebView(true);
onPageChange();
}
This is my InjestCSS function:
private void injectCSS(WebView webView) {
try {
webView.loadUrl("javascript:(function() {" +
"var css = document.createElement(\"style\");\n" +
"css.type = \"text/css\";\n" +
"css.innerHTML = \"" + readFileAsString() + "\";\n" +
"document.body.appendChild(css);" +
"})()");
} catch (Exception e) {
e.printStackTrace();
}
}
This function inject the CSS code to the HTML, as you can see in the function.
There are few places where you can handle this.
You could use evaluateJavaScript instead of loadUrl (API level 19) and pass callback in which you will set webview visible.
You could register your own javascript interface using addJavaScriptInterface and call it on the end of your script
You could set WebChromeClient and override onJsAlert then in your script raise alert with specific message.
UPDATE: Additionally this could be achieved by intercepting one of 'css' request, and append loaded file with needed content. This will allow you to inject your styles right before onPageFinished. Check this this thread.
All approaches I have combined in following example:
package com.j2ko.webviewapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
public class MainActivity extends AppCompatActivity {
private static final String MAIN_FUNC_FMT = "(function() { %s })()";
private static final String FUNC_BODY_FMT =
"var parent = document.loadedgetElementsByTagName('head').item(0);" +
"var css = document.createElement('style');" +
"css.type = 'text/css';" +
"css.innerHTML = %s;" +
"parent.appendChild(css);";
private static final String BASE64_DECODE_FMT = "window.atob('%s')";
WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
//Change it to whatever
injectWithEvaluateAndInterface(view);
}
#Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
}
});
mWebView.setVisibility(View.INVISIBLE);
mWebView.loadUrl("http://wiki.org");
}
private static class CSSInjectBuilder {
private final String mOrigin;
private String mAtEnd = null;
private boolean mUseBase64 = false;
public CSSInjectBuilder(String css) {
mOrigin = css;
}
public CSSInjectBuilder withBase64() {
mUseBase64 = true;
return this;
}
public CSSInjectBuilder withExpressionAtEnd(String expression){
mAtEnd = expression;
return this;
}
String build() {
String func_body = FUNC_BODY_FMT;
if (mAtEnd != null) {
func_body += mAtEnd;
}
final String css;
if (mUseBase64) {
byte[] buffer = mOrigin.getBytes();
css = String.format(BASE64_DECODE_FMT, Base64.encodeToString(buffer, Base64.NO_WRAP));
} else {
css = "'" + mOrigin + "'";
}
func_body = String.format(func_body, css);
return String.format(MAIN_FUNC_FMT, func_body);
}
}
byte[] loadAsset() {
try {
InputStream inputStream = getAssets().open("style.css");
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
inputStream.close();
return buffer;
} catch (Exception e) {
}
return null;
}
String loadCSS() {
return new String(loadAsset());
}
void injectWithEvaluate(final WebView view) {
view.evaluateJavascript(new CSSInjectBuilder(loadCSS()).withBase64().build(), new ValueCallback<String>() {
#Override
public void onReceiveValue(String value) {
view.setVisibility(View.VISIBLE);
}
});
}
void injectWithEvaluateAndInterface(WebView view) {
view.addJavascriptInterface(new WebViewInterface(), "WebViewBackEnd");
final String injector = new CSSInjectBuilder(loadCSS())
.withBase64()
.withExpressionAtEnd("window.WebViewBackEnd.CSSInjectionComplete();")
.build();
view.evaluateJavascript(injector, null);
}
void injectWithLoadUrlSimple(WebView view) {
view.loadUrl("javascript:" + loadCSS());
view.setVisibility(View.VISIBLE);
}
void injectWithLoadUrlAndCheckAlert(final WebView view) {
view.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
if (message.equals("CSSInjectionComplete")) {
view.setVisibility(View.VISIBLE);
return true;
}
return super.onJsAlert(view, url, message, result);
}
});
//alert could hang aplying scripts so put it on timeout
final String injector = new CSSInjectBuilder(loadCSS())
.withBase64()
.withExpressionAtEnd("setTimeout(function(){alert('CSSInjectionComplete');}, 1);")
.build();
view.loadUrl("javascript:" + injector);
}
private class WebViewInterface {
#JavascriptInterface
public void CSSInjectionComplete(){
mWebView.post(new Runnable() {
#Override
public void run() {
mWebView.setVisibility(View.VISIBLE);
}
});
}
}
}

parse data from a network thread object to another object android

I want to parse JSON object that returns from a url to a textview. for that I used class which extends AsyncTask to get the network connection. my problem is I can't parse the returning string value to my main class.
my main class as follows
package com.example.janitha.condd;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
final String ur ="https://maps.googleapis.com/maps/api/place/textsearch/json?query=keells+super&location=6.849813513872538,79.90265075223242&key=AIzaSyDQ6fVTYb1_3MmD7j3Sei4CAhbZ_eIOphs";
String outcome=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv=(TextView)findViewById(R.id.text1) ;
Connection con=new Connection();
con.execute(ur);
outcome =con.getFinalData();
tv.setText(outcome);
}
}
my connection class as follows
package com.example.janitha.condd;
import android.os.AsyncTask;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by Janitha on 7/10/2016.
*/
public class Connection extends AsyncTask<String, Void, String> {
String finalData="123";
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
finalData=result;
}
public String downloadUrl(String myurl) throws IOException {
InputStream is = null;
int len = 50000;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
is = conn.getInputStream();
String contentAsString = readIt(is, len);
return contentAsString;
} finally {
if (is != null) {
is.close();
}
}
}
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
public String getFinalData() {
return finalData;
}
}
each time when code executes it gives me the value as 123 which means the value that I initialized for variable finalData. what is wrong with my code?
You should understand how AsyncTask works. When you call con.execute(ur), it runs on the background thread (off UI/Main thread). Now control on your main thread reaches outcome =con.getFinalData() and by that time the background thread hasn't completed the task and thus con.getFinalData() returns "123" because finalData was not yet updated.
What you should do this is to provide a callback to the AysncTask and when onPostExecute is called, you should return the result using that callback.
Edit 1:
Your interface:
public interface OnTaskCompleted {
void onTaskCompleted(String value);
}
Your activity should implement this:
public class MainActivity implements OnTaskCompleted {
//...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
Connection con=new Connection(MainActivity.this);
con.execute(url);
...
}
#Override
public onTaskCompleted(String value) {
// you will receive the data here.
}
}
Changing constructor of the AsyncTask:
public class Connection extends AsyncTask<String, Void, String> {
private OnTaskCompleted listener;
public Connection(OnTaskCompleted listener){
this.listener=listener;
}
String finalData="123";
#Override
protected String doInBackground(String... urls) {
Return data onPostExecute:
#Override
protected void onPostExecute(String result) {
if(listener!=null) {
listener.onTaskCompleted(result);
}
}

Cannot Parse HTML Data Using Android / JSOUP

I'm having an issue where I'm attempting to use JSOUP to obtain data from an webpage (in this case - google.com) and when debugging the title data is returned and shown in the logcat - however my textview never seems to update with the freshly obtained data.
SOURCE:
package com.example.test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView textView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.TextView01);
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
Document doc = Jsoup.connect("http://google.com")
.userAgent("Mozilla")
.get();
// get page title
String title = doc.title();
System.out.println("title : " + title);
// get all links
Elements links = doc.select("a[href]");
for (Element link : links) {
// get the value from href attribute
System.out.println("\nlink : " + link.attr("href"));
System.out.println("text : " + link.text());
}
} catch (IOException e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String title) {
textView.setText(title);
}
}
public void onClick(View view) {
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.google.com" });
}
}
EDIT: (in response to superuser's suggestion - implementing handler)
public class MainActivity extends Activity {
private TextView textView;
private Handler handler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.TextView01);
handler = new Handler();
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
Document doc = Jsoup.connect("http://google.com")
.userAgent("Mozilla")
.get();
// get page title
String title = doc.title();
System.out.println("title : " + title);
// get all links
Elements links = doc.select("a[href]");
for (Element link : links) {
// get the value from href attribute
System.out.println("\nlink : " + link.attr("href"));
System.out.println("text : " + link.text());
}
} catch (IOException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {}});
}
return response;
}
#Override
protected void onPostExecute(String title) {
textView.setText(title);
View.invalidate();
}
}
public void onClick(View view) {
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.google.com" });
}
}
RESULTS (from edit shown above):
Cannot make a static reference to the non-static method invalidate() from the type View MainActivity.java
Cannot refer to a non-final variable title inside an inner class defined in a different method MainActivity.java
Sorry, was about to answer this question yesterday but fell asleep on my keyboard :P
But your result string: protected void onPostExecute(String result) doesn't get anything passed. The problem is easily solved.
Above your onCreate:
String title;
In your doInBackGround:
title = doc.title();
In your onPostExecute:
#Override
protected void onPostExecute(String result) {
textView.setText(title);
}
Try passing the textview as an contructor argument to your class DownloadWebPageTask.
DownloadWebPageTask task = new DownloadWebPageTask(textView);
In your DownloadWebPageTask class define a TextView variable to hold this object.
Update the same in onPostExecute() method.

Categories