how can open alert dialog box in android - android

I want to open alert dialog box after successfully submitted data.
I am using following code but not work.
dialog = ProgressDialog.show(TanantDetails.this, "", "Please Wait...", true);
new Thread(new Runnable() {
public void run() {
String response;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences sp=getSharedPreferences("login",MODE_WORLD_READABLE);
try {
Utility utility=new Utility();
//
new_url=url+mobile_no.getText().toString();
response = utility.getResponse(utility.urlEncode(new_url));
dialog.dismiss();
if (response.equals("Success"))
{
AlertDialog alertbox = new AlertDialog.Builder(getBaseContext())
//.setIcon(R.drawable.no)
.setTitle("Submit successfully")
.setMessage("“Police will verify documents between preferred timing")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
TanantDetails.this.finish();
Intent i=new Intent(getApplicationContext(),MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(i);
}
})
.show();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
}
}).start();
}
toast show the message response success.
I am new to android

Simple Alert Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Alert")
.setTitle("Warning");
AlertDialog alert =builder.create();
alert.show();
If you want to add ok, cancel buttons then add
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked cancel button
}
});

Try this code:
new AlertDialog.Builder(this)
.setTitle("Your title")
.setMessage("Your message")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Your code
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();

Your alert dialog needs to be displayed on the UI thread. The code you are running is on a separate thread. In most cases when you want to update a UI element while in a separate thread it is done by using runOnUiThread()
Please see the code below
if (response.equals("Success"))
{
runOnUiThread(new Runnable() {
#Override
public void run() {
AlertDialog alertbox = new AlertDialog.Builder(getBaseContext())
//.setIcon(R.drawable.no)
.setTitle("Submit successfully")
.setMessage("“Police will verify documents between preferred timing")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
TanantDetails.this.finish();
Intent i=new Intent(getApplicationContext(),MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(i);
}
}).show();
}
});
}

Related

Notify users for new version of Android app

I want to show a notification or dialog (when app opens) if the current installed app is not the Updated Version (available in play store).
How can i do that?
add this dependency to your gradle file..
com.github.rampo.updatechecker:library:2.1.8
And try this code in your Activity..
public static String NEW_VERSION = "1.1.0";
public void checkForAppUpdate () {
try {
if (!((Activity) context).isFinishing()) {
UpdateChecker.setNotice(Notice.NOTIFICATION);
UpdateChecker.setNoticeIcon(R.drawable.your_notification_logo);
String s = "Hello User, New version of this application is now available on play store.";
if (Comparator.isVersionDownloadableNewer((Activity) context, NEW_VERSION)){
SharedPreferences pref = context.getSharedPreferences(UpdateChecker.PREFS_FILENAME, 0);
boolean b = pref.getBoolean(UpdateChecker.DONT_SHOW_AGAIN_PREF_KEY + NEW_VERSION, false);
if (!b) {
displayAlertDialogforPlayStore(context, "Update Available", s);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
And Function displayAlertDialogforPlayStore() is...
public void displayAlertDialogforPlayStore(final Context context, String title,
String message) {
try {
final AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setIcon(R.drawable.your_notification_logo);
if (title != null) {
alert.setTitle(title);
}
alert.setMessage(message);
alert.setPositiveButton("Update Now", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final String appPackageName = context.getPackageName();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=" + appPackageName));
context.startActivity(intent);
}
});
alert.setNegativeButton("Later", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alert.show();
} catch (Exception e) {
e.printStackTrace();
}
}
This code display both notification and alertDailog for update.
You can use Firebase notifications as described here. You can choose your segment (e.g. app version) as described here.

Set timeout function with AsyncTask [Android]

In my case, I would like to get the button pressed and get process with the timeout. When button clicked then it will verify the accNo with web services, if the verification (ProgressDialog) is over 5 seconds then it will stop and display the alertDialog to notice user "Timeout".
But now I have not idea when I in testing with 1 milliseconds, in logically it will pause in alertDialog until get pressed, but now it will display the dialog in milliseconds then auto dismiss and intent to next activity. Here is my code:
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_information3);
btn_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (title.getText().toString().equals("INFO")) {
InfoAsyncTask infoAsyncTask = new InfoAsyncTask();
try {
infoAsyncTask.execute().get(1, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);
alertDialog.setTitle(":: Error ::");
alertDialog.setMessage("Verify Timeout. Please try again.");
alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
});
}
private class InfoAsyncTask extends AsyncTask<Void, Void, String> {
private String results;
private ProgressDialog pDialog;
private Object resultRequestSOAP;
String accNo = et_accNo.getText().toString().trim();
int timeout = 15000;
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(Information3.this);
pDialog.setMessage("Verifying...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("Code", InfoCode);
request.addProperty("AccNo", accNo);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL, timeout);
androidHttpTransport.debug = true;
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
String requestDumpString = androidHttpTransport.requestDump;
Log.d("request Dump: ", requestDumpString);
} catch (Exception e) {
e.printStackTrace();
}
try {
resultRequestSOAP = envelope.getResponse();
results = resultRequestSOAP.toString();
Log.d("Output: ", results);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
if (resultRequestSOAP == null) {
if (pDialog.isShowing()) {
pDialog.dismiss();
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);
alertDialog.setTitle(":: Error ::");
alertDialog.setMessage("Connection error, please check your internet connection.");
alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
pDialog.dismiss();
}
} else {
if (results.equals("false")) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);
alertDialog.setTitle(":: Warning ::");
alertDialog.setMessage("Please fill in correct account number");
alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
} else if (et_billNo.getText().toString().trim().isEmpty()) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);
alertDialog.setTitle(":: Warning ::");
alertDialog.setMessage("Please fill in bill number");
alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
} else if (et_amountNo.getText().toString().trim().isEmpty() || Integer.parseInt(et_amountNo.getText().toString().trim()) <= 0) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);
alertDialog.setTitle(":: Warning ::");
alertDialog.setMessage("Please fill in amount");
alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
} else if (results.equals("true")) {
Title = title.getText().toString();
String value1 = et_accNo.getText().toString().trim();
String value2 = et_billNo.getText().toString().trim();
int value3 = Integer.parseInt(et_amountNo.getText().toString().trim());
addSearchInput(value1);
addSearchInput(value2);
addSearchInput(String.valueOf(value3));
Intent intent = new Intent(Information3.this, confirmation3.class);
intent.putExtra("name", Title);
intent.putExtra("value1", value1);
intent.putExtra("value2", value2);
intent.putExtra("value3", value3);
startActivity(intent);
} else {
super.onPreExecute();
}
pDialog.dismiss();
}
}
}
get() method will block the UI thread and I guess you don't want this.
You should implement cancel mechanics in doInBackground and call AsyncTask.cancel() by timeout [like that](https://developer.android.com/reference/android/os/Handler.html#postDelayed(java.lang.Runnable, long))
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
AsyncTask.cancel();
}
}, 1);
Be aware there are many gotchas with AsyncTask, check my article.

