Android runOnUiThread to show progress dialog and to populate views - android

I usually work on .Net but I need to develop an Android app. So I am new on Android, sorry for mistakes in advance! :)
Here is my story,
I am populating a customer list(creating ui elements in code behind) with views in a button click. I am doing that pulling datas from database. So it takes some time to pull the data and creating views. What I wanna do is showing a progress dialog while customer list is being populated. Currently I am able to make it run. But the problem is it doesn't show the progress dialog immediately, then customerlist and progress dialog are displayed at the same time.
Here is my button click;
public void ShowCustomers(View view){
final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
runOnUiThread(new Runnable() {
#Override
public void run() {
dialog.setTitle("Title");
dialog.setMessage("Loading...");
if(!dialog.isShowing()){
dialog.show();
}
}
});
new Thread() {
public void run() {
try{
runOnUiThread(new Runnable() {
#Override
public void run() {
PopulateRecentGuests(); //Creates customer list dynamically
dialog.dismiss();
}
});
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
}.start();
}
And populating the customers;
public void PopulateRecentGuests(){
LinearLayout customers = (LinearLayout)findViewById(R.id.customers);
String query = "SELECT * from Table";
ModelCustomer customerModel = new ModelCustomer();
ArrayList<HashMap<String, String>> recentGuests = customerModel.RetrievingQuery(query);
customersCount = recentGuests.size();
Context context = getApplicationContext();
if(customersCount < 1)
Toast.makeText(context, "There is no available customer in database!", Toast.LENGTH_LONG);
else if(!recentGuests.get(0).containsKey("err")) {
for(int i = 0; i < recentGuests.size(); i++){
HashMap<String, String> guest = recentGuests.get(i);
Button button = new Button(context);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(0,5,0,5);
button.setLayoutParams(params);
button.setWidth(800);
button.setHeight(93);
button.setTag(guest.get("id"));
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("New button clicked! ID: " + v.getTag());
Intent intent = new Intent(getApplicationContext(), ProductPageActivity.class);
intent.putExtra("CustomerID", v.getTag().toString());
startActivity(intent);
}
});
button.setBackgroundColor(Color.parseColor("#EFEFEF"));
button.setText(guest.get("FirstName") + " " + guest.get("LastName") + " " + guest.get("GuideName"));
button.setTextColor(Color.BLACK);
button.setTextSize(20);
button.setEnabled(false);
customers.addView(button); // customers is a linear layout and button is being added to customers
Button guest_list_btn = (Button)findViewById(R.id.guest_list_btn);
guest_list_btn.setEnabled(true);
}
}
else{
CharSequence text = recentGuests.get(0).get("err");
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
Button guest_list_btn = (Button)findViewById(R.id.guest_list_btn);
Button guest_list_close_btn = (Button)findViewById(R.id.guest_list_close_btn);
customers.setVisibility(View.VISIBLE);
AnimationSet aset = new AnimationSet(true);
aset.setFillEnabled(true);
aset.setInterpolator(new LinearInterpolator());
AlphaAnimation alpha = new AlphaAnimation(0.0F, 1.0F);
alpha.setDuration(400);
aset.addAnimation(alpha);
TranslateAnimation trans = new TranslateAnimation(200, 0, 0, 0);
trans.setDuration(400);
aset.addAnimation(trans);
customers.startAnimation(aset);
guest_list_btn.setEnabled(false);
guest_list_close_btn.setEnabled(true);
for(int i = 0; i < customers.getChildCount(); i++){
View child = customers.getChildAt(i);
child.setEnabled(true);
}
}
After my research, I understand that runonuithread is called after looper. My question is How can I display the progress dialog immediately and then I can populate the customer list (creating ui elements). By the way, I tried to do that with asynctask first but I wasn't able to.
Thans in advance!

