How to finish execution of Async Task ? - android

I need to finish the execution of an async task before I make some checks for my login.
This is my async task
#Override
protected void onPostExecute(JSONArray jsonArray)
{
JSONObject json_data = null;
for (int i = 0; i < jsonArray.length(); i++) {
try {
json_data = jsonArray.getJSONObject(i);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
for (int j=0; j<jsonArray.length(); j++){
/*allMatrics.add(json_data.getString("matricNos"));
allPasswords.add(json_data.getString("password"));*/
if (user.equals(json_data.get("matricNos")) && pass.equals(json_data.get("password")))
{
ok = true;
System.out.println("hi i am ok");
break;
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Checking ok = "+ ok);
}
I need to finish this async task before I Check its status and then go on for my login authentication. It is supposed to be executed on the onclick of the login button
login.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
user = uedit.getText().toString();
pass = pedit.getText().toString();
if (user.equals(""))
{
Toast error = Toast.makeText(LogInScreen.this, "Enter Details", Toast.LENGTH_SHORT);error.show();
}
else
{
final GetMatricNos mat = new GetMatricNos();
mat.execute(new ServerConnector());
// have to finish task before enter user, have to implement logout as well
if ((mat.getStatus().equals(AsyncTask.Status.RUNNING))) - This has to be Status.FINISHED
{
System.out.println(ok);
/* if ((allMatrics.contains(user) && (allPasswords.contains(pass)))) */
if (ok)
{
Intent homescreen = new Intent(LogInScreen.this, HomeScreen.class);
homescreen.putExtra("username", user);
startActivity(homescreen);
}
else
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(LogInScreen.this);
alertDialogBuilder.setTitle(Html.fromHtml("<font color='#D41E46'>Invalid Login Details</font>"));
alertDialogBuilder
.setMessage("The login credentials you have entered are invalid. Please try again.")
.setIcon(R.drawable.alert)
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
}
}
});
ActionBar actionBar = getActionBar();
actionBar.hide(); // To hide the actionBar on LoginScreen
}
Now If I don't finish the task before checking it, it won't let me check the credentials that I am getting from the edit boxes, however first time if I login it doesn't make the check because the task runs when the login button is pressed, but for the second time if I login it goes through...?
Any help would be much appreciated, I tried task.cancel(true) before the check but that doesnt help...

If your task needs to finish executing before you do anything else then you must put the code that must wait in your onPostExecute which gets called when the task is finished

Related

toolbar button disappearing when dialog closed

my app is fairly simple and always works IF my IOT device is up.
i need to load a popup and show the ReScan button on the toolbar if the device cannot be found.
the app preloads IPaddress="-" and loads 2 asyncTask(s)
one uses NsdManager.DiscoveryListener to find the mDNS name and loads the IP into IPaddress
this task watches to see IPaddress change and gets the presets from the device by JSON and sets up the UI or pops up the error dialog with instructions if not found.
MY PROBLEM:
when counter >= 15 , i show the "Rescan" Button on the toolbar with setMenuVisible() then popup the error dialog but when the button in the dialog is pressed to close the dialog, the "Rescan" Button disappears again.
Also times out in about 5 seconds.
how do i get the "Rescan" Button to stay?
.
private class getSettingsFromClock extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
String mlooper = IPaddress;
Log.i(TAG, "LOG getSettingsFromClock doInBackground started ");
int counter = 0;
while ( mlooper.equals("-") ) {
mlooper = IPaddress;
try {
Thread.sleep(600);
} catch (InterruptedException e) {
e.printStackTrace();
}
counter++;
if (counter >= 15) // in normal operation counter never goes above 3
{
Log.i(TAG, "LOG getSettingsFromClock - NO IP Found, count= " + counter );
runOnUiThread(new Runnable() {
#Override
public void run() {
setMenuVisible( true, R.id.action_rescan); // show rescan button on toolbar
try { // delay is debugging only
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
//scanning failed Popup Dialog
final Dialog dialog = new Dialog(context );
dialog.setContentView(R.layout.popup);
dialog.setTitle("Scan Error");
Button button = dialog.findViewById(R.id.Button01);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
Toast.makeText(getApplicationContext(),
"Could Not get presets from clock. \n check Clock is on and on WiFi\n and reload app.",
Toast.LENGTH_LONG).show();
}
});
break;
}
}
if( IPaddress != "-" )
{
// gets JSON here
} else
{
// add popup - IOT Not found
}
// JSON starts here
if (JSON_return != null) {
try {
// loads presets from JSON to UI here
} catch (final JSONException e) {
Log.e(TAG, "LOG, JSON parsing error: " + e.getMessage());
}
} else
{
Log.e(TAG, "LOG, Could Not get JSON from Clock.");
}
return null;
}
} // end asyncTask class
// remember to run on main thread
// NOTE; private Menu option_Menu; declared in MainActivity
// ie; setMenuVisible( true, R.id.action_rescan);
public void setMenuVisible(boolean visible, int id) {
if (option_Menu != null) {
option_Menu.findItem(id).setVisible(visible);
}
}
Mike M. had it, Thank You Mike
added onPrepareOptionsMenu()
added showRescan = visible; and invalidateOptionsMenu(); to setMenuVisible()
all work perfectly now.
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
try {
if( showRescan )
{
option_Menu.findItem(R.id.action_rescan).setVisible( true );
} else
{
option_Menu.findItem(R.id.action_rescan).setVisible( false );
}
}
catch(Exception e) {
Log.e(TAG, "onPrepareOptionsMenu error");
}
return true;
}
// when task is completed you can show your menu just by calling this method
// remember to run on main thread
// ie; setMenuVisible( true, R.id.action_rescan);
public void setMenuVisible(boolean visible, int id) {
if (option_Menu != null) {
option_Menu.findItem(id).setVisible(visible);
showRescan = visible;
invalidateOptionsMenu();
}
}

