Data from Json query not getting populated in Android Text View - android

I used Json 1.9.2 library in Android to parse data from a website and then set the resulting data to a TextView in Android. But I am not able to set the fetched data on the TextView.
Sharing the relevant code. I'm using Fragments.
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tv1 = (EditText) getActivity().findViewById(R.id.trending_textView);
new Title().execute();
}
private class Title extends AsyncTask<Void, Void, Void> {
String title;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setTitle("Fetching the latest trends");
mProgressDialog.setMessage("#Trends");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
public Void doInBackground(Void... params) {
try {
doc = Jsoup.connect(url).get();
Elements links = doc.getElementsByTag("a");
for (Element link : links) {
//String linkHref = link.attr("href");
linkText = link.text();
//System.out.println("#"+linkText);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
public void onPostExecute(Void result) {
tv1.setText(linkText.toString());
mProgressDialog.dismiss();
}
}
Any help would be greatly appreciated.

you have to post the task result into UI thread by returning the result in doInbackground() method
and u will receive the result in onPostExecute() as argument , then you populate the views from there since onPostExecute() runs in UI thread
for more info :-
https://developer.android.com/reference/android/os/AsyncTask.html
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tv1 = (EditText) getActivity().findViewById(R.id.trending_textView);
new Title().execute();
}
private class Title extends AsyncTask<Void, Void, Elements> {
String title;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setTitle("Fetching the latest trends");
mProgressDialog.setMessage("#Trends");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
public Elements doInBackground(Void... params) {
Elements links ;
try {
doc = Jsoup.connect(url).get();
links = doc.getElementsByTag("a");
} catch (Exeption e ) {
return null ;
}
return links;
}
#Override
public void onPostExecute(Elements ...links) {
if(links.get(0) == null) return ;
for (Element link : links.get(0)) {
//String linkHref = link.attr("href");
linkText = link.text();
// u might add scrolling behavior
tv.append(linktext + "\n");
//System.out.println("#"+linkText);
}
}
}

Related

How to return Void function doInBackground in AsynTask?

how to get the result of the function void in asyntask
I've tried like this but the application always stops
I want to implement a progressbar in webview with asyntask when the waiting process
note: I've read this Webview with asynctask on Android
public class MainActivity extends AppCompatActivity {
EditText edInput;
Button btnCari;
WebView webView;
public String dataUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
initEvent();
new asynCaller().execute();
}
private void initUI(){
edInput = (EditText) findViewById(R.id.editText);
dataUrl = edInput.getText().toString();
btnCari = (Button) findViewById(R.id.button);
webView = (WebView) findViewById(R.id.webview);
}
private void initEvent() {
btnCari.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String dataUrl = edInput.getText().toString();
dataUrl = dataUrl.isEmpty() ? "google" : dataUrl;
loadWebview("https://" + dataUrl + ".com");
message("Data link is "+dataUrl);
}
});
}
private void message(String pesan){
Toast.makeText(MainActivity.this,pesan, LENGTH_SHORT).show();
}
private boolean checkConnection(){
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnectedOrConnecting();
}
private void statusConnection(){
if (checkConnection()){
message("Device Online");
}else{
message("Device Offline");
}
}
private void loadWebview(String url){
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(url);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSupportZoom(true);
}
public class asynCaller extends AsyncTask<Void, Void, Void> {
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
// progressDialog.setMessage("Loading...");
// progressDialog.show();
message("persiapan");
}
#Override
protected Void doInBackground(Void... params) {
statusConnection();
if (checkConnection()) {
dataUrl = dataUrl.isEmpty() ? "google" : dataUrl;
loadWebview("https://" + dataUrl + ".com");
message("Data link is " + dataUrl);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// progressDialog.dismiss();
message("selesai");
}
}
EDITED
thank's for your help
i change a method doInBackground to onProgressUpdate for showing Webview and work and i get new problem with progress dialog, the progress dialog can't dismiss()
#Override
protected String doInBackground(String... params) {
publishProgress();
return url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
url = edInput.getText().toString();
progressDialog.show(MainActivity.this,"Pesan","Memuat . . .",true);
}
#Override
protected void onPostExecute(String result) {
if (progressDialog.isShowing()){
progressDialog.dismiss();
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
loadWeb(url);
}
}
Change Your doInBackground() return type to String/int
public class asynCaller extends AsyncTask<Void, Void, String> {
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
// progressDialog.setMessage("Loading...");
// progressDialog.show();
message("persiapan");
}
#Override
protected String doInBackground(String... params) {
statusConnection();
if (checkConnection()) {
dataUrl = dataUrl.isEmpty() ? "google" : dataUrl;
loadWebview("https://" + dataUrl + ".com");
message("Data link is " + dataUrl);
}
return "Your Message";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// progressDialog.dismiss();
Log.d("Reached_postExe",result);
message("result");
}
}
The following is the code I would use, refactored from your own code. I have taken the liberty of making changes to your messaging to make it more meaningful in the console.
public class AsynCaller extends AsyncTask<Void, Void, String> {
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
System.out.println("AsynCaller.onPreExecute called");
// progressDialog.setMessage("Loading...");
// progressDialog.show();
message("AsynCaller.onPreExecute called");
}
#Override
protected String doInBackground(Void... params) {
System.out.println("AsynCaller.doInBackground called");
statusConnection();
final String result; // making it final forces it's definition whichever logic flow the code takes, which is good practice for a returned value
if (checkConnection()) {
dataUrl = dataUrl.isEmpty() ? "google" : dataUrl;
final String fullUrl = "https://" + dataUrl + ".com";
loadWebview(fullUrl);
result = "AsynCaller.doInBackground loadWebView called with " + fullUrl;
} else {
result = "AsynCaller.doInBackground checkConnection() is false");
}
// message(result); this is unnecessary as the Toast will appear due to the message() call in onPostExecute
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("AsynCaller.onPostExecute called");
// progressDialog.dismiss();
message(result);
}
}
I would, if I were you, replace the System.out calls with Log.d() so that the console output is only done in debuggable mode and not in any release version of your app. The reference for this is here Log
As a last suggestion I would not have the ProgressDialog being a property of the AsyncTask but instead call methods in MainActivity, as you have done with message() for instance. There are issues, for instance in this case, around possible memory leaks etc. if an object effectively holds a reference to an Activity context and the Activity is destroyed while the object continues to exist, as would be the case for a running AsyncTask.