But the problem is it doesn't show the progress dialog immediately,
then customerlist and progress dialog are displayed at the same time.
That's because you do the long operation(and closing the dialog sequentially) on the main UI thread. Instead you should separate things between retrieving the data(which takes time) and building the views(along with closing the dialog).
//...
new Thread() {
public void run() {
// do the long operation on this thread
final ArrayList<HashMap<String, String>> recentGuests = customerModel.RetrievingQuery(query);
// after retrieving the data then use it to build the views and close the dialog on the main UI thread
try{
runOnUiThread(new Runnable() {
#Override
public void run() {
// remove the retrieving of data from this method and let it just build the views
PopulateRecentGuests(recentGuests);
dialog.dismiss();
}
});
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
}.start();

Related

Android: AsyncTask crashing app

I have problem in my application.
I want to show user's profile, and I have two links in my app.
One link is via TextView, which run showUser(View v) method:
public void showUser(View v){
Intent i;
i=new Intent(getApplicationContext(), ShowProfile.class);
i.putExtra("id",user); // user is String with users ID
startActivity(i);
}
And the second link is in dialog, which user can open:
( I will post here whole method, but I'll highlight important part )
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder .setTitle(R.string.show_photo_show_rated_users_title)
.setNegativeButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
ListView modeList = new ListView(this);
String[] stringArray = new String[ratedUsers.size()];
for ( int i=0 ; i<ratedUsers.size() ; i++ ){
stringArray[i] = ratedUsers.get(i).get("name");
}
ArrayAdapter<String> modeAdapter = new ArrayAdapter<String>(this, R.layout.dropdown_item_white, android.R.id.text1, stringArray);
modeList.setAdapter(modeAdapter);
modeList.setOnItemClickListener(new ListView.OnItemClickListener(){
/*********************** IMPORTANT PART *********************************/
#Override
public void onItemClick(AdapterView<?> parent, View arg1, int index,long arg3) {
Intent i;
i=new Intent(ShowPhotoDetails.this , ShowProfile.class);
i.putExtra("id",ratedUsers.get(index).get("id"));
/**** ratedUsers is ArrayList<HashMap<String,String>> ****/
startActivity(i);
}});
builder.setView(modeList);
final Dialog dialog = builder.create();
dialog.show();
}
And finally here's ShowProfile.class:
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
Intent i = getIntent();
try {
id = i.getStringExtra("id");
}catch(Exception e){
e.printStackTrace();
Toast.makeText(getBaseContext(), "Error loading intent", Toast.LENGTH_SHORT).show();
finish();
}
try{
Log.w("ID",id); //always give right number
new GetUserInformations().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, id);
/*
If I comments this asyncTask, there's no error at all, but if I run it, It
open debug View in Eclipse, says that "Source not found" and crashes...
No LogCat Output
*/
}catch(Exception e){
e.printStackTrace();
}
...
I wonder why in one case it run perfectly and in the other it crashes. As I wrote in code, there's no LogCat output for this crash. It don't even say Uncaught exception or something like this.
EDIT: I found out what gives me the error.
public class GetUserInformations extends AsyncTask<String,Void,Void>{
Map<String,Object> tmpUser;
#Override
protected void onPreExecute(){
tmpUser = new HashMap<String,Object>();
}
#Override
protected Void doInBackground(String... arg) {
try{
int u_id = Integer.parseInt(arg[0]);
tmpUser = myDb.getUser(u_id); // downloading info
}catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void arg){
if ( tmpUser != null ){
Log.w("LOG",""+tmpUser.get("name"));
name = (String) tmpUser.get("name");
fbId = (String) tmpUser.get("id");
email = (String) tmpUser.get("email");
country = (Integer) tmpUser.get("country");
userName.setText(name);
profilepic.setProfileId(fbId);
userSubscribe.setVisibility(View.VISIBLE);
}
else {
Toast.makeText(getBaseContext(), "Error", Toast.LENGTH_SHORT).show();
finish();
}
}
}
When I open activity for first time, everything downloads fine, but when I backPress and click on link to this Activity again, then it gives me NullPointerException.
Do you know why ?
In your onItemClick function, try to put :
i = new Intent(getApplicationContext(), ShowProfile.class);
instead of :
i = new Intent(ShowPhotoDetails.this, ShowProfile.class);
remove this:
new GetUserInformations().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, id);
and use :
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) {
new GetUserInformations().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, id);
}
else {
new GetUserInformations().execute(id);
}
What is the API level on which you are facing this problem. Try to run it on different levels, taking Honeycomb as a reference.
Need to check the same and apply execute or executeONExecutor like this:
if (currentApiVersion >=
android.os.Build.VERSION_CODES.HONEYCOMB) {
new YourAsynctask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
new YourAsynctask().execute();
}
Check this asynctask-threading-regression-confirmed blog post

Android async task usage

