Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Native Development

Reply
Highlighted
New Developer
Posts: 104
Registered: ‎09-25-2013
My Device: BB 10
My Carrier: BB 10

Push Notification Message Display in BB 10 cascades

Hi All,

 

I am develping one BB 10 app. I would like to provide push message feature to It.I have been trying to display push message in this app. After a lot of reaserch , I am getting the push messages.

 

 

The Push Initiator (Server side) sends a  Alert Id to Push Enabled App. I need to get the details from my local database(SQLITE) based on this Alert Id and Display the push messages.Push Initiator sends the alert Id in this Format  AlertExecuted :Alert Id 

 

I am using the Push Collector sample gathered at https://github.com/blackberry/Cascades-Samples/tree/master/pushCollector/10.0/pushCollector

 

my understanding is that the push collector Sample app is storing the arrived messages in the local database.

 

I have added one more column(alert Id) in Push Coloctor sample as per my app requirement.

 

bool PushDAO::createPushTable()
{
    const QString query("CREATE TABLE  push (seqnum INTEGER PRIMARY KEY AUTOINCREMENT, pushdate TEXT, type TEXT, pushtime TEXT,alertId TEXT, extension TEXT, content BLOB, unread INTEGER);");

    // Execute the query.
    QSqlQuery sqlQuery(query, SQLConnection());

    const QSqlError err = sqlQuery.lastError();

    if (err.isValid()) {
        qWarning() << "Error executing SQL statement: " << query << ". ERROR: " << err.text();
        return false;
    }
   qDebug()<<"PushTable Created:::";
    return true;

}

 

when the push is Invoked, I am doing this.

void App::onInvoked(const InvokeRequest &request)
{
    if (m_configurationService.hasConfiguration()) {
        // The underlying PushService instance might not have been
        // initialized when an invoke first comes in
        // Make sure that we initialize it here if it hasn't been already
        // It requires an application ID (for consumer applications) so we have to check
        // that configuration settings have already been stored

        m_pushNotificationService.initializePushService();
        if (request.action().compare(BB_PUSH_INVOCATION_ACTION) == 0) {
            qDebug() << "Received push action";
            // Received an incoming push
            // Extract it from the invoke request and then process it
            PushPayload payload(request);
            if (payload.isValid()) {
                pushNotificationHandler(payload);
            }

        } else if (request.action().compare(BB_OPEN_INVOCATION_ACTION) == 0){

            qDebug() << "Received open action";
            SubcriptDB::deleteBBM();
            // Received an invoke request to open an existing push (ie. from a notification in the BlackBerry Hub)
            // The payload from the open invoke is the seqnum for the push in the database
            openPush(request.data().toInt());
        }
    }
}

 
 
 void App::openPush(int pushSeqNum)
{
    Push push = m_pushNotificationService.push(pushSeqNum);

    QVariantList indexPath = m_model->findExact(push.toMap());
    updatePushContent(push, indexPath);
}

void App::updatePushContent(Push &push, const QVariantList &indexPath)
{
    push.setUnread(false);
    m_pushNotificationService.markPushAsRead(push.seqNum());

    m_model->updateItem(indexPath, push.toMap());

    // The push has been opened, so delete the notification
    Notification::deleteFromInbox(NOTIFICATION_PREFIX + QString::number(push.seqNum()));

    m_pushContentController->setCurrentPush(push); // calls the PushContentController::setCurrentPush funtion 
}

