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.
Related
I am having a problem with my code.
I have an activity with an EditText , when the activity opens for the first time I would like to pass the value of the EditText to my server and receive an answer.
The problem is if I call the method in onCreate () it does not work.
If instead I call the method from the
click ()
event of the button it works.
Is there a way to call the method from the onCreate () and display the contents of the EditText?
This is my code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
First_Name = (EditText)findViewById(R.id.editText50);
parseContent = new ParseContentRistoratore(this);
preferenceHelper = new PreferenceHelperRistoratore(this);
CheckEditTextIsEmptyOrNot();
UserRegisterFunction(F_Name_Holder);
prova = (Button) findViewById(R.id.button10);
// If EditText is not empty and CheckEditText = True then this block will execute.
prova.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
//REGISTRATION
#RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
public void UserRegisterFunction(final String fk_id_ristorante){
class UserRegisterFunctionClass extends AsyncTask<String,Void,String> {
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
if(httpResponseMsg.equalsIgnoreCase("Prova gratuita terminata")){
// finish(); con finish(); l'attività finisce
Intent intent = new Intent(Main3Activity.this, Versione_scaduta.class);
startActivity(intent);
}
}
//REGISTRATION
#Override
protected String doInBackground(String... params) {
hashMap.put("fk_id_ristorante",params[0]);
finalResult = httpParse.postRequest(hashMap, HttpURLRegister);
return finalResult;
}
}
UserRegisterFunctionClass userRegisterFunctionClass = new UserRegisterFunctionClass();
userRegisterFunctionClass.execute(fk_id_ristorante);
}
//REGISTRAZIONE
public void CheckEditTextIsEmptyOrNot(){
F_Name_Holder = First_Name.getText().toString();
if(TextUtils.isEmpty(F_Name_Holder) )
{
CheckEditText = false;
}
else {
CheckEditText = true ;
}
}
#Override
protected void onResume() {
super.onResume();
AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
#Override
public void onSuccess(Account account) {
//editUserId = (EditText)findViewById(R.id.editUserEmail);
// editUserId.setText(String.format("Email Id %s",account.getEmail()));
First_Name.setText(String.format("r%s", account.getId()));
}
#Override
public void onError(AccountKitError accountKitError) {
}
});
}
}
If you can not do it, I'd like to know something else instead.
Why in my PHP code if I remove the Else from the IF Cycle the code does not work when it is started on Android studio?
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
include 'config.php';
$con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
$fk_id_ristorante = $_POST['fk_id_ristorante'];
$CheckSQL = "SELECT * FROM R_Iscrizioni WHERE data_scadenza < CURDATE() AND fk_id_ristorante='$fk_id_ristorante' AND pagamento = 'No' ";
$check = mysqli_fetch_array(mysqli_query($con,$CheckSQL));
if(isset($check)){
echo 'Prova gratuita terminata';
}
else {
echo 'Hello';
}
}
mysqli_close($con);
?>
What you need to do is just use CountDownTimer to let system load and be ready to let your code be execute right way.
Hope this helped you.
I'm having this error out of the blue and have no idea what's causing it or where it has come from.
Basically I've got a RecyclerView that gets populated with products. When a product is selected, I've got a custom Dialog that pops up where the user can increase product quantity or remove the product. This all works, however if I click the same product a second time it crashes the app with the following error:
System services not available to Activities before onCreate()
This is my RecyclerView.Adapter with the onBindViewHolder()
public class OrderAdapter extends RecyclerView.Adapter<OrderAdapter.MyViewHolder>{
#Override
public void onBindViewHolder(#NonNull OrderAdapter.MyViewHolder holder, int position) {
final Item Item = ItemList.get(position);
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog = new Dialog(context,R.style.Custom_Theme_Dialog);
//Code breaks on this line
dialog.setContentView(R.layout.dialog_cart_edit);
cartProdDesc = dialog.findViewById(R.id.lblcartProdDesc);
cartQuantity = dialog.findViewById(R.id.edit_quantity);
btnDone = dialog.findViewById(R.id.btn_dialog_done);
btnRemove = dialog.findViewById(R.id.btn_dialog_remove);
addQuantity = dialog.findViewById(R.id.addition_action);
minusQuantity = dialog.findViewById(R.id.minus_action);
cartProdDesc.setText(cartItem.getProductDescription());
cartPackSize.setText(cartItem.getPackSize());
addQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
quantity = Integer.parseInt(cartQuantity.getText().toString());
} catch (NumberFormatException nf) {
Log.e("Number Exception","Number Is Blank");
quantity = 0;
} catch (Exception e){
Log.e("ERROR",e.toString());
}
cartQuantity.setText(String.valueOf(++quantity));
}
});
minusQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
quantity = Integer.parseInt(cartQuantity.getText().toString());
} catch (NumberFormatException nf) {
Log.e("Number Exception","Number Is Blank");
quantity = 0;
} catch (Exception e){
Log.e("ERROR",e.toString());
}
cartQuantity.setText(String.valueOf(--quantity));
}
});
btnDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(cartQuantity.getText().toString().isEmpty() || cartQuantity.getText().toString().equals("0") || cartQuantity.getText().toString().contains("-")){
cartQuantity.setError("Enter a valid quantity");
} else {
newQuantity = cartQuantity.getText().toString();
db.updateCartItem(new CartItem(cartItem.getId(),cartItem.getProductCode(),cartItem.getBarcode(),cartItem.getNappiCode(),cartItem.getProductDescription(),cartItem.getPackSize(),newQuantity));
updateDataSet();
notifyDataSetChanged();
dialog.dismiss();
}
}
});
btnRemove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogInterface.OnClickListener dialogClickListner = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
db.deleteCartItem(cartItem.getId());
updateDataSet();
dialog.dismiss();
break;
case DialogInterface.BUTTON_NEGATIVE:
dialog.dismiss();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Are you sure you want to remove " + cartItem.getProductDescription()).setPositiveButton("Yes",dialogClickListner).setNegativeButton("No",dialogClickListner).show();
}
});
dialog.show();
}
});
}
}
I've got a private Dialog dialog; declaration further up on the Activity in case anyone was wondering.
The code breaks on the dialog = new Dialog(context,R.style.Custom_Theme_Dialog); however if I comment out the dialog.show() at the end I have no issues, apart from the dialog not showing, but that tells me that the problem isn't with the assigning of the dialog, or am I wrong on this train of thought ?
This is a line of code in my OrderActivity where I'm calling the adapter, I'm sending the context from here.
OrderAdapter = new OrderAdapter(this,ItemList);
This is my constructor where I'm assigning Context
public OrderAdapter(Context context, List<CartItem> cartItemList){
this.context = context;
this.cartItemList = cartItemList;
}
Depending on where that Context is coming from exactly, it might have already been "destroyed" by the time onClick() is called (well not really, because the Dialog is holding an implicit reference to it). In this case this is also a memory leak.
I'd suggest you to change the following:
#Override
public void onClick(View view) {
dialog = new Dialog(context, R.style.Custom_Theme_Dialog);
To this:
#Override
public void onClick(View view) {
dialog = new Dialog(view.getContext(), R.style.Custom_Theme_Dialog);
This way you'll always reference the Context the corresponding View is associated with.
(this is Not about nullpointer):
I have a progress bar in AsyncTask and i added a cancel button to cancel asynctask.
i can cancel the asynctask from outside the asynctask but i need to implement cancel function in progressdialog which is implemented under asynctask.
So the question is how to cancel asynctask with cancel button which is implemented in progressdialog under asynctask?
plse do check in "doInBackground"..the asynctask is not getting cancel
Download_result.java class:
public class Download_result extends AsyncTask<String,Integer,Void>{
ProgressDialog progressDialog;
Context context;
String pdfFile;
Download_result(Context context, String pdfFile){
this.context=context;
this.pdfFile=pdfFile;
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Downloading...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMax(200);
progressDialog.setCancelable(false);
progressDialog.setProgress(0);
progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Download_result.this.cancel(true);
dialog.dismiss();
}
});
progressDialog.show();
}
#Override
protected Void doInBackground(String... params) {
//given below
}
#Override
protected void onProgressUpdate(Integer... values) {
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void result) {
progressDialog.cancel();
}
}
my "doInBackground" method:
#Override
protected Void doInBackground(String... params) {
String url_1=params[0];
int file_length=0;
try {
URL url = new URL(url_1);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
file_length=urlConnection.getContentLength();
filesize=file_length;
File sdCard = Environment.getExternalStorageDirectory();
File new_folder = new File (sdCard.getAbsolutePath() + "/xxx");
File input_file = new File(new_folder,pdfFile);
InputStream inputStream = new BufferedInputStream(url.openStream(),8192);
byte[] data=new byte[1024];
int total=0,count=0;
OutputStream outputStream = new FileOutputStream(input_file);
while ((count=inputStream.read(data))!=-1){
total+=count;
outputStream.write(data,0,count);
int progress= (total*200)/file_length;
downloadedsize=total;
publishProgress(progress);
if(isCancelled()){
break; or return null; // same result
}
}
inputStream.close();
outputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;//"Download completed!";
}
you have not dismissed the dialog in cancel button press.. also use setButton instead
try this:
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Downloading...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMax(200);
progressDialog.setCancelable(false);
progressDialog.setProgress(0);
progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
download.cancel(true);
downloadstatus=false; //add boolean check
dialog.dismiss();
}
});
progressDialog.show();
}
To cancel an Async Task use:
Public Download_result download;
download = new Download_result();
download.execute();
download.cancel(true);
try this in doInbackGround()
while ((count=inputStream.read(data))!=-1){
if(!your_AsyncTask.isCancelled() || downloadstatus !=false){
total+=count;
outputStream.write(data,0,count);
int progress= (total*200)/file_length;
downloadedsize=total;
publishProgress(progress);
}else{
break;
}
}
Download_result(Context context, String pdfFile,Download_result download)
It does not make any sense to send a Download_result as a parameter to its own constructor. You can never have a valid reference to pass the constructor. You should change this constructor to
Download_result(Context context, String pdfFile)
Every method of Download_result already has a reference to a Download_result object called this. Since you need access to it in an inner class, use Download_result.this:
progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Download_result.this.cancel(true);
dialog.dismiss();
}
});
Create a "boolean keepGoing" in your AsyncTask and set it to true. Within your "doInBackground" procedure poll it regularly and return, if false. Bind the cancel button to a setter within the AsyncTask which sets the "keepGoing" flag to false. That should do the job.
Use DialogInterface listener on ProgressDialog's button, e.g.:
protected void onPreExecute() {
pd = new ProgressDialog(MainActivity.this);
pd.setTitle("PAUL app");
pd.setMessage("Loading data ...");
pd.setButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// User has cancelled task ... just quit!
MainActivity.this.finish();
return;
}
});
pd.show();
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have been trying to implement this dialog box for the past 3 hours and I can't figure out why it's not popping up, I think it's best to show my entire class to understand my issue:
Registration.java
public class Registration extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
}
//on submit press
public void SubmitRegistration(View view) {
// start an asynch request
class RequestTask extends AsyncTask<String, String, String>{
#Override
public String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Do anything with response..
}
}
// assign text in fields to string values
EditText first = (EditText)findViewById(R.id.first);
String first2 = first.getText().toString();
EditText last = (EditText)findViewById(R.id.last);
String last2 = last.getText().toString();
EditText display = (EditText)findViewById(R.id.display);
String display2 = display.getText().toString();
//calculates the number of characters in the display field
int length2 = display2.length();
EditText email = (EditText)findViewById(R.id.email);
String email2 = email.getText().toString();
EditText password = (EditText)findViewById(R.id.password);
String password2 = password.getText().toString();
EditText vpassword = (EditText)findViewById(R.id.vpassword);
String vpassword2 = vpassword.getText().toString();
//calculates the number of characters in the password field
int length = vpassword2.length();
// verifying the following in order: Passwords match? A Password field is empty?
//Password and Display Name less than 6 characters long? Email contains an # sign and a period?
if(!vpassword2.equals(password2)) {
Toast.makeText(getApplicationContext(), "Passwords do not match!", Toast.LENGTH_SHORT).show();
}
else if (password2.isEmpty() || vpassword2.isEmpty()){
Toast.makeText(getApplicationContext(), "Password field is empty", Toast.LENGTH_SHORT).show();
}
else if (length < 6 || length2 < 6 ) {
Toast.makeText(getApplicationContext(), "Password and Display Name must be at least 6 characters long", Toast.LENGTH_LONG).show();
}
else if (!email2.contains("#") || !email2.contains(".")){
Toast.makeText(getApplicationContext(), "Must enter valid email address.", Toast.LENGTH_SHORT).show();
}
//start else
else {
//send php with all the data to server for validation and insertion into table
String output = null;
try {
output = new RequestTask()
.execute("http://www.alkouri.com/android/registercheck.php?first=" + first2 + "&last=" + last2 + "&display=" + display2 + "&email=" + email2 + "&password=" + password2)
.get();
//example: www.alkouri.com/android/registercheck.php?first=Adam&last=Alkouri&display=arugala&email=arugala#blackbaud.com&password=123
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//if the response from website contains "duplicate" (which means there is a duplicate email address in the DB) then it will display toast.
if (output.contains("Duplicate")) {
Toast.makeText(getApplicationContext(), "Email address already in system, press back button if you forgot password and click on Forgot Password ", Toast.LENGTH_LONG).show();
}
//if the response from website contains "You have registered successfully" then it will send popup message and go to login screen
else if (output.contains("You have")){
//start dialogue
AlertDialog.Builder alertbox = new AlertDialog.Builder(Registration.this);
alertbox.setMessage("You have succesfully registered. Please check your email for further instructions."); // Please Restart Application // "Please restart the app and download your purchase again".
alertbox.setPositiveButton("YES", new DialogInterface.OnClickListener() {
//create button in dialogue
public void onClick(DialogInterface arg0, int arg1)
{
//on clicking "ok" in the dialogue box, current activity will close and return to last activity (login screen).
finish();
}
});
alertbox.show();
}
}//end else
} //end button click task
}//end class
So, at the very bottom, directly under the very last toast, I would like a dialogue box to pop up.
It's to let the user know they have registered and they should check their email for further instructions.
The toast is showing up just fine, but when I implement ANY of the following examples, nothing pops up.
I don't get any errors in the LogCat, it's just that nothing pops up....
I have tried the following examples that I Have seen online:
public class FireMissilesDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_fire_missiles)
.setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// FIRE ZE MISSILES!
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
http://stackoverflow.com/questions/2115758/how-to-display-alert-dialog-in-android
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("Write your message here.");
builder1.setCancelable(true);
builder1.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder1.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
What am I doing wrong?
AlertDialog.Builder alertbox = new AlertDialog.Builder(MainMenuActivity.this);
alertbox.setMessage("Please restart the app and download your data again."); // Please Restart Application // "Please restart the app and download your purchase again".
alertbox.setPositiveButton("YES", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
//code
}
});
alertbox.setNegativeButton("NO", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
//code
}
});
alertbox.show();
You need to put an OnclickListener for your submit button in onCreate() method and call your other functions from there.
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Call your submitregistration function function here
}
});
}
output = new RequestTask()
.execute("http://www.mywebsite.com/android/registercheck.php?first=" + first2 + "&last=" + last2 + "&display=" + display2 + "&email=" + email2 + "&password=" + password2)
.get();
Calling get does not make it asynchronous anymore. It blocks the ui thread waiting for the result.
Move the AsyncTask out of onClick
class RequestTask extends AsyncTask<String, String, String>{
http://developer.android.com/reference/android/os/AsyncTask.html#get()
public final Result get ()
Added in API level 3
Waits if necessary for the computation to complete, and then retrieves its result.
Also Declare your variables a instance variables and initialize your views in onCreate.
EditText first ;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
first = (EditText)findViewById(R.id.first);
On Button click get the text from editText
Invoke asynctask
new RequestTask().execute(params); // no get
The result of doInbackground computation is a param to onPostExecute. Based on the result you can display dialog in onPostExecute.
I am having trouble with an alert dialog that I cannot hide.
when the user press a button I show a dialog that is created with this code :
new AlertDialog.Builder(this)
.setTitle(R.string.enterPassword)
.setView(textEntryView)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String password = pwdText.getText().toString();
dialog.dismiss();
processUserAction(password,targetUri);
}
})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
})
.
create();
There are some heavy operations performed in the 'processUserAction' method, and inside it I am using an AysncTask that displays a ProgressDialog.
The problem I am having is that the dialog prompting for the password never goes of the screen (I have tried with dismiss(), cancel()).
I guess it stays there until the onClick method is finished.
So, my question is how to close that AlertDialog, so I can show the ProgressDialog?
Another approach I have been trying is to set a DismissListener in the AlertDialog and calling the heavy operations from there, but I have had no luck ( it didn't get called ).
EDIT: Adding AsyncTask code
public class BkgCryptOperations extends AsyncTask<File,Void,Integer>{
#Override
protected Integer doInBackground(File... files) {
if (files!=null && files.length > 0){
File source = files[0];
File target = files[1];
return cryptAction.process(source,password, target);
}
return Constants.RetCodeKO;
}
CryptAction cryptAction;
String password;
ProgressDialog progressDialog;
public BkgCryptOperations (CryptAction cryptAction,String password,ProgressDialog progressDialog){
this.cryptAction=cryptAction;
this.password=password;
this.progressDialog=progressDialog;
}
#Override
protected void onPreExecute() {
if (progressDialog!=null){
progressDialog.show();
}
}
protected void onPostExecute(Integer i) {
if (progressDialog!=null){
progressDialog.dismiss();
}
}
}
Thanks in advance
Here is a excample how I do it:
public void daten_remove_on_click(View button) {
// Nachfragen
if (spinadapter.getCount() > 0) {
AlertDialog Result = new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle(getString(R.string.dialog_data_remove_titel))
.setMessage(getString(R.string.dialog_data_remove_text))
.setNegativeButton(getString(R.string.dialog_no),
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialogInterface, int i) {
// Nicht löschen
dialogInterface.cancel();
}
})
.setPositiveButton(getString(R.string.dialog_yes),
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialogInterface, int i) {
String _quellenName = myCursor.getString(1);
deleteQuellenRecord(_quellenName);
zuletztGelöscht = _quellenName;
}
}).show();
} else {
// Keine Daten mehr vorhanden
Toast toast = Toast.makeText(Daten.this,
getString(R.string.dialog_data_remove_empty),
Toast.LENGTH_SHORT);
toast.show();
}
}
Here is the code of deleteQuellenRecord:
private void deleteQuellenRecord(String _quellenName) {
String DialogTitel = getString(R.string.daten_delete_titel);
String DialogText = getString(R.string.daten_delete_text);
// Dialogdefinition Prograssbar
dialog = new ProgressDialog(this) {
#Override
public boolean onSearchRequested() {
return false;
}
};
dialog.setCancelable(false);
dialog.setTitle(DialogTitel);
dialog.setIcon(R.drawable.icon);
dialog.setMessage(DialogText);
// set the progress to be horizontal
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// reset the bar to the default value of 0
dialog.setProgress(0);
// set the maximum value
dialog.setMax(4);
// display the progressbar
increment = 1;
dialog.show();
// Thread starten
new Thread(new MyDeleteDataThread(_quellenName)) {
#Override
public void run() {
try {
// Datensatz löschen
myDB.execSQL("DELETE ... ');");
progressHandler
.sendMessage(progressHandler.obtainMessage());
myDB.execSQL("DELETE ...);");
// active the update handler
progressHandler
.sendMessage(progressHandler.obtainMessage());
myDB.execSQL("DELETE ...;");
// active the update handler
progressHandler
.sendMessage(progressHandler.obtainMessage());
// Einstellung speichern
try {
settings.edit().putString("LetzteQuelle", "-1")
.commit();
} catch (Exception ex) {
settings.edit().putString("LetzteQuelle", "").commit();
}
} catch (Exception ex) {
// Wait dialog beenden
dialog.dismiss();
Log.e("Glutenfrei Viewer",
"Error in activity MAIN - remove data", ex); // log
// the
// error
}
// Wait dialog beenden
dialog.dismiss();
}
}.start();
this.onCreate(null);
}
Wiht Async Task I do it this way:
private class RunningAlternativSearch extends
AsyncTask<Integer, Integer, Void> {
final ProgressDialog dialog = new ProgressDialog(SearchResult.this) {
#Override
public boolean onSearchRequested() {
return false;
}
};
#Override
protected void onPreExecute() {
alternativeSucheBeendet = false;
String DialogTitel = getString(R.string.daten_wait_titel);
DialogText = getString(R.string.dialog_alternativ_text);
DialogZweiteChance = getString(R.string.dialog_zweite_chance);
DialogDritteChance = getString(R.string.dialog_dritte_chance);
sucheNach = getString(R.string.dialog_suche_nach);
dialog.setCancelable(true);
dialog.setTitle(DialogTitel);
dialog.setIcon(R.drawable.icon);
dialog.setMessage(DialogText);
dialog.setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface arg0) {
// TODO Auto-generated method stub
cancleBarcodeWorker();
if (alternativeSucheBeendet==false){
// Activity nur beenden wenn die Suche
// nicht beendet wurde, also vom User abgebrochen
Toast toast = Toast.makeText(SearchResult.this, SearchResult.this
.getString(R.string.toast_suche_abgebrochen),
Toast.LENGTH_LONG);
toast.show();
myDB.close();
SearchResult.this.finish();
}
}
});
dialog.show();
}
...
Can you show the code for processUserAction(..)? There is no need to include the dismiss.
I did something very similar and had no problems...
Here's the code:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Export data.\nContinue?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String file = getObra().getNome();
d = new ProgressDialog(MenuActivity.this);
d.setTitle("Exporting...");
d.setMessage("please wait...");
d.setIndeterminate(true);
d.setCancelable(false);
d.show();
export(file);
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
In export(file) I open the thread:
private void export(final String file) {
new Thread() {
public void run() {
try {
ExportData ede = new ExportData(
getApplicationContext(), getPmo().getId(),
file);
ede.export();
handlerMessage("Done!!");
} catch (Exception e) {
handlerMessage(e.getMessage());
System.out.println("ERROR!!!" + e.getMessage());
}
}
}.start();
}
In handlerMessage I dismiss the progressDialog and show the final message.
Hope it helps you.
You could create a listener outside of the AlertDialog, to abstract out the logic within the OnClickListener for the positive button. That way, the listener can be notified, and the AlertDialog will be dismissed immediately. Then, whatever processing of the user's input from the AlertDialog can take place independently of the AlertDialog. I'm not sure if this is the best way to accomplish this or not, but it's worked well for me in the past.
As far as I can tell, I don't see any obvious problems with your AsyncTask code.
public interface IPasswordListener {
public void onReceivePassword(String password);
}
IPasswordListener m_passwordListener = new IPasswordListener {
#Override
public void onReceivePassword(String password) {
processUserAction(password,targetUri);
}
}
public void showPasswordDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.enterPassword);
builder.setView(textEntryView);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
m_passwordListener.onReceivePassword(pwdText.getText().toString());
dialog.dismiss();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
builder.show();
}