On click of a button, I want to open a dialog box. On that dialog box I want to set the text dynamically (somewhat like a stopwatch) with the text which will come via a loop. Could someone please guide me with sample code? I tried many examples given on the net but not able to successfully achieve the result.
//Button where the action starts
public void onClickStart(View v) {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.activity_details);
dialog.setTitle("Your Step Details");
dialog.show();
DisplayTask dd= new DisplayTask();
dd.execute();
}
public void doWork(){
final Handler handler=new Handler();
new Thread(new Runnable (){
boolean isRunning=true;
#Override
public void run() {
while(isRunning){
try{
handler.post(new Runnable(){
#Override
public void run() {
try{
TextView txtCurrentTime= (TextView)findViewById(R.id.txtLeft);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String curTime = hours + ":" + minutes + ":" + seconds;
txtCurrentTime.setText(curTime);
}catch (Exception e) {}
}
});
}catch(Exception e){
}
}
}
}).start();
}
public class DisplayTask extends AsyncTask<Void , Void, Void> {
protected void onPostExecute(){
MainActivity main= new Mai`enter code here`nActivity();
main.doWork();
}
#Override
protected Void doInBackground(Void... params) {
onPostExecute();
return null;
}
}
If you want to do something on a timer, AsyncTask isn't the right method. Use a Handler, and post a message to it using postMessageDelayed. This will let you do something in a few milliseconds/seconds, but it will happen on the UI thread.

Android Handler - not working properly

I want to create a dialogBuilder with a text field and a button on it. The idea is to make the program wait for any further actions until the text in the field is entered and the OK button is clicked. Below is the code:
private static final Object wait = new int[0];
private static String result = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Handler h = new Handler();
final Context context = MainActivity.this;
h.post(new Runnable() {
public void run() {
final Builder dialogBuilder = new AlertDialog.Builder(context);
dialogBuilder.setTitle(R.string.app_name);
final LinearLayout panel = new LinearLayout(context);
panel.setOrientation(LinearLayout.VERTICAL);
final TextView label = new TextView(context);
label.setId(1);
label.setText(R.string.app_name);
panel.addView(label);
final EditText input = new EditText(context);
input.setId(2);
input.setSingleLine();
input.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_VARIATION_URI
| InputType.TYPE_TEXT_VARIATION_PHONETIC);
final ScrollView view = new ScrollView(context);
panel.addView(input);
view.addView(panel);
dialogBuilder
.setCancelable(true)
.setPositiveButton(R.string.app_name,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
result = input.getText().toString();
synchronized (wait) {
wait.notifyAll();
}
dialog.dismiss();
}
}).setView(view);
dialogBuilder.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface arg0) {
result = null;
synchronized (wait) {
wait.notifyAll();
}
}
});
dialogBuilder.create().show();
}
});
String localResult = null;
try {
synchronized (wait) {
Log.d("Waiting", "Waiting " + localResult);
wait.wait();
}
localResult = result;
result = null;
if (localResult == null) {
// user is requesting cancel
throw new RuntimeException("Cancelled by user");
}
Log.d("RESULT ", "RESULT " + localResult);
} catch (InterruptedException e) {
localResult = result;
result = null;
if (localResult == null) {
// user is requesting cancel
Log.d("CANCELED ", "CANCELED " + localResult);
throw new RuntimeException("Cancelled by user");
}
}
Log.d("RESULT AFTER THE DIALOG", "RESULT AFTER THE DIALOG " + result);
}
The program is going to Log.d("Waiting", "Waiting " + localResult); and after that just waiting. NO DIALOG BUILDER IS SHOWN on the activity window. I used the debug mode and saw that the program flow is not entering the run() method, but the value of the Handler.post() is true. And for this reason the dialog is not shown, and the program is waiting.
I have tried to remove the moment with waiting (remove the Handler.post()), just to see if the dialog will show, and it showed and all moved well, but the result was not I am needing - I want the program to wait the input from the dialog ... I am really out of ideas.
Would you please give me some suggestions as I am really out of ideas.
Thanks a lot!
Handlers don't run in a separate thread. So when you call wait() :
synchronized (wait) {
Log.d("Waiting", "Waiting " + localResult);
wait.wait();
}
It waits indefinitely since the handler runs on the same thread as the current thread. Your Runnable can only be executed after the onCreate() method finishes but this will never happen because you just called wait().
You should reconsider your idea and find a workaround (for example, show the dialog the usual way and disable the "OK" button as long as the user does not enter a valid text). But calling wait() on the UI thread cannot go well.
You should be running the display of the Dialog in the UI Thread, not a seperate thread.
An example would be something like this:
In the onCreate()
runOnUiThread(new Runnable() {
#Override
public void run() {
// Display progress dialog when loading contacts
dialog = new ProgressDialog(this);
// continue with config of Dialog
}
});
// Execute the Asynchronus Task
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// code to execute in background
return null;
}
#Override
protected void onPostExecute(Void result) {
// Dismiss the dialog after inBackground is done
if (dialog != null)
dialog.dismiss();
super.onPostExecute(result);
}
}.execute((Void[]) null);
Specifically what is happening here is the Dialog is being displayed on the UI thread and then the AsyncTask is executing in the background while the Dialog is running. Then at the end of the execution we dismiss the dialog.