login form doesnt send userid at firsttime

hiiii following is my login code
public class Login extends ActionBarActivity {
// flag for Internet connection status
Boolean isInternetPresent = false;
String shareduid;
// Connection detector class
ConnectionDetector cd;
ImageView imgview;
EditText uname;
EditText pass;
Button create,login;
TextView trouble;
public static final String MyPREFERENCES = "MyPrefs";
public static String userid = null;
SharedPreferences sharedpreferences;
private static final String TAG = "myAppSurun";
//private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
//End Drawer
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
String otpkey,vrfy;
// url to get all products list
private static String url_all_login = "http://xxx/xxx/xxxx/xxx";
//Globalstring
String username =null;
String password = null;
//Global Variable for login state checking
public boolean loginflag = false;
// RelativeLayout relativeLayout=new RelativeLayout(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
cd = new ConnectionDetector(getApplicationContext());
imgview=(ImageView)findViewById(R.id.imageView2);
uname=(EditText)findViewById(R.id.edituser);
pass=(EditText)findViewById(R.id.editpassword);
create=(Button)findViewById(R.id.create);
login=(Button)findViewById(R.id.Login);
trouble=(TextView)findViewById(R.id.trouble_login);
getSupportActionBar().setTitle("Surun Support");
ColorDrawable(Color.parseColor("#F58634")));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
ActionBar bar = getSupportActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F58634")));
//Click Text Animation
final Animation myanim, imganim;
myanim = AnimationUtils.loadAnimation(this, R.anim.link_text_anim);
imganim = AnimationUtils.loadAnimation(this, R.anim.rotate);
uname.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
validation.isValid(uname, "^[_a-zA-Z]+(\\.[_a-zA-Z 0-9-]+)*#[a-zA-Z]+(\\.[a-zA-Z]+)*(\\.[a-zA-Z]{2,})$", "Invalid UserName", true);
}
});
pass.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
validation.isValid(pass, "[0-9]{10}", "Invalid Mobile No", true);
}
});
//end of initializing component
create.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Create Click", Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), Registration_user.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
});//End of On click for button
//starting font settings this has prone to error try catch is mandatory while setting font(Overriding native font interface).
try {
Typeface myTypeface = Typeface.createFromAsset(this.getAssets(), "fonts/robotoregular.ttf");
create.setTypeface(myTypeface);
} catch (Exception e) {
Log.v(TAG, "Exception " + e);
}
//End of font settings
//Initializing shared preferences
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
//load preferences if exist
Log.v(TAG,""+sharedpreferences);
Log.v(TAG,"Preference is present loading it");
String shareduser = sharedpreferences.getString("User", "");
String sharedpass = sharedpreferences.getString("Password", "");
shareduid = sharedpreferences.getString("userid", "");
String sharedotp = sharedpreferences.getString("otp", "");
String sharedvrfy = sharedpreferences.getString("verified", "");
Log.v(TAG,"uid"+shareduser);
Log.v(TAG,"otp"+sharedpass);
Log.v(TAG,"vrfy"+sharedvrfy);
if ((shareduser.length() > 0) && (sharedpass.length() > 0)) {
//Navigating to main page
Log.v(TAG,"navigate to main");
Intent i = new Intent(getApplicationContext(), UserLogedIn.class);
i.putExtra("user", shareduser);
i.putExtra("pass", sharedpass);
i.putExtra("userid", shareduid);
i.putExtra("otpkey",sharedotp);
i.putExtra("vrfy", sharedvrfy);
//Starting An Activity
startActivity(i);
finish();
} else {
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// get Internet status
isInternetPresent = cd.isConnectingToInternet();
// check for Internet status
if (isInternetPresent) {
if (uname.getText().length() <= 0 || pass.getText().length() <= 0) {
AlertDialog alertDialog = new AlertDialog.Builder(Login.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("All Fields Are Mandatory");
// Setting Icon to Dialog
// alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "Please Enter Correct User Name And Password", Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();
if (pass.getText().length() > 10) {
Toast toast1 = Toast.makeText(getApplicationContext(), "Four Characters Only...", Toast.LENGTH_SHORT);
toast1.show();
trouble.setVisibility(View.VISIBLE);
//Log.v(TAG,"Not Valid");
}
} else if (pass.getText().length() > 10) {
AlertDialog alertDialog = new AlertDialog.Builder(Login.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("Mobile no Must be 10 digit only ");
// Setting Icon to Dialog
// alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "Please Enter Correct User Name And Password", Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();
} else if (!(validation.isValid(uname, "^[_a-zA-Z]+(\\.[_a-zA-Z0-9-]+)*#[a-zA-Z]+(\\.[a-zA-Z]+)*(\\.[a-zA-Z]{2,})$", "Invalid UserName", true))) {
AlertDialog alertDialog = new AlertDialog.Builder(Login.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("Email Is Incorrect");
// Setting Icon to Dialog
// alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "Email Id Is InCorrect", Toast.LENGTH_SHORT).show();
uname.requestFocus();
}
});
// Showing Alert Message
alertDialog.show();
} else {
//Animate Button load animation from anim/rotate.xml
imgview.startAnimation(imganim);
username = uname.getText().toString().toLowerCase();
password = pass.getText().toString();
//Sending Login Request To Server for validation Using Asynchronus Tasks where username and password as a parameter to method
Log.v(TAG, "Excuting check detail");
new CheckDetail().execute();
//Creating Shared Preferences
}//end of else_if fields are valid
}
else
{
AlertDialog alertDialog = new AlertDialog.Builder(Login.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("Internet is not active.Please Check Your NEtwork Setting");
// Setting Icon to Dialog
// alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "Internet Is Inactive", Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();
}
}
});//End of On click for button
}//If no shared preferences found
}//End of onCreate function
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_admin_home, menu);
return true;
}//End of onCreateOptionMenu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
//Remove Following Comment To Enable Drawer Toggling On Login Page
/*// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}*/
return super.onOptionsItemSelected(item);
}//End of onOptionItemSelected
//Alert Dialog when User Click Back Button
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Handle the back button
if(keyCode == KeyEvent.KEYCODE_BACK) {
//Ask the user if they want to quit
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.quit)
.setMessage(R.string.really_quit)
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Stop the activity
Login.this.finish();
}
})
.setNegativeButton("no", null)
.show();
return true;
}
else {
return super.onKeyDown(keyCode, event);
}
}//End of Alert Dialog Box
class CheckDetail extends AsyncTask<String,String, String> {
JSONArray datail=null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Logging in. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
*/
protected String doInBackground(String... args) {
try {
Log.v(TAG, "In Do in Background");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("pwd", password));
// getting JSON string from URL
JSONObject json =jParser.makeHttpRequest(url_all_login, "POST", params);
//Object Parsing Failed here hence by using trail guide using JSONParser.alternateJSONArray to parse user data.
//Hence not using json instance of object using a BACKUP static variable of Parser class for proccessing.
//To use this backup utility theme the process should be standard and return unique or two out put only or ether way use three logical step
if(json != null) {
// As if login fails it returns object handling fail logic here.
//We can make it general by sending array from server side so we can only use alternateJSONArray variable
}
if(JSONParser.alternateJSONArray != null)
{
Log.v(TAG, "USING BACKUP ARRAY");
//Check your log cat for JSON futher details
for (int jsonArrayElementIndex=0; jsonArrayElementIndex < JSONParser.alternateJSONArray.length(); jsonArrayElementIndex++) {
JSONObject jsonObjectAtJsonArrayElementIndex = JSONParser.alternateJSONArray.getJSONObject(jsonArrayElementIndex);
userid=jsonObjectAtJsonArrayElementIndex.getString("u_id");
otpkey=jsonObjectAtJsonArrayElementIndex.getString("OTP");
vrfy=jsonObjectAtJsonArrayElementIndex.getString("is_verified");
Log.v(TAG,"" +userid);
Log.v(TAG,"" +otpkey);
Log.v(TAG,"" +vrfy);
if(jsonObjectAtJsonArrayElementIndex.getString("email").equals(username) && jsonObjectAtJsonArrayElementIndex.getString("mobile").equals(password))
{
Log.v(TAG,"Login Successful Now setting loginflag true");
loginflag = true;
}
}
}
else
{
loginflag=false;
}
} catch (Exception e) {
e.printStackTrace();
Log.v(TAG, "Exception at end :" + e.toString());
//Log.e("TAG", "Error......!RecoverIt");
}
return null ;
}
protected void onPostExecute(String result)
{
// dismiss the dialog after getting all products
//super.onPostExecute();
// pDialog.dismiss();
Log.v(TAG,"verification"+vrfy);
Log.v(TAG,"userid"+userid);
/* if(vrfy==false)
{
Intent i = new Intent(getApplicationContext(), Verifyotp.class);
i.putExtra("userid", userid);
i.putExtra("isverified", vrfy);
startActivity(i);
}else*/
if(loginflag==true) {
Log.v(TAG, "Executing Shared Preferences...");
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("User", uname.getText().toString());
editor.putString("Password", pass.getText().toString());
Log.v(TAG, "Userid==================" + userid);
Log.v(TAG, "otpkey==============" + otpkey);
Log.v(TAG, "is verified " + vrfy);
editor.putString("userid", userid);
editor.putString("otp", otpkey);
editor.putString("vrfy", vrfy);
editor.commit();
Toast.makeText(getApplicationContext(), "Login Succeed", Toast.LENGTH_SHORT).show();
android.util.Log.v(TAG, "Login Succeed");
Intent i = new Intent(getApplicationContext(), UserLogedIn.class);
i.putExtra("user", shareduid);
Log.v(TAG, "" + userid);
startActivity(i);
finish();
}
else
{
Toast.makeText(getApplicationContext(),"Login failed,Invalid Details...!",Toast.LENGTH_LONG).show();
trouble.setVisibility(View.VISIBLE);
}
pDialog.dismiss();
}
}
i send userid from login.java to next activity but in other activity it doesnt receive that userid first time.at first time it display null but at other places it show/print userid correctely
if i restart app userid will be perfect and app will work fine
i dont know why it is happen at first time
code in other activity
Intent iin = getIntent();
Bundle b = iin.getExtras();
if (b != null) {
u_id = (String) b.get("userid");//first time it shows null but after restart it get correct value
Log.v(TAG, "userlogged in" + u_id);
}
because you sending null first time change below in your onpost method
Intent i = new Intent(getApplicationContext(), UserLogedIn.class);
i.putExtra("user", shareduid);
Log.v(TAG, "" + userid);
startActivity(i);
in above shareduid is null first time you setting by shared preference so just put below
Intent i = new Intent(getApplicationContext(), UserLogedIn.class);
i.putExtra("user", userid);
Log.v(TAG, "" + userid);
startActivity(i);
check with this and let me know also i think check with key if you putextra with 'user' key you have to access with the same 'user' key

