How to save Push Notification Data in SharedPreferences and display in RecyclerView - android

I have created an application that receives push notifications from PushBots.
I am successfully receiving the Push Notifications but I want to store the push data in SharedPreferences and display it another activity containing a RecyclerView.
I know Content providers is a better approach, but I want to stick with SharedPreferences as of now.
Here's my custom Broadcast Receiver
public class customHandler extends BroadcastReceiver
{
private static final String TAG = "customHandler";
#Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
Log.d(TAG, "action=" + action);
// Handle Push Message when opened
if (action.equals(PBConstants.EVENT_MSG_OPEN)) {
//Check for Pushbots Instance
Pushbots pushInstance = Pushbots.sharedInstance();
if(!pushInstance.isInitialized()){
Log.d("Initializing Pushbots.");
Pushbots.sharedInstance().init(context.getApplicationContext());
}
//Clear Notification array
if(PBNotificationIntent.notificationsArray != null){
PBNotificationIntent.notificationsArray = null;
}
HashMap<?, ?> PushdataOpen = (HashMap<?, ?>) intent.getExtras().get(PBConstants.EVENT_MSG_OPEN);
Log.w(TAG, "User clicked notification with Message: " + PushdataOpen.get("message"));
//Report Opened Push Notification to Pushbots
if(Pushbots.sharedInstance().isAnalyticsEnabled()){
Pushbots.sharedInstance().reportPushOpened( (String) PushdataOpen.get("PUSHANALYTICS"));
}
//Start Main Activity On CLicking Notification
String packageName = context.getPackageName();
Intent resultIntent = new Intent(context.getPackageManager().getLaunchIntentForPackage(packageName));
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_CLEAR_TASK);
resultIntent.putExtras(intent.getBundleExtra("pushData"));
Pushbots.sharedInstance().startActivity(resultIntent);
// Handle Push Message when received
}else if(action.equals(PBConstants.EVENT_MSG_RECEIVE)){
HashMap<?, ?> PushdataOpen = (HashMap<?, ?>) intent.getExtras().get(PBConstants.EVENT_MSG_RECEIVE);
Log.w(TAG, "User Received notification with Message: " + PushdataOpen.get("message"));
}
}
}

Create a custom PushData class and use Gson library to save as a string your data.
Here is a clean example

try it.
public void addNotification(String notification) {
// get old notifications
String oldNotifications = getNotifications();
if (oldNotifications != null) {
oldNotifications += "|" + notification;
} else {
oldNotifications = notification;
}
editor.putString(KEY_NOTIFICATIONS, oldNotifications);
editor.commit();
}
public String getNotifications() {
return pref.getString(KEY_NOTIFICATIONS, null);
}
and get it
String oldNotification = AppController.getInstance().getPrefManager().getNotifications();
List<String> messages = Arrays.asList(oldNotification.split("\\|"));

For putting string in SharedPreferences :
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
editor.commit();
For getting shared preferences in fragment :
SharedPreferences prefs = getActivity().getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String name = prefs.getString(key, "default value");

1. Initialize Shared Preference variables in onReceive method like below ,
SharedPreferences prf = context.getSharedPreferences("YOUR_PREFERENCE_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prf.edit();
2. Save Push Message to shared preference when receive,
................
................
// Handle Push Message when received
}else if(action.equals(PBConstants.EVENT_MSG_RECEIVE))
{
HashMap<?, ?> PushdataOpen = (HashMap<?, ?>) intent.getExtras().get(PBConstants.EVENT_MSG_RECEIVE);
Log.w(TAG, "User Received notification with Message: " + PushdataOpen.get("message"));
String message=(String) PushdataOpen.get("message");
editor.putString("push_message", message);
editor.commit();
}
3. Get saved push message from shared preference for display,
SharedPreferences prf = context.getSharedPreferences("YOUR_PREFERENCE_NAME", Context.MODE_PRIVATE);
String message=prf.getString("push_message", "");

Related

Firebase android push notification doesn't work on other device

sorry for my bad english.
I sending push notification from my codeigniter web to android app, I have 3 devices to test it.
My first device, it works well for me.
And then in my second and third device my android didn't receive any message.
I tried to send notification from my firebase console, then I choose target is user segment with my package name. All of my devices receive the message.
Then I tried to send notification using topic, which is my topic is global. Only my first device receives the message.
Here's my code :
public static final String TOPIC_GLOBAL = "global";
public static final String REGISTRATION_COMPLETE = "registrationComplete";
public static final String PUSH_NOTIFICATION = "pushNotification";
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// checking for type intent filter
if (intent.getAction().equals(Config.REGISTRATION_COMPLETE)) {
// gcm successfully registered
// now subscribe to `global` topic to receive app wide notifications
FirebaseMessaging.getInstance().subscribeToTopic(Config.TOPIC_GLOBAL);
displayFirebaseRegId();
} else if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
// new push notification is received
String message = intent.getStringExtra("message");
Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show();
// txtMessage.setText(message);
}
}
};
private void displayFirebaseRegId() {
SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
String regId = pref.getString("regId", null);
Log.e(TAG, "Firebase reg id: " + regId);
if (!TextUtils.isEmpty(regId))
{
//Toast.makeText(getApplicationContext(),regId,Toast.LENGTH_LONG).show();
}
// Toast.makeText(getApplicationContext(), regId, Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(),"Firebase Reg Id is not received yet!)",Toast.LENGTH_LONG).show();
}

