Issues in implementing notification to calender in android - android-layout

hiii
I am new to to android.I have created a calender where I am able to set alarm.
But the problem is I am unable to receive any message i.e if i set an alarm of 2.30pm,A message should appear that alarm received.I am not receiving this message ..Please suggest..
Please help
Here is the code...
alarm.java
package com.example.notificationalarm;
import java.util.Calendar;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
public class Alarm extends ActionBarActivity
{
TimePicker myTimePicker;
Button buttonstartSetDialog;
TextView textAlarmPrompt;
TimePickerDialog timePickerDialog;
final static int RQS_1 = 1;
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alarm);
textAlarmPrompt=(TextView)findViewById(R.id.alarm);
buttonstartSetDialog = (Button)findViewById(R.id.startSetDialog);
buttonstartSetDialog.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
textAlarmPrompt.setText("");
openTimePickerDialog(false);
}
});
}
private void openTimePickerDialog(boolean is24r){
Calendar calendar = Calendar.getInstance();
timePickerDialog = new TimePickerDialog(
Alarm.this,
onTimeSetListener,
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
is24r);
timePickerDialog.setTitle("Set Alarm Time");
timePickerDialog.show();
}
OnTimeSetListener onTimeSetListener= new OnTimeSetListener(){
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar calNow = Calendar.getInstance();
Calendar calSet = (Calendar) calNow.clone();
calSet.set(Calendar.HOUR_OF_DAY, hourOfDay);
calSet.set(Calendar.MINUTE, minute);
calSet.set(Calendar.SECOND, 0);
calSet.set(Calendar.MILLISECOND, 0);
if(calSet.compareTo(calNow) <= 0){
//Today Set time passed, count to tomorrow
calSet.add(Calendar.DATE, 1);
}
setAlarm(calSet);
}};
private void setAlarm(Calendar targetCal){
textAlarmPrompt.setText(
"\n\n***\n"
+ "Alarm is set# " + targetCal.getTime() + "\n"
+ "***\n");
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
}
}
AlarmReceiver .java
public class AlarmReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context arg0, Intent arg1)
{
Toast.makeText(arg0, "Alarm received!", Toast.LENGTH_LONG).show();
}
}

How have you declared your AlarmManager in the Manifest?
When I look on the code I cannot find any bug, so let's try this in your manifest.xml
<receiver
android:name="your.package.AlarmReceiver"/>
This might help

Related

OnClicklistener in RecyclerView [duplicate]

Thank you in advance and dont be very hard with me, it is my first question.
I was trying to add a new item to my recyclerView through the adapter by declaring a method in my adapter called addItem(String newItem)
Then I tried to call this method when the floating button is clikced and the problem is that the method does not even appear when i hit cntrl+space and if i write it down it gets on red.
I have already tried to rebuild the project and nothing changes.
¿Any ideas about how to solve it?
MainActivity class
package com.example.sakur.recyclerviewapp;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private FloatingActionButton mFloatingActionButton;
private List<String> recyclerItems = Collections.emptyList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerItems = new ArrayList<>();
recyclerItems.add("First item");
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyAdapter(recyclerItems);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.floating_action_button);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String itemNuevo = "New Card";
mAdapter.addItem(itemNuevo);
Snackbar.make(view, "Item added successfully", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
and the MyAdapter class
package com.example.sakur.recyclerviewapp;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;
/**
* Created by Sakur on 19/12/2015.
*/
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<String> mDataset= Collections.emptyList();
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(List<String> myDataset) {
mDataset = myDataset;
}
public void addItem(String newItem){
mDataset.add(newItem);
notifyDataSetChanged();
}
// Create new views (invoked by the layout manager)
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_card, parent, false);
// set the view's size, margins, paddings and layout parameters
//...
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.mTextView.setText(mDataset.get(position));
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView mTextView;
public ImageView mImageView;
public ViewHolder(View v) {
super(v);
mTextView = (TextView) v.findViewById(R.id.text_card);
}
}
}
addItem(String) is not a method of RecyclerView.Adapter, but of your MyAdapter subclass. Obviously, RecyclerView.Adapter has no knowledge of the existence neither of your MyAdapter nor of your addItem(String).
you can either change
private RecyclerView.Adapter mAdapter;
into
private MyAdapter mAdapter;
or cast mAdapter. E.g.
if (mAdater instanceof MyAdapter) {
((MyAdapter) mAdapter).addItem(...);
}