showing progress bar in alert dialog

I have an alert dialog box in my application for login authentication. While sending the request i want to show a progress bar and want to dismiss if the response is success.please help me if anyone knows.Iam using the below code:
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
LinearLayout login = new LinearLayout(this);
TextView tvUserName = new TextView(this);
TextView tvPassword = new TextView(this);
TextView tvURL = new TextView(this);
final EditText etUserName = new EditText(this);
final EditText etPassword = new EditText(this);
final EditText etURL = new EditText(this);
login.setOrientation(1); // 1 is for vertical orientation
tvUserName.setText(getResources().getString(R.string.username));
tvPassword.setText(getResources().getString(R.string.password));
tvURL.setText("SiteURL");
login.addView(tvURL);
login.addView(etURL);
login.addView(tvUserName);
login.addView(etUserName);
login.addView(tvPassword);
etPassword.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_VARIATION_PASSWORD);
login.addView(etPassword);
alert.setView(login);
alert.setTitle(getResources().getString(R.string.login));
alert.setCancelable(true);
alert.setPositiveButton(getResources().getString(R.string.login),
new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog,
int whichButton) {
strhwdXml = etURL.getText().toString();
strUserName = etUserName.getText().toString();
XmlUtil.username = strUserName;
strPassword = etPassword.getText().toString();
if ((strUserName.length() == 0)
&& (strPassword.length() == 0)
&& (strhwdXml.length() == 0)) {
Toast.makeText(
getBaseContext(),
getResources().getString(
R.string.userPassword),
Toast.LENGTH_SHORT).show();
onStart();
} else {
final SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor prefsEditor = prefs
.edit();
try {
StringBuffer inStreamBuf = new StringBuffer();
inStreamBuf = XmlUtil
.getLoginAuthResponse(strUserName,
strPassword, strhwdXml);
strXmlResponse = inStreamBuf.toString();
Log.e("Response:", strXmlResponse);
String parsedXML = ParseResponse(strXmlResponse);
if (parsedXML
.equalsIgnoreCase(getResources()
.getString(R.string.success))) {
}
It might be easier to use this
ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "",
"Loading. Please wait...", true);
You can read more about progress dialogs here
To cancel would be
dialog.dismiss();
This class was deprecated in API level 26. ProgressDialog is a modal
dialog, which prevents the user from interacting with the app. Instead
of using this class, you should use a progress indicator like
ProgressBar, which can be embedded in your app's UI. Alternatively,
you can use a notification to inform the user of the task's progress.For more details Click Here
Since the ProgressDialog class is deprecated, here is a simple way to display ProgressBar in AlertDialog:
Add fields in your Activity:
AlertDialog.Builder builder;
AlertDialog progressDialog;
Add getDialogProgressBar() method in your Activity:
public AlertDialog.Builder getDialogProgressBar() {
if (builder == null) {
builder = new AlertDialog.Builder(this);
builder.setTitle("Loading...");
final ProgressBar progressBar = new ProgressBar(this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
progressBar.setLayoutParams(lp);
builder.setView(progressBar);
}
return builder;
}
Initialize progressDialog:
progressDialog = getDialogProgressBar().create();
Show/Hide AlertDialog whenever u want using utility methods:
progressDialog.show() and progressDialog.dismiss()
If you want the progress bar to show, try the following steps and also you can copy and paste the entire code the relevant portion of your code and it should work.
//the first thing you need to to is to initialize the progressDialog Class like this
final ProgressDialog progressBarDialog= new ProgressDialog(this);
//set the icon, title and progress style..
progressBarDialog.setIcon(R.drawable.ic_launcher);
progressBarDialog.setTitle("Showing progress...");
progressBarDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//setting the OK Button
progressBarDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,
int whichButton){
Toast.makeText(getBaseContext(),
"OK clicked!", Toast.LENGTH_SHORT).show();
}
});
//set the Cancel button
progressBarDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int whichButton){
Toast.makeText(getApplicationContext(), "Cancel clicked", Toast.LENGTH_SHORT).show();
}
});
//initialize the dialog..
progressBarDialog.setProgress(0);
//setup a thread for long running processes
new Thread(new Runnable(){
public void run(){
for (int i=0; i<=15; i++){
try{
Thread.sleep(1000);
progressBarDialog.incrementProgressBy((int)(5));
}
catch(InterruptedException e){
e.printStackTrace();
}
}
//dismiss the dialog
progressBarDialog.dismiss();
}
});
//show the dialog
progressBarDialog.show();
The cancel button should dismiss the dialog.
Try below code
private class DownloadingProgressTask extends
AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(ShowDescription.this);
/** progress dialog to show user that the backup is processing. */
/** application context. */
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
try {
// write your request code here
**StringBuffer inStreamBuf = new StringBuffer();
inStreamBuf = XmlUtil
.getLoginAuthResponse(strUserName,
strPassword, strhwdXml);
strXmlResponse = inStreamBuf.toString();
Log.e("Response:", strXmlResponse);
String parsedXML = ParseResponse(strXmlResponse);
if (parsedXML
.equalsIgnoreCase(getResources()
.getString(R.string.success))) {**
return true;
} catch (Exception e) {
Log.e("tag", "error", e);
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
if (success) {
Toast.makeText(ShowDescription.this,
"File successfully downloaded", Toast.LENGTH_LONG)
.show();
imgDownload.setVisibility(8);
} else {
Toast.makeText(ShowDescription.this, "Error", Toast.LENGTH_LONG)
.show();
}
}
}
and call this in onclick event
new DownloadingProgressTask().execute();

