I am checking server available or not with AsyncTask class and its working fine with below code
class AsyncServerOnlineCheck extends AsyncTask {
boolean isReachable;
#Override
protected Object doInBackground(Object[] objects) {
isReachable = NetworkCheck.isReachable(SplashsActivity.this);
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
if (isReachable) {
new DownloadLatestData().execute();
Toast.makeText(SplashsActivity.this, "Server is online", Toast.LENGTH_SHORT).show();
} else {
if (database.isDataBaseCreated()) {
Toast.makeText(SplashsActivity.this, "Server is offline", Toast.LENGTH_SHORT).show();
Intent i = new Intent(SplashsActivity.this, MainActivity.class);
startActivity(i);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
finish();
} else {
connectionerror();
}
}
}
}
Now I want use isReachable condition in other method called connectionerror. Both is in same activity. connectionerror is like below
public void connectionerror() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(SplashsActivity.this);
alertDialog.setTitle("Error!");
alertDialog.setMessage("Connection Lost ! Try Again");
alertDialog.setPositiveButton("Retry",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (downloadLatestDataStatus != null) {
downloadLatestDataStatus.clear();
}
if (NetworkCheck.isInternetAvailable(SplashsActivity.this)) {
new DownloadLatestData().execute();
} else {
connectionerror();
}
}
});
alertDialog.show();
}
You can see one condition in connectionerror method like below
if (NetworkCheck.isInternetAvailable(SplashsActivity.this)) {
new DownloadLatestData().execute();
}
instead this condition for network check, I want use isReachable from AsyncTask....How can I do it ?
I have got solved via hire freelancer for fix it. He have done like below in alert dialogue
new AsyncServerOnlineCheck().execute();
Thanks all friends !!
Related
I have this block of code where my app, supposedly, when the user inserts a right password and a right email, goes to the main activity, although when I used the run method, it says that the variable is never used.
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
public void run() {
startActivity(new Intent(getBaseContext(), Second.class));
finish();
}
finish();
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
It is because you have incorrect code in your method. Take a look at the following code:
#Override
protected void onPostExecute(final Boolean success) {
...
if (success) {
public void run() {
...
}
finish();
} else {
...
}
}
You have a block of method named run() which is incorrect. So, you need to remove it. Your code should be something like this then:
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
startActivity(new Intent(getBaseContext(), Second.class));
finish();
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
I am using Firebase to sign in the user and have implemented the code to exit the app on double click. But the problem is the same screen is popping up again.
I tried a workaround setting a SharedPreference and then checking that in mAuthListner. But it did not work.
Here are the relevant sections of the code:
mAuthListener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
SharedPreferences d= getSharedPreferences("backPressed", Context.MODE_PRIVATE);
Boolean t = d.getBoolean("back",false);
if (firebaseAuth.getCurrentUser() != null && !t) {
startActivity(new Intent(MainActivity.this, Second.class));
}
if (t) {
d.edit().putBoolean("back",false);
}
}
};
Code for back button pressed:
boolean doubleBackToExitPressedOnce = false;
private Handler mHandler = new Handler();
private final Runnable mRunnable = new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
};
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
SharedPreferences d= getSharedPreferences("backPressed",Context.MODE_PRIVATE);
d.edit().putBoolean("back",true);
finish();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
mHandler.postDelayed(mRunnable, 2000);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mHandler != null) { mHandler.removeCallbacks(mRunnable); }
}
How can I exit the app on back pressed twice while keeping the user logged in?
This is not a Firebase issue as Firebase will not log out until you specifically call the "Log Out" method.
You do not need SharedPreferences. Just set an Activity level variable BackOnce to False then set it in the OnBackPressed as necessary.
boolean BackOnce = false;
#Override
public void onBackPressed() {
if (BackOnce) {
finish();
} else {
BackOnce = true;
Snackbar sb = Snackbar.make(myView, "Press back again to close app", Snackbar.LENGTH_SHORT);
sb.addCallback(new Snackbar.Callback() {
#Override
public void onDismissed(Snackbar snackbar, int event) {
super.onDismissed(snackbar, event);
BackOnce = false;
}
});
sb.show();
}
}
I implemented the onBackPressed for my activity where it will check the internet connection but when i click the back button in my tablet, it does nothing. I dont understand what is the cause of it. Can help?
Below is my code
if (!cd.isConnectingToInternet()) {
AlertDialog.Builder splash = new AlertDialog.Builder(this);
splash.setIcon(R.drawable.ic_fail)
.setTitle("No Internet Connection")
.setMessage(
"Please check your internet connection and try again.")
.setCancelable(false)
.setPositiveButton("Try again",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
Intent splash = new Intent(
getApplicationContext(),
SplashActivity.class);
startActivity(splash);
finish();
}
})
.setNegativeButton("Wifi Setting",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
startActivity(new Intent(
android.provider.Settings.ACTION_WIFI_SETTINGS));
dialog.cancel();
}
});
AlertDialog alert = splash.create();
alert.show();
} else {
Thread timer = new Thread() {
public void run() {
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent login = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(login);
finish();
}
}
};
timer.start();
}
}
public void onRestart() {
super.onRestart();
Intent splash = new Intent(getApplicationContext(),
SplashActivity.class);
startActivity(splash);
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
just try this code...
#Override
public void onBackPressed()
{
moveTaskToBack(true);
}
comment, and check
//super.onBackPressed();
- finish() is the proper way to close the Activity.
- But still if its doesn't, due to some reason use System.exit(0) after finish().. this will surely work.... I know its crude...but works...
///////////////////////////// Edited Part///////////////////////////////////////
- override the method onKeyDown() of Activity.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
this.finish();
}
return true;
}
try this instead. I think it will Work for you.
#Override
public void onBackPressed() {
//super.onBackPressed();
// finish your Activity
ActivityName.this.finish();
return;
}
Try This:
#Override
public void onBackPressed() {
yourclassname.this.finish();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
getParent().finish();
}
I am just a themer, not a programmer, any help/guidance is appreciated.
I am trying to add a Cancel button to this code:
public class gobuuf extends Activity {
/** Called when the activity is first created. */
class CustomAlertDialog extends AlertDialog {
public CustomAlertDialog(Context context) {
super(context);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
boolean ret = super.onKeyDown(keyCode, event);
finish();
return ret;
}
public void setCancel(int buttonNegative, String string, Object object) {
// TODO Auto-generated method stub
}
}
private CustomAlertDialog mDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (isExistSkin("com.gau.go.launcherex")) {
startGOLauncher("com.gau.go.launcherex");
finish();
return;
}
mDialog = new CustomAlertDialog(this);
mDialog.setTitle(R.string.dialogtitle);
mDialog.setMessage(getResources().getString(R.string.dialogcontent));
mDialog.setCancel(DialogInterface.BUTTON_NEGATIVE, getResources().getString(R.string.dialognothanks), null);
mDialog.setButton(DialogInterface.BUTTON_POSITIVE, getResources().getString(R.string.dialogok),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String marketuriString = "market://search?q=pname:com.gau.go.launcherex";
Intent EMarketintent = new Intent(Intent.ACTION_VIEW, Uri.parse(marketuriString));
EMarketintent.setPackage("com.android.vending");
EMarketintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(marketuriString));
try {
startActivity(EMarketintent);
} catch (ActivityNotFoundException e) {
String link = "http://61.145.124.93/soft/3GHeart/com.gau.go.launcherex.apk";
Uri browserUri = Uri.parse(link);
Intent browserIntent = new Intent(Intent.ACTION_VIEW, browserUri);
browserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
startActivity(browserIntent);
} catch (ActivityNotFoundException e2) {
// TODO: handle exception
e2.printStackTrace();
}
} catch (Exception e3) {
// TODO: handle exception
e3.printStackTrace();
}
finish();
}
});
mDialog.show();
}
#Override
protected void onDestroy() {
super.onDestroy();
android.os.Process.killProcess(android.os.Process.myPid());
}
private boolean isExistSkin(String packageName) {
try {
createPackageContext(packageName,
Context.CONTEXT_IGNORE_SECURITY);
} catch (NameNotFoundException e) {
return false;
}
return true;
}
private void startGOLauncher(String packageName){
PackageManager packageMgr = this.getPackageManager();
Intent launchIntent = packageMgr.getLaunchIntentForPackage(packageName);
if (null != launchIntent){
try
{
this.startActivity(launchIntent);
}
catch(ActivityNotFoundException e)
{
}
}
}
}
I have added the corresponding string, but don't know what else to do: add an onclicklistener, I know I need some kind of action coded somewhere finish(); or .cancel something. Thanks for any help, again.
I should say, I've been playing around with this bit you see:
mDialog.setCancel(DialogInterface.BUTTON_NEGATIVE,getResources().getString(R.string.dialognothanks), null);
I am not sure if this is exactly what you are looking for, but you can do something like this... this one just closes the dialog.
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
For a very good tutorial on creating dialogs, I would recommend using : http://developer.android.com/guide/topics/ui/dialogs.html. This should be very helpful.
It's now working and performing how I wanted it to by doing this:
1) I removed:
public void setCancel(int buttonNegative, String string, Object object) {
// TODO Auto-generated method stub
}
and
mDialog.setCancel(DialogInterface.BUTTON_NEGATIVE, getResources().getString(R.string.dialognothanks), null);
2) and added:
mDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getResources().getString(R.string.dialognothanks),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mDialog.cancel();
finish();
}
});
just before the
mDialog.show();
Trial and Error FTW. Maybe I should learn Java and Android from the ground up to save me the time later.
Now I have to learn how to make the Cancel button not only finish(); but also start another activity.
I figured out how to start an activity by following the answer on this page:
Android: How to start an Activity from an alert dialog
So my code now looks like:
mDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getResources().getString(R.string.dialognothanks),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(getBaseContext(), AboutActivityOverview.class);
startActivity(i);
}
});
public class classified extends Activity
{
private ArrayAdapter<String> aaagency ;
String strdata="";
String strerrormess="";
public void onCreate(Bundle savedInstanceState)
{
setTitle("Classified Ad. Booking");
super.onCreate(savedInstanceState);
this.setContentView(R.layout.classified);
}
public void srcAgency(View view) throws IOException
{
Log.i("Classified Ad","srcAgency");
new srcAgency().execute();
srcAgency srcagen = new srcAgency();
strdata = srcagen.strtempdata;
Log.i("AgencyData2", strdata);
Log.i("AgencyData3", strerrmess);
if(strerrmess.equals(""))
{
strarr= fun1.split(strdata, "^");
aaagency = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item , strarr);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Agency");
builder.setAdapter(aaagency, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
txtAgency.setText(strarr[item]);
}
});
builder.show();
}
}
class srcAgency extends AsyncTask<Void, String, Void>
{
String strtempdata="";
ProgressDialog dialog;
#Override
protected void onPreExecute()
{
strerrmess="";
super.onPreExecute();
dialog = ProgressDialog.show(classified.this, "", "Please wait...", true);
dialog.show();
}
#Override
protected Void doInBackground(Void... unused)
{
try
{
stragency = txtAgency.getText().toString().trim();
intagencyBrac1= stragency.lastIndexOf('(');
intagencyBrac2= stragency.lastIndexOf(')');
if (stragency.length() < 3)
{strerrmess="Please Enter atleast 3 Characters for Agency Searching";}
else if(intagencyBrac1>=0||intagencyBrac2>=0)
{strerrmess="Please Enter Characters for Agency Searching";}
else
{
if(stragency.indexOf(' ')!=-1)
{stragency = stragency.replace(' ', '!');}
Log.i("AgencyUrl",strurl);
strdata = "Client1^Client2^Client3^Client4^Client5^Client6^Client1";
Log.i("AgencyData",strdata);
strtempdata = strdata;
if(!strdata.equals(""))
{
}
else
{strerrmess ="No Data Available";}
}
}
catch(Exception e)
{
}
return null;
}
#Override
protected void onPostExecute(Void unused)
{
dialog.dismiss();
if (strerrmess.equals("Please Enter atleast 3 Characters for Agency Searching"))
{Toast(strerrmess);intflag=1;}
else if(strerrmess.equals("Please Enter Characters for Agency Searching"))
{Toast(strerrmess);intflag=1;}
else if(strerrmess.equals("Your Session Got Expired. Please login again."))
{
Intent intent = new Intent(classified.this, loginscreen.class);
startActivity(intent);
Toast(strerrmess);
intflag=1;
}
else
{intflag=0;}
}
}
}
I am unable to get the value of strdata which i have initialized in asynctask function in the srcagency function. What should I do? Even though strdata is a global variable.
I have also tried this but I think you can't initialize array adapter in onpostexecute function...
#Override
protected void onPostExecute(Void unused)
{
dialog.dismiss();
if (strerrmess.equals("Please Enter atleast 3 Characters for Agency Searching"))
{Toast(strerrmess);intflag=1;}
else if(strerrmess.equals("Please Enter Characters for Agency Searching"))
{Toast(strerrmess);intflag=1;}
else if(strerrmess.equals("Your Session Got Expired. Please login again."))
{
Intent intent = new Intent(classified.this, loginscreen.class);
startActivity(intent);
Toast(strerrmess);
intflag=1;
}
else
{strarr= fun1.split(strdata, "^");
aaagency = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item , strarr);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Agency");
builder.setAdapter(aaagency, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
txtAgency.setText(strarr[item]);
}
});
builder.show();}
}
Any help or comments would be appreciated.
Thanks
Log.i("Classified Ad","srcAgency");
new srcAgency().execute();
srcAgency srcagen = new srcAgency();
strdata = srcagen.strtempdata;
This does not work. You are saying, start an AsyncTask that will set your strdata at some point in the future but also immediately return and after creating a new AsyncTask have it know what the last AsyncTask did.
Try this:
void srcAgency(View v){
//We only want to start the AsyncTask here, nothing else.
// Whatever you did before and whatever triggered the srcAgency(View) method
srcAgency srcagen = new srcAgency();
srcagen.execute();
return;
}
public void realSrcAgency(View v) {
... // The rest of original srcAgency(View)
}
// Inside of asyncTask srcAgency ...
public void postExecute() {
// Call the new method we just had, but after our asyncTask is done.
realSrcAgency(null);
}
Basically you can't expect all these things to happen simultaneously. It would be easy to help you if you trimmed down the specifics of your code. It looks like you just want a button or some click to start an async task that fills a strings. However after that string is filled do something else with it. Also I don't believe you need an async task for any of this.