Get EditText value displayed AlertDialog - java

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)

Related

How to Clear shared Preference for a Time Picker on Cancel button?

I am Working on a project where i have two buttons and a textview (in layout) for a time picker to set notification,
buttonTimepicker & buttonCancelAlarm.
I used to save the Time, selected in the Time Picker by shared Preferences.
The shared preferences are working properly.
But the problem i am facing is that, when i click the Cancel button, My app still showing me the notification set by time picker, Even i had implement editor.clear(); on shared preference on click of Cancel button Listner.
When i remove the shared preferences it work properly canceling the time and notification.
Here, what i want is to save the time in a shared preference on Set Time button, And clear shared preference on cancel Time button.
public class drvschedule extends AppCompatActivity implements
TimePickerDialog.OnTimeSetListener {
private TextView mTextView;
SharedPreferences myPrefdrv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drvschedule);
mTextView = findViewById(R.id.drtmslctd);
Button buttonTimePicker = findViewById(R.id.setdrvtm);
buttonTimePicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment timePicker = new TimePickerFragment();
timePicker.show(getSupportFragmentManager(), "time picker");
}
});
Button buttonCancelTime = findViewById(R.id.cncldrvtm);
buttonCancelTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor=myPrefdrv.edit();
editor.clear();
editor.apply();
cancelAlarm();
}
});
myPrefdrv=getPreferences(MODE_PRIVATE);
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, 0);
updateTimeText(c);
startAlarm(c);
}
private void updateTimeText(Calendar c) {
String timeText = "Notification set for Driving: ";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
timeText +=
DateFormat.getTimeInstance(DateFormat.SHORT).format(c.getTime());
}
mTextView.setText(timeText);
}
private void startAlarm(Calendar c) {
AlarmManager alarmManager = (AlarmManager)
getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1,
intent, 0);
if (c.before(Calendar.getInstance())) {
c.add(Calendar.DATE, 1);
}
SharedPreferences.Editor editor=myPrefdrv.edit();
editor.apply();
alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(),
pendingIntent);
}
private void cancelAlarm() {
AlarmManager alarmManager = (AlarmManager)
getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1,
intent, 0);
alarmManager.cancel(pendingIntent);
mTextView.setText("Notification canceled");
}
}
//used to save preferences....
SharedPreferences.Editor editor=myPrefdrv.edit();
editor.apply();
//used to clear preference....
SharedPreferences.Editor editor=myPrefdrv.edit();
editor.clear();
editor.apply();
Please try this code To store ,get and clear sharedprefereces data
we have pass two parameters in this method getsharedpreferences(String PREFS_NAME ,int mode )
PREFS_NAME is the name of the file.
mode is the operating mode.
StoreData
SharedPreferences pref = getSharedPreferences("mypref", 0);
SharedPreferences.Editor editor = pref.edit();
editor.putString("deviceToc",token); // Storing string
editor.apply();
getData
SharedPreferences sharedpreferences = getSharedPreferences("mypref", 0);
SharedPreferences prefs = sharedpreferences;
String string = prefs.getString("deviceToc", null);
clear data
SharedPreferences sharedpreferences = getSharedPreferences("mypref", 0);
sharedpreferences.edit().clear().commit();
You can use this instead of time picker
editors.putLong("lastlogin", new Date().getTime());
this answer

Need some help troubleshooting code that schedules daily notifications