void PushContentController::setCurrentPush(const Push &push)
{
	Helper::writeToLog("PushContentController::setCurrentPush is Called ");
    // Fill the property values with the data from the passed Push object
    m_pushDateTime = QString::fromLatin1("%1 - %2").arg(push.pushDateAsString()).arg(push.pushTime());

    if (push.contentType() == CONTENT_TYPE_TEXT || push.fileExtension() == FILE_EXTENSION_XML) {
        m_contentType = QLatin1String("plainText");



     QByteArray arry= push.content();
       QString content= QString (arry);


    	bool isBool,ok;
    	QString temp =content.split("AlertExecuted:").at(1);
    	QString temp1 = temp.split(';').at(0);
    	int alertId = temp1.toInt(&isBool);


    	QList<QVariantMap> list =DatabaseOperations::read_Alert_Records_serverid(alertId);
		// here I am reading the data from local database (SQLITE) based on AlertId


    	if (list.size() > 0) {
			QMap<int, QString> map = Helper::getJsonMap();

			QString symb = map[list.at(0)["AlertSymb"].toInt(&ok)]; // symbol name

			//if(Helper::lang_settings=="English")  //Alert: XXXX is reached : YYYY

			// QString appTitle = QString::fromLocal8Bit(symb.toAscii());
			QString alertText = tr("Alert:  ") + symb + " "+ tr("is reached :  ")+ list.at(0)["AlertPrice"].toString();

			//  m_textContent = QString::fromUtf8(push.content().data());
			// QString data=  push.content().data();

			m_textContent = alertText;
			QString data = push.alertId();
			
			Helper::writeToLog("PushContentController::setCurrentPush "+symb+" is Reched");

			DatabaseOperations::deleteOf(data.toInt());
    	}

    } else if (push.contentType() == CONTENT_TYPE_IMAGE) {
        m_contentType = QLatin1String("image");
        m_imageContent = QVariant::fromValue(bb::cascades::Image(push.content()));
    } else if (push.fileExtension() == FILE_EXTENSION_HTML) {
        m_contentType = QLatin1String("richText");
        m_textContent = QString::fromUtf8(push.content().data());
    }

    // Emit the change notification signal to let the UI update itself
    emit pushContentChanged();
}

 But the push messages are displaying as shown below.

 

image003.jpg

 

 The end user doesn't understand what is 479 in the above image. I would like to change it to a meaningful text

like 

 

Alert: ABSD is reached : 1234 .

 

Is there any thing wrong in the above Procedure/Code. 

 

please guide me the corect way to display the push meeasges to Alert: XXXX is reached : YYYY Format and where to make changes in the push collector sampe app. I am looking forword to a reply.

 

Thanks !!!

 

 

 

 

 

Retired
Posts: 1
Registered: ‎01-21-2014
My Device: 9810
My Carrier: Vodafone

Re: Push Notification Message Display in BB 10 cascades

[ Edited ]

Hi,

I just got a nudge via other BlackBerry personnel: Prakash Sainani -> Adam Sosnowski .  I am maintaining the device-side Push infrastructure, including the pushcollector sample.


First, I should not be sure that adding the "alert" column to that table would be appropriate.  That table, "push", contains the content of a pushed message.  I am thinking that the "alert ID" to which you refer is peculiar to a business application that uses the Push Initiator, i.e., it has business meaning peculiar to a business process, which uses Push, rather than being intrinsic to Push.  And, the table to which you are adding the column is about things that are intrinsic to Push, not to a business process.

So, I am thinking that the alert ID is something that is contained in the content of the pushed message, e.g., one of the HTTP headers or part of the rest of the payload.  In that case, an extra table that is part of the business process, not the intrinsic Push process, and which is in a relationship to the push table, could be appropriate.

 

Let's discuss further.

Kind regards, John.

New Developer
Posts: 104
Registered: ‎09-25-2013
My Device: BB 10
My Carrier: BB 10

Re: Push Notification Message Display in BB 10 cascades

[ Edited ]

Hi johodgson,

 

we made few assumption and added one more extra column in bool PushDAO::createPushTable()  funtion. 

 

but that assumption doesn't work for us, so we keep the  bool PushDAO::createPushTable() as It is defined in push collector app.

 

now the exact scenario is push initiator sends the push message in

 

 

AlertExecuted:617 (as shown in above screenshot). // where 479 is unique for each alert Id

 

push enabled app need to modify push message format as 

 

Alert: ABSD is reached : 1234 . // where ABSD is unique symbol for 479.

 

Push enabled app knows what  617 (alert Id)  

 

we are getting the push message as below image.

 

IMG_00000100.png

 

 

we are trying to change the push message by making the following changes.

 