Use parse.com in android app

I'm new in android developer and I use parse.com in my first android app.
My problem is when the user singup to the app, the user save in the core. but then the app crashes.
This is my code:
save = (Button) findViewById(R.id.saveButton);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(password.getText().toString().equals(againPassword.getText().toString()))) {
Toast.makeText(getApplicationContext(), "You have mistake in password!", Toast.LENGTH_SHORT).show();
} else {
ParseUser newUser = new ParseUser();
newUser.put("name", firstName.getText().toString());
newUser.put("lastName", lastName.getText().toString());
newUser.setEmail(email.getText().toString());
newUser.setUsername(userName.getText().toString());
newUser.setPassword(password.getText().toString());
newUser.put("rosterArray", rosterArray);
myParse parse = new myParse();
try {
parse.saveUserInParse(newUser);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
});
The code of methed 'saveUserInParse' is
public void saveUserInParse(ParseUser newUser)
{
newUser.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
AlertDialog.Builder singUpSucceed = new AlertDialog.Builder(context);
singUpSucceed.setTitle("Sing up succeed!!!");
singUpSucceed.setCancelable(true);
singUpSucceed.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = singUpSucceed.create();
alert11.show();
} else {
String theMessage = e.getMessage();
AlertDialog.Builder singUpSucceed = new AlertDialog.Builder(context);
singUpSucceed.setTitle("Sing up feild!!!");
singUpSucceed.setMessage(theMessage);
singUpSucceed.setCancelable(true);
singUpSucceed.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = singUpSucceed.create();
alert11.show();
}
}
});
}
What did I do wrong? This problam is also in login method.
Thank you.
Here is my demo project for parse Sample Parse, you an use for refrence.

Call Thread.wait()