"Busy" progress dialog causes strange code processing

Let me sum up the situation for you:
I have a button (btnChooseEp), and when you press it an AlertDialog appears.
When something is picked in the AlertDialog, three if statements must be evaluated.
While they are being evaluated, a ProgressDialog appears. It indicates that the app is "busy".
After the evaluation of these statements, the ProgressDialog must disappear.
My problem is described beneath the code.
The entire code block is shown here:
ProgressDialog getTracklistProgressDialog = null;
...
Button btnChooseEp = (Button)findViewById(R.id.btnChooseEp);
btnChooseEp.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
final AlertDialog.Builder builder = new AlertDialog.Builder(GA.this);
builder.setTitle(getText(R.string.chooseEpisode));
builder.setItems(episodes, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, final int pos)
{
getTracklistProgressDialog = ProgressDialog.show(GA.this, "Please wait...",
"Retrieving tracklist...", true);
new Thread()
{
public void run()
{
try
{
String str1, epURL;
if(pos < 9)
{
str1 = getResources().getString(R.string.epNo1);
epURL = String.format(str1, pos+1);
setTracklist(epURL, tracklist);
}
else if(pos < 100)
{
str1 = getResources().getString(R.string.epNo2);
epURL = String.format(str1, pos+1);
setTracklist(epURL, tracklist);
}
else if(pos >= 100)
{
str1 = getResources().getString(R.string.epNo3);
epURL = String.format(str1, pos+1);
setTracklist(epURL, tracklist);
}
}
catch(Exception e)
{}
// Remove progress dialog
getTracklistProgressDialog.dismiss();
}
}.start();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
Not sure if needed, but here is the code for the function setTracklist:
public void setTracklist(String string, TextView tv)
{
try
{
tv.setText(getStringFromUrl(string));
}
catch(Exception e)
{
e.printStackTrace();
}
}
And the code for the function getStringFromUrl can be seen here: http://pastebin.com/xYt3FwaS
Now, the problem:
Back when I didn't implement the ProgressDialog thing (which I have from here, btw: http://www.anddev.org/tinytut_-_displaying_a_simple_progressdialog-t250.html), it worked fine - the setTracklist function retrieves a string from a text file on the internet, and sets the text to a TextView. Now, when I have added the ProgressDialog code, and put the original code into the try statement, only a very little part of the text file is added to the TextView - approximately 22-24 characters, not more. The "busy" ProgressDialog shows up just fine. It worked perfectly before; it was more than capable of loading more than 1300 characters into the TextView.
I don't know if it has anything to do with the thread - I have Googled a lot and found no answer.
So, how do I get it to load in all data instead of just a small part?
(By the way, I would love to be able to set the line "setTracklist(epURL, tracklist);" beneath all of the if statements, but then it says it can't resolve "epURL". Seems stupid to write the same line 3 times!)
Updated 25/1 with current code:
final Handler uiHandler = new Handler();
final Button btnChooseEp = (Button)findViewById(R.id.btnChooseEp);
btnChooseEp.setEnabled(false);
btnChooseEp.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
builder.setTitle(getText(R.string.chooseEpisode));
builder.setItems(episodes2, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, final int pos)
{
replay.setVisibility(View.VISIBLE);
replayWeb.setVisibility(View.VISIBLE);
getTracklistProgressDialog = ProgressDialog.show(GA.this, "Please wait...",
"Retrieving tracklist...", true);
new Thread()
{
public void run()
{
try
{
String str1, epURL;
if(pos < 9)
{
str1 = getResources().getString(R.string.gaEpNo1);
epURL = String.format(str1, pos+1);
setTracklist2(epURL, tracklist);
}
else if(pos < 100)
{
str1 = getResources().getString(R.string.gaEpNo2);
epURL = String.format(str1, pos+1);
setTracklist2(epURL, tracklist);
}
else if(pos >= 100)
{
str1 = getResources().getString(R.string.gaEpNo3);
epURL = String.format(str1, pos+1);
setTracklist2(epURL, tracklist);
}
}
catch(Exception e)
{}
// Remove progress dialog
uiHandler.post(new Runnable()
{
public void run()
{
getTracklistProgressDialog.dismiss();
}
}
);
}
}.start();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
public void setTracklist2(final String string, final TextView tv)
{
try
{
uiHandler.post(
new Runnable()
{
public void run()
{
try
{
tv.setText(getStringFromUrl(string));
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
}
Notes: "replay" and "replayWeb" are just two TextView's. "btnChooseEp" is enabled when another button is pressed.
My guess is that you are getting bizarre behavior because you are invoking a ui method on a non-ui thread.
getTracklistProgressDialog.dismiss();
must be executed on a ui thread. My guess is that it is crashing and your thread is crashing then leaving some of your resources in a bad state. This would explain why you get a varying amount of characters.
I would try creating a final Handler in your onCreate method which would get bound to the uiThread. In that thread, you can then call
uiHandler.post(
new Runnable() {
public void run(){
getTracklistPRogressDialog.dismiss();
}
}
);
This is quick, so it may not be syntactically correct, check your ide.
This is the best i can get from what you've posted. If you post more of the code I can try to run it to give you more help.
Update:
I think I found your problem:
The idea of having another thread is to do the long running work there, but what we have right now actually does the long running work on the ui thread, the opposite of our goal. What we need to do is move the call to getStringFromUrl(url) from the setTracklist call up into the thread. I would rewrite setTracklist as follows:
public void setTracklist(String tracklistContent, TextView tv)
{
try
{
runOnUiThread(
new Runnable() {
public void run() {
tv.setText(tracklistContent);
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
}
Then in your inner onClick method, do this:
public void onClick(DialogInterface dialog, final int pos)
{
getTracklistProgressDialog = ProgressDialog.show(GA.this, "Please wait...",
"Retrieving tracklist...", true);
new Thread()
{
public void run()
{
try
{
String str1, epURL;
if(pos < 9)
{
str1 = getResources().getString(R.string.epNo1);
epURL = String.format(str1, pos+1);
String tlContent = getStringFromUrl(epUrl);
setTracklist(epURL, tracklist);
}
else if(pos < 100)
{
str1 = getResources().getString(R.string.epNo2);
epURL = String.format(str1, pos+1);
String tlContent = getStringFromUrl(epUrl);
setTracklist(epURL, tracklist);
}
else if(pos >= 100)
{
str1 = getResources().getString(R.string.epNo3);
epURL = String.format(str1, pos+1);
String tlContent = getStringFromUrl(epUrl);
setTracklist(epURL, tracklist);
}
}
catch(Exception e)
{}
// Remove progress dialog
getTracklistProgressDialog.dismiss();
}
}.start();
}
I'm so, we make the call to the web service/url before we regain ui thread execution. The long running internet retrieval runs on the bg thread and then the ui update happens on the ui thread. Think this should help.

Categories

Resources