Alarm notification is not working for API>=26 android emulators

I am trying to send a notification that appears under the top navigation bar as follows:
My codes work for android emulator with API < 26, but they do not work for android emulator with API >= 26. I found that it is because I need to add channel, so I did. However, although the codes compile well and go through all loops, and there is no error in logcat. Still, the notification does not appear on the screen.
Any help will be greatly appreciated. FYI, here is my FragmentAlarm.java:
package com.example.dailybible3;
import android.app.AlarmManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
import java.util.Calendar;
public class FragmentAlarm extends Fragment {
private View view;
private CheckBox box_sun, box_mon, box_tue, box_wed, box_thu, box_fri, box_sat;
private CheckBox order_history, order_bible;
private CheckBox ninety_days, one_year;
private Button btn_save;
public static FragmentAlarm newInstance() {
FragmentAlarm fragmentAlarm = new FragmentAlarm();
return fragmentAlarm;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_alarm, container, false);
/* start of set notification */
createNotificationChannel();
/* end of set notification */
//save button
btn_save = (Button) view.findViewById(R.id.save_button);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message = "This is a notificaiton example";
NotificationCompat.Builder builder = new NotificationCompat.Builder(
getContext(), "notifyBibleVerse"
)
.setSmallIcon(R.drawable.ic_bible_english)
.setContentTitle("Today's Verse")
.setContentText("Genesis 1 - 3")
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
/* start of setting notification */
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("message", message);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
NotificationManager notiifcationManager = (NotificationManager) getActivity().getSystemService(
Context.NOTIFICATION_SERVICE
);
notiifcationManager.notify(0, builder.build());
toastMessage("Alarm is set!");
}
});
return view;
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "DailyBibleChannel";
String description = "Channel for Bible Verse Reminder";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("notifyBibleVerse", name, importance);
channel.setDescription(description);
}
}
private void toastMessage(String message){
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
}
}
I am still not sure how to solve the above problem, but I found the working code from here: https://codinginflow.com/tutorials/android/alarmmanager. The major difference I see is that the working code has AlarmManager. Hope this help someone who is having troubles to set a notification.

save last position of videoView saved by sharedprefrence and start in last position (android studio)

save last position of videoView saved by sharedprefrence and start in last position (android studio)
hello I serch for my problam in stackaverflow and other refrences but I dont get my answer
.
I use VideoView In my app
I want to save the last position of videview in a sharedPrefrence to start again from the last position but it start in 0 every time
please check my code and tel me what should i do.
package com.rewass.qurankurdishaudiotranslatev2.activitys;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import com.rewass.qurankurdishaudiotranslatev2.R;
import com.rewass.qurankurdishaudiotranslatev2.adapters.RecyclerViewAdapter;
import com.rewass.qurankurdishaudiotranslatev2.model.ModelRecycler;
import com.rewass.qurankurdishaudiotranslatev2.text.Text002;
import java.util.ArrayList;
import java.util.List;
public class A002 extends AppCompatActivity {
List<ModelRecycler> listItems;
private InterstitialAd mInterstitialAd;
String AudioURL = "https://download.quranicaudio.com/quran/mishaari_raashid_al_3afaasee/002.mp3";
VideoView videoView;
ProgressBar progressBar008;
TextView te008;
int progress;
RecyclerView myrv;
String kurdish002 = "http://sirwaan.com/aaap/audios/kurdish/sound/quran/qurankurdish/002.mp3";
String v2kurdish002 = "https://sirwaan.com/aaap/audios/kurdish/sound/quran/newversionqurankurdish/002.mp3";
Handler handler;
GridLayoutManager layoutManager;
int seekkk;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a002);
audioSora();
}
SharedPreferences preferences ;
private void audioSora() {
preferences = getSharedPreferences("pref55",MODE_PRIVATE);
videoView = findViewById(R.id.videoview002);
videoView.setVideoPath(v2kurdish002);
//control media
MediaController mediaController = new MediaController(this);
//set view with controller
videoView.setMediaController(mediaController);
//set Controller to view
mediaController.setAnchorView(videoView);
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
SharedPreferences.Editor editor = preferences.edit();
int progress = videoView.getCurrentPosition();
editor.putInt("seekto", progress);
editor.apply();
seekkk = preferences.getInt("seekto", 0);
Toast.makeText(A002.this, seekkk+"", Toast.LENGTH_SHORT).show();
handler.postDelayed(this, 1000); }};
handler.postDelayed(r, 1000);
videoView.seekTo(seekkk);
videoView.start();
}
});
}
}
private int time = 0;
private ScheduledExecutorService mScheduledExecutorService;
Runnable getPositionVideo = () -> {
time = binding.epVideoView.getCurrentPosition();
Log.d(TAG, ": " + time);
};
binding.epVideoView.setOnPreparedListener(mediaPlayer -> {
mediaController.setAnchorView(binding.epVideoView);
binding.epVideoView.start();
mScheduledExecutorService = new ScheduledThreadPoolExecutor(1);
mScheduledExecutorService.scheduleWithFixedDelay(() -> {
runOnUiThread(getPositionVideo);
MediaControllerCustom.init(url, time);
}, 1000, 1000, TimeUnit.MILLISECONDS);
});