Indeterminate ProgressBar not showing during AsyncTask operation

I have a GoogleTranslate.java file that has a class, GoogleTranslate, that extends AsyncTask. The purpose of this task is to perform Google translations.
I have another class, MyVocab, that allows the user to input a word to translate in an alert dialog. So on a click to the alert dialog button, the word will be translated to the desired language by calling on the GoogleTranslate class. However, when I pass a progress bar from MyVocab to GoogleTranslate it doesn't work. When the operation is running (for an observable amount of time), the progress bar doesn't show. I set the progress bar as VISIBLE in onPreExecute and set it as GONE in onPostExecute.
I'm wondering if it's because I have GoogleTranslate and MyVocab in two different java files since most of the examples I see have async class and the class that calls it in the same java file. Please let me know if there's anything I'm doing wrong that's causing this problem.
Here's the related code:
GoogleTranslate.java
public class GoogleTranslate extends AsyncTask<String, Void, String>{
private ProgressBar mProgressBar;
public GoogleTranslate(ProgressBar progressBar) {
super();
mProgressBar = progressBar;
}
#Override
protected void onPreExecute() {
mProgressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String s) {
mProgressBar.setVisibility(View.GONE);
}
#Override
protected String doInBackground(String... params) {
String vocab = params[0];
String source = params[1];
String target = params[2];
String sourceQuery = "";
String targetQuery = "&target=" + target;
// "" means its
if (!source.equals("Detect Language")) {
sourceQuery = "&source=" + source;
}
try {
String APIKey = "MY_API_KEY";
String encodedQuery = URLEncoder.encode(vocab, "UTF-8");
URL url = new URL("https://www.googleapis.com/language/translate/v2?key=" +
APIKey +
"&q=" +
encodedQuery +
sourceQuery +
targetQuery);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally {
urlConnection.disconnect();
}
}
catch (Exception e) {
return null;
}
}
}
Parts of method from MyVocab:
protected void addVocabAlertDialog(final VocabDbHelper dbHelper, final String category,
final VocabCursorAdapter cursorAdapter) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add Vocab");
LayoutInflater li = LayoutInflater.from(CategoryItem.this);
View promptsView = li.inflate(R.layout.alert_dialog_add_vocab, null);
final EditText vocabInput = (EditText) promptsView.findViewById(R.id.vocabInput);
final EditText definitionInput = (EditText) promptsView.findViewById(R.id.definitionInput);
final ProgressBar progressBar = (ProgressBar) promptsView.findViewById(R.id.progressBar);
builder.setView(promptsView);
final GoogleTranslate googleTranslate = new GoogleTranslate(progressBar);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String vocab = vocabInput.getText().toString();
String definition = definitionInput.getText().toString();
dbHelper.insertVocab(category, vocab, definition, 0);
if (!category.equals(VocabDbContract.CATEGORY_NAME_MY_WORD_BANK)) {
dbHelper.insertVocab(VocabDbContract.CATEGORY_NAME_MY_WORD_BANK, vocab, definition, 0);
}
// Update Cursor
Cursor cursor = dbHelper.getVocabCursor(category);
cursorAdapter.changeCursor(cursor);
}
});
final AlertDialog dialog = builder.create();
dialog.show();
dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String vocab = vocabInput.getText().toString();
SharedPreferences sharedPreferences = getSharedPreferences("Translation", MODE_PRIVATE);
int sourcePos = sharedPreferences.getInt("Source", 0); // 0 is for Detect Language
int targetPos = sharedPreferences.getInt("Target", 19); // 19 is for English
String source = LanguageOptions.FROM_LANGUAGE_CODE[sourcePos];
String target = LanguageOptions.TO_LANGUAGE_CODE[targetPos];
final AlertDialog.Builder builder = new AlertDialog.Builder(CategoryItem.this);
builder.setMessage("Network is unavailable. Please try again later.");
builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
if (isNetworkAvailable()) {
AsyncTask<String, Void, String> asyncTask = googleTranslate.execute(vocab, source, target);
try {
String translatedJSON = asyncTask.get();
JSONParser jsonParser = new JSONParser();
String translatedText = jsonParser.parseJSONForTranslation(translatedJSON);
definitionInput.setText(translatedText);
} catch (Exception e) {
dialog.show();
}
}
else {
dialog.show();
}
}
});
}
XML file that contains progress bar:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Vocab"
android:id="#+id/vocabInput"
android:inputType="textAutoComplete"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Definition"
android:id="#+id/definitionInput"
android:inputType="textAutoComplete"
android:layout_below="#+id/vocabInput"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone"
android:indeterminate="true"
android:id="#+id/progressBar"/>
I'd suggest using ProgressDialog instead.
I switched from ProgressBar because I faced a similar issue, even after programmatically creating one in the default constructor of my AsyncTask.
public class GoogleTranslate extends AsyncTask<String, Void, String> {
private ProgressDialog mProgressDialog;
private Context mContext;
public GoogleTranslate(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(
mContext,
"Please wait", // Title
"Translating", // Message
true // Indeteriminate flag
);
}
#Override
protected String doInBackground(String... params) {
...
}
#Override
protected void onPostExecute(String s) {
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
...
}
}
Call this AsyncTask like this:
new GoogleTranslate(getActivity() /* or getContext() */).execute(vocab, source, target);
Try to avoid the AsyncTask get() method and use a listener instead.
You should update your code this way:
1) In your googleTranslate class, add a listener:
private Listener listener;
public interface Listener{
void onTaskResult(String string);
}
public void setListener(Listener listener){
this.listener = listener;
}
and call it in your onPostExecute:
#Override
protected void onPostExecute(String s) {
if (listener!=null){ listener.onTaskResult(s); }
mProgressBar.setVisibility(View.GONE);
}
2) update your main class replacing the get with the listener management, replacing this:
AsyncTask<String, Void, String> asyncTask = googleTranslate.execute(vocab, source, target);
try {
String translatedJSON = asyncTask.get();
JSONParser jsonParser = new JSONParser();
String translatedText = jsonParser.parseJSONForTranslation(translatedJSON);
definitionInput.setText(translatedText);
} catch (Exception e) {
dialog.show();
}
with this:
googleTranslate.setListener(new GoogleTranslate.Listener() {
#Override
public void onTaskResult(String string) {
String translatedJSON = string;
JSONParser jsonParser = new JSONParser();
String translatedText = jsonParser.parseJSONForTranslation(translatedJSON);
definitionInput.setText(translatedText);
}
});
googleTranslate.execute(vocab, source, target);
I hope it helped.
add this before executing the googleTranslate :
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
AsyncTask<String, Void, String> asyncTask = googleTranslate.execute(vocab,source, target);
and also implement the onProgressUpdate in googleTranslate.
this link may help :
http://www.concretepage.com/android/android-asynctask-example-with-progress-bar
Try passing ProgressBar as constructor argument of GoogleTranslate class.
Add progress bar in your onPreExecute method and hide it in onPostExecute.
private class MyAsyncThread extends AsyncTask<Void, Void, String>
{
#SuppressWarnings("finally")
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
// your code
}
catch (Exception e) {
// TODO: handle exception
}
finally
{
return "OK";
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (progressDialog != null) {
progressDialog.dismiss();
progressDialog = null;
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(this, null, "Please wait....");
}
That's because you are blocking Main Thread by asyncTask.get() call, so no UI operations can run until asyncTask completes.
Remove this call and process the asyncTask's results in its onPostExecute(String s) and onCancelled() callbacks instead.

Android JSoup with AsyncTask - can't see the content

I use this code inorder to get the content of some website.
the textview stay empty. What I am doing wrong?
I added the jar into librires and also add internet permission to manifest.
public class MainActivity extends Activity {
MyTask mt;
TextView tvInfo;
String URL="http://www.example.com/";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvInfo = (TextView) findViewById(R.id.textView1);
}
public void onclick(View v) {
mt = new MyTask();
mt.execute(URL);
}
class MyTask extends AsyncTask<String, Void, String> {
Document doc;
String title=null;
#Override
protected void onPreExecute() {
super.onPreExecute();
tvInfo.setText("Please wait");
}
#Override
protected String doInBackground(String... params) {
try {
TimeUnit.SECONDS.sleep(2);
// doc = Jsoup.connect(params[0]).get();
// String title = doc.title();
doc = Jsoup.connect("http://www.example.com/").get();
Element content = doc.select("a").first();
title = content.text();
Log.d("AsyncTask doInBackground","URL: " + params[0]);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return title;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tvInfo.setText(title);
}
}
}
I also not understand excaly when each method here is called
THANKS A LOT!
EDIT - the code after what was suggested in answer. Still not working:
public class MainActivity extends Activity implements OnClickListener{
MyTask mt;
TextView tvInfo;
String URL="http://www.example.com/";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvInfo = (TextView) findViewById(R.id.textView1);
tvInfo.setOnClickListener(this);
}
private class MyTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String title = "hh";
try{
Document doc = Jsoup.connect("http://google.com").userAgent("Mozilla").get();
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 title;
}
#Override
protected void onPostExecute(String result) {
tvInfo.setText(result);
}
#Override
protected void onPreExecute() {
tvInfo.setText("Please wait");
}
}
#Override
public void onClick(View v) {
mt = new MyTask();
mt.execute(URL);
}
}
The AsyncTask executes everything in doInBackground() inside of another thread, which does not have access to the GUI where your views are.
preExecute() and postExecute() offer you access to GUI before and after the heavy lifting occurs in this new thread, you can even pass the result of the long operation to postExecute() to then show any results of processing.
private class MyTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try{
Document doc = Jsoup.connect("http://google.com").userAgent("Mozilla").get();
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();
}
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
super.onPreExecute();
tvInfo.setText("Please wait");
}
}

