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
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?
whenever I use the app switcher or the app gets paused in any other way then upon resuming it I will get a NullPointerException when trying to use findViewById in my fragment. The same happens when trying to use getActivity() or anything related to the Main activity. I've tried checking of the fragment is attached or not with isAdded() and it returns true but still gives the error. (Don't mind the way the code looks, I still need to clean it up)
All irrelevant classes and methods are not included (ex. Profanity class).
MainActivity onStart method (Launch activity)
#Override
public void onStart() {
super.onStart();
Profanity.downloadList();
if (AskForPermissions()) {
if (mAuth.getCurrentUser() != null) {
mAuth.getCurrentUser().reload().addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.MainFragment, new LoginFragment()).commit();
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.MainFragment, new HomeFragment()).commit();
}
});
} else {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.MainFragment, new LoginFragment()).commit();
}
} else {
onStart();
}
}
HomeFragment (The one that crashes, crash happens under Started() on the 4th line)
#SuppressWarnings("all")
#Override
public void onStart() {
super.onStart();
loadVariables();
final String UUID = ((MainActivity) getActivity()).mAuth.getCurrentUser().getUid();
User.UUID = UUID;
if (User.userName == null || User.userName.equals("")) {
Functions.loadUserData(UUID).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.getResult() == null) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose your username");
final EditText input = new EditText(getActivity());
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
final AlertDialog dialog = builder.create();
dialog.show();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (input.getText() != null && !input.getText().toString().equals("") && !input.getText().toString().equals(" ")) {
if (input.getText().toString().toCharArray().length > 16) {
dialog.dismiss();
Functions.showBottomMessage(getView(), "Your username must be maximum 16 characters.");
dialog.show();
} else if (Profanity.contains(input.getText().toString())) {
dialog.dismiss();
Functions.showBottomMessage(getView(), "Please refrain from using restricted words in your username.");
input.setText("");
dialog.show();
} else {
User.userName = input.getText().toString();
dialog.dismiss();
FirebaseReferences.users.child(User.UUID).child("name").setValue(User.userName);
Functions.showBottomMessage(getView(), "Username saved.");
}
} else {
dialog.dismiss();
Functions.showBottomMessage(getView(), "Please enter a valid username.");
dialog.show();
}
}
});
Started();
} else {
HashMap temp = (HashMap) task.getResult();
if (temp.containsKey("name")) {
User.userName = temp.get("name").toString();
} else {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose your username");
final EditText input = new EditText(getActivity());
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
final AlertDialog dialog = builder.create();
dialog.show();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (input.getText() != null && !input.getText().toString().equals("") && !input.getText().toString().equals(" ")) {
User.userName = input.getText().toString();
dialog.dismiss();
FirebaseReferences.users.child(UUID).child("name").setValue(input.getText().toString());
} else {
dialog.dismiss();
dialog.show();
}
}
});
}
if (temp.containsKey("place")) {
User.place = temp.get("place").toString();
}
if (temp.containsKey("ratedImages")) {
User.ratedImages = (ArrayList<String>) temp.get("ratedImages");
}
if (temp.containsKey("developer")) {
if (Boolean.valueOf(temp.get("developer").toString().toLowerCase()))
User.isDeveloper = true;
}
Started();
}
}
});
} else {
Started();
}
}
#SuppressWarnings("all")
private void Started() {
mainImageProgressBar.setVisibility(View.VISIBLE);
secondaryImageProgressBar.setVisibility(View.VISIBLE);
CacheHandler.update(getActivity(), imageView, secondImageView, true);
/*THIS IS THE FIRST CRASH POINT - */getView().findViewById(R.id.fabSendImage).setOnClickListener(getBtnSendImageOnClickListener());
getView().findViewById(R.id.btnReportImage).setOnClickListener(btnReportImageOnClick);
}
All view related code must be moved on to onCreateView(). So just place your code to onCreateView in case of fragment and onCreate in case of activity.
For more info just go through https://developer.android.com/guide/components/fragments.html
Crashing because of getView(). Because its not able get the view.
You need to pass the view which hold the view with id R.id.fabSendImage and try calling the view.findViewById(R.id.fabSendImage) to initialize.
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());
}
}
}
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();
I want to display an alert dialog depending upon the property and when the user clicks on the OK button, call the function again to get updated values within the running process.
I have the following code:
importingProgress = ProgressDialog.show(context, getString(R.string.progressNewsListTitle),
getString(R.string.progressProjectListMessage), true);
new Thread(new Runnable() {
public void run() {
try {
app.SetOtherTaskRunning(true);
Ib_clients client = db.Ib_clients_GetById(app.GetCustomerId());
try {
LogManager.WriteToFile("---------------- Getting News from Webservice :- " + DateFormat.getDateTimeInstance().format(new Date()) + "----------------");
CommonFuctions.CreateXml(context, h, client, db, app.GetBookMonth(), app.GetBookQuater(), app.GetBookYear(), Constants.News, app.GetWebServiceLastSyncDate(Constants.ServiceType.NEWS.toString()), Constants.ServiceType.NEWS, null, null, null, null, null);
Return reponse = null;
do {
reponse = CommonFuctions.SendingRequest(context, handler, db);
if (reponse.type.compareTo("warning") == 0) {
h.post(new Runnable() {
public void run() {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle(context.getString(R.string.information));
alert.setMessage("dsgdgd");
alert.setPositiveButton(context.getString(R.string.logoutDialogOk), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.show();
}
});
}
} while (reponse.type.compareTo("warning") == 0);
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
//Log.d(Constants.TAG, e.getMessage());
e.printStackTrace();
}
if (importingProgress != null) {
importingProgress.dismiss();
importingProgress = null;
}
}
}).start();
If response type is warning, then display a message to the user and if the user clicks the OK button , then call CommonFuctions.SendingRequest(context, handler, db) again to get updated values. Until we get a.response type of warning , we need to display an alert dialog to the user and call CommonFuctions.SendingRequest(context, handler, db) again.
Class to return:
public class Return {
public String type;
public String msg;
public boolean isSuccess;
public int client_id; // for getting clientid from server
public int booking_id; // for getting bookingid form server
}
You will have to use handler to display the AlertDialog because UI can be handled by the main thread only.
The other way is to use asyncTask for multiprocessing and then using the onPostExcecute() of asyncTask to display the AlertDialog
Please feel free to ask any further doubts.
Try to run your dialog as below in runonUIthread:
runOnUiThread(new Runnable() {
#Override
public void run() {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle(context.getString(R.string.information));
alert.setMessage("dsgdgd");
alert.setPositiveButton(context.getString(R.string.logoutDialogOk), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.show();
}
});