I need to make currentThread wait when do some operations in UiThread and then in UiThread call currentThread().notify() . I was trying this code
Handler uiHandler = new Handler(Looper.getMainLooper());
uiHandler.post(new Runnable() {
#Override
public void run() {
try {
currentThread().wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
AlertDialog.Builder facultyChooser = new AlertDialog.Builder(ctx);
facultyChooser.setTitle("choose")
.setCancelable(false)
.setItems(arr, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
currentThread().notify();
}
})
.create()
.show();
}
});
}
but got java.lang.IllegalMonitorStateException: object not locked by thread before wait() exception. Please help me.
Try this code:
final Thread CURRENT_THREAD = currentThread();
Handler uiHandler = new Handler(Looper.getMainLooper());
uiHandler.post(new Runnable() {
#Override
public void run() {
AlertDialog.Builder facultyChooser = new AlertDialog.Builder(ctx);
facultyChooser.setTitle("choose")
.setCancelable(false)
.setItems(arr, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
synchronized(CURRENT_THREAD) {
CURRENT_THREAD.notify();
}
}
})
.create()
.show();
}
});
}
synchronized(CURRENT_THREAD) {
try {
CURRENT_THREAD.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

progressDialog didn't show with several views in one activity

I created 3 views in one activity depending on the process of the workflow.
i.e. viewA->viewB->viewC, then on viewC, when I do HTTP-POST(using AsyncTask), show progress dialog.
I tried 2 ways to show progress dialog:
using runOnUiThread() to show progressDialog, it didn't show.
write show progressDialog code in AsyncTask. Make progress dialog show in onPreExecute() and dismiss in onPostExecute(), it shows after doinbackground task, and onPostExecute() didn't execute as well.
Anyone can help?
Thanks
sam
Here is the main activity code:
public void setA(){
setContentView(R.layout.a_fm);
Button aNextBtn=(Button)findViewById(R.id.aNextBtn);
aNextBtn.setOnClickListener(this);
}
public void setB(){
setContentView(R.layout.b_fm);
Button bNextBtn=(Button)findViewById(R.id.bNextBtn);
bNextBtn.setOnClickListener(this);
}
public void setC(){
setContentView(R.layout.c_fm);
Button cNextBtn=(Button)findViewById(R.id.cNextBtn);
cNextBtn.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.aNextBtn:
setB();
break;
case R.id.bNextBtn:
setB();
break;
case R.id.cNextBtn:
postmsg();
break;
}
}
public void postmsg(final Info info)
{
postDialog=new ProgressDialog(AssistFm.this);
postDialog.setMessage(getString(R.string.alert_sendmsg_sending));
postDialog.show();
this.runOnUiThread(new Runnable() {#Override
public void run() {
// TODO Auto-generated method stub
send_online=sendlogtowebservice(info);
SEND_COUNT++;
if (send_online)
{
postDialog.dismiss();
AlertDialog.Builder builder = new Builder(A_activity.this);
builder.setMessage(getString(R.string.alert_sendmsg_success));
builder.setTitle(getString(R.string.sendmsg_title));
builder.setPositiveButton(getString(R.string.button_OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
setA();
SEND_COUNT=0;
}
});
builder.create().show();
}
else
{
postDialog.dismiss();
if (SEND_COUNT<SEND_COUNT_MAX)
{
AlertDialog.Builder builder = new Builder(A_activity.this);
builder.setMessage(getString(R.string.alert_sendmsg_retry));
builder.setTitle(getString(R.string.sendmsg_title));
builder.setNegativeButton(getString(R.string.button_Cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setPositiveButton(getString(R.string.button_OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
postmsg(info);
SEND_COUNT++;
}
});
builder.create().show();
}
else
{
AlertDialog.Builder builder = new Builder(AssistFm.this);
builder.setMessage(getString(R.string.alert_sendmsg_error));
builder.setTitle(getString(R.string.sendmsg_title));
builder.setPositiveButton(getString(R.string.button_OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
setA();
}
});
builder.create().show();
}
}
}
});
}
private boolean sendlogtowebservice(Info info) {
boolean isTrue = false;
int result_code = 0;
Object []param = new Object[3];
HttpResponse response = null;
String result_str;
try {
String sURL=url;
HttpClient client = new DefaultHttpClient();
ArrayList<BasicNameValuePair> paierList = new ArrayList<BasicNameValuePair>();
paierList.add(new BasicNameValuePair("person_firstname", info.person_firstname));
paierList.add(new BasicNameValuePair("person_lastname", info.person_lastname));
paierList.add(new BasicNameValuePair("person_mobile", info.person_mobile));
param[0] = sURL;
param[1] = paierList;
param[2] = client;
AsyncTask<Object, Object, HttpResponse> res = new HttpReqTask().execute(param);
response = (HttpResponse) res.get();
result_code=response.getStatusLine().getStatusCode();
result_str = EntityUtils.toString(response.getEntity());
if ( result_str.equals("00"))
{
isTrue = true;
}
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e)
{
Log.e("HttpAPI.callHttpPost()", "Error", e);
}
return isTrue;
};
Here is the HTTP-POST AsyncTask code:
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.protocol.HTTP;
import android.os.AsyncTask;
public class HttpReqTask extends AsyncTask<Object, Object, HttpResponse>{
#Override
protected HttpResponse doInBackground(Object... params){
String url = (String)params[0];
ArrayList<NameValuePair> paierList = (ArrayList<NameValuePair>)params[1];
HttpClient httpclient = (HttpClient)params[2];
HttpPost request = new HttpPost(url);
HttpResponse response = null;
try {
request.setEntity(new UrlEncodedFormEntity(paierList, HTTP.UTF_8));
response = httpclient.execute(request);
} catch (Exception e) {
throw new RuntimeException(e);
}
return response;
}
}
No one know how this happened?
I changed the AsyncTask to below, the progress dialog just show a flush away when it is trying to dismiss the progress dialog.
public class HttpReqTask extends AsyncTask<Object, Object, HttpResponse>{
private Context mCtx;
private ProgressDialog progressDialog;
public HttpReqTask(Context context){
myLog.i("HttpReqTask constructor, before show dialog!");
progressDialog = new ProgressDialog(mCtx);
progressDialog.setMessage("Your progress dialog message...");
progressDialog.show();
myLog.i("HttpReqTask constructor finish, start show dialog!");
}
#Override
protected HttpResponse doInBackground(Object... params){
myLog.i("do in background execute");
String url = (String)params[0];
ArrayList<NameValuePair> paierList = (ArrayList<NameValuePair>)params[1];
HttpClient httpclient = (HttpClient)params[2];
String s=null;
HttpPost request = new HttpPost(url);
HttpResponse response = null;
try {
request.setEntity(new UrlEncodedFormEntity(paierList, HTTP.UTF_8));
response = httpclient.execute(request);
//add for longer process time.
for (int i=0;i<10000000;i++)
{
s="a";
}
} catch (Exception e) {
throw new RuntimeException(e);
}
myLog.i("finish in background execute");
return response;
}
#Override
protected void onPostExecute(HttpResponse result) {
myLog.i("HttpReqTask onPostExecute(), before dismiss dialog!");
if (progressDialog!=null) progressDialog.dismiss();
myLog.i("HttpReqTask onPostExecute(), after dismiss dialog!");
}
}
It seems no one knows the answer...
Under my research, I can make the progessDialog shown by creating a new thread, however the AlertDialog in the new thread, can not be shown now...
public void postmsg(final OnlineHistoryInfo info)
{
dialog=new ProgressDialog(mActivity.this);
dialog.setMessage(getString(R.string.alert_sendmsg_sending));
dialog.setCancelable(false);
dialog.show();
myLog.i("dialog show!");
new Thread(){
#Override
public void run()
{
try
{
myLog.i("new thread: run!");
// TODO Auto-generated method stub
send=sendlogtowebservice(info);
//send_online=true;
SEND_COUNT++;
}
finally
{
dialog.dismiss();
if (send)
{
myLog.i("send:true!");
new DataRule(AssistFm.this).saveOnlineHistory(info);
AlertDialog.Builder builder = new Builder(mActivity.this);
builder.setMessage(getString(R.string.alert_sendmsg_success));
builder.setTitle(getString(R.string.sendmsg_title));
builder.setPositiveButton(getString(R.string.button_OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
setA();
SEND_COUNT=0;
}
});
builder.create().show();
}
else
{
myLog.i("send:false!");
if (SEND_COUNT<SEND_COUNT_MAX)
{
AlertDialog.Builder builder = new Builder(mActivity.this);
builder.setMessage(getString(R.string.alert_sendmsg_retry));
builder.setTitle(getString(R.string.sendmsg_title));
builder.setNegativeButton(getString(R.string.button_Cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setPositiveButton(getString(R.string.button_OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
postmsg(info);
SEND_COUNT++;
}
});
builder.create().show();
}
else
{
AlertDialog.Builder builder = new Builder(mActivity.this);
builder.setMessage(getString(R.string.alert_sendmsg_error));
builder.setTitle(getString(R.string.sendmsg_title));
builder.setPositiveButton(getString(R.string.button_OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
setA();
}
});
builder.create().show();
}
}
}
}
}.start();
}//postmsg() finish

Categories

Resources