Android Firebase Push Notification Double values

Hi all i am implementing Firebase Push notifications in Android. Everything is working fine except when i am retrieving the messages, they are duplicated twice. I tried debugging a whole day but could not succeed. Help me out please!
I am using shared preferences for storing the message. And i am sending through Api and its topic based.
Below is my onMessageReceived() method code of my MyFirebaseMessagingService class
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}
String message = remoteMessage.getData().get("message");
SharedPreferences sp = getSharedPreferences("mypreference", Context.MODE_PRIVATE);
String prev = sp.getString("msg", "-");
String newp;
if(prev != "-"){
newp = prev+","+messageBody;
}else{
newp = messageBody;
}
Log.d("prev123",prev);
SharedPreferences.Editor e = sp.edit();
e.putString("msg",newp);
Log.d("afterstore", newp);
e.commit();
e.apply();
}
And the class where I am showing the message is:
#Override
public void onResume() {
super.onResume();
String msg = sp.getString("msg", null);
Log.d("message", msg);
String[] pqrs = msg.split(",");
Log.d("Array msg",pqrs);
ArrayAdapter<String> adp = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,android.R.id.text1,pqrs);
listView.setAdapter(adp);
In Log once message is received it shows but just after fraction of second same message is appended to the log. Don't know how. Please help.
I don't get it what's exactly duplicated. İf it's data that you saved it may be the reason that you save it twice.
e.commit();
e.apply()
Just use one of them. They do same operation unlike async or sync.
Good luck
Emre
Did you clear data of application after removing commit line? You might test with old duplicated data after fix?
Also if your calling intent in other classes, give it a try to remove it. As I know it's calling automatically by base classes of firebase.

Android : Set Notification Image

In my project, i'm using pushbot to push the notifications to the device. Now it is displaying the app logo but i want a particular say "R.drawable.alert" to be displayed instead of the app logo. So how to go about it. Below i'm posting the code for the Custom Handler class. I'm working with pushbots.
Custom Handler class
public class customHandler extends BroadcastReceiver
{
private static final String TAG = "customHandler";
#Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
android.util.Log.d(TAG, "action=" + action);
// Handle Push Message when opened
if (action.equals(PBConstants.EVENT_MSG_OPEN)) {
//Check for Pushbots Instance
Pushbots pushInstance = Pushbots.sharedInstance();
if(!pushInstance.isInitialized()){
com.pushbots.push.utils.Log.d("Initializing Pushbots.");
Pushbots.sharedInstance().init(context.getApplicationContext());
}
//Clear Notification array
if(PBNotificationIntent.notificationsArray != null){
PBNotificationIntent.notificationsArray = null;
}
HashMap<?, ?> PushdataOpen = (HashMap<?, ?>) intent.getExtras().get(PBConstants.EVENT_MSG_OPEN);
android.util.Log.w(TAG, "User clicked notification with Message: " + PushdataOpen.get("message"));
//Report Opened Push Notification to Pushbots
if(Pushbots.sharedInstance().isAnalyticsEnabled()){
Pushbots.sharedInstance().reportPushOpened( (String) PushdataOpen.get("PUSHANALYTICS"));
}
//Start lanuch Activity
String packageName = context.getPackageName();
Intent resultIntent = new Intent(context.getPackageManager().getLaunchIntentForPackage(packageName));
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_CLEAR_TASK);
resultIntent.putExtras(intent.getBundleExtra("pushData"));
Pushbots.sharedInstance().startActivity(resultIntent);
// Handle Push Message when received
}else if(action.equals(PBConstants.EVENT_MSG_RECEIVE)){
HashMap<?, ?> PushdataOpen = (HashMap<?, ?>) intent.getExtras().get(PBConstants.EVENT_MSG_RECEIVE);
android.util.Log.w(TAG, "User Received notification with Message: " + PushdataOpen.get("message"));
}
}
}
All you have to do it ,Upload icon to server, and in server pushbots >"Custom Payload" ,write in Key=largeIcon, and Value=URL of icon.
Image Example
More information in here: PushBots tutorial

Issue reading data from sharedpreferences. I have to run the app twice before it gets the data stored

