Hebrew letters are empty - android

I am building an app which needs to support Hebrew letters (שלום). I am sending a message thru GCM (Google Cloud Messaging). Whenever my OnMessage is called the string (Hebrew) that I am receiving is empty.
Is there any easy workaround for this? Thanks in advance!
protected void onMessage(Context context, Intent intent) {
String message = intent.getStringExtra(GCM_COMMAND);
String action = intent.getAction();
if ("com.google.android.c2dm.intent.RECEIVE".equals(action)) {
message = intent.getStringExtra(GCM_COMMAND);
String s = message.toString();
ItemBean ib =parseJson(s,context);
}
private ItemBean parseJson(String text,Context con) {
ItemBean item = null;
if (text != null) {
JSONObject temp;
try {
temp = new JSONObject(text);
String itemMessage = temp.get(GCM_MESSAGE).toString();
//This String is Empty!
String itemDate = temp.get(GCM_DATE).toString();
long currentTime = System.currentTimeMillis();
item = new ItemBean(currentTime,itemMessage,itemDate);
sendNotification(con,itemMessage,itemDate);
}
}
return item;
}
Server code from NetBeans
JSONObject json = new JSONObject();
System.out.println("******גגגגגגשלום*********");
json.put(GCM_MESSAGE, ib.getmMessage());
//This is hebrew no problem!
json.put(GCM_DATE, ib.getmDate());
Message.Builder builder = new Message.Builder();
Message message = builder.build();
MulticastResult result = sender.send(message, listOfRegisteredDevices, 5);
int success = result.getSuccess();

Can you try :
String itemMessage = temp.getString(GCM_MESSAGE);
and also
json.put(GCM_MESSAGE, JSonObject.quote( ib.getmMessage() ) );

Related

FCM onReceived method to implement Shortcut Badger library

I found this library (https://github.com/leolin310148/ShortcutBadger) to implement app icon counter badge in android.
badge works when i implement in activity. but i want to implement this when push notification is received. i currently have the initialize code in onMesseageReceived() method in Firebase messaging service but its not working.
see code below:
Thanks for your help
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Logger.i("Received message");
//Shourtcut Badger
int badgeCount = 1;
ShortcutBadger.applyCount(context, badgeCount);
//parseNotification(bundle);
parseNotification(remoteMessage.getData());
if (remoteMessage.getData() != null) {
String str = remoteMessage.getData().get("notification");
String from_user = "";
String message = "";
String name = "";
int type = 0;
if (str != null && str.length() > 0) {
try {
JSONObject jobj = new JSONObject(str);
from_user = jobj.optString("from");
message = jobj.optString("message");
name = jobj.optString("name");
type = Integer.parseInt(jobj.optString("type"));
if (type == LIKE_STATUS) {
handleStatusLikeByFriendPush(jobj, "" + type);
} else if (type == PHOTO_UPDATE) {
handlePhotoUpdateByFriendPush(jobj, "" + type);
} catch (Exception e) {
e.printStackTrace();
}
} else {
message = "";//bundle.getString("message");
from_user = "";//bundle.getString("source");
if (from_user != null && from_user.contains(IMHandler.AT + IMHandler.DOMAIN)) {
from_user = from_user.substring(0, from_user.indexOf(IMHandler.AT));
}
showNotification(from_user, message, type, name);
}
}
}
public void handleStatusLikeByFriendPush(JSONObject jobj, String pushType) {
// method
}
public void handlePhotoLikeByFriendPush(JSONObject jobj, String pushType) {
//method implement
}
}
private void showNotification(String from, String body, int type, String name) {
}
}
After lots of research i understand implementation of this Shortcut badge is not working in FCM service. I Am Able to resolve this issue by simply calling a a custom service from FCM service each time push notification is received and the custom service handles the badge codes and there affter destroys itself.
This way is working perfectly.

Web API server controller doesn't get parametrs