JSONarray login and logout

I have one problem I am writing code for login and logout using SharedPreferneces.
When i click logout it run perfectly and go back to login screen.
Now the problem is that when i logout and come on login screen at that time if i entered invalid detail then server give failed message and but login will success and go to next screen.
here is code
public class Login extends ActionBarActivity {
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
ImageView imgview;
EditText uname;
EditText pass;
Button create,login;
TextView trouble;
public static final String MyPREFERENCES = "MyPrefs";
SharedPreferences sharedpreferences;
private static final String TAG = "myAppSurun";
//Drawer
//private ListView mDrawerList;
//private DrawerLayout mDrawerLayout;
//private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
//End Drawer
//Asynchronous task variable
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
String userid,otpkey,vrfy;
// url to get all products list
private static String url_all_login = "http://xxx/xxx/xxx/xxx";
//Globalstring
String username =null;
String password = null;
//Global Variable for login state checking
public static boolean loginflag = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
cd = new ConnectionDetector(getApplicationContext());
imgview=(ImageView)findViewById(R.id.imageView2);
uname=(EditText)findViewById(R.id.edituser);
pass=(EditText)findViewById(R.id.editpassword);
create=(Button)findViewById(R.id.create);
login=(Button)findViewById(R.id.Login);
trouble=(TextView)findViewById(R.id.trouble_login);
getSupportActionBar().setTitle("Surun Support");
//getSupportActionBar().setDisplayShowHomeEnabled(true);
//getSupportActionBar().setLogo(R.drawable.dotlogo1);
//getSupportActionBar().setDisplayUseLogoEnabled(true);
//ActionBar bar = getSupportActionBar();
//bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F58634")));
// Start Drawer Settings
//mDrawerList = (ListView) findViewById(R.id.navListlog);
//mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout_login);
//mActivityTitle = getTitle().toString();
//addDrawerItems();
//setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
ActionBar bar = getSupportActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F58634")));
// End of Drawer Settings
//Click Text Animation
final Animation myanim, imganim;
myanim = AnimationUtils.loadAnimation(this, R.anim.link_text_anim);
imganim = AnimationUtils.loadAnimation(this, R.anim.rotate);
//End of animation
//Initialize the component
uname.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
validation.isValid(uname, "^[_a-z]+(\\.[_a-z0-9-]+)*#[a-z]+(\\.[a-z]+)*(\\.[a-z]{2,})$", "Invalid UserName", true);
}
});
pass.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
validation.isValid(pass, "[0-9]{10}", "Invalid Mobile No", true);
}
});
//end of initializing component
// Creating underlined text
// String udata = "Create Account";
//SpannableString content = new SpannableString(udata);
//content.setSpan(new UnderlineSpan(), 0, udata.length(), 0);
//create.setText(content);
//end of creating underlined text
//Toast.makeText(getApplicationContext(), "Create", Toast.LENGTH_LONG).show();
//Log.v("TEST", "TEST");
create.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Create Click", Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), Registration_user.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
});//End of On click for button
//starting font settings this has prone to error try catch is mandatory while setting font(Overriding native font interface).
try {
Typeface myTypeface = Typeface.createFromAsset(this.getAssets(), "fonts/robotoregular.ttf");
create.setTypeface(myTypeface);
} catch (Exception e) {
Log.v(TAG, "Exception " + e);
}
//End of font settings
//Initializing shared preferences
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
//load preferences if exist
Log.v(TAG,""+sharedpreferences);
Log.v(TAG,"Preference is present loading it");
String shareduser = sharedpreferences.getString("User", "");
String sharedpass = sharedpreferences.getString("Password", "");
String shareduid = sharedpreferences.getString("userid", "");
String sharedotp = sharedpreferences.getString("otp", "");
String sharedvrfy = sharedpreferences.getString("verified", "");
Log.v(TAG,"uid"+shareduser);
Log.v(TAG,"otp"+sharedpass);
if ((shareduser.length() > 0) && (sharedpass.length() > 0)) {
//Navigating to main page
Log.v(TAG,"navigate to main");
Intent i = new Intent(getApplicationContext(), UserLogedIn.class);
i.putExtra("user", shareduser);
i.putExtra("pass", sharedpass);
i.putExtra("userid", shareduid);
i.putExtra("otpkey",sharedotp);
i.putExtra("vrfy", sharedvrfy);
//Starting An Activity
startActivity(i);
finish();
} else {
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// get Internet status
isInternetPresent = cd.isConnectingToInternet();
// check for Internet status
if (isInternetPresent) {
if (uname.getText().length() <= 0 || pass.getText().length() <= 0) {
AlertDialog alertDialog = new AlertDialog.Builder(Login.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("All Fields Are Mandatory");
// Setting Icon to Dialog
// alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "Please Enter Correct User Name And Password", Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();
if (pass.getText().length() > 10) {
Toast toast1 = Toast.makeText(getApplicationContext(), "Four Characters Only...", Toast.LENGTH_SHORT);
toast1.show();
trouble.setVisibility(View.VISIBLE);
//Log.v(TAG,"Not Valid");
}
} else if (pass.getText().length() > 10) {
AlertDialog alertDialog = new AlertDialog.Builder(Login.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("Mobile no Must be 10 digit only ");
// Setting Icon to Dialog
// alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "Please Enter Correct User Name And Password", Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();
} else if (!(validation.isValid(uname, "^[_a-z]+(\\.[_a-z0-9-]+)*#[a-z]+(\\.[a-z]+)*(\\.[a-z]{2,})$", "Invalid UserName", true))) {
AlertDialog alertDialog = new AlertDialog.Builder(Login.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("Email Is Incorrect");
// Setting Icon to Dialog
// alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "Email Id Is InCorrect", Toast.LENGTH_SHORT).show();
uname.requestFocus();
}
});
// Showing Alert Message
alertDialog.show();
} else {
//Animate Button load animation from anim/rotate.xml
imgview.startAnimation(imganim);
username = uname.getText().toString();
password = pass.getText().toString();
//Sending Login Request To Server for validation Using Asynchronus Tasks where username and password as a parameter to method
Log.v(TAG, "Excuting check detail");
new CheckDetail().execute();
//Creating Shared Preferences
}//end of else_if fields are valid
}
else
{
AlertDialog alertDialog = new AlertDialog.Builder(Login.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("Internet is not active.Please Check Your NEtwork Setting");
// Setting Icon to Dialog
// alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "Internet Is Inactive", Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();
}
}
});//End of On click for button
}//If no shared preferences found
}//End of onCreate function
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_admin_home, menu);
return true;
}//End of onCreateOptionMenu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
//Remove Following Comment To Enable Drawer Toggling On Login Page
/*// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}*/
return super.onOptionsItemSelected(item);
}//End of onOptionItemSelected
//Alert Dialog when User Click Back Button
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Handle the back button
if(keyCode == KeyEvent.KEYCODE_BACK) {
//Ask the user if they want to quit
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.quit)
.setMessage(R.string.really_quit)
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Stop the activity
Login.this.finish();
}
})
.setNegativeButton("no", null)
.show();
return true;
}
else {
return super.onKeyDown(keyCode, event);
}
}//End of Alert Dialog Box
/**
* Background Async Task to Login by making HTTP Request
*/
class CheckDetail extends AsyncTask<String,String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
JSONArray datail=null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Logging in. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
*/
protected String doInBackground(String... args) {
try {
Log.v(TAG, "In Do in Background");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("pwd", password));
// getting JSON string from URL
JSONObject json =jParser.makeHttpRequest(url_all_login, "POST", params);
//Object Parsing Failed here hence by using trail guide using JSONParser.alternateJSONArray to parse user data.
//Hence not using json instance of object using a BACKUP static variable of Parser class for proccessing.
//To use this backup utility theme the process should be standard and return unique or two out put only or ether way use three logical step
if(json != null) {
// As if login fails it returns object handling fail logic here.
//We can make it general by sending array from server side so we can only use alternateJSONArray variable
}
if(JSONParser.alternateJSONArray != null)
{
Log.v(TAG, "USING BACKUP ARRAY");
//Check your log cat for JSON futher details
for (int jsonArrayElementIndex=0; jsonArrayElementIndex < JSONParser.alternateJSONArray.length(); jsonArrayElementIndex++) {
JSONObject jsonObjectAtJsonArrayElementIndex = JSONParser.alternateJSONArray.getJSONObject(jsonArrayElementIndex);
userid=jsonObjectAtJsonArrayElementIndex.getString("u_id");
otpkey=jsonObjectAtJsonArrayElementIndex.getString("OTP");
vrfy=jsonObjectAtJsonArrayElementIndex.getString("is_verified");
Log.v(TAG,"" +userid);
Log.v(TAG,"" +otpkey);
Log.v(TAG,"" +vrfy);
if(jsonObjectAtJsonArrayElementIndex.getString("email").equals(username) && jsonObjectAtJsonArrayElementIndex.getString("mobile").equals(password))
{
Log.v(TAG,"Login Successful Now setting loginflag true");
loginflag = true;
}
}
}
else
{
//JSON is null ether no data or 204 returned by server
}
} catch (Exception e) {
e.printStackTrace();
Log.v(TAG, "Exception at end :" + e.toString());
//Log.e("TAG", "Error......!RecoverIt");
}
return null ;
}
protected void onPostExecute(String result)
{
// dismiss the dialog after getting all products
//super.onPostExecute();
// pDialog.dismiss();
if(loginflag==true) {
Log.v(TAG, "Executing Shared Preferences...");
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("User", uname.getText().toString());
editor.putString("Password", pass.getText().toString());
Log.v(TAG, "" + userid);
Log.v(TAG, "" + otpkey);
Log.v(TAG, "" + vrfy);
editor.commit();
Toast.makeText(getApplicationContext(), "Login Succeed", Toast.LENGTH_SHORT).show();
android.util.Log.v(TAG, "Login Succeed");
Intent i = new Intent(getApplicationContext(), UserLogedIn.class);
startActivity(i);
finish();
}
else
{
Toast.makeText(getApplicationContext(),"Login failed,Invalid Details...!",Toast.LENGTH_LONG).show();
trouble.setVisibility(View.VISIBLE);
}
pDialog.dismiss();
}
}
String getMD5(String pass) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(pass.getBytes());
BigInteger number = new BigInteger(1, messageDigest);
String hashtext = number.toString(16);
// Now we need to zero pad it if you actually want the full 32 chars.
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
return hashtext;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
/* private int returnParsedJsonObject(String result) {
JSONObject resultObject = null;
int returnedResult = 0;
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}*/
}
When i logout and at login activity if i enter wrong detail it will give following logcat
I think backuparray is not nnull when i logout
loginflag is static. once it is set to true it is never set back to false until you restart the app.
Okey .
First make your AsyncTask extends AsyncTask<Void, Void, Boolean> then return true in Boolean doInBackground(Void... params) if your server gives Success response and set it as false if server gives you failed message.
Now in your onPostExecute(Boolean result) , if result is true then set your login flag here as True else false.

