How to use volley inside alert dialog? - android

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.

Related

Stop program execution until the option of dialogalert is chosen in android

If the location is disabled I want to show box and stop the execution process until I turn ON the location and come back to my app. Please Help with necessary suggestions.
function,
alertDialog.setTitle("GPS Setting");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("OK ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Toast.makeText(mContext, "Sorry we cannot proceed", Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();// Showing Alert Message
You should use ProgressDialog at https://developer.android.com/reference/android/app/ProgressDialog.html
see this example:
private ProgressDialog progressDialog;
public void cerrarSession() {
try {
showDialog();
// do something
} catch (InternetException e) {
// some exception
e.printStackTrace();
}
}
private void showDialog() {
progressDialog = new ProgressDialog(SavingsRequestsManager.getActivity());
progressDialog.setCancelable(false);
closeDialog();
progressDialog.setMessage(SavingsRequestsManager.getActivity().getString(R.string.progress));
progressDialog.show();
}
public void closeDialog() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}

Password Prompt Comes Only first time

I want when user click on Uninstall Button,there prompt a password dialog. This Dialog is coming only one time.I'm using this code:
public void run() {
Looper.prepare();
while (!exit) {
// get the info from the currently running task
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(MAX_PRIORITY);
String activityName = taskInfo.get(0).topActivity.getClassName();
Log.d("topActivity", "CURRENT Activity ::" + activityName);
if (activityName.equals("com.android.packageinstaller.UninstallerActivity")) {
//Toast.makeText(context, "Uninstall Clicked", Toast.LENGTH_LONG).show();
Intent startIntent = new Intent(this.context, Alert_Dialog.class);
startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.context.startActivity(startIntent);
exit = true;
} else if (activityName.equals("com.android.settings.ManageApplications")) {
Toast.makeText(this.context, "Back", Toast.LENGTH_LONG).show();
exit = true;
}
}
Looper.loop();
}//Run
I want whenever user click on Unistall Prompt should come , below is the code in onClick,
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView.findViewById(R.id.edit_text);
alertDialogBuilder
.setCancelable(false)
.setNegativeButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
/** DO THE METHOD HERE WHEN PROCEED IS CLICKED*/
String user_text = (userInput.getText()).toString();
/** CHECK FOR USER'S INPUT **/
if (user_text.equals("abc"))
{
Log.d(user_text, "HELLO THIS IS THE MESSAGE CAUGHT :)");
Toast.makeText(myContext,"PAssword Correct",Toast.LENGTH_LONG).show();
Alert_Dialog.this.finish();
//Search_Tips(user_text);
}
else{
Log.d(user_text,"string is empty");
String message = "The password you have entered is incorrect." + " \n \n" + "Please try again!";
AlertDialog.Builder builder = new AlertDialog.Builder(myContext);
builder.setTitle("Error");
builder.setMessage(message);
builder.setPositiveButton("Cancel", null);
builder.create().show();
Alert_Dialog.this.finish();
}
}
});
// .setPositiveButton("Cancel",
// new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog,int id) {
// Alert_Dialog.this.finish();
//
// }
//
// }
// );
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
Once the dialog calls dismiss(), the view you set for the dialog also would be destroyed.
In your case, this line set the view,
alertDialogBuilder.setView(promptsView);
But when the dialog is closed, the view promptsView is destroyed,
The promptsView should be re-created once again you use it.
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
promptsView = new PromptsView();//new or inflate the view
//....
alertDialogBuilder.setView(promptsView);

how to start an activity inside a custom alertdialog

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);

Android: Session is restored when back is pressed twice

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"

Android - Show alert dialog in AsyncTask

I'm trying to show an alert dialog when a user fails to enter valid email and password to log in. Since the login process has to deal with HTTP request and JSON, I put it all in an AsyncTask and I'm not sure if that's the problem why my alert dialog can't show (I hope not). So this is method checkUser, which is called within onPostExecute of the AsyncTask class:
public void checkUser(JSONObject json){
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
if (tag == login_tag){
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
// code omitted
} else{
// Error in login
mProgressDialog.dismiss();
builder.setMessage("Incorrect username/password")
.setTitle("Error")
.setNeutralButton("OK", new OnClickListener() {
public void onClick(final DialogInterface dialog,final int which) {
dialog.cancel();
}
}).create().show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Somehow my alert dialog can never show and I don't know why. If you have any idea what the reason of this problem is, please help me out. Thanks a lot!
EDIT: Turns out I only close my Progress Dialog after executing this method, so I decided to dismiss it before showing the alert dialog. But it still hasn't solved the problem.
So I solved this myself this way: somehow the Alert dialog only works outside the method checkUser. So I move the bits within the error if clause outside, below the dismiss() of Progress dialog in onPostExecute():
protected void onPostExecute(JSONObject json) {
checkUser(json);
mProgressDialog.dismiss();
try {
if (json.get(ERROR_MSG) != null){
String errorMsg = json.getString(ERROR_MSG);
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage(errorMsg)
.setTitle("Error")
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).create().show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And voila, it works!
P.s: I still don't know why the dialog can't show when put within checkUser though.
missing builder.create()
// Error in login
builder.setMessage("Incorrect username/password")
.setTitle("Error")
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
dialog.cancel();
}
}).create().show();

Categories

Resources