Android - Parse.com retrieve the whole object of a query and display in ArrayList

In the following code I search HighScore class for the best time results ordered by ascending.
So I'm getting list of best results.
What I having a difficulty is to add the name and the school name to of each time result to the list.(please see the attached images)
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
// Override this method to do custom remote calls
protected Void doInBackground(Void... params) {
// Gets the current list of bestTime in sorted order
ParseQuery query = new ParseQuery("TestsTopRecords");
query.orderByAscending("bestTime");
try {
results = query.find();
} catch (ParseException e) {
}
return null;
}
#Override
protected void onPreExecute() {
HighScoreTable.this.progressDialog = ProgressDialog.show(HighScoreTable.this, "",
"Loading...", true);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result) {
// Put the list of results into the list view
ArrayAdapter<Double> adapter = new ArrayAdapter<Double>(HighScoreTable.this,R.layout.todo_row);
for (ParseObject object : results) {
adapter.add((Double) object.get("bestTime"));
}
setListAdapter(adapter);
HighScoreTable.this.progressDialog.dismiss();
TextView empty = (TextView) findViewById(android.R.id.empty);
empty.setVisibility(View.VISIBLE);
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_high_score_table);
TextView empty = (TextView) findViewById(android.R.id.empty);
empty.setVisibility(View.INVISIBLE);
new RemoteDataTask().execute();
registerForContextMenu(getListView());
}
Here's probably the simplest hack to do this.
Use String instead of Double and do this
ArrayAdapter<String> adapter = new ArrayAdapter<String>(HighScoreTable.this,R.layout.todo_row);
for (ParseObject object : results) {
adapter.add((Double) object.get("bestTime") + " " + object.getString("Name") + " " + object.getString("SchoolAndCity"));
}

