I'm trying to build this app which checks a folder size on an interval, and if the folder size is bigger than whatever user have set, a notification appears. The problem is when user disables the notification, it still keeps on notifying ("ShowNotif" is called), what am I doing wrong?
ScheduleFragment.java
public class ScheduleFragment extends Fragment {
SharedPreferences.Editor editor;
AlarmManager manager;
PendingIntent pendingIntent;
SharedPreferences share;
EditText telegSizeText;
CheckBox telegramSize;
private boolean telegramSizeIsSet = false;
CheckBox notif;
public ScheduleFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_schedule, container, false);
telegramSize = (CheckBox)view.findViewById(R.id.telegramSize);
telegSizeText = (EditText)view.findViewById(R.id.telegSizeText);
notif = (CheckBox) view.findViewById(R.id.notif);
share = getActivity().getSharedPreferences("setting", 0);
editor = this.share.edit();
telegramSize.setChecked(share.getBoolean("telegram_selected", false));
telegramSizeIsSet = true;
int var2 = share.getInt("telegram_size", -1);
if(var2 != -1) {
telegSizeText.setText(String.valueOf(var2));
} else {
telegSizeText.setText("");
}
this.telegramSize.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton var1, boolean var2) {
if (telegramSizeIsSet) {
if(!var2) {
manager = (AlarmManager)getContext().getSystemService(Context.ALARM_SERVICE);
Intent var11 = new Intent(getActivity(), ShowNotif.class);
pendingIntent = PendingIntent.getBroadcast(getActivity(), 1,var11,PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntentNoti = PendingIntent.getBroadcast(getActivity(), 1, var11,PendingIntent.FLAG_UPDATE_CURRENT);
manager.cancel(pendingIntent);
manager.cancel(pendingIntentNoti);
Toast.makeText(getContext(), "Disabled!", Toast.LENGTH_SHORT).show();
editor.putBoolean("telegram_selected", false);
editor.putInt("telegram_size", -1);
telegSizeText.setText("");
editor.commit();
return;
}
if(telegSizeText.getText().toString() == null || telegSizeText.getText().toString().equals("")) {
Toast.makeText(getContext(), "Can't be empty", Toast.LENGTH_SHORT).show();
telegramSizeIsSet = false;
telegramSize.setChecked(false);
telegramSizeIsSet = true;
return;
}
Intent var9 = new Intent(getActivity(), CheckTelegramSizeReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, var9, 0);
manager = (AlarmManager)getContext().getSystemService(Context.ALARM_SERVICE);
manager.cancel(pendingIntent);
editor.putInt("telegram_size", Integer.valueOf(telegSizeText.getText().toString()).intValue());
editor.putBoolean("telegram_selected", true);
editor.commit();
manager = (AlarmManager)getContext().getSystemService(Context.ALARM_SERVICE);
manager.setRepeating(0, System.currentTimeMillis(), (long) 10000, pendingIntent); //check every 10 seconds
Toast.makeText(getContext(), "Enabled!", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}}
CheckTelegramSizeReceiver.java
public class CheckTelegramSizeReceiver extends BroadcastReceiver {
private AlarmManager manager;
private AlarmManager manager2;
private AlarmManager manager3;
private boolean notificationCanceled;
boolean notificationCreated = false;
String path;
private PendingIntent pendingIntent;
private PendingIntent pendingIntent2;
long totalSizes = 0L;
int userSelectedSize = 0;
private long getFileSize(String var1) {
long var2 = 0L;
File[] var4 = (new File(var1)).listFiles();
if (var4 != null) {
for (int var5 = 0; var5 < var4.length; ++var5) {
File var6 = var4[var5];
if (var6.isDirectory()) {
var2 += this.getFileSize(var6.getPath());
} else {
var2 += var6.length();
}
}
}
return var2;
}
public void onReceive(final Context var1, Intent var2) {
File var3 = Environment.getExternalStorageDirectory();
this.path = var3 + "/Telegram";
(new AsyncTask<Void, Integer, Integer>() {
protected Integer doInBackground(Void... var1x) {
totalSizes = getFileSize(path) / 1048576L;
//
SharedPreferences var2 = var1.getSharedPreferences("setting", 0);
userSelectedSize = var2.getInt("telegram_size", -1);
return 1;
}
protected void onPostExecute(Integer var1x) {
SharedPreferences var2 = var1.getSharedPreferences("setting", 0);
Editor var3 = var2.edit();
CheckTelegramSizeReceiver.this.userSelectedSize = var2.getInt("telegram_size", -1);
CheckTelegramSizeReceiver.this.notificationCreated = var2.getBoolean("notificationIsShowing", false);
CheckTelegramSizeReceiver.this.notificationCanceled = var2.getBoolean("notificationIsShowingCanceled", false);
if ((int) CheckTelegramSizeReceiver.this.totalSizes > CheckTelegramSizeReceiver.this.userSelectedSize && !CheckTelegramSizeReceiver.this.notificationCreated) {
Intent var11 = new Intent(var1, ShowNotif.class);
CheckTelegramSizeReceiver.this.pendingIntent = PendingIntent.getBroadcast(var1, 1, var11, 0);
CheckTelegramSizeReceiver.this.manager2 = (AlarmManager) var1.getSystemService(Context.ALARM_SERVICE);
CheckTelegramSizeReceiver.this.manager2.setRepeating(0, System.currentTimeMillis(), (long) 28800000, CheckTelegramSizeReceiver.this.pendingIntent);
var3.putBoolean("notificationIsShowing", true).commit();
var3.putBoolean("notificationIsShowingCanceled", false).commit();
CheckTelegramSizeReceiver.this.notificationCreated = true;
CheckTelegramSizeReceiver.this.notificationCanceled = false;
}
if ((int) CheckTelegramSizeReceiver.this.totalSizes < CheckTelegramSizeReceiver.this.userSelectedSize && CheckTelegramSizeReceiver.this.notificationCreated && !CheckTelegramSizeReceiver.this.notificationCanceled) {
System.out.println("test");
Intent var5 = new Intent(var1, ShowNotif.class);
CheckTelegramSizeReceiver.this.pendingIntent = PendingIntent.getBroadcast(var1, 1, var5, 0);
CheckTelegramSizeReceiver.this.manager2 = (AlarmManager) var1.getSystemService(Context.ALARM_SERVICE);
CheckTelegramSizeReceiver.this.manager2.cancel(CheckTelegramSizeReceiver.this.pendingIntent);
CheckTelegramSizeReceiver.this.notificationCreated = false;
CheckTelegramSizeReceiver.this.notificationCanceled = true;
var3.putBoolean("notificationIsShowingCanceled", true).commit();
var3.putBoolean("notificationIsShowing", false).commit();
}
}
}).execute(null, null, null);
}}
ShowNotif.java
public class ShowNotif extends BroadcastReceiver {
public void onReceive(Context var1, Intent var2) {
int var3 = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
if (var3 <= 22 && var3 >= 10) {
Uri var4 = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Bitmap var5 = BitmapFactory.decodeResource(var1.getResources(), R.drawable.icon_notif);
NotificationCompat.Builder var6 = (new NotificationCompat.Builder(var1)).setSmallIcon(R.drawable.icon_notif).setLargeIcon(var5).setContentTitle("My App").setContentText("Notification Text").setSound(var4).setAutoCancel(true);
var6.setContentIntent(PendingIntent.getActivity(var1, 0, new Intent(var1, MainActivity.class), 0));
((NotificationManager) var1.getSystemService(Context.NOTIFICATION_SERVICE)).notify(0, var6.build());
}
}}
Thanks in advance.
if (telegramSizeIsSet) {
if(!var2) {
Intent var3 = new Intent(getActivity(), CheckTelegramSizeReceiver.class);
manager = (AlarmManager)getContext().getSystemService(Context.ALARM_SERVICE);
pendingIntent = PendingIntent.getBroadcast(var1, 1,var11,PendingIntent.FLAG_UPDATE_CURRENT);
pendingIntentNoti = PendingIntent.getBroadcast(var1, 1, var11,PendingIntent.FLAG_UPDATE_CURRENT);
manager.cancel(pendingIntent);
manager.cancel(pendingIntentNoti);
Toast.makeText(getContext(), "Disabled!", Toast.LENGTH_SHORT).show();
editor.putBoolean("telegram_selected", false);
editor.putInt("telegram_size", -1);
telegSizeText.setText("");
editor.commit();
return;
}
Basically you just cancel the Alarm for CheckTelegramSizeReceiver receiver. but you forget to cancel the alarm set up by CheckTelegramSizeReceiver receiver that is ShowNoti Receiver. So ShowNoti receiver shows the notification again and again so you need to cancel the ShowNoti alaram too and use FLAG_UPDATE_CURRENT instead of 0. Thanks It may help you!
Related
Im trying to make a service that would provide data of usagestat every x second. However i always getting the same value after x second. I already clear the map to include new data set from usagemanager. below is my service class thank you in advance.
I do know that in order to retrieve queries every x time, we may use queryevent. However, the total time in foreground for this fit my project, and i already tested using the code for adapter. In the adapter, it do retrieve usage time, however it only provide new value on restarting the activity where the adapter used.
public class PushService extends Service {
private static final int NOTIF_ID = 1;
private static final String NOTIF_CHANNEL_ID = "Channel_Id_1";
private static final String NOTIF_CHANNEL_ID2 = "Channel_Id_2";
private static final int _DISPLAY_ORDER_USAGE_TIME = 0;
private static final int _DISPLAY_ORDER_LAST_TIME_USED = 1;
private static final int _DISPLAY_ORDER_APP_NAME = 2;
private static final boolean localLOGV = false;
private int mDisplayOrder = _DISPLAY_ORDER_USAGE_TIME;
private AppNameComparator mAppLabelComparator;
private LastTimeUsedComparator mLastTimeUsedComparator;
private UsageTimeComparator mUsageTimeComparator;
private PackageManager mPm;
private UsageStatsManager mUsageStatsManager;
public HashMap<String, Long> mapToFirebase = new HashMap<>();;
public ArrayList<UsageStats> mPackageStats;
public ArrayMap<String, String> mAppLabelMap;
public List<UsageStats> stats;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
/*notice*/
startForeground();
if (intent != null){
String uid = intent.getStringExtra("parentUID");
if (!uid.equals("")){
Toast.makeText(this, uid, Toast.LENGTH_SHORT).show();
Handler ha=new Handler();
ha.postDelayed(new Runnable() {
#Override
public void run() {
//call function
pushAppList();
mapToFirebase.clear();
loadDataToMapForFirebase();
Log.d("mapservice", mapToFirebase.toString());
ha.postDelayed(this, 5000);
}
}, 10000);
}
}
return super.onStartCommand(intent, flags, startId);
}
public static class AppNameComparator implements Comparator<UsageStats> {
private Map<String, String> mAppLabelList;
AppNameComparator(Map<String, String> appList) {
mAppLabelList = appList;
}
#Override
public final int compare(UsageStats a, UsageStats b) {
String alabel = mAppLabelList.get(a.getPackageName());
String blabel = mAppLabelList.get(b.getPackageName());
return alabel.compareTo(blabel);
}
}
public void pushAppList(){
mAppLabelMap = new ArrayMap<>();
mPackageStats = new ArrayList<>();
mPm = getPackageManager();
mUsageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -5);
mLastTimeUsedComparator = new LastTimeUsedComparator();
mUsageTimeComparator = new UsageTimeComparator();
stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, cal.getTimeInMillis(), System.currentTimeMillis());
if (stats == null) {
return;
}
ArrayMap<String, UsageStats> map = new ArrayMap<>();
int statCount = stats.size();
for (int i = 0; i < statCount; i++) {
Log.d("", String.valueOf(stats.get(i).getTotalTimeInForeground()));
android.app.usage.UsageStats pkgStats = stats.get(i);
// load application labels for each application
try {
ApplicationInfo appInfo = mPm.getApplicationInfo(pkgStats.getPackageName(), 0);
String label = appInfo.loadLabel(mPm).toString();
mAppLabelMap.put(pkgStats.getPackageName(), label);
UsageStats existingStats =
map.get(pkgStats.getPackageName());
if (existingStats == null) {
map.put(pkgStats.getPackageName(), pkgStats);
} else {
existingStats.add(pkgStats);
}
} catch (PackageManager.NameNotFoundException e) {
// This package may be gone.
}
}
mPackageStats.addAll(map.values());
// Sort list
mAppLabelComparator = new AppNameComparator(mAppLabelMap);
sortList();
}
public static class LastTimeUsedComparator implements Comparator<UsageStats> {
#Override
public final int compare(UsageStats a, UsageStats b) {
// return by descending order
return (int)(b.getLastTimeUsed() - a.getLastTimeUsed());
}
}
public static class UsageTimeComparator implements Comparator<UsageStats> {
#Override
public final int compare(UsageStats a, UsageStats b) {
return (int)(b.getTotalTimeInForeground() - a.getTotalTimeInForeground());
}
}
private void sortList() {
if (mDisplayOrder == _DISPLAY_ORDER_USAGE_TIME) {
if (localLOGV) Log.i(TAG, "Sorting by usage time");
Collections.sort(mPackageStats, mUsageTimeComparator);
} else if (mDisplayOrder == _DISPLAY_ORDER_LAST_TIME_USED) {
if (localLOGV) Log.i(TAG, "Sorting by last time used");
Collections.sort(mPackageStats, mLastTimeUsedComparator);
} else if (mDisplayOrder == _DISPLAY_ORDER_APP_NAME) {
if (localLOGV) Log.i(TAG, "Sorting by application name");
Collections.sort(mPackageStats, mAppLabelComparator);
}
}
public void loadDataToMapForFirebase(){
/*TODO UPDATE DATA ONBACKGROUND*/
String system_sign = "android";
PackageManager pm = getPackageManager();
if (mPackageStats.size() != 0){
for (int i = 0; i < mPackageStats.size(); i++){
if (pm.checkSignatures(system_sign, mPackageStats.get(i).getPackageName()) == PackageManager.SIGNATURE_MATCH) {
Log.d("CheckAppSys", mPackageStats.get(i).getPackageName() + " is sys.");
} else {
String usagetime = DateUtils.formatElapsedTime(mPackageStats.get(i).getTotalTimeInForeground() / 1000);
Pattern special= Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Matcher matcher = special.matcher(Objects.requireNonNull(mAppLabelMap.get(mPackageStats.get(i).getPackageName())));
boolean constainsSymbols = matcher.find();
if(!constainsSymbols){
mapToFirebase.put(mAppLabelMap.get(mPackageStats.get(i).getPackageName()), mPackageStats.get(i).getTotalTimeInForeground());
}
Log.d("maptofirebase", mapToFirebase.toString());
Log.d("CheckApp", mPackageStats.get(i).getPackageName() + " is not sys.");
}
}
}
}
private void startForeground() {
Intent notificationIntent = new Intent(this, UsageStatsActivity.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel1 = new NotificationChannel(
NOTIF_CHANNEL_ID,
"Channel 1",
NotificationManager.IMPORTANCE_HIGH
);
channel1.setDescription("This is channel 1");
NotificationChannel channel2 = new NotificationChannel(
NOTIF_CHANNEL_ID2,
"Channel 2",
NotificationManager.IMPORTANCE_LOW
);
channel2.setDescription("This is channel 2");
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel1);
manager.createNotificationChannel(channel2);
}
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
startForeground(NOTIF_ID, new NotificationCompat.Builder(this,
NOTIF_CHANNEL_ID) // don't forget create a notification channel first
.setOngoing(true)
.setSmallIcon(R.drawable.logo)
.setContentTitle(getString(R.string.app_name))
.setContentText("Monitoring apps.")
.setContentIntent(pendingIntent)
.build());
}
}
I'm trying to start a service that adds an item to RecyclerView every 24 hours (every day). I used this code but it doesn't work:
BackgroundService.java
public class BackgroundService extends Service {
private boolean isRunning;
private Context context;
private Thread backgroundThread;
SharedPreferences pref;
String isMorningChecked;
String isEveningChecked;
String isNightChecked;
String isEchuraistChecked;
String isConfessChecked;
String isBibleChecked;
String Date;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
this.context = this;
this.isRunning = false;
this.backgroundThread = new Thread(addNewNote);
}
private Runnable addNewNote = new Runnable() {
#Override
public void run() {
Log.e("isRunning", "Yeeeeeeeeeees!");
pref = getApplicationContext().getSharedPreferences("checkStates", 0);
String checkMorningState = pref.getString("morning", "False");
String checkEveningState = pref.getString("evening", "False");
String checkNightState = pref.getString("night", "False");
String checkEchuraistState = pref.getString("echuraist", "False");
String checkConfessState = pref.getString("confess", "False");
String checkBibleState = pref.getString("bible", "False");
String writeYourNotes = pref.getString("writeNotes", "");
SimpleDateFormat sdf = new SimpleDateFormat("E", new Locale("ar"));
final SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy.MM.dd");
final Timestamp timestamp = new Timestamp(System.currentTimeMillis());
Date = sdf2.format(timestamp).toString();
if(checkMorningState.equals("True")){
isMorningChecked = "+";
}else{
isMorningChecked = "-";
}
if(checkEveningState.equals("True")){
isEveningChecked = "+";
}else{
isEveningChecked = "-";
}
if(checkNightState.equals("True")){
isNightChecked = "+";
}else{
isNightChecked = "-";
}
if(checkEchuraistState.equals("True")){
isEchuraistChecked = "+";
}else{
isEchuraistChecked = "-";
}
if(checkConfessState.equals("True")){
isConfessChecked = "+";
}else{
isConfessChecked = "-";
}
if(checkBibleState.equals("True")){
isBibleChecked = "+";
}else{
isBibleChecked = "-";
}
AppDatabase db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "Note").allowMainThreadQueries().build();
db.userDao().insertAll(new Note(sdf.format(timestamp), sdf2.format(timestamp).toString(), isMorningChecked, isEveningChecked, isNightChecked, isEchuraistChecked, isConfessChecked, isBibleChecked, writeYourNotes));
stopSelf();
}
};
#Override
public void onDestroy() {
super.onDestroy();
this.isRunning = false;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(!this.isRunning){
this.isRunning = true;
this.backgroundThread.start();
}
return START_STICKY;
}
}
BoardCastReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, BackgroundService.class));
}
}
Home.java
Intent alarm = new Intent(this, AlarmReceiver.class);
boolean alarmRunning = ((PendingIntent.getBroadcast(this,0,alarm,PendingIntent.FLAG_NO_CREATE)) != null);
if(alarmRunning == false){
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,alarm,0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 1000, pendingIntent);
I have tried this but the Service works once or twice and then it stops and sometimes it gives me the following error:
java.lang.IllegalStateException: Not allowed to start service Intent
Background service can not be used for long running tasks on Android 8.0 onwards. Please use JobScheduler API or Workmanager to achieve the desired results. Consult the following link for details.
https://developer.android.com/topic/libraries/architecture/workmanager
I'm tried to manage a set of push notifications.
1. My first problem is that only last notification set up receive my smartphone. I believe that it hasn't create new instance but it overwrite the unique istance. How can I solve it?
2. My second problem is that i want that from app, the user can delete a schedule of a determinate notification.
This is my code in MovieAdapter.java (main methods are getNotification, scheduleNotification and deleteNotification ):
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.ViewHolder>{
private PendingIntent pendingIntent = null;
private Context context;
private List<Movie> movies;
private View itemView;
private RecyclerView rv;
//per la data
private EditText fromDateEtxt;
private EditText eReminderTime;
private boolean active = false;
private int mese = (Calendar.getInstance().getTime().getMonth())+1;
private int anno = (Calendar.getInstance().getTime().getYear())+1900 ;
private int giorno = Calendar.getInstance().getTime().getDate();
private int ora;
private int minuti;
private int secondi;
private boolean modify = false;
private Date datatime;
private static String tipo = "NOTIFY";
//non sono ancora sicuro se metterlo qui
private WorkManager mWorkManager;
static MoviesFragment fragmentInstance;
static SectionsPageAdapter spa;
public MoviesAdapter(Context context, List<Movie> movies, MoviesFragment fragment) {
this.context = context;
this.movies = movies;
this.fragmentInstance = fragment;
this.spa = null;
}
public MoviesAdapter(Context context, List<Movie> movies, SectionsPageAdapter spa) {
this.context = context;
this.movies = movies;
this.spa = spa;
this.fragmentInstance = null;
}
#Override
public MoviesAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
/*if(getTipo().equals("Suggested"))
{
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_movie, parent, false);
return new ViewHolder(itemView);
}
else if(getTipo().equals("Watched"))
{
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_movie_watched, parent, false);
return new ViewHolder(itemView);
}
else if(getTipo().equals("Notify"))
{*/
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_movie, parent, false);
return new ViewHolder(itemView);
//}
//return null;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
mWorkManager = WorkManager.getInstance();
final Movie movie = movies.get(position);
Glide.with(context)
.load(movie.getPosterUrl())
.placeholder(R.drawable.poster_placeholder)
.into(holder.posterView);
holder.title_movie.setText(movie.getTitle());
// prende solo la data + anno
String yourString = String.valueOf(movie.getReleaseDate());
String date = yourString.substring(0, 10);
String year = yourString.substring(yourString.length()-5,yourString.length());
//per fare il testo bold
final SpannableStringBuilder sb = new SpannableStringBuilder("Release: "+date+year);
final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD); // Span to make text bold
final StyleSpan nss = new StyleSpan(Typeface.NORMAL); //Span to make text italic
sb.setSpan(bss, 0, 7, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make first 4 characters Bold
sb.setSpan(nss, 7, sb.length()-1, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make last 2 characters Italic
holder.release_date.setText(sb);
if(getTipo().equals("NOTIFY")) {
Toast.makeText(context, "Notify", Toast.LENGTH_LONG).show();
holder.movie_notify.setVisibility(View.VISIBLE);
holder.notifyButton.setVisibility(View.GONE);
holder.changeDateTimeButton.setVisibility(View.VISIBLE);
holder.watchedButton.setVisibility(View.VISIBLE);
holder.removeButton.setVisibility(View.VISIBLE);
String yourString1 = String.valueOf(movie.getNotifyDate());
Log.i("STRINGA",yourString1);
if(!(yourString1.equals("null"))) {
date = yourString1.substring(0, 16);
year = yourString1.substring(yourString1.length() - 5, yourString1.length());
//per fare il testo bold
final SpannableStringBuilder sb1 = new SpannableStringBuilder("Notify: " + date + year);
final StyleSpan bss1 = new StyleSpan(android.graphics.Typeface.BOLD); // Span to make text bold
final StyleSpan nss1 = new StyleSpan(Typeface.NORMAL); //Span to make text normal
sb1.setSpan(bss1, 0, 6, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make first 4 characters Bold
sb1.setSpan(nss1, 6, sb.length() - 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make last 2 characters Italic
holder.movie_notify.setText(sb1);
}
holder.removeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MovieDatabase md = new MovieDatabase(context);
md.deleteMovie(movies.get(position).getId());
deleteNotify(pendingIntent);
refreshLists();
}
});
holder.changeDateTimeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alertFormElements(position, true);
}
});
holder.watchedButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MovieDBModel mdm = new MovieDBModel(movies.get(position).getId(), movies.get(position).getTitle(), movies.get(position).getOverview(),
movies.get(position).getPosterUrl(), movies.get(position).getBackdropUrl(), movies.get(position).getTrailerUrl(),
movies.get(position).getReleaseDate(), movies.get(position).getRating(), movies.get(position).isAdult(),null);
MovieDatabase.updateMovieType(movies.get(position).getId(), 2,MainActivity.getMovieDatabase());
String testo = "Added " + movies.get(position).getTitle() + "\n" + "in tab watched";
Toast tostato = Toast.makeText(context, testo, Toast.LENGTH_SHORT);
tostato.show();
refreshLists();
}
});
}
//solo se è di tipo suggested
if(getTipo().equals("SUGGESTED")) {
//disabilitare bottone remove
holder.movie_notify.setVisibility(View.GONE);
holder.removeButton.setVisibility(View.GONE);
holder.notifyButton.setVisibility(View.VISIBLE);
holder.watchedButton.setVisibility(View.VISIBLE);
holder.changeDateTimeButton.setVisibility(View.GONE);
Toast.makeText(context,"Suggested", Toast.LENGTH_LONG).show();
holder.notifyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alertFormElements(position, false);
}
});
holder.watchedButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MovieDBModel mdm = new MovieDBModel(movies.get(position).getId(), movies.get(position).getTitle(), movies.get(position).getOverview(),
movies.get(position).getPosterUrl(), movies.get(position).getBackdropUrl(), movies.get(position).getTrailerUrl(),
movies.get(position).getReleaseDate(), movies.get(position).getRating(), movies.get(position).isAdult(),null);
MovieDatabase.insertMovie(mdm, 2, MainActivity.getMovieDatabase());
String testo = "Added " + movies.get(position).getTitle() + "\n" + "in tab watched";
Toast tostato = Toast.makeText(context, testo, Toast.LENGTH_SHORT);
tostato.show();
refreshLists();
}
});
}
if (getTipo().equals("WATCHED")) {
holder.movie_notify.setVisibility(View.GONE);
holder.notifyButton.setVisibility(View.GONE);
holder.watchedButton.setVisibility(View.GONE);
holder.removeButton.setVisibility(View.VISIBLE);
holder.changeDateTimeButton.setVisibility(View.GONE);
holder.removeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MovieDatabase md = new MovieDatabase(context);
md.deleteMovie(movies.get(position).getId());
refreshLists();
}
});
Toast.makeText(context,"WATCHED", Toast.LENGTH_LONG).show();
}
}
//nuovo codice riguardo l'alerDialog
public final void alertFormElements(final int position, final boolean modify) {
/*
* Inflate the XML view. activity_main is in
* res/layout/form_elements.xml
*/
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View formElementsView = inflater.inflate(R.layout.form_elements,
null, false);
// You have to list down your form elements
/*final CheckBox myCheckBox = (CheckBox) formElementsView
.findViewById(R.id.myCheckBox);*/
final RadioGroup genderRadioGroup = (RadioGroup) formElementsView
.findViewById(R.id.NotifyAlertRadioGroup);
//nuovo codice
genderRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
switch (checkedId)
{
case R.id.OneDayRadioButton:
actv(false);
break;
case R.id.ReleaseDayRadioButton:
actv(false);
break;
case R.id.OnRadioButton:
actv(true);
break;
}
}
});
//questo sarà sostituito con un calendario.
/*final EditText nameEditText = (EditText) formElementsView
.findViewById(R.id.nameEditText);*/
//parte data
fromDateEtxt = (EditText) formElementsView.findViewById(R.id.nameEditText);
fromDateEtxt.setEnabled(active);
fromDateEtxt.setClickable(active);
fromDateEtxt.setInputType(InputType.TYPE_NULL);
fromDateEtxt.requestFocus();
//metodo data
//setDateTimeField();
//fromDatePickerDialog.show();
//Calendario ci servirà dopo per inserire i dati nel DB
fromDateEtxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Calendar c = Calendar.getInstance();
DatePickerDialog dpd = new DatePickerDialog( context ,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
fromDateEtxt.setText(dayOfMonth + "-"
+ (monthOfYear + 1) + "-" + year);
anno = year;
giorno = dayOfMonth;
mese = monthOfYear + 1;
}
},
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
dpd.show();
}
});
//parte orario
ora = 9;
minuti = 30;
eReminderTime = (EditText) formElementsView.findViewById(R.id.timeEditText);
eReminderTime.setText( ora + ":" + minuti);
eReminderTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(context, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute)
{
eReminderTime.setText( selectedHour + ":" + selectedMinute);
ora = selectedHour;
minuti = selectedMinute;
}
//}
}, hour, minute, true);//Yes 24 hour time
mTimePicker.setTitle("Select Time");
mTimePicker.show();
}
});
// the alert dialog
new AlertDialog.Builder(context).setView(formElementsView)
.setTitle(movies.get(position).getTitle()+" Notify")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#TargetApi(11)
public void onClick(DialogInterface dialog, int id) {
//fromDateEtxt.setText(dateFormatter.format(newDate.getTime()));
String toastString = "";
String titleMovie = movies.get(position).getTitle();
String releaseDate = String.valueOf(movies.get(position).getReleaseDate());
String date = releaseDate.substring(0, 10);
String year = releaseDate.substring(releaseDate.length()-5,releaseDate.length());
releaseDate = date+year;
toastString = toastString + titleMovie + "\n" + releaseDate +"\n";
/*
* Detecting whether the checkbox is checked or not.
*/
/*if (myCheckBox.isChecked()) {
toastString += "Happy is checked!\n";
} else {
toastString += "Happy IS NOT checked.\n";
}*/
/*
* Getting the value of selected RadioButton.
*/
// get selected radio button from radioGroup
int selectedId = genderRadioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
RadioButton selectedRadioButton = (RadioButton) formElementsView
.findViewById(selectedId);
Date datatime = null;
if(selectedRadioButton.getId() == R.id.ReleaseDayRadioButton) {
toastString += "Selected radio button is: " + selectedRadioButton.getText() +"!\n";
Date release = movies.get(position).getReleaseDate();
release.setHours(ora);
release.setMinutes(minuti);
release.setSeconds(secondi);
datatime = new Date (anno-1900,mese-1,giorno,ora, minuti, secondi);
}
else if(selectedRadioButton.getId() == R.id.OneDayRadioButton) {
toastString += "Selected radio button is: "
+ selectedRadioButton.getText() + "!\n";
Date release = movies.get(position).getReleaseDate();
release.setHours(ora);
release.setMinutes(minuti);
release.setSeconds(secondi);
datatime = new Date (anno-1900,mese-1,giorno-1,release.getHours(),release.getMinutes(), release.getSeconds());
}
else if(selectedRadioButton.getId() == R.id.OnRadioButton) {
toastString += "Selected radio button is: " + fromDateEtxt.getText() +"!\n";
datatime = new Date (anno-1900,mese-1,giorno,ora, minuti, secondi);
}
setDataTime(datatime);
toastString += eReminderTime.getText();
//Date(int year, int month, int date, int hrs, int min, int sec)
//Date datatime = new Date (anno-1900,mese-1,giorno,ora, minuti, secondi);
//ora scriviamo tutta questa roba sulla base di dati
/*String testo = movies.get(position).getTitle()+ "\n" + "I WATCH IT";
Toast tostato = Toast.makeText(context,testo,Toast.LENGTH_SHORT);
tostato.show();*/
if(modify == false) {
// public MovieDBModel(int id, String title, String overview, String posterUrl, String backdropUrl, String trailerUrl,
// Date releaseDate, float rating, boolean adult, date datatime){
//Log.i("DATATIME", datatime.toString());
MovieDBModel mdm2 = new MovieDBModel(movies.get(position).getId(), movies.get(position).getTitle(), movies.get(position).getOverview(),
movies.get(position).getPosterUrl(), movies.get(position).getBackdropUrl(), movies.get(position).getTrailerUrl(),
movies.get(position).getReleaseDate(), movies.get(position).getRating(), movies.get(position).isAdult(), datatime);
MovieDatabase.insertMovie(mdm2, 1, MainActivity.getMovieDatabase());
//notifyRequestID= scheduleNotify(datatime,position);
pendingIntent=scheduleNotification(getNotification(movies.get(position).getTitle()),datatime,movies.get(position).getId());
refreshLists();
}
else {
// provare la base di dati
MovieDatabase md = new MovieDatabase(context);
Log.i("DATATIME","ID"+ movies.get(position).getId() +"DATATIME: "+ datatime);
md.updateNotifyDate(movies.get(position).getId(),datatime);
//deleteNotify(notifyRequestID);
//inserire funzione deleteNotify
deleteNotify(pendingIntent);
pendingIntent=scheduleNotification(getNotification(movies.get(position).getTitle()),datatime, movies.get(position).getId());
refreshLists();
}
String testo = "Added " + movies.get(position).getTitle() + "\n" + "in tab watched";
Toast tostato = Toast.makeText(context, testo, Toast.LENGTH_SHORT);
tostato.show();
/*
* Getting the value of an EditText.
*/
/*toastString += "Name is: " + nameEditText.getText()
+ "!\n";*/
Toast toast = Toast.makeText(context, toastString, Toast.LENGTH_LONG);
toast.show();
dialog.cancel();
}
}).show();
}
//nuovo codice
/*#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_movie, null);
holder = new ViewHolder();
holder.title_movie = (TextView) convertView.findViewById(R.id.movie_title);
holder.release_date = (TextView) convertView
.findViewById(R.id.movie_release_date);
Movie row_pos = movies.get(position);
//holder.profile_pic.setImageResource(row_pos.getProfile_pic_id());
holder.title_movie.setText(row_pos.getTitle());
holder.release_date.setText((CharSequence) row_pos.getReleaseDate());
//holder.contactType.setText(row_pos.getContactType());
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}*/
#Override
public void onViewRecycled(ViewHolder holder) {
super.onViewRecycled(holder);
Glide.clear(holder.posterView);
}
#Override
public int getItemCount() {
return movies.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.poster)
public ImageView posterView;
#BindView(R.id.movie_title)
public TextView title_movie;
#BindView(R.id.movie_release_date)
public TextView release_date;
#BindView(R.id.movie_time_notify)
public TextView movie_notify;
#BindView(R.id.editNotify)
public Button notifyButton;
#BindView(R.id.iWatchItMovie)
public Button watchedButton;
#BindView(R.id.remove)
public Button removeButton;
#BindView(R.id.change)
public Button changeDateTimeButton;
public ViewHolder(View v) {
super(v);
ButterKnife.bind(this, v);
}
}
//parte per attivare/disattivare l'editText
private void actv(final boolean active)
{
fromDateEtxt.setEnabled(active);
if (active)
{
fromDateEtxt.requestFocus();
fromDateEtxt.setText(giorno+"-"+mese+"-"+anno);
}
}
public static void setTipo(String tipo) {
MoviesAdapter.tipo = tipo;
}
public static void setFragment(MoviesFragment fragment) {
MoviesAdapter.fragmentInstance = fragment;
}
public static String getTipo() {
return tipo;
}
public Date getDatatime() {
return datatime;
}
public void setDataTime(Date datatime) {
this.datatime = datatime;
}
private Data createInputDataForUri(Movie movie) {
Data.Builder builder = new Data.Builder();
if (movie != null) {
builder.putString(KEY_MOVIE,movie.getTitle());
}
return builder.build();
}
private PendingIntent scheduleNotification(Notification notification, /*int delay*/Date d, int id) {
Intent notificationIntent = new Intent(context, NotificationPublisher.class);
//
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, id);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, notification);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//long futureInMillis = SystemClock.elapsedRealtime() + delay;
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
//alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
alarmManager.set(AlarmManager.RTC_WAKEUP,d.getTime(), pendingIntent);
return pendingIntent;
}
public void deleteNotify(PendingIntent p)
{
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
manager.cancel(p);//cancel the alarm manager of the pending intent
}
private Notification getNotification(String content) {
Notification.Builder builder = new Notification.Builder(context);
builder.setContentTitle("WARNING!!! REMEMBER MOVIE: ");
builder.setContentText(content);
builder.setDefaults(DEFAULT_ALL);
builder.setSmallIcon(R.drawable.ic_launcher_foreground);
return builder.build();
}
public void refreshLists(){
if(fragmentInstance!= null){
fragmentInstance.onRefresh();
}else{
MoviesFragment mf1 = (MoviesFragment)spa.getItem(0);
mf1.setArgFragType(MoviesFragment.Type.NOTIFY);
mf1.onRefresh();
MoviesFragment mf2 = (MoviesFragment)spa.getItem(1);
mf2.setArgFragType(MoviesFragment.Type.SUGGESTED);
mf2.onRefresh();
MoviesFragment mf3 = (MoviesFragment)spa.getItem(2);
mf3.setArgFragType(MoviesFragment.Type.WATCHED);
mf3.onRefresh();
}
}
}
NotificationPublisher.java
package com.example.msnma.movienotifier.notify;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class NotificationPublisher extends BroadcastReceiver
{
public static String NOTIFICATION_ID = "notification-id";
public static String NOTIFICATION = "notification";
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = intent.getParcelableExtra(NOTIFICATION);
int id = intent.getIntExtra(NOTIFICATION_ID, 0);
notificationManager.notify(id, notification);
}
}
Change this line
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
To
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, notificationIntent, PendingIntent.FLAG_ONE_SHOT); //Here 0 is the intent requestcode.
Make sure intent request code is unique in order to differentiate intents.
Hi in the below code I am getting array index out of bounds exception.Here friend array it's giving two values.
For ex:
friendinfo[0]=user1,friendinfo1=user2 and with checkbox when i am selecting user1 I want to show friend.length to 2 and checked value should be 1.
this is sample screen how to add the use3 and user1 when i am clicking the create button.
GroupList.java
public class GroupList extends ListActivity
{
boolean[] checkBoxState;
private IAppManager imService = null;
private FriendListAdapter friendAdapter;
public String ownusername = new String();
private class FriendListAdapter extends BaseAdapter
{
#SuppressWarnings("unused")
class ViewHolder {
TextView text;
ImageView icon;
CheckBox check1;
}
private LayoutInflater mInflater;
private Bitmap mOnlineIcon;
private Bitmap mOfflineIcon;
private FriendInfo[] friends = null;
public FriendListAdapter(Context context) {
super();
mInflater = LayoutInflater.from(context);
mOnlineIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.greenstar);
mOfflineIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.redstar);
}
public void setFriendList(FriendInfo[] friends)
{
this.friends = friends;
}
public int getCount() {
return friends.length;
}
public FriendInfo getItem(int position) {
return friends[position];
}
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.grouplist, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
holder.check1 = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(friends[position].userName);
holder.icon.setImageBitmap(friends[position].status == STATUS.ONLINE ? mOnlineIcon : mOfflineIcon);
checkBoxState = new boolean[friends.length];
holder.check1.setChecked(checkBoxState[position]);
holder.check1.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checkBoxState[position]=isChecked;
String check=friends[position].userName;
Toast.makeText(getApplicationContext(),friends[position].userName+"checked", Toast.LENGTH_LONG).show();
}
});
return convertView;
}
}
public class MessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("Broadcast receiver ", "received a message");
Bundle extra = intent.getExtras();
if (extra != null)
{
String action = intent.getAction();
if (action.equals(IMService.FRIEND_LIST_UPDATED))
{
GroupList.this.updateData(FriendController.getFriendsInfo(),
FriendController.getUnapprovedFriendsInfo());
}
}
}
};
public MessageReceiver messageReceiver = new MessageReceiver();
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((IMService.IMBinder)service).getService();
FriendInfo[] friends = FriendController.getFriendsInfo();
if (friends != null) {
GroupList.this.updateData(friends, null);
}
String groupname = getIntent().getStringExtra("nick");
setTitle(groupname);
ownusername = imService.getUsername();
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(GroupList.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
#SuppressLint("NewApi")
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
setContentView(R.layout.group_list_screen);
friendAdapter = new FriendListAdapter(this);
Button create=(Button)findViewById(R.id.create);
create.setOnClickListener(new OnClickListener() {
#SuppressWarnings("unused")
#Override
public void onClick(View v) {
String groupname = getIntent().getStringExtra("nick");
try {
FriendInfo[] friend=FriendController.getFriendsInfo();
//checkBoxState = new CheckBox[friend.length];
/*try {
for(int i=0;i <=friend.length ;i++){
if(checkBoxState[i].isChecked()){
check[i]="1";
}
}
}catch (Exception e) {
e.printStackTrace();
}*/
String result1 = imService.CreateGroup(groupname,imService.getUsername(),friend);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Group Created Sucessfully",Toast.LENGTH_LONG).show();
}
});
}
public void updateData(FriendInfo[] friends, FriendInfo[] unApprovedFriends)
{
if (friends != null) {
friendAdapter.setFriendList(friends);
setListAdapter(friendAdapter);
}
if (unApprovedFriends != null)
{
NotificationManager NM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (unApprovedFriends.length > 0)
{
String tmp = new String();
for (int j = 0; j < unApprovedFriends.length; j++) {
tmp = tmp.concat(unApprovedFriends[j].userName).concat(",");
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.stat_sample)
.setContentTitle(getText(R.string.new_friend_request_exist));
/*Notification notification = new Notification(R.drawable.stat_sample,
getText(R.string.new_friend_request_exist),
System.currentTimeMillis());*/
Intent i = new Intent(this, UnApprovedFriendList.class);
i.putExtra(FriendInfo.FRIEND_LIST, tmp);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
i, 0);
mBuilder.setContentText("You have new friend request(s)");
mBuilder.setContentIntent(contentIntent);
NM.notify(R.string.new_friend_request_exist, mBuilder.build());
}
else
{
NM.cancel(R.string.new_friend_request_exist);
}
}
}
#Override
protected void onPause()
{
unregisterReceiver(messageReceiver);
unbindService(mConnection);
super.onPause();
}
#Override
protected void onResume()
{
super.onResume();
bindService(new Intent(GroupList.this, IMService.class), mConnection , Context.BIND_AUTO_CREATE);
IntentFilter i = new IntentFilter();
i.addAction(IMService.FRIEND_LIST_UPDATED);
registerReceiver(messageReceiver, i);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
You probably wanted to write :
if(checkBoxState[i]==isChecked)
if checkBoxState and friend arrays have the same length, checkBoxState[friend.length] is out of bounds, since the indices of an array are from 0 to length - 1.
Also note that your if condition contained an assignment operator = instead of a comparison operator ==.
Just use the index inside the for loop. Also since isChecked is already a boolean you can just assign it directly to checkBoxState
for (int i = 0; i < friend.length; i++) {
checkBoxState[i] = isChecked;
}
You are trying to access the index 2nd position in an array that has only a length of 2 (positions 0 and 1).
So please change the code as below,
if(checkBoxState[i]==isChecked)
I have an adapter that extends FragmentPagerAdapter and takes advantage of the ICS style actionBar. This actionbar has actions that take input from the currently selected page.
Specifically, I have a screenshot icon in the actionbar that takes the url of the current page and displays any screenshots from that url. However, I dont know how to retrieve the currently selected page.
How can I implement something like a
public int getActivePage() {
return position;
Im still working on the viewpager implementation, so my code is still heavily reliant on examples, so disregard the mess :P
The problem areas are marked below.
public class ListFragmentViewPagerActivity extends FragmentActivity {
ArrayList<String> URLS;
ArrayList<String> TITLES;
BroadcastReceiver receiver;
String threadTitle = null;
public static String threadUrl = null;
String type = null;
String threadAuthor = null;
String ident = null;
boolean isFav = false;
String author = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thread_view);
Bundle extras = getIntent().getExtras();
threadTitle = extras.getString("title");
threadUrl = extras.getString("url");
type = extras.getString("type");
ident = extras.getString("ident");
author = extras.getString("author");
try {
URLS = extras.getStringArrayList("urls");
TITLES = extras.getStringArrayList("titles");
} catch (Exception e) {
URLS = null;
}
final FDBAdapter db = new FDBAdapter(this);
db.open();
Cursor c = db.getAllFavs();
if (c.getCount()>0) {
if (c.getString(2).equals(threadTitle)) {
isFav = true;
}
try {
while (c.moveToNext()) {
Log.d("FAVS", c.getString(2));
if (c.getString(2).equals(threadTitle)) {
isFav = true;
}
}
} catch (Exception ep) {
ep.printStackTrace();
}
}
c.close();
db.close();
ViewPager pager = (ViewPager) findViewById(android.R.id.list);
pager.setAdapter(new ExamplePagerAdapter(getSupportFragmentManager()));
TitlePageIndicator indicator = (TitlePageIndicator)findViewById( R.id.indicator );
indicator.setViewPager(pager);
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns);
int icon = R.drawable.ic_launcher; // icon from resources
CharSequence tickerText = "Download ready!"; // ticker-text
long when = System.currentTimeMillis(); // notification time
CharSequence contentTitle = "OMG"; // expanded message title
CharSequence contentText = "Your download is finished!"; // expanded message text
Intent notificationIntent = new Intent(context, ExampleListFragment.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
final int HELLO_ID = 1;
mNotificationManager.notify(HELLO_ID, notification);
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
public class ExamplePagerAdapter extends FragmentPagerAdapter implements TitleProvider{
public ExamplePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return URLS.size();
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new ExampleListFragment();
// set arguments here, if required
Bundle args = new Bundle();
args.putString("url", URLS.get(position));
fragment.setArguments(args);
return fragment;
}
#Override
public String getTitle(int pos) {
return TITLES.get(pos);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuinflate = new MenuInflater(this);
menuinflate.inflate(R.menu.thread_menu, menu);
if (type.equals("xda")) {
menu.removeItem(R.id.ss_view);
}
if (isFav) {
menu.getItem(2).setIcon(R.drawable.fav_ab);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
break;
case R.id.ss_view:
Intent ssi = new Intent(this, SSActivity.class);
ssi.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Bundle b = new Bundle();
//I need to get the position of the currently active page here so that I can retrieve the //corresponding values for the title and url.
b.putString("title", threadTitle);
b.putString("url", threadUrl);
ssi.putExtras(b);
startActivity(ssi);
break;
case R.id.restart:
break;
case R.id.fav_ab:
threadUrl = new String(threadUrl.replaceAll("http://", ""));
FDBAdapter fdb = new FDBAdapter(this);
fdb.open();
if (isFav) {
Cursor c = fdb.getAllUrls();
while (c.moveToNext()) {
String id = c.getString(c.getColumnIndex("_id"));
int rowId = Integer.parseInt(id);
if(c.getString(c.getColumnIndex("url")).equals(threadUrl)) {
if (fdb.deleteUrl(rowId)) {
Log.d("THREAD", "SUCCESS");
} else {
Log.d("THREAD", "FAILED");
}
}
}
c.close();
item.setIcon(R.drawable.fav_ab_off);
isFav = false;
} else {
fdb.insertFav(threadUrl, threadTitle, ident, type, author, "thread");
item.setIcon(R.drawable.fav_ab);
isFav = true;
}
fdb.close();
default:
return super.onOptionsItemSelected(item);
}
return false;
}
#Override
public void onStop() {
super.onStop();
unregisterReceiver(receiver);
}
#Override
public void onStart() {
super.onStart();
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
}
Heres what I mean by the currently selected page.
I believe what you are looking for is onPageChangedListener(). This method belongs to the TitlePageIndicator. Something like...
indicator.setOnPageChangedListener(new OnPageChangedListener() {
// Implement unimplemented methods...
});
you can also ask to viewpager
in java
ViewPager pager = (ViewPager) findViewById(android.R.id.list);
pager.getCurrentItem()
in kotlin
pager.currentItem