Search code examples
javaandroidandroid-listviewretrofit2android-notifications

How to make notification OnItemchange when a new item is displayed in the list


i made an app using java and retrofit2 to fetch datas from the server.My listview can only display 30 item. when a new item is displayed in the listView the last one is removed automatically and the new one is displayed on that listview. my Event model :

public class Event {
    public int id, user_id, device_id, position_id, alert_id;
    // geofence_id
    public String message;
    public String address;
    public float altitude;
    // course
    public float latitude, longitude;
    // power
    public float speed;
    public String time;
    // deleted

    public String device_name, geofence_name;
}

my Event Activity:

public class EventsActivity extends AppCompatActivity
{
    @Bind(R.id.back) View back;
    @Bind(R.id.list) ListView list;
    @Bind(R.id.clearAllEvents) View clearAllEvents;
    @Bind(R.id.content_layout) View content_layout;
    @Bind(R.id.loading_layout) View loading_layout;
    @Bind(R.id.nodata_layout) View nodata_layout;
    @Bind(R.id.search) View search;
    String searchtext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_events);
        ButterKnife.bind(this);

        final String api_key = (String) DataSaver.getInstance(EventsActivity.this).load("api_key");
        final EventsAdapter adapter = new EventsAdapter(this);
        list.setAdapter(adapter);

        loading_layout.setVisibility(View.VISIBLE);
        API.getApiInterface(this).getEvents(api_key, getResources().getString(R.string.lang), 0, new Callback<ApiInterface.GetEventsResult>() {
            @Override
            public void success(ApiInterface.GetEventsResult result, Response response)
            {
                adapter.setArray(result.items.data);

                loading_layout.setVisibility(View.GONE);
                if(result.items.data.size() != 0)
                    content_layout.setVisibility(View.VISIBLE);
                else
                    nodata_layout.setVisibility(View.VISIBLE);
            }

            @Override
            public void failure(RetrofitError retrofitError) {
                Toast.makeText(EventsActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

my EventAdapter :

public class EventsAdapter extends AwesomeAdapter<Event> {
    public EventsAdapter(Context context) {
        super(context);
    }

    ArrayList<Event> original;
    @Override
    public void setArray(ArrayList<Event> array) {
        super.setArray(array);
        if(original == null)
            original = array;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(convertView == null)
            convertView = getLayoutInflater().inflate(R.layout.adapter_events, null);

        Event item = getItem(position);
        TextView device_name = (TextView) convertView.findViewById(R.id.device_name);
        device_name.setText(item.device_name);
        TextView date = (TextView) convertView.findViewById(R.id.date);
        date.setText(item.time);
        TextView message = (TextView) convertView.findViewById(R.id.message);
        message.setText(item.message);
        TextView geofence_name = (TextView) convertView.findViewById(R.id.geofence_name);
        geofence_name.setText(item.geofence_name);

        return convertView;
    }

}

The problem is i would like to make a local notification when the new item is added in the server i can get a notification of the displayed item on the listview. i have tried to make something it's working but when starting my activity, the notifications don't stop coming. i don't know why, here is my example :

API.getApiInterface(this).getEvents(api_key, getResources().getString(R.string.lang), 0, new Callback<ApiInterface.GetEventsResult>() {
            @SuppressLint("SetTextI18n")
            @Override
            public void success(ApiInterface.GetEventsResult result, Response response)
            {
                adapter.setArray(result.items.data);
                if(result.items.data.size() != 0) {
                    layout_evennements.setVisibility(View.VISIBLE);
                    text_count.setText("Evennements recu:" + listview_evennements.getAdapter().getCount());
                    //to upload all list one to one together.
                    for(int i = result.items.data.size(); i <= result.items.data.size(); i++) {
                                int notificationId = new Random().nextInt(100);
                                String channelId = "notification_channel_1";
                                 Event item = new Event();
                                NotificationManager notificationManager =  (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                               if(i > result.items.data.size()){
                                   Intent intent = new Intent(MapActivity.this, EventActivity.class);
                                   intent.putExtra("event", new Gson().toJson(listview_evennements.getItemAtPosition(0)));
                                   startActivity(intent);
                                   getIntent().addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                   @SuppressLint("UnspecifiedImmutableFlag") PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),
                                           0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
                                   NotificationCompat.Builder builder = new NotificationCompat.Builder(
                                           getApplicationContext(), channelId
                                   );

                                   builder.setSmallIcon(R.drawable.ic_notification_original);
                                   builder.setDefaults(NotificationCompat.DEFAULT_ALL);
                                   builder.setContentTitle("GPSTrackr");
                                   builder.setContentText("Evenement" + item.device_name);
                                   builder.setContentIntent(pendingIntent);
                                   builder.setAutoCancel(true);
                                   builder.setPriority(NotificationCompat.PRIORITY_MAX);
                                   if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
                                       if(notificationManager != null && notificationManager.getNotificationChannel(channelId) ==null){
                                           NotificationChannel notificationChannel = new NotificationChannel(
                                                   channelId, "Notification channel 1", NotificationManager.IMPORTANCE_HIGH
                                           );
                                           notificationChannel.setDescription("Notificatoins evenements");
                                           notificationChannel.enableLights(true);
                                           notificationChannel.enableVibration(true);
                                           notificationManager.createNotificationChannel(notificationChannel);
                                       }
                                   }
                                   Notification notification = builder.build();
                                   if (notificationManager != null) {
                                       notificationManager.notify(notificationId, notification);
                                   }
                               }else if(i == result.items.data.size()){
                                   MotionToast.Companion.darkColorToast(MapActivity.this, "Aucune Notification",
                                           MotionToast.TOAST_INFO,
                                           MotionToast.GRAVITY_CENTER,
                                           MotionToast.SHORT_DURATION,
                                           ResourcesCompat.getFont(MapActivity.this, R.font.helveticacompressed5871d14b6903a));
                               }
                    }
                }else {
                    rien_a_voir.setVisibility(View.VISIBLE);
                }
            }
            @Override
            public void failure(RetrofitError retrofitError) {
                rien_a_voir.setVisibility(View.VISIBLE);
                layout_evennements.setVisibility(View.GONE);
            }
        });

my APIInterface:

@GET("/get_events")
    void getEvents(@Query("user_api_hash") String user_api_hash, @Query("lang") String lang, @Query("page") int page, Callback<GetEventsResult> cb);

    public static class GetEventsResult
    {
        public int status;
        public GetEventsResultItems items;

        public class GetEventsResultItems
        {
            public int total, per_page, current_page, last_page, from, to;
            public ArrayList<Event> data;
        }

    }

if you have any solution please i need you help. thank you in advance.


Solution

  • I didn't understand the requirement clearly, but I can see that you are creating notifications in for loop which iterates for adapter.getCount times. You might want to move it outside of the for loop.