I'm build my app with Mortar + Flow. I'm trying to figure out the correct way to show a popup that requests some text from the user. I've created this popup class:
public class SavedPageTitleInputPopup implements Popup<SavedPageTitleInput, Optional<String>> {
private final Context context;
private AlertDialog dialog;
public SavedPageTitleInputPopup(Context context) {
this.context = context;
}
#Override public Context getContext() {
return context;
}
#Override
public void show(final SavedPageTitleInput info, boolean withFlourish,
final PopupPresenter<SavedPageTitleInput, Optional<String>> presenter) {
if (dialog != null) throw new IllegalStateException("Already showing, can't show " + info);
final EditText input = new EditText(context);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
input.setText(info.savedPage.getName());
dialog = new AlertDialog.Builder(context).setTitle(info.title)
.setView(input)
.setMessage(info.body)
.setPositiveButton(info.confirm, new DialogInterface.OnClickListener() {
#Override public void onClick(DialogInterface d, int which) {
dialog = null;
final String newTitle = Strings.emptyToNull(String.valueOf(input.getText()));
presenter.onDismissed(Optional.fromNullable(newTitle));
}
})
.setNegativeButton(info.cancel, new DialogInterface.OnClickListener() {
#Override public void onClick(DialogInterface d, int which) {
dialog = null;
presenter.onDismissed(Optional.<String>absent());
}
})
.setCancelable(true)
.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override public void onCancel(DialogInterface d) {
dialog = null;
presenter.onDismissed(Optional.<String>absent());
}
})
.show();
}
#Override public boolean isShowing() {
return dialog != null;
}
#Override public void dismiss(boolean withFlourish) {
dialog.dismiss();
dialog = null;
}
}
This class works as expected. It uses the SavedPage to figure out what to display in the dialog and it returns the users input to the PopupPresenter using PopupPresenter#onDismissed when the correct button is pressed.
My problem is writing the PopupPresenter subclass used to present the dialog and process the input. This is what I have right now:
new PopupPresenter<SavedPage, Optional<String>>() {
#Override protected void onPopupResult(Optional<String> result) {
if (result.isPresent()) {
// The user entered something, so update the API
// Oh wait, I don't have a reference to the SavedPage
// that was displayed in the dialog!
}
}
}
As the comments say, I don't have a reference to the SavedPage that was displayed in the dialog. It was stored in the whatToShow field in PopupPresenter, but this field is nulled out right before onPopupResult is called. It seems like I would be unnecessarily repeating myself to keep an additional copy of the SavedPage.
There isn't a lot of documentation yet on PopupPresenter and Popup. The only thing I have seen is a basic example in the sample project. They create a ConfirmerPopup based on data within the Confirmation object. The purpose of the ConfirmerPopup is to capture a boolean decision from the user based on the title/body given to the Confirmation object as seen by the class declaration.
public class ConfirmerPopup implements Popup<Confirmation, Boolean> {
In your case you want to capture additional user inputted text from the user. When PopupPresenter#onPopupResult is called the result object should contain all of the data needed from SavedPageTitleInputPopup. Modify your SavedPageTitleInputPopup as follows
public class SavedPageTitleInputPopup implements Popup<SavedPage, SavedPageResults> {
private final Context context;
private AlertDialog dialog;
public SavedPageTitleInputPopup(Context context) {
this.context = context;
}
#Override public Context getContext() {
return context;
}
#Override
public void show(SavedPage info, boolean withFlourish, final PopupPresenter<SavedPage, SavedPageResults> presenter) {
if (dialog != null) throw new IllegalStateException("Already showing, can't show " + info);
// Create your Dialog but scrape all user data within OnClickListeners
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
//Anything else you need to do... .setView() or .setTitle() for example
builder.setPositiveButton(info.confirm, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface d, int which) {
dialog = null;
//Save data to SavedPageResults
final SavedPageResults results = new SavedPageResults():
presenter.onDismissed(results);
}
});
builder.setNegativeButton(info.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface d, int which) {
dialog = null;
final SavedPageResults results = new SavedPageResults();
presenter.onDismissed(results);
}
});
dialog = builder.show();
}
#Override public boolean isShowing() {
return dialog != null;
}
#Override public void dismiss(boolean withFlourish) {
dialog.dismiss();
dialog = null;
}
}
Your PopupPresenter doesn't need to know anything about the Dialog's implementation now.
new PopupPresenter<SavedPage, SavedPageResults>() {
#Override protected void onPopupResult(SavedPageResults result) {
if (result.isPresent()) {
updateUi(result.getSavedText());
}
}
}
Related
I need to make an app that sends an SMS message after showing a progress bar in increments of 10. I have the action bar set up and I think I should use AsyncTask? The user is inputing number and message into the main activity, and that's where I have the SendSMS method set up, not sure how to make this work so that it forwards to AsyncTask and calls on that method there.
public class MainActivity extends AppCompatActivity {
private int MY_PERMISSIONS_REQUEST_SMS_RECEIVE = 10;
private static final String SMS_SENT = "SMS_SENT";
private static final String SMS_DELIVERED= "SMS_DELIVERED";
private EditText etPoruka;
private EditText etBroj;
private ProgressDialog progressDialog;
private Context context = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initWidgets();
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECEIVE_SMS},
MY_PERMISSIONS_REQUEST_SMS_RECEIVE);
}
private void initWidgets() {
etPoruka = findViewById(R.id.etPoruka);
etBroj = findViewById(R.id.etBroj);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_send:
MyAsyncTask<Void, Void, Void> updateTask = new MyAsyncTask<Void, Void, Void>(context);
updateTask.execute();
break;
case R.id.action_sent:
Toast.makeText(this, R.string.add_test, Toast.LENGTH_LONG).show();
// BROADCAST RECEIVER ??
break;
case R.id.action_received:
Toast.makeText(this, R.string.add_test, Toast.LENGTH_LONG).show();
//BROADCAST RECEIVER ??
//BOUND SERVICE
break;
case R.id.action_exit:
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Close app");
builder.setMessage("Are you sure?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
return true;
}
public void sendSMS() {
try{
SmsManager smgr = SmsManager.getDefault();
smgr.sendTextMessage(etBroj.getText().toString(),null,etPoruka.getText().toString(),null,null);
Toast.makeText(MainActivity.this, "SMS sent successfully", Toast.LENGTH_SHORT).show();
}
catch (Exception e){
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}
}
ASYNCTASK
public class MyAsyncTask extends
AsyncTask {
private final String DIALOG_MESSAGE = "Sending message";
private ProgressDialog mDialog = null;
private void setDialog(Context context) {
this.mDialog = new ProgressDialog(context);
this.mDialog.setMessage(DIALOG_MESSAGE);
this.mDialog.setCancelable(false);
}
public MyAsyncTask(Context context) {
this.setDialog(context);
}
#Override
protected void onPreExecute() {
this.mDialog.show();
}
#Override
protected Result doInBackground(Params... arg0) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Result result) {
if (this.mDialog.isShowing()) {
this.mDialog.dismiss();
}
} }
You can create an Interface and implement in your MainActivity.
For More Details Please check these answers:
how do i send data back from onPostExecute in an AsyncTask?
How to pass data from an asynchronous task to an activity that called it?
I am trying to make my own Alert dialogs using "utility" class that extends AppCompatDialogFragment. But when I try to set my own messages, they didn't change, but the default ones of the class I created continue to appear.
For example in my AlertDialogConnection class I made Override of onCreateDialog, but in my activity, while I perform http request, I can't make my own texts.
My own class that extends AppCompatDialogFragment
public class AlertDialogConnection extends AppCompatDialogFragment {
private Builder builder;
private String title;
private String text;
public AlertDialogConnection(){
this.builder = null;
this.text = "";
this.title = "";
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
if((this.title == "") || (this.text == "") || (this.builder == null)){
this.builder = new Builder(getActivity());
this.builder.setTitle("Error");
this.builder.setMessage("Default Error: Error! try later");
this.builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
});
}else {
this.builder = new Builder(getActivity());
this.builder.setTitle(this.title);
this.builder.setMessage(this.text);
this.builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
});
}
return builder.create();
}
public void setTitle(String title){
this.title = title;
}
public void setText(String text){
this.text = text;
}
}
Some code using that class
in this class, in case of error I continue to see the default error of the class AlertDialogConnection, instead of my serverError title and text.
private AlertDialogConnection serverError = new AlertdialogConnection();
private void requestData(String url) throws MalformedURLException {
Request request = new Request.Builder().url(url).build();
final Intent intent = new Intent(this, ModelResultData.class);
httpClient.connectTimeoutMillis(); //server timeout
httpClient.writeTimeoutMillis();
httpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.d("HTTP-Error", "HTTP request error!");
AlertDialogConnection errorDialog = new AlertDialogConnection();
errorDialog.setTitle("server error!");
errorDialog.setText("server messaging error, try later");
errorDialog.show(getSupportFragmentManager(), "messaging error!");
//Toast.makeText(getApplicationContext(), "results not found", Toast.LENGTH_LONG).show();
}
#Override
public void onResponse(#NotNull Call call, Response response) throws IOException {
if(response.isSuccessful()){
/* HTTP-code: 200 */
final String body = response.body().string();
ModelSearchActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
intent.putExtra("ACTIVITY_SOURCE", "ModelSearchActivity");
intent.putExtra("json_data", body);
startActivity(intent);
}
});
}else{
//System.out.println(response.code());
//if (response.code() == 403) {
//Toast.makeText(getApplicationContext(), "results not found", Toast.LENGTH_LONG).show();
//} else if (response.code() == 500) {
/* Http-code: 500 */
Log.d("HTTP-Error", "server error!");
serverError.setTitle("server error!");
serverError.setText("server error, try later");
serverError.show(getSupportFragmentManager(), "server error!");
//}
}
}
});
}
I have tried making comparisons with response code, but nothing change.
The default value (in the constructor) you've set for builder is null.
This causes it to always get through the if condition since builder == null would return true. Try something along the following lines,
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
this.builder = new Builder(getActivity());
if(this.title.isEmpty() || this.text.isEmpty()){
this.builder.setTitle("Error");
this.builder.setMessage("Default Error: Error! try later");
this.builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
});
}else {
this.builder.setTitle(this.title);
this.builder.setMessage(this.text);
this.builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
});
}
return builder.create();
}
You don't need to have a separate utility for creating your own alert dialogue you can simply create a view and use the setView method to show that view in your app. See the snippet below
private void showDialog()
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
View view = getLayoutInflater().inflate(R.layout.sortdialog,null);//Replace it
alertDialogBuilder.setView(view);
alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
This will allow you to create custom alert dialog boxes using the layout which you have created
By using the retrofit as REST Client,
private void doGetRestBagLotNumber(int bagNumber, String lotNumber, final BagLotNumberRestService callback) {
Call<BagLotNumberModel> call = bagLotNumberRestService.getAntamBagLotNumber(bagNumber, lotNumber);
call.enqueue(new Callback<BagLotNumberModel>() {
#Override
public void onResponse(Call<BagLotNumberModel> call, Response<BagLotNumberModel> response) {
if (response.code() == 404 || response.code() == 422) {
Toast.makeText(getApplicationContext(), response.message(), Toast.LENGTH_SHORT).show();
} else {
int id = response.body().getId();
int bagNumber = response.body().getBagNumber();
String lotNumber = response.body().getLotNumber();
// Adding the response to recylerview
preparedObjectDataBagLotNumber(id, bagNumber, lotNumber);
callback.onSuccess(response.body() != null);
}
}
#Override
public void onFailure(Call<BagLotNumberModel> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
I have a method to display a dialog that contains several edit text
to input data from the user.
Here's the code.
private void addItemTextMethod() {
// get prompts.xml view
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompts_antam_incoming, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set prompts.xml to alertDialog builder
alertDialogBuilder.setView(promptsView);
final EditText bagNumber = (EditText) promptsView.findViewById(R.id.editTextDialogAntamBagNumber);
final EditText lotNumber = (EditText) promptsView.findViewById(R.id.editTextDialogLotNumber);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("Search", null)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialogInterface) {
Button button = ((AlertDialog) alertDialog).getButton(AlertDialog.BUTTON_POSITIVE);
button.setOnClickListener(view -> {
doGetRestBagLotNumber(
Integer.parseInt(bagNumber.getText().toString()), lotNumber.getText().toString(),
new BagLotNumberRestService() {
#Override
public void onSuccess(boolean value) {
if($value){
// The question is here
// Show Big Thick in center of dialog
// Show bottom option, Close or Adding More
// If user choose Adding More , display this dialog again
}
}
#Override
public Call<BagLotNumberModel> getAntamBagLotNumber(int bagNumber, String lotNumber) {
return null;
}
}
);
});
}
});
alertDialog.show();
}
How when the result of the doGetRestBagLotNumber callback is true,
the app show option like this:
Show Big Thick in center of dialog as Success message
Show bottom option, Close or Adding More.
If user choose Adding More , display this dialog again
Any help it so appreciated
Use the instance of your inflated view to change the child views inside it. For example use this inside your onSuccess method:
((ImageView)promptsView.findViewById(R.id.tickIndicationView)).setImageResource(R.drawable.ic_tick);
I'm coding through Deitel: Android How to program examples and in two of them my Android Studio gives warning/error on anonymous inner classes. It declares that Fragments should be static.
What's the correct way to go through this? If I make static non-anonymous inner class then there is no warning about the class, but I can't reference to non-static class variables(?). Other way could be to make a separate class (not inner class), but there is same problem with referencing variables.
This problem in with example Cannon Game, class CannonView, method showGameOverDialog (below) and also on FlagQuiz.
private void showGameOverDialog(final int messageId) {
final DialogFragment gameResult =
new DialogFragment() {
#Override
public Dialog onCreateDialog(Bundle bundle) {
AlertDialog.Builder builder =
new AlertDialog.Builder(getActivity());
builder.setTitle(getResources().getString(messageId));
builder.setMessage(getResources().getString(
R.string.result_format, shotsFired, totalElapsettime
));
builder.setPositiveButton(R.string.reset_game,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialogIsDisplayed = false;
newGame();
}
});
return builder.create();
}
};
activity.runOnUiThread(
new Runnable() {
#Override
public void run() {
showSystemBars();
dialogIsDisplayed = true;
gameResult.setCancelable(false);
gameResult.show(activity.getFragmentManager(), "results");
}
}
);
}
// display an AlertDialog when the game ends
private void showGameOverDialog(final int messageId) {
// DialogFragment to display game stats and start new game
final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(getResources().getString(messageId));
// display number of shots fired and total time elapsed
builder.setMessage(getResources().getString(
R.string.results_format, shotsFired, totalElapsedTime));
builder.setPositiveButton(R.string.reset_game,
new DialogInterface.OnClickListener() {
// called when "Reset Game" Button is pressed
#Override
public void onClick(DialogInterface dialog,
int which) {
dialogIsDisplayed = false;
newGame(); // set up and start a new game
}
}
);
/* final DialogFragment gameResult =
new DialogFragment() {
// create an AlertDialog and return it
#Override
public Dialog onCreateDialog(Bundle bundle) {
// create dialog displaying String resource for messageId
AlertDialog.Builder builder =
new AlertDialog.Builder(getActivity());
builder.setTitle(getResources().getString(messageId));
// display number of shots fired and total time elapsed
builder.setMessage(getResources().getString(
R.string.results_format, shotsFired, totalElapsedTime));
builder.setPositiveButton(R.string.reset_game,
new DialogInterface.OnClickListener() {
// called when "Reset Game" Button is pressed
#Override
public void onClick(DialogInterface dialog,
int which) {
dialogIsDisplayed = false;
newGame(); // set up and start a new game
}
}
);
return builder.create(); // return the AlertDialog
}
};
*/
// in GUI thread, use FragmentManager to display the DialogFragment
activity.runOnUiThread(
new Runnable() {
public void run() {
final AlertDialog gameResult = builder.create();
showSystemBars();
dialogIsDisplayed = true;
gameResult.setCancelable(false); // modal dialog
// gameResult.show(activity.getFragmentManager(), "results");
gameResult.show();
}
}
);
}
Ok so I recently completed an android app - my first one :D! - and because it is a paid app Google tells me I have to add the licensing stuff. That's fine and dandy, except I've been getting mind f*cked by it for the past five hours. Finally think I understand it a little and got it going, but in testing it in my emulator I come up with two issues:
I'm using the google API for 4.1, as instructed by their handy how-to on the developer console, but nomatter what I always end up coming up with my Connection Error dialog. Code here:
public void dontAllow(int reason) {
if(isFinishing()){
return;
}
displayResults("Access Denied");
if(reason==Policy.RETRY){
showDialog(DIALOG_RETRY);
}else{
showDialog(DIALOG_ERROR);
}
}
public void applicationError(int errorCode) {
dontAllow(0);
}
public void displayResults(String result){
}
And cooresponding dialog being called:
protected Dialog onCreateDialog(int id){
switch(id){
case DIALOG_RETRY:
Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Connection Error: Retry?");
builder.setCancelable(true);
builder.setPositiveButton("Retry", new RetryOnClickListener());
builder.setNegativeButton("Cancel", new CancelOnClickListener());
AlertDialog dialog = builder.create();
dialog.show();
break;
case DIALOG_ERROR:
Builder builder1 = new AlertDialog.Builder(this);
builder1.setMessage("Would you like to purchase Landscape ID! ?");
builder1.setCancelable(true);
builder1.setPositiveButton("Yes!", new BuyOnClickListener());
builder1.setNegativeButton("No.", new CancelOnClickListener());
AlertDialog dialog1 = builder1.create();
dialog1.show();
break;
}
return super.onCreateDialog(id);
}
private final class RetryOnClickListener implements
DialogInterface.OnClickListener{
public void onClick(DialogInterface dialog, int which) {
checker.checkAccess(checkerCB);
}
}
private final class CancelOnClickListener implements
DialogInterface.OnClickListener{
public void onClick(DialogInterface dialog, int which) {
onDestroy();
finish();
}
}
private final class BuyOnClickListener implements
DialogInterface.OnClickListener{
public void onClick(DialogInterface dialog, int which) {
Intent open = new Intent(Intent.ACTION_VIEW);
open.setData(Uri.parse("market://details? id=com.mustaroenterprise.landscapeid"));
startActivity(open);
}
}
My first question: How come it isn't connecting to the server as it should be? I've constructed my testing apratus as instructed by their tutorial. I've gone over it three times!
Second question: When I do launch the app on the emulator, the Connection Error dialog shows up fine. I hit retry, and it works. I hit Cancel, and it kills the app. However, if I simply click anywhere else in the window, outside the dialog, it closes the dialog and the app works normally. That kindof defeats the whole purpose, eh? How do I make that... not so?
Just in case I'm an idiot and the error lies elsewhere, here's the whole class:
private static final int DIALOG_RETRY = 10;
private static final int DIALOG_ERROR=20;
private static final byte[] SALT = {1,2,3,4,5,6,72,88,-37,-55,-23,34,22,14,15,16,17,18,19,-20};
private static final String BASE64_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqvh1xrNmvio909T06vAUxW3rtc98E3xNLA6qR/zdq2zHNW tQUJkDmJGukrkWj4Vd38NiD+nW92MX3HY2/dfw4AIcwS2oyeYceYc3hi4y2KeVL84y3DrOO0fCKNqBr6/Ve0cefN9HVyy57Psl4B0y8OaG9500xuEUeguO+PyIAMqFrtHVyi/seimnrcYLTYJo9IfGTRhcwi6QqQE8OlplidaT+uYwR4hNfcNLbnWnr7xDeG5gL2usibFPg+cvhFVhIGKO/aFuAVUIH2Yoarudc888X3/ZjTbmYAGuGhS8GRxiHhTVknCznX3BcxBJNeMA+xPTZ4OnaryRkHVvoJx5WQIDAQAB";
private LicenseCheckerCallback checkerCB;
private LicenseChecker checker;
TextView title, description, cure;
ImageView image;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//LICENSING
checkerCB = new CallBack();
final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
checker = new LicenseChecker(
this, new ServerManagedPolicy(this,
new AESObfuscator(SALT, getPackageName(),tm.getDeviceId())),
BASE64_PUBLIC_KEY);
checker.checkAccess(checkerCB);
//END LICENSING
setContentView(R.layout.activity_main);
title = (TextView)findViewById(R.id.title);
description = (TextView)findViewById(R.id.description);
image = (ImageView)findViewById(R.id.image);
cure =(TextView)findViewById(R.id.cure);
Spinner dropdown = (Spinner)findViewById(R.id.mainMenu);
//List Menu Items
final String options[] = {
//TURF DISEASES
"-Turf Diseases-", "Dollar Spot","Red Thread","Pythium Blight", "Necrotic Ring","Summer Patch","Brown Patch","Fairy Ring"
,"White Patch","Rust"
//TURF INSECTS
,"-Turf Insects-","Chinch Bug","Army Worm","Hunting Billbug","Aphid","Black Cutworm","Leaf Hopper","White Grub"
//ORNAMENTAL DISEASES
,"-Ornamental Diseases-","Powdery Mildew","Leaf Spot"
//ORNAMENTAL INSECTS
,"-Ornamental Insects-","Aphid","Leaf Miner","Japanese Beatle","Spider Mites","White Fly","Euonymus Scale","Web Worm"
};
//End List Menu Items
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,options);
dropdown.setAdapter(adapter);
dropdown.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View v,
int position, long id) {
newSelection(options[position]);
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void newSelection(String selection){
if(!selection.contains("-")){
title.setText(selection);
selection=selection.replace(" ", "_");
selection=selection.toUpperCase();
description.setText(getResourceID("DESC_"+selection, R.string.class));
image.setImageResource(getResourceID(selection.toLowerCase(), R.drawable.class));
}else{
title.setText("Select a disease or insect.");
description.setText("");
cure.setText("");
image.setImageResource(getResourceID("logo", R.drawable.class));
}
}
#SuppressWarnings("rawtypes")
public int getResourceID(String name, Class resType){
try{
Class res = null;
if(resType == R.drawable.class)
res=R.drawable.class;
if(resType==R.id.class)
res=R.id.class;
if(resType==R.string.class)
res=R.string.class;
java.lang.reflect.Field field = res.getField(name);
int retID = field.getInt(null);
return retID;
}catch(Exception e){
}return 0;
}
protected void onResume() {
newSelection("-");
super.onPause();
}
protected void onDestroy(){
super.onDestroy();
checker.onDestroy();
}
//LICENSING CALLBACK CLASS
private class CallBack implements LicenseCheckerCallback{
public void allow(int reason) {
if(isFinishing()){
return;
}
displayResults("Access Granted");
}
public void dontAllow(int reason) {
if(isFinishing()){
return;
}
displayResults("Access Denied");
if(reason==Policy.RETRY){
showDialog(DIALOG_RETRY);
}else{
showDialog(DIALOG_ERROR);
}
}
public void applicationError(int errorCode) {
dontAllow(0);
}
public void displayResults(String result){
}
}
//DIALOG CLASS AND ACTION LISTENERS
protected Dialog onCreateDialog(int id){
switch(id){
case DIALOG_RETRY:
Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Connection Error: Retry?");
builder.setCancelable(true);
builder.setPositiveButton("Retry", new RetryOnClickListener());
builder.setNegativeButton("Cancel", new CancelOnClickListener());
AlertDialog dialog = builder.create();
dialog.show();
break;
case DIALOG_ERROR:
Builder builder1 = new AlertDialog.Builder(this);
builder1.setMessage("Would you like to purchase Landscape ID! ?");
builder1.setCancelable(true);
builder1.setPositiveButton("Yes!", new BuyOnClickListener());
builder1.setNegativeButton("No.", new CancelOnClickListener());
AlertDialog dialog1 = builder1.create();
dialog1.show();
break;
}
return super.onCreateDialog(id);
}
private final class RetryOnClickListener implements
DialogInterface.OnClickListener{
public void onClick(DialogInterface dialog, int which) {
checker.checkAccess(checkerCB);
}
}
private final class CancelOnClickListener implements
DialogInterface.OnClickListener{
public void onClick(DialogInterface dialog, int which) {
onDestroy();
finish();
}
}
private final class BuyOnClickListener implements
DialogInterface.OnClickListener{
public void onClick(DialogInterface dialog, int which) {
Intent open = new Intent(Intent.ACTION_VIEW);
open.setData(Uri.parse("market://details? id=com.mustaroenterprise.landscapeid"));
startActivity(open);
}
}
}
For your second question, I would set setCanceledOnTouchOutside to false like so:
Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Connection Error: Retry?");
builder.setCancelable(true);
builder.setPositiveButton("Retry", new RetryOnClickListener());
builder.setNegativeButton("Cancel", new CancelOnClickListener());
AlertDialog dialog = builder.create();
//Add this
dialog.setCanceledOnTouchOutside(false);
dialog.show();