How to show dialogue for network change states? - java

I have a code for network change state in android. but now problem is that code shows the snack-bar when network state changed. i want that it will show dialogue box when network state get changed. I already done everything. i just want instead of snack-bar dialogue will be shown.
IntentFilter intentFilter = new IntentFilter(NetworkStateChangedReceiver.NETWORK_AVAILABLE_ACTION);
LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
boolean isNetworkAvailable = intent.getBooleanExtra(IS_NETWORK_AVAILABLE, false);
String networkStatus = isNetworkAvailable ? "connected" : "disconnected";
Snackbar.make(findViewById(R.id.activity_dashboard), "Network Status: " + networkStatus, Snackbar.LENGTH_LONG).show();
}
}, intentFilter);

Just use the AlertDialog.Builder to create an alert dialog instead of Snackbar. Something along the following lines should work,
IntentFilter intentFilter = new IntentFilter(NetworkStateChangedReceiver.NETWORK_AVAILABLE_ACTION);
LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
boolean isNetworkAvailable = intent.getBooleanExtra(IS_NETWORK_AVAILABLE, false);
String networkStatus = isNetworkAvailable ? "connected" : "disconnected";
//Snackbar.make(findViewById(R.id.activity_dashboard), "Network Status: " + networkStatus, Snackbar.LENGTH_LONG).show();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_message).setTitle(R.string.dialog_title);
AlertDialog dialog = builder.create();
}
}, intentFilter);

This is a simple AlertDialog that you can use:
public static Dialog createSimpleOkDialog(Context context, String title, String message) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context)
.setTitle(title)
.setMessage(message)
.setNegativeButton(android.R.string.ok, null);
return alertDialog.create();
}

Related

Firebase Crashlytics error logs in samsung phone