App::App(bb::cascades::Application *app) :  m_invokeManager(new InvokeManager(this))
, m_registerPrompt(new SystemCredentialsPrompt(this))
, m_unregisterPrompt(new SystemCredentialsPrompt(this))
, m_shouldRegisterToLaunch(false)
, m_shouldUnregisterFromLaunch(false)
, m_hasBeenInForeground(false)
, m_configSaveAction(false)
, m_pushContentController(new PushContentController(this))
, m_model(new GroupDataModel(this))
 {
	fapp = app;
	Helper::device_pin=getImeiNum();

	qmlRegisterType<bb::system::SystemUiButton>("bb.system", 1, 0,
			"SystemUiButton");
	qmlRegisterType<SystemDialog>("bb.system", 1, 0, "SystemDialog");
	qmlRegisterType<PushContentController>();

	DatabaseOperations::initDatabase();

	m_model->setSortingKeys(QStringList() << "pushdate" << "pushtime");
	m_model->setGrouping(ItemGrouping::ByFullValue);
	m_model->setSortedAscending(false);

	QObject::connect(app, SIGNAL(fullscreen()), this, SLOT(onFullscreen()));
	connect(m_model, SIGNAL(itemAdded(QVariantList)),
			SIGNAL(modelIsEmptyChanged()));
	connect(m_model, SIGNAL(itemUpdated(QVariantList)),
			SIGNAL(modelIsEmptyChanged()));
	connect(m_model, SIGNAL(itemRemoved(QVariantList)),
			SIGNAL(modelIsEmptyChanged()));
	connect(m_model,
			SIGNAL(itemsChanged(bb::cascades::DataModelChangeType::Type, QSharedPointer<bb::cascades::DataModel::IndexMapper>)),
			SIGNAL(modelIsEmptyChanged()));

	// initialize the registerPrompt
	m_registerPrompt->setTitle(tr("Register"));
	m_registerPrompt->confirmButton()->setLabel(tr("Register"));
	m_registerPrompt->setIncludeRememberMe(false);
	QObject::connect(m_registerPrompt,
			SIGNAL(finished(bb::system::SystemUiResult::Type)), this,
			SLOT(onRegisterPromptFinished(bb::system::SystemUiResult::Type)));

	// initialize the unregisterPrompt
	m_unregisterPrompt->setTitle(tr("Unregister"));
	m_unregisterPrompt->confirmButton()->setLabel(tr("Unregister"));
	m_unregisterPrompt->setIncludeRememberMe(false);
	QObject::connect(m_unregisterPrompt,
			SIGNAL(finished(bb::system::SystemUiResult::Type)), this,
			SLOT(onUnregisterPromptFinished(bb::system::SystemUiResult::Type)));

	// load the configuration settings for Push Notification
	loadConfiguration();
	saveConfiguration();



	// connect the push notification service signals and slots

	QObject::connect(&m_pushNotificationService,
			SIGNAL(createSessionCompleted(const bb::network::PushStatus&)),
			this,
			SLOT(onCreateSessionCompleted(const bb::network::PushStatus&)));
	QObject::connect(&m_pushNotificationService,
			SIGNAL(createChannelCompleted(const bb::network::PushStatus&, const QString)),
			this,
			SLOT(onCreateChannelCompleted(const bb::network::PushStatus&, const QString)));
	QObject::connect(&m_pushNotificationService,
			SIGNAL(destroyChannelCompleted(const bb::network::PushStatus&)),
			this,
			SLOT(onDestroyChannelCompleted(const bb::network::PushStatus&)));
	QObject::connect(&m_pushNotificationService,
			SIGNAL(registerToLaunchCompleted(const bb::network::PushStatus&)),
			this,
			SLOT(onRegisterToLaunchCompleted(const bb::network::PushStatus&)));
	QObject::connect(&m_pushNotificationService,
			SIGNAL(unregisterFromLaunchCompleted(const bb::network::PushStatus&)),
			this,
			SLOT(onUnregisterFromLaunchCompleted(const bb::network::PushStatus&)));
	QObject::connect(&m_pushNotificationService,
			SIGNAL(piRegistrationCompleted(int, const QString)), this,
			SLOT(onPIRegistrationCompleted(int, const QString)));
	QObject::connect(&m_pushNotificationService,
			SIGNAL(piDeregistrationCompleted(int, const QString)), this,
			SLOT(onPIDeregistrationCompleted(int, const QString)));
	QObject::connect(&m_pushNotificationService, SIGNAL(simChanged()), this,
			SLOT(onSimChanged()));
	QObject::connect(&m_pushNotificationService,
			SIGNAL(pushTransportReady(bb::network::PushCommand::Type)), this,
			SLOT(onPushTransportReady(bb::network::PushCommand::Type)));
	QObject::connect(&m_pushNotificationService,
			SIGNAL(noPushServiceConnection()), this,
			SLOT(onNoPushServiceConnection()));
	QObject::connect(&m_pushNotificationService, SIGNAL(allPushesRemoved()),
			this, SLOT(onAllPushesRemoved()));

	//qDebug()<<"\n size ::::::::"<<SubcriptDB::readBBMState();
	QString qmlDocument = "asset:///main.qml";

				QmlDocument *qml = QmlDocument::create(qmlDocument).parent(this);
				qml->setContextProperty("_pushAPIHandler", this);
				qml->setContextProperty("appRef", this);

				NavigationPane *root = qml->createRootObject<NavigationPane>();


				// populate the model with the pushes that are stored in the database
			//	m_model->insertList(m_pushNotificationService.pushes());

				// connect to InvokeManager "invoked" signal to handle incoming push notifications.
				// We will ignore non-push invoke requests.
				connect(m_invokeManager,
						SIGNAL(invoked(const bb::system::InvokeRequest&)),
						SLOT(onInvoked(const bb::system::InvokeRequest&)));

						
				
				saveConfiguration(); // PPG URL,APLICATION _ID are Hard-coded 
				createChannel();
				initializePushSession();
				UserDAO *dao = new UserDAO(); //USER_ID,PASSWORD are Hard-coded 
				dao->initSave(); 

				// here we are checking  if any push messages  are reached. If push messages are found, we are trying // to show push screen other wise push enabled app home screen 
				QVariantList model_list_temp=	m_pushNotificationService.pushes();
				int size=model_list_temp.size();
				QVariantList model_list;

	if ( size > 0) {
 //  If push messages are found, we are trying  to show push screen 
			fapp->setScene(root);
			Helper::writeToLog("\n App::setScene push message  is called");

		for (int i = 0; i < size; i++) {
			Helper::writeToLog("\n Push Message Size"+size);

			QString content = model_list_temp.at(i).toString();

			Helper::writeToLog("\n Push Content "+content);

			bool isBool, ok;
			QString temp = content.split("AlertExecuted:").at(1); 
			QString temp1 = temp.split(';').at(0);// returns alert_id as String and Alert_id is unique for each alerts
			int alert_id = temp1.toInt(&isBool); // converting into integer 

			QList < QVariantMap > list =
					DatabaseOperations::read_Alert_Records_serverid(alert_id);


			if (list.size() > 0) {
				QMap<int, QString> map = Helper::getJsonMap();

				// gets the corresponding symbol name for alert_id
				QString symb = map[list.at(0)["AlertSymb"].toInt(&ok)]; 
				

			     
				// converting into required push message format (for example: Alert: ABSD is reached : 1234 )
				QString alertText = tr("Alert:  ") + symb + " "+ tr("is reached :  ")	+list.at(0)["AlertPrice"].toString();

				Helper::writeToLog("\n Push Alert Format"+alertText);
				qDebug()<<"\n Push Alert Format"+alertText;


				model_list.append(alertText); // giving the push messages to model for displaying in list-view
				
				// once the push messages are shown to user, we have to delete the local push history for fresh pushes. 

				QString sid = list.at(0)["Id"].toString();
				qDebug() << "\n sid::::" << sid;
				Helper::writeToLog("App::App " + symb+ " is Reached");

				qDebug()<<"App::App " + symb+ " is Reached";

				DatabaseOperations::deleteOf(sid.toInt(&ok));
				Helper::writeToLog("\n Locally saved  Alert is deleted");
				qDebug()<<"\n Locally saved  Alert is deleted";
			}
		}


			// populate the model with the pushes that are stored in the database
			m_model->insertList(model_list);
			Helper::writeToLog("\n Pushes are given to Push model");
	
			bool yes=m_pushNotificationService.removeAllPushes();
			bool ok=m_pushNotificationService.removeAllPushHistory();
			if(yes){
				Helper::writeToLog("\n all the pushes  are removed");
				qDebug()<<"\n  all the pushes  are removed";
			}
			if(ok){
				Helper::writeToLog("\n all push history are removed");
				qDebug()<<"\n all push history are removed";
			}

	} else {
			// otherwise Navigating push enabled app home screen.

		}
}

   but app is crashing whie opening the app after receiving the push message and not opening the app home page    at all.

 

   can you guide me how to fix this and display push message.

 

    Thanks !!!