Progress dialog is not showing while calling a web service

I am new to android. I want to show progress dialog when user click on login button. I tried this but the dialog is not showing
btn_logIn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
getUserCredentials();
}
}); //end of anonymous class
private void showProgressDialog() {
if (dialog == null) {
dialog = new ProgressDialog(this);
}
dialog.setMessage("Please Wait. Your authentication is in progress");
dialog.setButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
dialog.dismiss();
}
}); //end of anonymous class
dialog.show();
} //end of showProgressDialog()
private void getUserCredentials() {
EditText txt_userName = (EditText) findViewById(R.id.txt_userName);
String userName = txt_userName.getText().toString();
EditText txt_password = (EditText) findViewById(R.id.txt_password);
String password = txt_password.getText().toString();
if (userName != null && !userName.trim().equals("") && password != null && !password.trim().equals("")) {
showProgressDialog();
callWebService(userName, password);
}
} //end of getUserCredentials()
private void callWebService(String userName, String password) {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("userName", userName);
....
Object result = envelope.getResponse();
if (result.equals("true")) {
dialog.dismiss();
Toast.makeText(this, result.toString(), Toast.LENGTH_SHORT).show();
} else {
dialog.dismiss();
Toast.makeText(this, result.toString(), Toast.LENGTH_SHORT).show();
}
} catch (SocketTimeoutException e) {
dialog.dismiss();
Toast.makeText(this, "Service is not connected, Please make sure your server is running", Toast.LENGTH_LONG).show();
} catch(Exception e) {
e.printStackTrace();
dialog.dismiss();
Toast.makeText(this, "Unable to connect, please try again later. Thank you", Toast.LENGTH_LONG).show();
}
} //end of callWebServide()
Am i doing anything wrong. When i click on login button and service is not running then it shows message that Service is not connected, Please make sure your server is running", but the dialog isn't showing...Why? My logic is when user click on login button and fields have values then start showing progress dialog and if anything happens like when result come or server is not running or if any exception happen , then i remove the dialog and show the appropriate message, but dialog isn't showing...Why? What i am doing wrong? Please help..
Thanks
Try this,
Change your getUserCredentials() like this,
private void getUserCredentials() {
EditText txt_userName = (EditText) findViewById(R.id.txt_userName);
String userName = txt_userName.getText().toString();
EditText txt_password = (EditText) findViewById(R.id.txt_password);
String password = txt_password.getText().toString();
if (userName != null && !userName.trim().equals("") && password != null && !password.trim().equals("")) {
showProgressDialog();
Thread t=new Thread(new Runnable() {
public void run() {
callWebService(userName, password);
}
}); t.start();
}
}
And your callWebService method like this,
private void callWebService(String userName, String password) {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("userName", userName);
....
Object result = envelope.getResponse();
if (result.equals("true")) {
dialog.dismiss();
Toast.makeText(this, result.toString(), Toast.LENGTH_SHORT).show();
} else {
ActivityName.this.runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
Toast.makeText(this, result.toString(), Toast.LENGTH_SHORT).show();
}
});
}
} catch (SocketTimeoutException e) {
ActivityName.this.runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
Toast.makeText(this, "Service is not connected, Please make sure your server is running", Toast.LENGTH_LONG).show();
}
});
} catch(Exception e) {
e.printStackTrace();
ActivityName.this.runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
Toast.makeText(this, "Unable to connect, please try again later. Thank you", Toast.LENGTH_LONG).show();
}
});
}
}
Update 1
To answer your questions from your comments,
1)Yes Async Task is more efficient. It has its own methods to do the same task what I have described here.
AsyncTask has the following methods,
i)onPreExecute()-which can be used to start your Dialog
ii)doInBackground()-which acts as the background thread.
iii)onPostExecute()-which gets called at the end where you can dismiss the dialog.
The reason why I didn't mention is that, there are possibilities that you might have to change your working code's structure to adapt to Async task.
2)runonUiThread- as the name indicates, anything inside this will be considered as it is running in the main UI thread. So basically to update the screen you have to use this. There are also other methods available, like Handlers which can also do the same task.
Use AsyncTask for it when ever task started at that time initialise your widget and then call your webservice from run method and close your progress bar on stop method.

"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