I am new to android programming and just started working on my first app recently. I am trying to create a daily notification that a user would get at the same time every day. I've looked through documentation and some tutorials and came up with this. For some reason the code below does not work. It has no errors, runs just fine, but doesn't do the job and I can't seem to find the problem. There is also some code that is responsible for re-scheduling notifications when the device restarts but I don't think the problem lies there since I don't even get the initial notifications.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show = (Button)findViewById(R.id.btn_show);
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAlarm(true,true);
}
});
myWebView = (WebView)findViewById(R.id.webView1);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("http://google.com");
myWebView.setWebViewClient(new WebViewClient());
}
private void startAlarm(boolean isNotification, boolean isRepeat) {
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent myIntent;
PendingIntent pendingIntent;
// SET TIME HERE
Calendar calendar= Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,14);
calendar.set(Calendar.MINUTE,45);
myIntent = new Intent(MainActivity.this,AlarmNotificationReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this,0,myIntent,0);
if(!isRepeat)
manager.set(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime()+3000,pendingIntent);
else
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,pendingIntent);
}
AlarmNotificationReciever.Java
public class AlarmNotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
Intent myIntent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
context,
0,
myIntent,
FLAG_ONE_SHOT );
builder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Zodiac")
.setContentIntent(pendingIntent)
.setContentText("Check out your horoscope")
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
.setContentInfo("Info");
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1,builder.build());
}
}
It should basically schedule a notification at 14:45 after pressing the button but for some reason it doesn't.
Since Android Oreo, implicit broadcast receivers won’t work when
registered in the AndroidManifest.xml
To use Implicit Receivers in your application, you need to define them programmatically in your code, using
registerReceiver().
3.Using registerReceiver() we can programmatically register and unregisterReceiver() during the lifecycle of the activity. This way
implicit receivers would only be called when our
activity/application is alive and not at other times.
we working fine:
[public class MainActivity extends AppCompatActivity {
Button show;
WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// register custom intent filter
*registerReceiver(new AlarmNotificationReceiver(),new IntentFilter(Intent.ACTION_BATTERY_CHANGED));*
\[enter image description here\]\[1\]
show = (Button)findViewById(R.id.btn_show);
show.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onClick(View v) {
startAlarm(true,true);
}
});
myWebView = (WebView)findViewById(R.id.webView1);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("http://google.com");
myWebView.setWebViewClient(new WebViewClient());
}
#RequiresApi(api = Build.VERSION_CODES.N)
private void startAlarm(boolean isNotification, boolean isRepeat) {
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent myIntent;
PendingIntent pendingIntent;
// SET TIME HERE
Calendar calendar= Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,14);
calendar.set(Calendar.MINUTE,45);
myIntent = new Intent(MainActivity.this,AlarmNotificationReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this,0,myIntent,0);
if(!isRepeat)
manager.set(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime()+3000,pendingIntent);
else
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,pendingIntent);
}
}][1]
1)But the above code may not work in all versions i.e notofication will not came oreo(8.0) and above.beacause of NotificationBuilder is depricated and background execution limits.Go to
2)Use Notification Channel .like below
use this code.hope its works fine!!!
void issueNotification()
{
// make the channel. The method has been discussed before.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
makeNotificationChannel("CHANNEL_1", "Example channel", NotificationManager.IMPORTANCE_DEFAULT);
}
// the check ensures that the channel will only be made
// if the device is running Android 8+
NotificationCompat.Builder notification =
new NotificationCompat.Builder(this, "CHANNEL_1");
// the second parameter is the channel id.
// it should be the same as passed to the makeNotificationChannel() method
notification
.setSmallIcon(R.mipmap.ic_launcher) // can use any other icon
.setContentTitle("Notification!")
.setContentText("This is an Oreo notification!")
.setNumber(3); // this shows a number in the notification dots
NotificationManager notificationManager =
(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
assert notificationManager != null;
notificationManager.notify(1, notification.build());
// it is better to not use 0 as notification id, so used 1.
}

How to back to Main activity from the notification activity?