I have an issues reading from sharedpreferences in android. The data is stored in the preference file, and i ma sure of this because i used logcat to log the data when i read it back IMMEDIATELY as it was stored as well as i used a toast message to display the data after i read it back from preferences. However when i try to read the data again from a new activity it returns the default of an empty sting. When i exist the app and run it again it read the data that was previously stored. Here is my code for when i initially save the data, it also contains the comments i used to verify that the data stored was read back:
public void downloadMatchesAsync() {
brawtaAPIAdapter.runGetMatches(new Callback<JSONKeys>() {
#Override
public void success(JSONKeys jsonKeys, Response response) {
Log.d(ApplicationConstants.TAG, "blarg");
Success = jsonKeys.isSuccess();
message = jsonKeys.getErrorMessage().toString();
if(!message.isEmpty()){
Toast.makeText(MyApplication.getAppContext(), message, Toast.LENGTH_SHORT).show();
}
Gson gson = new Gson();
String jsonObject = gson.toJson(jsonKeys); //converts java object into json string'
Preferences.saveToPreferences(activity, ApplicationConstants.match_data, jsonObject);
//data =Preferences.readFromPreferences(activity, ApplicationConstants.match_data, "no data");
//Toast.makeText(MyApplication.getAppContext(), "In networkOperation" + data, Toast.LENGTH_LONG).show();
}
#Override
public void failure(RetrofitError error) {
}
}); // Call Async API
//return data;
}
In a different activity i try to read the data previously written like so:
jsonString = Preferences.readFromPreferences(MatchSelect.this, ApplicationConstants.match_data, "");
but the code only returns the data stored if i exist the app and run it again.
this is my preference class:
public class Preferences {
private static final String PrefName = "net.brawtasports.brawtasportsgps";
public static void saveToPreferences(Context context, String key, String value) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PrefName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.apply();
}
public static String readFromPreferences(Context context, String key, String defaultValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PrefName, Context.MODE_PRIVATE);
return sharedPreferences.getString(key, defaultValue);
}
}
What is the issue?
apply() is an asynchronous call, so the data doesn't have to be stored immediately. Try calling .commit() instead.

Push Notifications using Urban Airship returns apID as null at the first launch

I have successfully integrated urban airship push notification to my android application. I ran into an issue here, that is the apID becomes null with the very first launch and then with the second launch, apId comes correctly.
This is how I grab the apId:
String apid = PushManager.shared().getAPID();
This is the class that I have used:
public class MyApplication extends Application {
public static SharedPreferences PREFS_TOKEN;
public static final String PREFERENCE = "UrbanAirship";
public static String tokenKey;
#Override
public void onCreate(){
AirshipConfigOptions options = AirshipConfigOptions.loadDefaultOptions(this);
UAirship.takeOff(this, options);
PushManager.enablePush();
Logger.logLevel = Log.VERBOSE;
// use CustomPushNotificationBuilder to specify a custom layout
CustomPushNotificationBuilder nb = new CustomPushNotificationBuilder();
nb.statusBarIconDrawableId = R.drawable.paw;// custom status bar icon
nb.layout = R.layout.notification;
nb.layoutIconDrawableId = R.drawable.paw;// custom layout icon
nb.layoutIconId = R.id.icon;
nb.layoutSubjectId = R.id.subject;
nb.layoutMessageId = R.id.message;
// customize the sound played when a push is received
// nb.soundUri =
// Uri.parse("android.resource://"+this.getPackageName()+"/"
// +R.raw.cat);
String apid = PushManager.shared().getAPID();
Logger.info("My Application onCreate - App APID: " + apid);
PREFS_TOKEN = this.getSharedPreferences(PREFERENCE,
Context.MODE_PRIVATE);
Editor edit = PREFS_TOKEN.edit();
if (apid != null && apid != "") {
edit.putString(PREFERENCE, apid);
edit.commit();
} else {
edit.putString(PREFERENCE, apid);
edit.commit();
}
tokenKey = PREFS_TOKEN.getString(PREFERENCE, "");
System.out.println("---------- - App APID: " + tokenKey);
PushManager.shared().setNotificationBuilder(nb);
PushManager.shared().setIntentReceiver(IntentReceiver.class);
}
}
I also have an IntentReceiver class. Any help is appreciated.
I found out that the reason is a delay, to get the apId, it takes some time, therefore, in your IntentReceiver class, you have to wait for `PushManager.ACTION_REGISTRATION_FINISHED to fire. From there, you can get the apId:
if (action.equals(PushManager.ACTION_REGISTRATION_FINISHED)) {
Log.i(logTag,"Registration complete. APID:" + intent.getStringExtra(PushManager.EXTRA_APID)+ ". Valid: "+ intent.getBooleanExtra( PushManager.EXTRA_REGISTRATION_VALID, false));
// Notify any app-specific listeners
String apid = PushManager.shared().getAPID();
Intent launch = new Intent(UAirship.getPackageName()+ APID_UPDATED_ACTION_SUFFIX);
UAirship.shared().getApplicationContext().sendBroadcast(launch);
}

Categories

Resources