Why does the program not call the method "onLocationChanged"?

i wrote this simple code for getting the GPS coordinates but it doesnt call the method "onChangedLocation". I know it should jump into the method only when the coordinates change, but at first start it always should jump into that method or not?
It should display the longtitude and latitude in the catlog.
Im using my phone for debugging.
package tabs;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import androfenix.whetoo.R;
public class Tab1 extends ListFragment implements LocationListener {
double latitude;
double longitude;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_local, container, false);
String[] abc = {"Message1", "Message2", "Message3", "Message1", "Message2", "Message3", "Message1", "Message2", "Message3", "Message1", "Message2", "Message3"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, abc);
setListAdapter(adapter);
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
return v;
}
#Override
public void onLocationChanged(Location location) {
Log.d("onLocationChanged", "onLocationChanged wird aufgerufen");
longitude = location.getLongitude();
String name = String.valueOf(longitude);
Log.d("longtitude", name);
latitude = location.getLatitude();
String name2 = String.valueOf(latitude);
Log.d("latitude", name2);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}

How do i send my location online in android studio

I'm a beginner to android studio. I'm trying to build an my project app that can send my location to another client with just one click. i.e through online server.
At first I'm trying to test if my button gets the latitude and longitude value from the LocationListener.
below is my mainActivity
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
public class MainActivity extends AppCompatActivity implements View.OnClickListener, LocationListener {
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
private String myLoc = " ";
GoogleMap mMap;
Button bShare;
private static final int ERROR_DIALOG_REQUEST = 9001;
private static final double Shillong_Lat = 25.5667,
Shillong_Lng = 91.8833;
private GoogleApiClient mLocationClient;
private com.google.android.gms.location.LocationListener mListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 1000, this);
if (servicesOK() ){
setContentView(R.layout.activity_map);
bShare = (Button) findViewById(R.id.bShare);
bShare.setOnClickListener(this);
if(initMap()) {
Toast.makeText(MainActivity.this, "Ready to map", Toast.LENGTH_SHORT).show();
gotoLocation(Shillong_Lat, Shillong_Lng, 15 );
mMap.setMyLocationEnabled(true);
}else{
Toast.makeText(this, "Map not Connected!", Toast.LENGTH_SHORT).show();
}
}else {
setContentView(R.layout.activity_main);
}
}
private void gotoLocation(double latitude, double longitude, float zoom) {
LatLng latLng = new LatLng(latitude, longitude);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(
latLng, zoom);
mMap.moveCamera(update);
}
public boolean servicesOK(){
int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(isAvailable == ConnectionResult.SUCCESS){
return true;
}else if(GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable, this, ERROR_DIALOG_REQUEST);
dialog.show();
}else {
Toast.makeText(this, "Can't connect to map", Toast.LENGTH_SHORT).show();
}return false;
}
private boolean initMap() {
if (mMap == null){
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = mapFragment.getMap();
}
return(mMap != null);
}
#Override
public void onLocationChanged(Location location) {
Toast.makeText(MainActivity.this, "Location changed: " + location.getLatitude() + ", " + location.getLongitude(), Toast.LENGTH_SHORT).show();
double latitude = location.getLatitude();
double longitude = location.getLongitude();
myLoc = GetAddressDetailed(latitude, longitude);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.bShare){
Toast.makeText(MainActivity.this, "Sent: " + myLat + ", " + myLon ,Toast.LENGTH_SHORT).show();
}
}
}

Resources