AlertDialog.Builder helper class cannot resolve constructor - java

I've built a helper class to store various AlertDialog types. I thought it would be helpful so that I could call them anywhere in my code. Unfortunately I get an error below at new AlertDialog.Builder(). It says Cannot resolve constructor `Builder(). How can I get this to work?
public class AlertDialogHelper {
public void showAboutDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder();
builder.setTitle(R.string.about);
builder.setMessage("A weather app made by Martin Erlic")
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Ok
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
In my activity:
private void showAboutAlertDialog() {
AlertDialogHelper alertDialogHelper = new AlertDialogHelper();
alertDialogHelper.showAboutDialog();
}

You should pass a Context in the constructor like this:
AlertDialog.Builder builder = new AlertDialog.Builder(context);
From your activity:
alertDialogHelper.showAboutDialog(this);
now:
public void showAboutDialog(Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
....

I did it like this:
public class AlertDialogHelper {
public static Dialog CreateDialog(Context mContext) {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle(R.string.about);
builder.setMessage("A weather app made by Martin Erlic")
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Ok
}
});
return builder.create();
}
}
In my activity:
AlertDialogHelper.CreateDialog(this).show();

Related

Issue with AlertDialog

I've just implemented an AlertDialog into a fragment within my Android app and it is causing my application to crash when it is shown.
Any ideas on why this might be?
Dialog
void addSiteOption() {
String[] options = {"Auto", "Manual"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity().getApplicationContext());
builder.setTitle("Add");
builder.setMessage("Auto add - download. \n Manually add - no internet connection.");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int selectionIndex) {
switch (selectionIndex)
{
case 0:
break;
case 1:
break;
}
}
});
builder.show();
}
Error:
E/AndroidRuntime: FATAL EXCEPTION: main
android.content.res.Resources$NotFoundException: Resource ID #0x0
You are getting Application context here but you need to get the calling activity's context.So change your code
From this:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity().getApplicationContext());
To this:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
Context=container.getContext();
private void showAlert() {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Are you sure to clear history?");
builder.setPositiveButton("sure", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}

On click in adapter class (ListView)

I need some help with my on click in my adapter class.
This is the code that I want to run when an item is clicked. connectOrDisconnectUser()
private void connectOrDisconnectUser(final int position) {
final AlertDialog.Builder builder = new AlertDialog.Builder(
RelationshipRemoved.this);
builder.setMessage("Do you want to un tag " + usersInfo.get(position).get(
RelationshipRemoved.likedOne))
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
//do something
public void onClick(DialogInterface dialog, int randomvar) {
Log.d("OkHttpRemove", "getting removing!");
String username = (globalInt);
String UT = usersInfo.get(position).get(
RelationshipRemoved.likedOne);
String type = "remove";
BackgroundWorker backgroundWorker = new BackgroundWorker(getApplicationContext());
backgroundWorker.execute(type, username, UT);
startActivity(new Intent(RelationshipRemoved.this, MainActivity.class));
Toast.makeText(context, "UnTagged!",
Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
The file that holds the adapter is called AdapterClass and the class that uses the adapter class is Called RelationshipRemoved. When I try to write this code. I get an error on RelationshipRemoved.this on this line RelationshipRemoved.this);, startActivity and RelationshipRemoved.this on this line startActivity(new Intent(RelationshipRemoved.this, MainActivity.class));
What's wrong?

I want to dismiss the dialog box as soon as it is connected to internet

Here I want to show two dialog boxes...one for if there is net connection available and other if there is no connection..but i want that when one dialog box is shown, the other dialogue box should be dismissed .......dismiss() is not working in this case....and somehow if I use AlertDialog instead of AlertDialog.Builder to use dismiss(), then i am not able give setPositive, setNegative and setNeutral buttons....any help will be appreciated.......
BroadcastReceiver br;
#Override
protected void onCreate(Bundle savedInstanceState) {
...........//
getStarted();
}
private void getStarted() {
if (br == null) {
br = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
...............//
if (state == NetworkInfo.State.CONNECTED) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setCancelable(false);
builder1.setTitle("Connected");
builder1.setMessage("Online");
builder1.setNeutralButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//
}
});
builder1.show();
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(false);
builder.setTitle("No Internet ");
builder.setMessage("Offline");
builder.setNeutralButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//
}
});
builder.show();
}
}
};
final IntentFilter if = new IntentFilter();
if.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
getActivity().registerReceiver(br, if);
}
}
}
Dismiss Your dialog if NetworkInfo.State.CONNECTED is connected,Please change builder1.show(); into builder1.dismiss();
if (state == NetworkInfo.State.CONNECTED) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setCancelable(false);
builder1.setTitle("Connected");
builder1.setMessage("Online");
builder1.setNeutralButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//
}
});
builder1.dismiss();
}
Use broadcast receiver to react when the connection is changed with intent filter android.net.ConnectivityManager.CONNECTIVITY_ACTION. So, you can do your stuffs when the receiver receive the intent (or there connection is changed). See here.

How to force user to deal with dialog before allowing access to activity? AND What's wrong with my licensing code?

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

Code breaks at AlertDialog creation. I think I have Context wrong...?

i can't seem to figure out why my app/code is crashing in this section. Any help would be appreciated. I think the problem lies on the creation of an AlertDialog in the else if statement.
Basically, this method is called on first launch of the application and asks the user to choose between two options: OCPS and Other. When OCPS is chosen, a SharedPreference is set. When other is selected, an AlertDialog with text box should pop up, allowing the user to input their own local URL, which is then saved to the SharedPreference.
Full code is available here: https://github.com/danielblakes/progressbook/
code follows:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean firstrun = getSharedPreferences(
"com.danielblakes.progressbook", MODE_PRIVATE).getBoolean(
"firstrun", true);
if (firstrun) {
new AlertDialog.Builder(this).setTitle("First Run").show();
pickDistrict(this);
getSharedPreferences("com.danielblakes.progressbook", MODE_PRIVATE)
.edit().putBoolean("firstrun", false).commit();
}
else {
String saved_district = getSharedPreferences(
"com.danielblakes.progressbook", MODE_PRIVATE).getString(
"district", null);
startupWebView(saved_district);
}
}
public Dialog pickDistrict(final Context context) {
AlertDialog.Builder districtalert = new AlertDialog.Builder(context);
districtalert
.setTitle(R.string.choose_district)
.setItems(R.array.districts,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int i) {
if (i == 0) {
String district_site = "https://parentaccess.ocps.net/General/District.aspx?From=Global";
startupWebView(district_site);
getSharedPreferences(
"com.danielblakes.progressbook",
MODE_PRIVATE)
.edit()
.putString("district",
district_site).commit();
} else if (i == 1) {
AlertDialog.Builder customdistrict = new AlertDialog.Builder(context);
customdistrict
.setTitle(
R.string.custom_district_title)
.setMessage(
R.string.custom_district_message);
final EditText input = new EditText(
getParent());
customdistrict.setView(input);
customdistrict
.setPositiveButton(
"Ok",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
String custom_url = input
.getText()
.toString();
getSharedPreferences(
"com.danielblakes.progressbook",
MODE_PRIVATE)
.edit()
.putString(
"district",
custom_url)
.commit();
}
});
customdistrict
.setNegativeButton(
"Cancel",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
return;
}
}).show();
}
}
}).show();
return districtalert.create();
}
}
Change
AlertDialog.Builder customdistrict = new AlertDialog.Builder(this);
to
AlertDialog.Builder customdistrict = new AlertDialog.Builder(context);
also,
final EditText input = new EditText(getParent());
needed to be changed to
final EditText input = new EditText(context);

Categories