I have uploaded a signed app on the play store. and today when I opened my firebase pannel in crashlytics it's showing 2 crashes in the last 24 hours. Both the crashes were on the same java class and line and also both on the Samsung phone only.
Here is the error: Fatal Exception: java.lang.RuntimeException
Error receiving broadcast Intent { act=android.net.conn.CONNECTIVITY_CHANGE flg=0x4200010....
It's in my receiver class: below is the code for the same
public void onReceive(final Context context, Intent intent) {
connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
if (alertdialog != null) {
alertdialog.dismiss();
}
} else {
builder = new AlertDialog.Builder(context);
View view = LayoutInflater.from(context).inflate(R.layout.internet_dialouge, null);
builder.setView(view);
builder.create();
builder.setCancelable(true);
alertdialog = builder.show();
view.findViewById(R.id.btnDismiss)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alertdialog.dismiss();
}
});
view.findViewById(R.id.btnSetting)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
context.startActivity(new Intent(Settings.ACTION_SETTINGS));
}
});}}}}
Crashlytics showing error in this line: alertdialog = builder.show();
And I use this receiver class in the main activity like this:
myReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
myReceiver = new MyReceiver();
registerReceiver(myReceiver, intentFilter);
I am not understanding why this error in crashlytics.
"context" may be not initialized when your application reaches the line
builder = new AlertDialog.Builder(context);
Please check context is always initialized. You can check like this.
if(context!=null) {
//build alertdialog. }

Broadcastreceiver cannot receive when activity not opened

I have a notepad activity that opens up a window dialog version of it where user can go to another app and still type on the notepad
For both notepad to have the same content, I used broadcastReceiver to set the text of the notepad activity to the one in the dialog when the user is done.
Activity's BroadcastReceiver:
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final globalVariable globalVariable = (globalVariable) getApplicationContext();
et_editor.setText(globalVariable.getScriptEditorText());
Toast.makeText(Script_editor.this, "Script Editor have been updated", Toast.LENGTH_SHORT).show();
}
};
Close Button of the Dialog:
btn_Close = (Button) view.findViewById(R.id.button_Close);
btn_Close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog alertDialog = new AlertDialog.Builder(getApplicationContext())
.setTitle("Would you like to update the editor?")
.setNegativeButton("No, discard the changes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(ColorCoordinatePickerService.this, "Changes have been discarded", Toast.LENGTH_SHORT).show();
dialog.dismiss();
stopSelf();
}
})
.setPositiveButton("Yes, update with changes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final globalVariable globalVariable = (globalVariable) getApplicationContext();
globalVariable.setScriptEditortext(CCEditor.getText().toString());
Intent intent = new Intent(BROADCAST_ACTION);
sendBroadcast(intent);
dialog.dismiss();
stopSelf();
}
})
.create();
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.show();
}
});
It works BUT the user have to go back to the notepad activity (cannot be in another app or activity).
How do I update the notepad's content without having to "open" it up?
Queue the changes in BroadcastReceiver and when NotepadActivity resumes set the changes in the EditText. The queue doesn't need to be an actual queue, you can persist the last broadcast receiver data somewhere.
I am not sure, but it may be clear your global variable on moving from activity to another activity, also you are declaring the instance of global variable so it will set value in instance not in main variable and therefor you will not get it on receiver.
So I think you should set value in intent and then get it on receiver and manage it so it will work.
Check below, first your click event of dialog box method
#Override
public void onClick(DialogInterface dialog, int which) {
final globalVariable globalVariable = (globalVariable) getApplicationContext();
globalVariable.setScriptEditortext(CCEditor.getText().toString());
Intent intent = new Intent(BROADCAST_ACTION);
intent.putExtra("global_variable","" + CCEditor.getText().toString());
sendBroadcast(intent);
dialog.dismiss();
stopSelf();
}
And now get value in receiver as like below.
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final globalVariable globalVariable = (globalVariable) getApplicationContext();
String strData = intent.getExtras().getString("global_variable");
et_editor.setText(strData);
Toast.makeText(Script_editor.this, "Script Editor have been updated", Toast.LENGTH_SHORT).show();
}
};
Hope this will work
without opening acitivity,you want to update data then only one way you can do it.when you receive in receiver set all data into sharepreference.Whenever your notepad activity opens you can set take data from sharepreference and set it into notepad activity.
Use LocalBroadcastManager.
Example: How to use it

Get EditText value displayed AlertDialog

