Syntax error in onPostExecute() - java

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

Related

How to use RxJava instead of AsyncTask to load data?

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();
}

How can i use two web service methods in the same activity?

I have two methods which are from soap webservice. I am calling them in asyntask that is a superclass of info.java page and tring to get the results in onPost method of asyntask. The calling code of info.java/onCreate is below.
try{
PropertyInfo propertyInfo1 = new PropertyInfo();
properties.clear();
propertyInfo1 = new PropertyInfo();
propertyInfo1.setName("Module_id");
propertyInfo1.setType(String.class);
propertyInfo1.setValue(Utils.selectedModule_id);
properties.add(propertyInfo1);
new Info.AsyncTaskService().execute(new ServiceParams("GetInfo", properties), new ServiceParams("GetInfo_Photo", properties));
} catch (Exception e) {
Toast.makeText(Info.this, "Please check your internet connection.", Toast.LENGTH_LONG);
}
Both of the service methods takes the same properties thats why i gave them same properties. My problem is i can't take the results because i know that it needs to call these two methods in different threads with an order but i don't know how to do it. Could you help me please? The codes of asynctask class is also below thank you.
public class AsyncTaskService extends AsyncTask<ServiceParams, Void, Void> {
String resp = "";
String resp2 = "";
ProgressDialog progressDialog;
#Override
protected Void doInBackground(ServiceParams... params) {
resp = WebService.invoke(params[0].properties, params[0].methodName);
resp2 = WebService.invoke(params[1].properties, params[1].methodName);
return null;
}
#Override
protected void onPostExecute(Void result) {
Log.w("WEBSERVICE RESPONSE===", resp);
Log.w("WEBSERVICE RESPONSE===", resp2);
try {
JSONArray ja = new JSONArray(resp);
Utils.subMenuArrayList.clear();
Info_Item info_item=new Info_Item(ja.getJSONObject(0));
((TextView)findViewById(R.id.txtInfo)).setText(info_item.getInfo());
((TextView)findViewById(R.id.txtModule)).setText(Utils.selectedMenuName);
} catch (JSONException e) {
e.printStackTrace();
}
if (progressDialog != null)
progressDialog.dismiss();
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(Info.this);
if (progressDialog != null) {
progressDialog.setCancelable(false);
progressDialog.setMessage("İşlem yapılıyor ...");
progressDialog.show();
}
}
protected void onProgressUpdate(Integer... progress) {
if (progressDialog != null)
progressDialog.setProgress(progress[0]);
}
}
I have found how to do it! Wanted to share with you too.
First of all describe you async tasks as below. I have two methods which i want to use in one activity at the same time(paralel) so i described two async task classes.
public class FirstAsyncTask extends AsyncTask<ServiceParams, Void, Void> {
String resp = "";
ProgressDialog progressDialog;
#Override
protected Void doInBackground(ServiceParams... params) {
resp = WebService.invoke(params[0].properties, params[0].methodName);
return null;
}
#Override
protected void onPostExecute(Void result) {
Log.w("WEBSERVICE RESPONSE===", resp);
try {
JSONArray ja = new JSONArray(resp);
Utils.subMenuArrayList.clear();
Info_Item info_item=new Info_Item(ja.getJSONObject(0));
((TextView)findViewById(R.id.txtInfo)).setText(info_item.getInfo());
((TextView)findViewById(R.id.txtModule)).setText(Utils.selectedMenuName);
} catch (JSONException e) {
e.printStackTrace();
}
if (progressDialog != null)
progressDialog.dismiss();
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(Info.this);
if (progressDialog != null) {
progressDialog.setCancelable(false);
progressDialog.setMessage("İşlem yapılıyor ...");
progressDialog.show();
}
}
protected void onProgressUpdate(Integer... progress) {
if (progressDialog != null)
progressDialog.setProgress(progress[0]);
}
}
Then you should call the tasks like this with executeOnExecuter in your activity's onCreate method. I used a property array here to hold the parameters i am going to send to web service method and describe a serviceparameter with properties and method name and send them in executeOnExecuter() method. I used same properties for my both web service methods but you can describe an other property array like this "private ArrayList properties = new ArrayList<>();" and add informations you need for parameters you will send to web service method.
try{
PropertyInfo propertyInfo1 = new PropertyInfo();
properties.clear();
propertyInfo1 = new PropertyInfo();
propertyInfo1.setName("Module_id");
propertyInfo1.setType(String.class);
propertyInfo1.setValue(Utils.selectedModule_id);
properties.add(propertyInfo1);
ServiceParams serviceparams=new ServiceParams("GetInfo", properties);
ServiceParams serviceparams2=new ServiceParams("GetInfo_Photo", properties);
FirstAsyncTask asyncTask = new FirstAsyncTask(); // First
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, serviceparams);
SecondAsyncTask asyncTask2 = new SecondAsyncTask(); // Second
asyncTask2.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, serviceparams2);
} catch (Exception e) {
Toast.makeText(Info.this, "Please check your internet connection.", Toast.LENGTH_LONG);
}

Can't get website using jsoup on Android

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());

Asynctask w/ ProgressDialog

