I am making a login app with android. Evrything is working fine but the problem is when the back button is pressed twice the session loggedout will be restored? Whatseems to be the problem
code snippet for logging out
public void logoutUser(){
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
Intent i = new Intent(_context, Login.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
_context.startActivity(i);
}
Calling the logout method
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Launching All products Activity
session.logoutUser();
Intent i = new Intent(getApplicationContext(), Login.class);
startActivity(i);
}
});
Login code:
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
//System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
//tv.setText("Response from PHP : " + response);
dialog.dismiss();
}
});
String username = et.getText().toString().trim();
if(response.equalsIgnoreCase("User Found")){
session.createLoginSession(username);
runOnUiThread(new Runnable() {
public void run() {
//Toast.makeText(Login.this,"Login Success", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Login.this, AndroidTabLayoutActivity.class));
}
});
}else if(response.equalsIgnoreCase("Not Employee")){
showAlertNotEmployee();
}else if(response.equalsIgnoreCase("Disabled")){
showAlertDisabled();
}else{
showAlertNotFound();
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlertNotFound(){
Login.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(Login.this);
builder.setTitle("Login Error.");
builder.setMessage("User not Found.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
public void showAlertDisabled(){
Login.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(Login.this);
builder.setTitle("Login Error.");
builder.setMessage("Account Disabled.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
public void showAlertNotEmployee(){
Login.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(Login.this);
builder.setTitle("Login Error.");
builder.setMessage("Employee Account Only")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
try adding to the androidmanifest.xml in your Activity tags
android:noHistory="true"
Related
Here let me explain my issue need to add volley inside alertdialog which i have done successfully its like pinging the entered Url its working fine but what I need to do is in onErrorResponse method alert dialog gets hide suppose when user enter wrong url it will go to onErrorResponse method in this my alertdialog gets hide need to stay awake the dialog even when error gets occurred so far what I have tried is:
This is my code:
final AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Add Self Hosted URL "); //Set Alert dialog title here
alert.setMessage("Enter The Url Here"); //Message here
final EditText input = new EditText(context);
alert.setView(input);
ConnectivityManager cn = (ConnectivityManager) PingingActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf = cn.getActiveNetworkInfo();
if (nf != null && nf.isConnected()) {
final ProgressDialog progressDialog=new ProgressDialog(this);
progressDialog.hide();
Toast.makeText(getApplicationContext(), "Network Available", Toast.LENGTH_LONG).show();
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, int whichButton) {
progressDialog.show();
progressDialog.setMessage("Pinging Please Wait");
final String srt = input.getEditableText().toString();
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.GET, srt,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("resp", response);
SharedPreferences settings = getSharedPreferences(PingingActivity.id, 0); // 0 - for private mode
SharedPreferences.Editor editor = settings.edit();
editor.putString("Url", srt);
editor.putBoolean("URLflag", true);
editor.apply();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// alert.show();
// input.setText(srt);
//final String srt = input.getEditableText().toString();
String str = error.toString();
if (str != null) {
Toast.makeText(getApplicationContext(), "Please Check the Entered URL", Toast.LENGTH_SHORT).show();
// progressDialog.cancel();
}
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Toast.makeText(context, srt, Toast.LENGTH_LONG).show();
}
});
alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
dialog.cancel();
}
}).setIcon(R.drawable.ic_info_black_24dp).show(); //End of alert.setNegativeButton
/* Alert Dialog Code End*/
}
else {
showAlertDialog("No Network", "Please Check Your Network Connectivity", true);
}
even in onerrorresponse need to display my alertdialog how can i achieve this. It may be a dumb question but as a beginner am struggling with this can anyone help me
Create a bool method returning the status , call it
alert.setPositiveButton("OK", new DialogInterface.OnClickListener()
return true from response and false from onError()
if the response return success start your desired Activity , otherwise let the alert dialog show.
Here I use this Activatedialog method in onPostExecute inside registration >activity , and need to start a login activity when the alert dialog dissmiss ..however I tried to do this, but I get error.
public void Activatedialog(String jsonmsg, final String name)
{
final AlertDialog.Builder alert = new AlertDialog.Builder(ct);
alert.setTitle("Activate Account");
alert.setMessage(jsonmsg);
// Set an EditText view to get user input
final EditText input = new EditText(ct);
alert.setView(input);
alert.setCancelable(true);
Log.d("MYLOG","before +ve button click");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
String code = input.getText().toString();
Log.d("MYLOG","before try");
try{
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("u",name ));
params.add(new BasicNameValuePair("code",code ));
JSONObject json = jsonParser.makeHttpRequest(ACTIVATION_URL,"POST", params);
Log.d("MYLOG","after request for json");
stcode = json.getJSONObject("activate").getInt("statuscode");
stmsg = json.getJSONObject("activate").getString("statusmessage");
Log.d("MYLOG","after json parsing : json data is "+stmsg+"stcodeis "+stcode);
if(stcode == 1)
{
dialog.dismiss();
Log.d("MYLOG"," in check json data is "+stmsg+" stcodeis "+stcode);
Intent i = new ("LOGIN");startActivity(i);![i get this error][1]
Toast.makeText(ct, " "+stmsg, Toast.LENGTH_SHORT).show();
}
else if(stcode == 0)
{
Log.d("MYLOG"," in check json data is "+stmsg+" stcodeis "+stcode);
Toast.makeText(ct, " "+stmsg+" "+stcode, Toast.LENGTH_SHORT).show();
}
}
catch(JSONException e)
{
e.printStackTrace();
Toast.makeText(ct, ""+e, Toast.LENGTH_LONG).show();
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
// Canceled.
Toast.makeText(ct, "Your Account is not Activated.Login to Activate", Toast.LENGTH_LONG).show();
}
});
alert.show();
}
}
To start an Activity, the intent must have following parameters. A context and target activity. Lets start activity "Login.java" .
Intent i = new Intent(getApplicationContext(), Login.class);
startActivity(i);
you have created intent incorrectly.
1> add the relevant activity you want to open say Loginby adding new activity to the project.
2>create the intent as below
Intent intent = new Intent(getApplicationContext(), Login.class);
3>start activity using the intent created
startActivity(i);
You can do something like this:
AlertDialogManager alert = new AlertDialogManager(StartActivity.this);
AlertDialogManager constructor:
public void AlertDialogManager(final Context context) {
activity = (Activity) context;
}
and you can launch the activity like this:
Intent intent = new Intent(activity , Login.class);
activity.startActivity(intent);
I am having a dialog which must execute some code on canceled. I set a negative button but its not executing when dialog is canceled from back button.
here is my code.
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Licence expired");
builder.setCancelable(false);
builder.setMessage("Your licence for " + url
+ " has been expired, Please renew it or select another server");
builder.setPositiveButton("Renew now",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Open url in webview
Intent intent = new Intent(MainActivity.this,
WebActivity.class);
intent.putExtra("ServerDomain", url);
startActivity(intent);
/*
* URL domain; try { domain = new URL(url);
* intent.putExtra("ServerDomain", domain.getHost());
* startActivity(intent); } catch (MalformedURLException
* e) { e.printStackTrace(); }
*/
/*
* String url = "http://www.google.com"; Intent i = new
* Intent(Intent.ACTION_VIEW);
* i.setData(Uri.parse(url)); startActivity(i);
*/
}
});
builder.setNegativeButton("Switch Server",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
showServerList();
}
});
builder.create().show();
Create a cancel listner for dialog.
builder.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
showServerList();
}
});
In my android app, I'm producing a lot of data which I store at the moment in a .txt file simply called "logData". Now my boss wants me to give him the possibility to save it as an extra file, like the Save As Button in various windows programms.
At the moment I have a method for generating a logFile and write first data to it and one for writing all coming data to it. But how can I implement a "Save as" functionality?
Here the code of both methods and the used variables:
private String logData = "logData.txt";
private String logText = "";
private File extStorageDir = Environment.getExternalStorageDirectory();
private File mLogFile = new File(extStorageDir, "DCULogData/logData.txt");
generating:
public void generateLogFileOnSD(String sFilename, String sBody) {
try {
File logFile = new File(extStorageDir, sFilename);
FileWriter writer = new FileWriter(logFile);
writer.append(sBody);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
writing:
public void writeLogFileOnSD(String sFilename, String sBody) {
if (mLogFile.exists()) {
try {
FileOutputStream fOut = new FileOutputStream(mLogFile);
OutputStreamWriter mOutWriter = new OutputStreamWriter(fOut);
mOutWriter.append(sBody);
mOutWriter.close();
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
generateLogFileOnSD(logData, logText);
}
}
EDIT : This is my solution based on Simple Plan's answer. Thanks for this!
I also tested some scenarios with filenames like "/blabla", "m/m/m/m/m/". No failure found until now :)
public Button.OnClickListener saveLogFileOnClickListener = new Button.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(
DiagnosisActivity.this);
builder.setTitle(R.string.save_file_dialog);
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
final EditText input = new EditText(
DiagnosisActivity.this);
input.setSingleLine();
AlertDialog.Builder ad = new Builder(
DiagnosisActivity.this);
ad.setTitle("Enter save as File Name");
ad.setView(input);
ad.setCancelable(true);
ad.setPositiveButton("Save as",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
int len = input.length();
if (len != 0) {
final_filename = input
.getText().toString()
.trim();
generateLogFileOnSD(
"DCULogData/"
+ final_filename
+ ".txt",
ReceiverThread
.getLogText());
Toast.makeText(
getApplicationContext(),
"Saved!",
Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(
getApplicationContext(),
"Enter a proper name",
Toast.LENGTH_LONG)
.show();
}
}
});
ad.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
dialog.cancel();
}
});
AlertDialog alert = ad.create();
alert.show();
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert1 = builder.create();
alert1.show();
}
};
First add Button into your Layout as a text Save as and implement OnClickListner()
String final_filename;
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
annual_crop.setTextColor(Color.BLUE);
AlertDialog.Builder al1 = new Builder(youractivity);
al1.setMessage("Do you want to save a file?");
al1.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
final EditText input = new EditText(
youractivity.this);
input.setSingleLine();
AlertDialog.Builder al = new Builder(
AgriListView.this);
al.setTitle("Enter save as File Name");
al.setView(input);
al.setCancelable(true);
al.setIcon(R.drawable.bt);
al.setPositiveButton(
"Save as",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
int len = input
.length();
if (!(len == 0)) {
final_filename=input.getText().toString.trim();
);
} else {
Toast.makeText(
getApplicationContext(),
"Enter Name Properly",
Toast.LENGTH_LONG)
.show();
}
}
});
al.setNegativeButton(
"Cancel",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
dialog.cancel();
}
});
AlertDialog alert = al.create();
alert.show();
}
});
al1.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
dialog.cancel();
}
});
AlertDialog alert1 = al1.create();
alert1.show();
}
});
}
});
And used final_filename like below:
File folder = new File(Environment.getExternalStorageDirectory(), "DCULogData");
File mLogFile = new File(folder.getPath(), final_filename);
And add permission in your manifest.xml file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I am trying to use parse.com in an android application of mine, how to get the context at the place of *** in the code AlertDialog.Builder(*******)? I tried using getApplicationcontext which doesn't work.Can anyone with experience in the android help me with respect to this?
mSignInButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mVibrator.vibrate(100);
//Checking for internet connection...
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//internet connection inactive... show alert...
if (!(netInfo != null && netInfo.isConnectedOrConnecting())) {
AlertDialog.Builder adb = new AlertDialog.Builder(arg0.getContext());
adb.setTitle("ALERT");
adb.setMessage("Please turn on Internet.");
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
// Action for 'Ok' Button
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
// Action for 'Cancel' Button
dialog.cancel();
}
});
adb.setIcon(R.drawable.ic_launcher);
adb.show();
}else{
ParseQuery<ParseObject> query = ParseQuery.getQuery("Admin");
query.whereEqualTo("password", mUserNameEditText.getText().toString());
query.whereEqualTo("userName", mPasswordEditText.getText().toString());
query.countInBackground(new CountCallback() {
public void done(int count, ParseException e) {
if (e == null) {
// The count request succeeded. Log the count
Log.d("test", "Sean has played " + count + " games");
if(count>0){
// save the login status... loggedIn/notloggedIn...
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(LoginScreenActivity.this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("isLoggedIn", true);
editor.commit();
// if user name password is correct, navigate to next activity...
Intent intent = new Intent(LoginScreenActivity.this,OptionScreenActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(intent, 0);
overridePendingTransition(R.layout.fade_in, R.layout.fade_out);
}else{
AlertDialog.Builder adb = new AlertDialog.Builder(*********************);
adb.setTitle("ALERT");
adb.setMessage("Wrong username or password.");
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
// Action for 'Ok' Button
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
// Action for 'Cancel' Button
dialog.cancel();
}
});
adb.setIcon(R.drawable.ic_launcher);
adb.show();
}
} else {
// The request failed
}
}
});
Try out as below:
AlertDialog.Builder adb = new AlertDialog.Builder(getApplicationContext());
OR
AlertDialog.Builder adb = new AlertDialog.Builder(<YourActivity>.this);