Is it possible to get the user-input text from an EditText and display it in an AlertDialog? The Main Activity prompts the user to set an alarm, then enter a message to be displayed later once the alarm goes off. I want to be able to display whatever message the user typed in an AlertDialog.
MainActivity.java
public class MainActivity extends Activity{
TimePicker picker;
DatePicker datepicker;
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.settings, menu);
return true;
}
public void setAlarm(View view) {
picker = (TimePicker)findViewById(R.id.timePicker1);
datepicker = (DatePicker)findViewById(R.id.datePicker1);
Calendar AlarmCal = Calendar.getInstance();
Intent intent = new Intent(this, AlarmBoadcastReceiver.class);
PendingIntent pendingintent = PendingIntent.getBroadcast(this.getApplicationContext(), 9988, intent, 0);
AlarmCal.setTimeInMillis(System.currentTimeMillis());
AlarmCal.set(Calendar.HOUR_OF_DAY, picker.getCurrentHour());
AlarmCal.set(Calendar.MINUTE, picker.getCurrentMinute());
AlarmCal.set(Calendar.DATE, datepicker.getDayOfMonth());
AlarmCal.set(Calendar.YEAR, datepicker.getYear());
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, AlarmCal.getTimeInMillis(), pendingintent);
}
}
AlarmBroadCastReciever.java
public class AlarmBoadcastReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
showNotification(context);
Vibrator vibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(1000);
}
private void showNotification(Context context) {
PendingIntent contentintent = PendingIntent.getActivity(context, 0, new Intent(context, ShowDialog.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_notif)
.setContentTitle("Reminder")
.setContentText("Click Here To View Message");
mBuilder.setContentIntent(contentintent);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
ShowDialog.java
public class ShowDialog extends Activity {
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_dialog);
showDialog();
}
void showDialog() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setTitle("Message");
alertDialogBuilder
.setMessage("message")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ShowDialog.this.finish();
closeApp();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
So when the notification is clicked on, the AlertDialog shows up, but not with the message the user entered. Ive tried getting the values and putting them in a string, but that doesnt work. Any Ideas?
Try to create your own Dialog extending from Dialog class and add this message to constructor.
I hate to answer my own question but I took the advice #StarsSky gave and used Shared Preferences to store and retrieve the message to display in the AlertDialog
save
SharedPreferences.Editor editor = getSharedPreferences(null, MODE_PRIVATE).edit();
editor.putString("text", editText.getText().toString());
editor.commit();
receive
SharedPreferences prefs =getSharedPreferences(null, MODE_PRIVATE);
String text = prefs.getString("text", null);
Add the message as an EXTRA to the alarm pendingIntent:
Intent intent = new Intent(this, AlarmBoadcastReceiver.class);
intent.putExtra("message", yourMessageString);
Get the string in AlarmBoadcastReceiver onReceive method
yourMessageString = intent.getExtras().getString("message","No message");
In showNotification add that string as an EXTRA to pendingintent:
intent = new Intent(context, ShowDialog.class);
intent.putExtra("message", yourMessageString);
PendingIntent contentintent = PendingIntent.getActivity(context, 0, intent, 0);
On ShowDialog onCreate method get the intent extra:
userMessage = getIntent().getExtras().getString("message","No message");
Then set that message to AlertDialog
alertDialogBuilder.setMessage(userMessage)

AlertDialog is giving an "undefined" error

My code is:
View.OnClickListener menuHandle = new View.OnClickListener() {
public void onClick(View v) {
//inflate menu
final String [] items = new String[] {"Rate This App", "Quit"};
final Integer[] icons = new Integer[] {R.drawable.star, R.drawable.quit};
ListAdapter adapter = new ArrayAdapterWithIcon(MainActivity.this, items, icons);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.DialogSlideAnim)
.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item ) {
//Toast.makeText(MainActivity.this, "Item Selected: " + item, Toast.LENGTH_SHORT).show();
switch (item) {
case 0:
//Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_VIEW);
//Try Google play
intent.setData(Uri.parse("market://details?id=com.test.testing"));
if (MyStartActivity(intent) == false) {
//Market (Google play) app seems not installed, let's try to open a web browser
intent.setData(Uri.parse("https://play.google.com/store/apps/details?com.test.testing"));
if (MyStartActivity(intent) == false) {
//Well if this also fails, we have run out of options, inform the user.
//let the user know nothing was successful
}
}
break;
case 1:
finish();
break;
default:
//do nothing
}
}
});
AlertDialog alert = builder.create();
alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
alert.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
alert.getWindow().setGravity(Gravity.BOTTOM);
alert.show();
}
};
I get the following error:
The constructor AlertDialog.Builder(MainActivity, int) is undefined
What do I have to modify to get rid of the error?
Note: My MainActivity class extends Activity and DialogSlideAnim as been initialized in the res/values/styles.xml file
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.DialogSlideAnim) will work only on API level 11 and above.
If you are targeting all the platforms then use following.
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this, R.style.DialogSlideAnim))
try
new AlertDialog.Builder(v.getContext(), R.style.DialogSlideAnim)
instead of
new AlertDialog.Builder(MainActivity.this, R.style.DialogSlideAnim)
I think its because the AlertDialog.Builder is inside a inner class(menuHandle.setOnClickListener), try changing to: new AlertDialog.Builder(TheNameOfYourClass.this,R.style.DialogSlideAnim);
Like this way :
public void onClick(View v) {
new AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.DialogSlideAnim);
^^^
....
}
Try to set the Style in your AlertDialog as below:
new AlertDialog.Builder(
new ContextThemeWrapper(MainActivity.this, R.style.DialogSlideAnim)

AlertDialog from within BroadcastReceiver?? Can it be done?

AlertDialog from within BroadcastReceiver? Can it be done? I am working on a app that will pop up a Dialog box if I get SMS message. I am trying to code this within a BroadcaseReceiver. But I cant use this line of code AlertDialog.Builder builder = new AlertDialog.Builder(this);. Can someone please help me with a hint!
public class SMSPopUpReceiver extends BroadcastReceiver {
private static final String LOG_TAG = "SMSReceiver";
public static final int NOTIFICATION_ID_RECEIVED = 0x1221;
static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
public void onReceive(Context context, Intent intent) {
Log.i(LOG_TAG, "onReceive");
if (intent.getAction().equals(SMSPopUpReceiver.ACTION)) {
StringBuilder sb = new StringBuilder();
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
for (Object pdu : pdus){
SmsMessage messages =
SmsMessage.createFromPdu((byte[]) pdu);
sb.append("Received SMS\nFrom: ");
sb.append(messages.getDisplayOriginatingAddress());
sb.append("\n----Message----\n");
sb.append( messages.getDisplayMessageBody());
}
}
Log.i(SMSPopUpReceiver.LOG_TAG,
"[SMSApp] onReceiveIntent: " + sb);
Toast.makeText
(context, sb.toString(), Toast.LENGTH_LONG).show();
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
}
}
Principal issue: try to avoid placing time consuming functionalities into BroadcastReceiver. It should just receive and initiate further processing in bound Activity/Service.
UPDATE:
Please check following sources that might be helpful:
Similar questions on StackOverflow:
How to send data from BroadcastReceiver to an Activity in android?
Android SMS receiver not working
Android SDK demo example:
android-sdk-windows\samples\android-8\ApiDemos\src\com\example\android\apis\os\SmsMessagingDemo.java
And of course standard Android API documentation: http://developer.android.com/reference/android/content/BroadcastReceiver.html
UPDATE2:
Added app skeleton as it should look. Please note that no content view is defined. It is because your app will have transparent screen. To achieve that
#android:style/Theme.Translucent
is entered under Theme tag for this activity in AndroidManifest.xml.
public class NotifySMSReceived extends Activity
{
private static final String LOG_TAG = "SMSReceiver";
public static final int NOTIFICATION_ID_RECEIVED = 0x1221;
static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter(ACTION);
this.registerReceiver(mReceivedSMSReceiver, filter);
}
private void displayAlert()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?").setCancelable(
false).setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private final BroadcastReceiver mReceivedSMSReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION.equals(action))
{
//your SMS processing code
displayAlert();
}
}
};
}
I've been looking into it and the documentation of the BroadcastReceiver actually says:
public abstract void onReceive
(Context context, Intent intent)
Since: API Level 1 This method is
called when the BroadcastReceiver is
receiving an Intent broadcast. During
this time you can use the other
methods on BroadcastReceiver to
view/modify the current result values.
The function is normally called within
the main thread of its process, so you
should never perform long-running
operations in it (there is a timeout
of 10 seconds that the system allows
before considering the receiver to be
blocked and a candidate to be killed).
You cannot launch a popup dialog in
your implementation of onReceive().
You cannot launch a popup dialog in
your implementation of onReceive()
So it seems it is not possible
This is late but this may help someone.
You cannot use alert dialog inside broadcast receiver, we can use this only in activity or service. Try like this
In your onReceive method of broadcastreceiver add
Intent i = new Intent(context, yourclass.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
and in yourclass set your dialog message, so that it will appear when you trigger the receiver event. I tried this and it worked me. Hope this may help some one :-)
you can create a new transparent activity and then create Alert Dialog in that activity, whenever your alert is to be displayed call that activity from your broadcast reciever ,this could work, not tested
replace the word "this" inside the AlertDilaog with "context" -- the first parameter on you onRecieve method.
public void onReceive(Context context, Intent intent)

Categories

Resources