When I press the notification the activity opens, but when I click back the App go to background and still on the same activity.
I wanna go back to MainActivity when I click back. what's wrong in my code?
public class MainActivity extends AppCompatActivity {
NotificationManagerCompat notificationManager;
NotificationCompat.Builder n;
String ID = "a" ;
int id=1 ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void b2(View view) {
Intent i = new Intent(MainActivity.this, Main2.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(i);
PendingIntent pi = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
n = new NotificationCompat.Builder(this, ID)
.setSmallIcon(R.drawable.xx)
.setContentTitle("don't forget")
.setContentText("Hello0o0o0o")
.setContentIntent(pi)
.setAutoCancel(true);
notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(id , n.build());
id++;
}
public void b1(View view) {
Intent i4 = new Intent(this,Read.class);
startActivity(i4);
}
}
From your code I don't see the problem, but you could override the onBackPressed() function to move back to MainActivity. It's a solution. Also check if you actually are calling this function b2.

ImageButton isnt working on Custom Notification - Android

I'm trying to create a custom notification with ImageButton.
When onclicked, the ImageButton should start an activity named TaskActivity, but i'm unable to achieve this.
The followings are my codes:
MainActivity.java
public void onCreate(Bundle savedInstanceState) {
//button intents
Intent cmdIntent = new Intent(
MainActivity.this, cmdButtonListener.class);
PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(
MainActivity.this, 0, cmdIntent, 0);
//notification mgr
int notifyID = 001;
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotifyMgr = (NotificationManager)getSystemService(ns);
//new notification
int icon = R.drawable.icon3;
long when = System.currentTimeMillis();
#SuppressWarnings({ "deprecation" })
Notification notify = new Notification(icon,getString(R.string.text),when);
//remote views
RemoteViews contentView = new RemoteViews(getPackageName(),R.layout.custom_notification);
contentView.setImageViewResource(R.id.notification_image, R.drawable.icon4);
contentView.setTextViewText(R.id.notification_title, "APP TITLE");
contentView.setTextViewText(R.id.notification_text, "hello");
contentView.setOnClickPendingIntent(R.id.notification_image, pendingSwitchIntent);
notify.contentView = contentView; //set
//notification intent
Intent nIntent = new Intent(MainActivity.this,MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, nIntent, 0);
notify.contentIntent = contentIntent;
mNotifyMgr.notify(notifyID,notify);
}
public class cmdButtonListener extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent){
System.out.println("Here, I am here");
Intent newAct = new Intent(MainActivity.this, TaskActivity.class);
startActivity(newAct);
}
}
Android Manifest
<receiver android:name=".MainActivity$cmdButtonListener" />
I dont know, where i'm wrong as i'm doing exactly as it is shown in most of the tutorials online. :(
Finally I've found a solution...
Declare the below variable
private static Context mContext;
Add below code inside public void onCreate(Bundle savedInstanceState) {
mContext = this;
Finally, change the below piece of code in public class cmdButtonListener extends BroadcastReceiver{
Intent newAct = new Intent(MainActivity.this, TaskActivity.class);
startActivity(newAct);
To
Intent Act = new Intent(mContext,TaskActivity.class);
mContext.startActivity(Act);

Error with Notification.Builder in notify

Hello I am new to Android, and I 'm trying to create notifications Notification.Builder and I failed . When launching the notification I get error
nm.notify(IDNOTIFICACIONUNO,notif); // Error in notif
I have downloaded the API 'S 16 17 18 19 23,
and this is all code :
public class MainActivity extends AppCompatActivity {
NotificationManager nm;
private static final int IDNOTIFICACIONUNO = 1;
Notification notif;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnLanzar = (Button) findViewById(R.id.boton_notificacion);
btnLanzar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),segundaVentana.class);
PendingIntent intencionPendiente = PendingIntent.getActivity(getApplicationContext(),0,i,0);
Notification.Builder notif = new Notification.Builder(getApplicationContext());
notif.setSmallIcon(R.drawable.tree);
notif.setTicker("App Nature ¡TIP!");
notif.setWhen(System.currentTimeMillis());
notif.setContentTitle("App Nature ¡TIP!");
notif.setContentText("Cierra la llave, cuando te estes cepillando");
notif.setContentInfo("TIP");
notif.setContentIntent(intencionPendiente);
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
nm.notify(IDNOTIFICACIONUNO,notif);
}
});
}
I also libraries . Thank you for your help
there is a ` characheter after notif.setSmallIcon(R.drawable.tree);
remove that charachter and code will run.
final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//Connect to the button
Button iconBtn = (Button) findViewById(R.id.btn_icon);
//Set the button on click listener
iconBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, 0, notificationIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
Notification notification = builder.setContentIntent(contentIntent).setTicker("This is a notification marquee")
.setSmallIcon(R.drawable.ic_launcher).setWhen(System.currentTimeMillis())
.setAutoCancel(true).setContentTitle("Message Title")
.setContentText("Message Content").build();
//Show the notification
nm.notify(1, notification);
}
});

Categories

Resources