Progress Dialog only shows up when the job is already done

I have a problem which I don't understand. I want to show a simple Progress Dialog in Android. So I created an AsyncTask and create the dialog in the constructor. I use the methods onPreExceution to initialise the dialog and the onPostExecute method I destory the dialog. So until now this looks total correct for me. But when I start the App on my Nexus 7 the dialog doesn't show up till the job is done. So it shows up for a half of a second at the end of the job... What am I doing wrong?
Thank you for your help ;)
public class ParseHTMLCodeNew extends AsyncTask<String, Void, String> {
ProgressDialog dialog;
public ParseHTMLCodeNew(Context context) {
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
//einrichten des Wartedialogs
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}
#Override
protected String doInBackground(String params) {
InputStream is = null;
String data = "";
try
{
URL url = new URL( params[0] );
is = url.openStream();
data = new Scanner(is).useDelimiter("//html//").next();
}
catch ( Exception e ) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String result) {
//Dialog beenden RSS Feed ist fertig geparst
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
}
UPDATE
This is my new AsyncTask:
public class ParseHTMLCodeNew extends AsyncTask<String, String, String> {
ProgressDialog dialog;
private final OnCompleteTaskListener onCompleteTaskListener;
public interface OnCompleteTaskListener {
void onComplete(String data);
}
public ParseHTMLCodeNew(Context context, OnCompleteTaskListener taskListener) {
onCompleteTaskListener = taskListener;
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
//einrichten des Wartedialogs
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}
#Override
protected String doInBackground(String... params) {
InputStream is = null;
String data = "";
try
{
URL url = new URL( params[0] );
is = url.openStream();
data = new Scanner(is).useDelimiter("//html//").next();
}
catch ( Exception e ) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String result){
onCompleteTaskListener.onComplete(result);
//Dialog beenden RSS Feed ist fertig geparst
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
}
And i am calling it this way:
new ParseHTMLCodeNew(this,new OnCompleteTaskListener() {
#Override
public void onComplete(String data) {
gData = data;
}
}).execute(url);
As i commented on your post, data has no value.
If you calling this code so:
String data = new ParseHTMLCodeNew(CommentActivity.this).execute(url).get();
Then you do not really see your dialogue because there is a blocking UI.
Method get() waits if necessary for the computation to complete, and then retrieves its result.
Call so:
new ParseHTMLCodeNew(CommentActivity.this).execute(url);
and the result of the work is handled directly in the AsyncTask.
If you need to transfer the data to the main thread, you should tell him that the task was completed.
Wat is the simple code, I just added OnCompleteTaskListener interface
public class ParseHTMLCodeNew extends AsyncTask<String, Void, String> {
private final OnCompleteTaskListener onCompleteTaskListener;
private ProgressDialog dialog;
public interface OnCompleteTaskListener {
void onComplete(String data);
}
public ParseHTMLCodeNew(Context context, OnCompleteTaskListener taskListener) {
onCompleteTaskListener = taskListener;
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
// einrichten des Wartedialogs
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}
#Override
protected String doInBackground(String... params) {
StringBuilder sb = new StringBuilder();
// your code here
try {
for (int i = 0; i < 100; i++) {
Thread.sleep(100);
sb.append(i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
// Dialog beenden RSS Feed ist fertig geparst
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
onCompleteTaskListener.onComplete(result);
}
}
And the example of a call
new ParseHTMLCodeNew(this,new OnCompleteTaskListener() {
#Override
public void onComplete(String data) {
Toast.makeText(CommentActivity.this, data, Toast.LENGTH_LONG).show();
}
}).execute("your_url");
Be careful, this code can produce errors when you rotate your Phone.
When Activity destroyed but task is performed:
- progress dialog will close and will not open again
- local variable to dialog or context is incorrect.
If the operation is performed for a long time can make it through the of the services?
I've wrote a code that get data from online database and populate that data in lisview here is the part of my code hope that help !
class LoadMyData extends AsyncTask<String, String, String> {
//Before starting background thread Show Progress Dialog
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getParent());
pDialog.setMessage("Loading. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
//Your code here
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting the data
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// In my case use my adapter to display the data in a listview
adapter = new MyAdaper();
list.setAdapter(adapter);
}
});
}
}
Progress dialog should be shown from UI thread
runOnUiThread(new Runnable() {
public void run() {
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}});

Categories

Resources