I send JSON data from android app. In server side I have issue - Web API server controller doesn't get parametrs. From client side I send json data like this:
{ "TypeID ": "1",
"FullName": "Alex",
"Title": "AlexTitle",
"RegionID": "1",
"CityID ": "1",
"Phone1": "+7(705)105-78-70"
}
Any help appreciated, please if you have some information, idea let me know, thank you!
This is controller
[System.Web.Http.HttpPost]
public HttpResponseMessage PostRequisition([FromBody]string requisition)
{
Requisition postReq = new Requisition();
if (!String.IsNullOrEmpty(requisition))
{
dynamic arr = JValue.Parse(requisition);
//PostReq model = JsonConvert.DeserializeObject<PostReq>(requisition);
postReq.FullName = arr.FullName;
postReq.CityID = Convert.ToInt32(arr.CityID);
postReq.RegionID = Convert.ToInt32(arr.RegionID);
postReq.TypeID = Convert.ToInt32(arr.TypeID);
postReq.UserID = 8;
postReq.Title = arr.Title;
postReq.Date = Convert.ToDateTime(arr.Date, CultureInfo.CurrentCulture);
postReq.Decription = arr.Description;
postReq.Phone1 = arr.Phone1;
postReq.Activate = false;
postReq.ClickCount = 0;
try
{
db.Requisition.Add(postReq);
db.SaveChanges();
Message msg = new Message();
msg.Date = DateTime.Now;
msg.Type = "POST";
msg.Text = "OK";
db.Message.Add(msg);
db.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, postReq);
}
catch (Exception ex)
{
Message msg = new Message();
msg.Date = DateTime.Now;
msg.Type = "POST";
msg.Text = "ERROR";
db.Message.Add(msg);
db.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, ex.Message);
}
}
else
{
Message msg = new Message();
msg.Date = DateTime.Now;
msg.Type = "POST";
msg.Text = "null";
db.Message.Add(msg);
db.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, "null");
}
}
Your problem is simple. You are sending a JSON object but are expecting a string in your POST action. Simple way to fix this is creating a class that maps to your JSON object:
public class RequisitionViewModel
{
public int TypeID {get; set;}
public string FullName {get; set;}
public string Title {get; set;}
public int RegionID {get; set;}
public int CityID {get; set;}
public string Phone1 {get; set;}
}
Then, change your action signature to:
[FromBody]RequisitionViewModel requisition)
You also don't need all the converting in your code:
postReq.FullName = requisition.FullName;
postReq.CityID = requisition.CityID;
//other fields...

Unable to send messages to multiple recipients through Sinch in Android App