I know that have a lot of answers about this, but I can't find exactly what I need:
1) When users click on the button, shows a progress Dialog;
2) Executes a class AsyncTask and wait for the answer (it's a response using HTTPUrlConnection);
3) Dismiss Progress Dialog;
I tried a lot of things, but the progress dialog is not "appearing". My code:
public class MainActivity extends Activity implements OnTaskCompleted{
..
private ProgressDialog progressDialog;
private Button btnLogin;
..
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
progressDialog = ProgressDialog.show(MainActivity.this,
"", "Scanning Please Wait", true);
try {
String param1 = "testParam1";
String param2 = "testParam2";
String response = new SyncHelper(MainActivity.this).execute("http://server.example.com/api", param1, param2).get(); //this way, my activity waits of the answer
Log.d(TAG, "Finished: " + response);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} else {
// user didn't entered username or password
Toast.makeText(getApplicationContext(),
"Done",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
}
}
});
}
public void onTaskCompleted()
{
progressDialog.dismiss();
}
public class SyncHelper extends AsyncTask<Object, Void, String>
{
..
private OnTaskCompleted listener;
..
protected String doInBackground(Object... url) {
String response = "";
try {
response = getRequest((String) url[0],(String) url[1], (String) url[2]); //Here I make a HttpURLConnection
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPreExecute() {
}
protected void onPostExecute(String result) {
listener.onTaskCompleted();
}
}
public interface OnTaskCompleted{
void onTaskCompleted();
}
public class MainActivity extends Activity{
..
private Button btnLogin;
..
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
String param1 = "testParam1";
String param2 = "testParam2";
new SyncHelper(MainActivity.this).execute("http://server.example.com/api", param1, param2); //this way, my activity waits of the answer
Log.d(TAG, "Finished: " + response);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} else {
// user didn't entered username or password
Toast.makeText(getApplicationContext(),
"Done",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
}
}
});
}
public class SyncHelper extends AsyncTask<String, Void, String>
{
..
Context context;
private ProgressDialog pd;
..
public SyncHelper (Context c)
{
context = c;
}
#Override
protected void onPreExecute() {
pd = new ProgressDialog(context);
pd.setTitle("Processing...");
pd.setMessage("Please wait.");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
protected String doInBackground(String... url) {
String response = "";
try {
response = getRequest(url[0], url[1], url[2]); //Here I make a HttpURLConnection
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
protected void onPostExecute(String result) {
// here you will be getting the response in String result.
if (pd.isShowing())
pd.dismiss();
}
}
When you are using get, using AsyncTask doesn't make any sense. Because get() will block the UI Thread, maybe thats why are not able to see the progress dialog. If you want to send the response back to the MainActivity then use the callback interface as you were using beofre.

How can i to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

I read and apply something from this link:How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class? but I get an error NullPointerException onPostExecute on the line delegate.processFinish(result); What is the problem in my code? Here is the code:
public class MainActivity extends Activity implements AsyncResponse{
ProductConnect asyncTask =new ProductConnect();
public void processFinish(String output){
//this you will received result fired from async class of onPostExecute(result) method.
Log.v(TAG, output);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
asyncTask.delegate = this;
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button1);
final Intent i=new Intent(MainActivity.this, second.class);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new ProductConnect().execute(true);
startActivity(i);
//startActivity(new Intent(MainActivity.this, second.class));
}
});
}
// START DATABASE CONNECTION
class ProductConnect extends AsyncTask<Boolean, String, String> {
public AsyncResponse delegate=null;
private Activity activity;
public void MyAsyncTask(Activity activity) {
this.activity = activity;
}
#Override
protected String doInBackground(Boolean... params) {
String result = null;
StringBuilder sb = new StringBuilder();
try {
// http post
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet("http://192.168.2.245/getProducts.php");
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != 200) {
Log.d("MyApp", "Server encountered an error");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF8"));
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
Log.d("test", result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
t = json_data.getString("name");
delegate.processFinish(result);
}
} catch (JSONException e1) {
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
super.onPostExecute(result);
}
protected void onPreExecute() {
super.onPreExecute();
ProgressDialog pd = new ProgressDialog(MainActivity.this);
pd.setTitle("Lütfen Bekleyiniz");
pd.setMessage("Authenticating..");
pd.show();
}
}
You initialize your variable to null
public AsyncResponse delegate=null;
so naturally it will give NPE when you try to use it. You give it a value in your Activity so you could pass that to the constructor of your AsyncTask and initialize it to that object.
Your are starting a new AsyncTask in this line:
new ProductConnect().execute(true);
you should execute your asyncTask change that line with this:
asyncTask.execute(true);
I think the best way to do this is using interfaces.. Create a listener for this.
[]'s
you can access asynctask() method when creating new object from it.
sample:
LoginSyncProvider syncProvider = (LoginSyncProvider) new LoginSyncProvider(){
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//TODO write something here
}
}
}.execute();
You've to pass context to that AsyncTask.
Then, on postExecute, cast context to your Activity.
Example:
((MyActivity)context).doSomethingWithResults(resultOfAsyncTask);
Edit:
Your Activity:
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
new MyAsyncTask(this).execute();
}
public void sayHello(String name){
Log.d("log","hello "+name+"!!!");
}
}
Your asynctask:
class MyAsyncTask extends AsyncTask<String,String,String>{
Context context;
public AutoPassarImatges(Context cont) {
super();
this.context = cont;
// TODO Auto-generated constructor stub
}
#Override
protected String doInBackground(String... params) {
[.......]
return null;
}
#Override
protected void onPostExecute(String result) {
((MyActivity)context).sayHello(result);
}
}

Categories

Resources