Iam new to android,I want to show alert dialog box in service,I used two methods as shown below
First one without Layout
AlertDialog.Builder builder = new AlertDialog.Builder(MyService.this);
builder.setTitle("Test dialog");
builder.setMessage("Content");
builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
});
AlertDialog alert = builder.create();
alert.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);
alert.show();
but iam getting error like this as shown as below
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.materialdialoginservice, PID: 25846
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:993)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:387)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:95)
at android.app.Dialog.show(Dialog.java:344)
at com.example.materialdialoginservice.MyService$3.run(MyService.java:98)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7561)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:995)
Second one with Layout
AlertDialog.Builder builder = new AlertDialog.Builder(MyService.this);
View view = View.inflate(context, R.layout.activity_layout_view, null);
AlertDialog dialog = builder.create();
dialog.setView(view);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//8.0 new features
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY - 1);
} else {
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);
}
dialog.show();
Window dialogWindow = dialog.getWindow();
dialogWindow.setGravity(Gravity.CENTER);
I am getting error like this,
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.textstuff, PID: 27418
java.lang.RuntimeException: Unable to start service com.example.textstuff.MyService#134fed7 with Intent { cmp=com.example.textstuff/.MyService }: android.view.WindowManager$InvalidDisplayException: Unable to add window android.view.ViewRootImpl$W#124c071 -- the specified display can not be found
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4196)
at android.app.ActivityThread.access$2000(ActivityThread.java:233)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1946)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7561)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:995)
Added permission in Manifest file like this
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.SYSTEM_OVERLAY_WINDOW"/>
Just remove :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // 8.0 new features
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY - 1);
} else {
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);
}
And try :
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT)
UPDATE
In Android 6.0 Marshmallow, the user must explicitly allow your app to "draw over other apps". So add
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
Now in marshmallow use this method to handle runtime permission:
#TargetApi(Build.VERSION_CODES.M)
private void handleOverlaySettings() {
final Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
try {
startActivityForResult(intent, 11);
} catch (ActivityNotFoundException e) {
Log.e(TAG, e.getMessage());
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 11:
final boolean overlayEnabled = Settings.canDrawOverlays(this);
// handle the remaining logic
break;
}
}
Now show the dialog in service as below:
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this, R.style.AppTheme_MaterialDialogTheme);
dialogBuilder.setTitle(R.string.dialog_title);
dialogBuilder.setMessage(R.string.dialog_message);
dialogBuilder.setNegativeButton(R.string.btn_back,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}
);
final AlertDialog dialog = dialogBuilder.create();
final Window dialogWindow = dialog.getWindow();
final WindowManager.LayoutParams dialogWindowAttributes = dialogWindow.getAttributes();
// Set fixed width (350dp) and WRAP_CONTENT height
final WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialogWindowAttributes);
lp.width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 350, getResources().getDisplayMetrics());
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
dialogWindow.setAttributes(lp);
// Set to TYPE_SYSTEM_ALERT so that the Service can display it
dialogWindow.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
dialogWindowAttributes.windowAnimations = R.style.DialogAnimation;
dialog.show();
All set now this solution should work. Good luck
Related
I have a react native app, I use this java code to check the camera permission :
int permission = PermissionChecker.checkSelfPermission(getReactApplicationContext(), Manifest.permission.CAMERA);
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.CAMERA}, PERMISSION_REQUEST_CAMERA);
}
promise.resolve(permission);
On Android 6.0, when the camera permission is off, the native permission popup shows thanks to the requestPermissions function.
However, it doesn't show on Android 7.0.
I checked the result of :
ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.CAMERA)
It's false on Android 6.0 and 7.0
Thanks for your answer,
This is how we check and manage all the end user input when dealing with permissions just change to the permission you want to deal with
First check
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
} else {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 666); // Comment 26
}
}
Then manage end user input
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 666: // User selected Allowed Permission Granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Snackbar s = Snackbar.make(findViewById(android.R.id.content), "Permission Granted", Snackbar.LENGTH_LONG);
View snackbarView = s.getView();
snackbarView.setBackgroundColor(Color.WHITE);
TextView textView = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.RED);
textView.setTextSize(18);
textView.setMaxLines(6);
s.show();
// do your work here
// User selected the Never Ask Again Option Change settings in app settings manually
} else if (Build.VERSION.SDK_INT >= 23 && !shouldShowRequestPermissionRationale(permissions[0])) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this, R.style.MyAlertDialogStyle);
alertDialogBuilder.setTitle("Change Permissions in Settings");
alertDialogBuilder
.setMessage("Click SETTINGS to Manually Set\n\n" + "Permissions to use Database Storage")
.setCancelable(false)
.setPositiveButton("SETTINGS", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, 1000);
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
} else {
// User selected Deny Dialog to EXIT App ==> OR <== RETRY to have a second chance to Allow Permissions
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this, R.style.MyAlertDialogStyle);
alertDialogBuilder.setTitle("Second Chance");
alertDialogBuilder
.setMessage("Click RETRY to Set Permissions to Allow\n\n" + "Click EXIT to the Close App")
.setCancelable(false)
.setPositiveButton("RETRY", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(MainActivity.this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
})
.setNegativeButton("EXIT", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
break;
}};
I've tried using the context from new AlertDialog.Builder(mContext) with the context from adapter constructor, i.e. mContext, with
My deleteComment() function:
private void deleteComment(int position) {
String currentUserObjectId = ParseUser.getCurrentUser().getObjectId();
ParseQuery<ParseObject> query = new ParseQuery<>("Yeet");
query.whereEqualTo(ParseConstants.KEY_OBJECT_ID, mYeets.get(position).getObjectId());
query.whereContains(ParseConstants.KEY_SENDER_ID, currentUserObjectId);
query.findInBackground((yeet, e) -> {
if (e == null) {
for (ParseObject yeetObject : yeet) {
if (yeetObject.getParseObject(ParseConstants.KEY_SENDER_AUTHOR_POINTER).getObjectId().equals((ParseUser.getCurrentUser().getObjectId()))) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(mContext);
dialogBuilder.setTitle("Delete");
dialogBuilder.setMessage("Do you want to delete this Yeet?");
dialogBuilder.setPositiveButton("Yes", (dialog, which) -> {
// Iterate over all messages and delete them
for (ParseObject delete : yeet) {
delete.deleteInBackground();
/*this.adapter.remove(mYeets.get(position));*/
this.adapter.notifyDataSetChanged();
Toast.makeText(mContext, "Yeet deleted", Toast.LENGTH_SHORT).show();
}
});
dialogBuilder.setNegativeButton("No", (dialog, which) -> {
});
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
}
}
} else {
Log.e("Error", e.getMessage());
}
});
}
The exception:
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
at android.view.ViewRootImpl.setView(ViewRootImpl.java:571)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:310)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at android.app.Dialog.show(Dialog.java:319)
at com.yitter.profile.UserProfileAdapter.lambda$deleteComment$115(UserProfileAdapter.java:286)
at com.yitter.profile.UserProfileAdapter.access$lambda$2(UserProfileAdapter.java:0)
at com.yitter.profile.UserProfileAdapter$$Lambda$3.done(Unknown Source)
at com.parse.ParseTaskUtils$2$1.run(ParseTaskUtils.java:116)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Here is a gist of my Adapter class if that helps:
https://gist.github.com/santafebound/bf496bbfee2da81b60312207121853b0
Make sure mContext is an Activity.
Calling new AlertDialog.Builder(activity.getApplicationContext()) will throw this same error, but new AlertDialog.Builder(activity) works fine when calling show().
Looks like AlertDialog is designed to use context from visible elements only, as an Activity, and not from an ApplicationContext, Service, etc.
So I have this page in my app which lets user choose to either take a picture with their camera or pick an image from gallery.
Upon choosing an alert dialog with the chosen image set as icon will be shown confirming.
Now here comes my problem, whenever I try to get an image, using either the gallery picker or camera intent, my app crashes right after with error:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=-1, data=null} to activity {my.com.thelorry.ken.thelorrypartner/com.example.Activity}:
If I am using the camera intent or if I used the gallery picker this shows:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=-1, data=null} to activity {com.example/com.example.Activity}:
Below are the codes I used to start my camera intent:
public void startCamera(){
ContentValues values;
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From phone Camera");
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
And my codes to start gallery picker:
public void pickGallery(){
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, GALLERY_REQUEST);
}
This is my codes to handle the results:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
photo = null;
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK ) {
try {
photo = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
photo = getResizedBitmap(photo, 600, 450);
File file = new File(imageurl);
file.delete();
} catch (Exception e) {
e.printStackTrace();
}
createDialog(photo);
}if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK && data != null) {
Uri pickedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
photo = getResizedBitmap(bitmap, 600, 450);
cursor.close();
createDialog(photo);
}
}
Also, odd enough, this codes seems to crash only on Samsung phones based on my crash reports, and only on some models such as the Galaxy J7, Note5, Note4 (so far, app doesn't have a huge userbase yet).
Edit: After actually getting a phone that could reproduce the crash I realize that codes above might not be the problem after all, this is the what I have in logcats:
Process: com.example, PID: 6220
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=-1, data=null} to activity {com.example/com.example.Activity}: android.content.res.Resources$NotFoundException: Resource ID #0xffffffff
at android.app.ActivityThread.deliverResults(ActivityThread.java:4019)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4062)
at android.app.ActivityThread.access$1400(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1483)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5930)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0xffffffff
at android.content.res.Resources.getValue(Resources.java:1542)
at android.support.v7.widget.ResourcesWrapper.getValue(ResourcesWrapper.java:204)
at android.support.v7.widget.AppCompatDrawableManager.loadDrawableFromDelegates(AppCompatDrawableManager.java:321)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:197)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:192)
at android.support.v7.widget.AppCompatImageHelper.setImageResource(AppCompatImageHelper.java:66)
at android.support.v7.widget.AppCompatImageView.setImageResource(AppCompatImageView.java:71)
at com.android.internal.app.AlertController.setupTitle(AlertController.java:565)
at com.android.internal.app.AlertController.setupView(AlertController.java:474)
at com.android.internal.app.AlertController.installContent(AlertController.java:240)
at android.app.AlertDialog.onCreate(AlertDialog.java:356)
at android.app.Dialog.dispatchOnCreate(Dialog.java:373)
at android.app.Dialog.show(Dialog.java:274)
at com.example.Activity.createDialog(Activity.java:697)
at com.example.Activity.onActivityResult(Activity.java:618)
at android.app.Activity.dispatchActivityResult(Activity.java:6441)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4015)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4062)
at android.app.ActivityThread.access$1400(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1483)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5930)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
Also:
FATAL EXCEPTION: main
Process: com.example, PID: 9794
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1889, result=-1, data=Intent { dat=content://media/external/images/media/3196 flg=0x1 (has extras) }} to activity {com.example/com.example.Activity}: android.content.res.Resources$NotFoundException: Resource ID #0xffffffff
at android.app.ActivityThread.deliverResults(ActivityThread.java:4019)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4062)
at android.app.ActivityThread.access$1400(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1483)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5930)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0xffffffff
at android.content.res.Resources.getValue(Resources.java:1542)
at android.support.v7.widget.ResourcesWrapper.getValue(ResourcesWrapper.java:204)
at android.support.v7.widget.AppCompatDrawableManager.loadDrawableFromDelegates(AppCompatDrawableManager.java:321)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:197)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:192)
at android.support.v7.widget.AppCompatImageHelper.setImageResource(AppCompatImageHelper.java:66)
at android.support.v7.widget.AppCompatImageView.setImageResource(AppCompatImageView.java:71)
at com.android.internal.app.AlertController.setupTitle(AlertController.java:565)
at com.android.internal.app.AlertController.setupView(AlertController.java:474)
at com.android.internal.app.AlertController.installContent(AlertController.java:240)
at android.app.AlertDialog.onCreate(AlertDialog.java:356)
at android.app.Dialog.dispatchOnCreate(Dialog.java:373)
at android.app.Dialog.show(Dialog.java:274)
at com.example.Activity.createDialog(Activity.java:697)
at com.example.Activity.onActivityResult(Activity.java:639)
at android.app.Activity.dispatchActivityResult(Activity.java:6441)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4015)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4062)
at android.app.ActivityThread.access$1400(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1483)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5930)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
More info, this is my createDialog function which actually causing problems.
Drawable icon = new BitmapDrawable(this.getResources(),photo);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.business_post_camera_dialog_title))
.setMessage(getString(R.string.business_post_camera_dialog_message))
.setCancelable(false)
.setPositiveButton(R.string.sign_confirm_btn, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
doSomething();
}
})
.setNegativeButton(R.string.sign_cancel_btn, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(-1).setIcon(icon); //setIcon(-1) as a workaround for bug in Android Lollipop 5.0
AlertDialog alert = builder.create();
alert.show();
Apparently .setIcon(-1) causes the crash on Samsung phones, but without it I wouldn't be able to display my images there on certain phones still on Lollipop 5.0, any solution?
The problem is here:
...
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0xffffffff
...
You are trying to use setImageResource(int id) with a non-exist image. You can use it like this:
imageView.setImageResource(R.drawable.image_name)
The same thing is available for TextView too.
textView.setText("" + intValue);
Try to use below method for dialog,
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
Drawable icon = new BitmapDrawable(this.getResources(),photo);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.business_post_camera_dialog_title))
.setMessage(getString(R.string.business_post_camera_dialog_message))
.setCancelable(false)
.setPositiveButton(R.string.sign_confirm_btn, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
doSomething();
}
})
.setNegativeButton(R.string.sign_cancel_btn, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
});
if (currentapiVersion >= android.os.Build.VERSION_CODES.LOLLIPOP){
builder.setIcon(-1).setIcon(icon);
} else{
builder.setIcon(icon);
}
AlertDialog alert = builder.create();
alert.show();
I am trying to make an on click button which makes phone calls when pressed.
Here is my code for java:
public void CampusSafClick(View view){
Intent callIntent =new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:6038994210"));
startActivity(callIntent);
}
I understand how to make onclick buttons, so that is not the issue.
I have this code in the manifest:
<uses-permission android:name="android.permision.CALL_PHONE"></uses-permission>
I keep getting the error Unfortunately your app has stop working.
Here is the working code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialContactPhone("123123123");
}
});
}
private void dialContactPhone(final String phoneNumber) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", phoneNumber, null)));
}
You need Action_Dial,
use below code it will open Dealer with number specified.
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:0123456789"));
startActivity(intent);
The tel: prefix is required, otherwhise the following exception will be thrown: java.lang.IllegalStateException: Could not execute method of the activity.
Action_Dial doesn't require any permission.
If you want to initiate the call directly without user's interaction, you can use action Intent.ACTION_CALL. In this case, you must add the following permission in your AndroidManifest.xml:
<uses-permission android:name="android.permission.CALL_PHONE" />
I need to enter code above the application list on the manifest:
<uses-permission android:name="android.permission.CALL_PHONE"/>
You can use the following code
intent =new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:+251999999999"));
startActivity(intent);
and include in manifest file
<uses-permission android:name="android.permission.CALL_PHONE"/>
ivCall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (serviceListDates.get(position).getUser_mobile().length() != 0) {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("NKA SERVICE");
alertDialog.setMessage("Do you want to Call ?");
alertDialog.setIcon(R.drawable.call_icon);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
((DeliveredServiceOilActivity) mContext).callPhoneNumber
(serviceListDates.get(position).getUser_mobile());
}
});`enter code here
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
} else
AlertUtils.SHOW_TOAST(mContext, mContext.getString(R.string.please_add_number));
}
});
For make a call using android, It can be implement using Intents.
public void MakePhoneCall(View view){
Intent callIntent =new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:9961907453"));
if (ActivityCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
return;
}
startActivity(callIntent);
}
I have this code in the manifest:
<uses-permission android:name="android.permision.CALL_PHONE"></uses-permission>
If you are using SDK version greater than Lolipop then you should include request permission.
I'm trying to get my alertDialog working in an arrayAdapter. This is how my function looks like.
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final Noodnummers currentNoodnummer = noodnummers.get(position);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(layoutResourceId, parent, false);
TextView txt_noodnummer_name = (TextView) rowView.findViewById(R.id.txt_noodnummer_name);
txt_noodnummer_name.setText(currentNoodnummer.naam);
TextView txt_noodnummer_telefoon = (TextView) rowView.findViewById(R.id.txt_noodnummer_telefoon);
txt_noodnummer_telefoon.setText(Html.fromHtml(currentNoodnummer.telefoonNummer));
txt_noodnummer_telefoon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
//To change body of implemented methods use File | Settings | File Templates.
try {
new AlertDialog.Builder(this)
.setTitle("")
.setMessage("Bent u zeker dat u" + currentNoodnummer.telefoonNummer + "wilt bellen?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
String uri = currentNoodnummer.telefoonNummer;
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(uri));
v.getContext().startActivity(intent);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
} catch (ActivityNotFoundException activityException) {
Log.e("genkonstage", "Call failed", activityException);
}
}
});
return rowView;
}
The first problem is, that new AlertDialog.Builder(this) is given me an error on the word this. Then I found that I maybe should use a context. But when I say new AlertDialog.Builder(context) I get no error but when I click the app crashes.
Can someone help me with this?
EDIT
06-18 10:56:20.689 12980-12980/be.appmax.genkOnStage E/AndroidRuntime: FATAL EXCEPTION: main
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
at android.view.ViewRootImpl.setView(ViewRootImpl.java:571)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:246)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:281)
at android.app.AlertDialog$Builder.show(AlertDialog.java:951)
at be.appmax.genkOnStage.adapters.NoodnummersArrayAdapter$1.onClick(NoodnummersArrayAdapter.java:57)
at android.view.View.performClick(View.java:4204)
at android.view.View$PerformClick.run(View.java:17355)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Creation of arrayAdapter inside NoodnummersActivity
ListView listView = (ListView) findViewById(R.id.listViewNoodnummers);
//addList(noodnummersArrayList, listView);
NoodnummersArrayAdapter adapter = new NoodnummersArrayAdapter(getBaseContext(), R.layout.noodnummers_list, noodnummersArrayList);
// fill the listview with adapter.
listView.setAdapter(adapter);
setListViewHeightBasedOnChildren(listView);
"Never" use getBaseContext()! From a Google Engineer
Try with NoodnummersActivity.this
NoodnummersArrayAdapter adapter = new NoodnummersArrayAdapter(NoodnummersActivity.this, R.layout.noodnummers_list, noodnummersArrayList);
and then try with
new AlertDialog.Builder(context)
By the way, I suggest at the beginning of your activity to define a private field with the context. I found this suggestion here somewhere and I find it awesome:
public class MyActivity extends Activity {
private Context context = MyActivity.this;
}
in this way you can use "context" without any worries.
Use this method for context:
private Context getDialogContext() {
Context context;
if (getParent() != null)
context = getParent();
else
context = this;
return context;
}
try this it will work.