I have tried sending a Sinch message in my Android app and it works perfectly when sending to a single recipient
MyClass
String userId= "abc";
CustomReplyMessageBuild customMessage = new CustomReplyMessageBuild();
customMessage.setRecepientIDs(userId);
Map<String, String> m1 = new HashMap<String, String>();
m1.put(“param1", "YES");
m1.put(“param2”, 123);
m1.put(“param3", time);
customMessage.setHeaders(m1);
messageService.sendMessage(customMessage);
MyBean
private List<String> RecepientIds = new ArrayList<String>();
private Map map;
private void setHeaders(Map map) {
this.map = map;}
private void setRecepientIDs(String id) {
this.RecepientIds.add(id);
}
MyService
private MessageClient messageClient = client.getMessageClient();
public void sendMessage(MyClass.CustomReplyMessageBuild conf_message){`
if(messageClient != null){
WritableMessage message = new WritableMessage(conf_message);
messageClient.send(message);
}
}
But when i try passing a list of recipient ids (for a broadcast sort of feature) , i am unable to receive the message at the other end .
MyBroadcastClass
List<String> broadcastIdList;
String recepId = "a,b,c";
CustomReplyMessageBuild customMessage = new CustomReplyMessageBuild();
broadcastIdList = Arrays.asList(recepId.split(","));
customMessage.setRecepientIdList(broadcastIdList);
Map<String, String> m1 = new HashMap<String, String>();
m1.put(“param1", "YES");
m1.put(“param2”, 123);
m1.put(“param3", time);
customMessage.setHeaders(m1);
messageService.sendMessage(customMessage);
MyBroadcastBean
private List<String> RecepientIds = new ArrayList<String>();
private Map map;
private void setHeaders(Map map) {
this.map = map;}
private void setRecepientIdList(List<String> idList) {
this.RecepientIds.addAll(idList);
}
Please let me know if you spot an error or can post a sample snippet or link to solve this problem.
Thanks a ton!
To send messages to multiple recipients try the following constructor:
// Create a WritableMessage and send to multiple recipients
WritableMessage message = new WritableMessage(
{"recipient user id 1", "recipient user id 2"},
"Hello recipients! How are you?");
// Send it
messageClient.send(message);

gmail-api marking as "read"

Using gmail-api I am trying to mak a message as "read" as below but it s not working.
ModifyMessageRequest mods = new ModifyMessageRequest()
.setRemoveLabelIds(new ArrayList<String>(Arrays.asList("UNREAD")));
com.google.api.services.gmail.model.Message message = null;
try {
message = mService.users().messages().modify(acct.sEmail, gmsailID, mods).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
The argument for setRemoveLabelIds() is not the Label String but the Label ID.
So get the label ID from the code below and use that in your function
List<String> labels = new ArrayList<String>();
ListLabelsResponse listResponse = service.users().labels().list(userId).execute();
for (Label label : listResponse.getLabels()) {
Label countLabel = service.users().labels().get(userId, label.getId()).execute();
if (countLabel.getName().equalsIgnoreCase("UNREAD"))
unreadId = countLabel.getId();
}
List<String> add = new ArrayList<String>();
List<String> remove = new ArrayList<String>();
remove.add(unreadId);
modifyMessage(service, userId, message.getId(), add, remove);
public static void modifyMessage(Gmail service, String userId, String messageId,
List<String> labelsToAdd, List<String> labelsToRemove) throws IOException {
ModifyMessageRequest mods = new ModifyMessageRequest().setAddLabelIds(labelsToAdd)
.setRemoveLabelIds(labelsToRemove);
Message message = service.users().messages().modify(userId, messageId, mods).execute();
}
Here is one that I use (after getting messageId with ListMessagesResponse):
public void modifyMessage(String userId, String messageId) throws IOException {
List<String> lblIDRemove=new ArrayList<String>();
lblIDRemove.add("UNREAD");
ModifyMessageRequest mods = new ModifyMessageRequest()
.setAddLabelIds(null)
.setRemoveLabelIds(lblIDRemove);
Message message = mService.users().messages().modify(userId, messageId, mods).execute();
}

Finish the activity after receiving response from server

I want to finish the activity when received complete response from server in another java class.
Category.java
This is main activity
public void onListItemClick(ListView parent, View v, int position, long id)
{
// Get the selected category id & name.
String catId = "";
String catName = "";
LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayout1);
View view = ll.getChildAt(0);
if(view instanceof ListView) {
ListView lView = (ListView) view;
RowData rowData = (RowData) lView.getAdapter().getItem(position);
catId = rowData.mCatId;
catName = rowData.mTitle;
}
String url = "http://global.thinlenses.co.uk/virtualMirror/productlisting.php";
String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "<category><Id>" + catId + "</Id>"
+ "<Data>" + "pList" + "</Data></category>";
if(getIntent().getBooleanExtra("VM", false))
new SpinnerHelper().serverCall(Category.this, "ProductListVM", url, xml, catName);
else
new SpinnerHelper().serverCall(Category.this, "ProductList", url, xml, catName);
}
SpinnerHelper.java Regular Class not Activity
void serverCall(Context context, final String target, final String url, final String xml, String extraValue)
{
try {
this.context = context;
this.target = target;
this.extraValue = extraValue;
ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if(conMan.getActiveNetworkInfo() != null && conMan.getActiveNetworkInfo().isConnected())
{
dialog = new ProgressDialog(context);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(true);
dialog.setTitle(R.string.app_name);
dialog.setMessage(context.getString(R.string.progressing));
dialog.show();
// Create a thread for updating the spinner.
Thread progressThread = new Thread(new Runnable() {
public void run() {
try {
while(!isExecuted) {
Thread.sleep(1000); // Wait 1000ms between each update.
handler.sendMessage(handler.obtainMessage()); // Active the update handler.
}
}
catch (InterruptedException e) {
Log.e("VM", "Exception while spinner is updating at: " + e.getMessage());
}
}
});
progressThread.start();
// Create a thread to get response from server.
Thread registerThread = new Thread(new Runnable() {
public void run()
{
// Get response XML from server and parse it.
String resXML = new Connection().getResponse(url, xml);
XMLParser parser = new XMLParser();
Document doc = parser.getDomElement(resXML);
if(doc != null)
{
if(target.equals("Category")) {
NodeList nodeList = doc.getElementsByTagName("Category");
name = new String[nodeList.getLength()];
id = new String[nodeList.getLength()];
// Fetch all node values and store into arrays.
for(int index = 0; index < nodeList.getLength(); index++)
{
Element element = (Element) nodeList.item(index);
id[index] = parser.getValue(element, "id");
name[index] = parser.getValue(element,"CategoryName");
}
result = "yes";
}
}
}
This handler is called when i recieved complete reponse from server.
Handler handler = new Handler()
{
public void handleMessage(Message message)
{
if(isExecuted)
{
dialog.dismiss();
isExecuted = false;
if(result.equals("yes"))
{
/////HERE i want to start the next activity and finish the Category(previous activity).
}
you can use your context reference for this
Intent intent = new Intent(context,nextActivity.class);
context.startActivity(intent);
((Activity) context).finish();

Categories

Resources