I am working on a project where i am creating a java app for watering plants.The idea to get weather information from online and based on that output should be if we plants require water or not.For weather information,i found an API OpenWeatherMap and i tried to implement it using educational video from YouTube.I don't have past experience with API's. The video i am using is "https://www.youtube.com/watch?v=og5h5ppwXgU" .I tried to implement my program the same way that guy did,but i am not getting any output.It just prints what's in the print statements ,not the actual data.
public static Map<String,Object> jsonToMap(String str){
Map<String,Object> map = new Gson().fromJson(str,new
TypeToken<HashMap<String,Object>> () {}.getType());
return map;
}
public static void main(String[] args) {
String API_KEY = "16 digit Private Key";
String LOCATION = "Los Angeles,CA";
String urlString = "http://api.openweathermap.org/data/2.5/weather?
q=" + LOCATION + "&appid=" + API_KEY + "&units =imperial";
try{
StringBuilder result = new StringBuilder();
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader (conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null){
result.append(line);
}
rd.close();
System.out.println(result);
Map<String, Object > respMap = jsonToMap (result.toString());
Map<String, Object > mainMap = jsonToMap (respMap.get("main").toString());
Map<String, Object > windMap = jsonToMap (respMap.get("wind").toString());
System.out.println("Current Temperature: " + mainMap.get("temp") );
System.out.println("Current Humidity: " + mainMap.get("humidity") );
System.out.println("Wind Speed: " + windMap.get("speed") );
System.out.println("Wind Angle: " + windMap.get("deg") );
}catch (IOException e){
System.out.println(e.getMessage());
}
}
I received errors that gson library doesn't exist ,but after i cretaed my own library in net beans with javadoc,class path and soureces,the problem got resolved ,so i think that correct.Also the API key for openweathermap is also valid.I am just not able to get the code to get online information.
Output :
http://api.openweathermap.org/data/2.5/weatherq=Los Angeles,CA&appid="16 digit Private Key"&units =imperial
Expected Output : Current weather information of LA
Implementation of OpenWeatherMapApi with given latitude and longitude. For Network request Retrofit & Jsonschema2pojo to create model.
Hope this will help.
public void getWeatherDetails(double latitude, double longitude) {
String url = "http://api.openweathermap.org/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url) //This is the only mandatory call on Builder object.
.addConverterFactory(GsonConverterFactory.create()) // Convertor library used to convert response into POJO
.build();
WeatherApiService weatherApiService = retrofit.create(WeatherApiService.class);
weatherApiService.requestWeather(String.valueOf(latitude), String.valueOf(longitude), "metric", "10").enqueue(new UpasargaCallback<WeatherModel>() {
#Override
public void onResponse(Call<WeatherModel> call, Response<WeatherModel> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
if (getView() != null) {
getView().onWeatherApiSuccess(response.body());
}
}
}
}
#Override
public void onFailure(Call<WeatherModel> call, Throwable t) {
if (getView() != null) {
getView().onWeatherApiFailure(String.valueOf(t.getMessage()));
}
}
});
}
WeatherApiService
public interface WeatherApiService {
#Headers("x-api-key: " + AppConstants.WEATHER_API_KEY)
#GET("data/2.5/forecast")
Call<WeatherModel> requestWeather(#Query("lat") String lat,#Query("lon") String lon,#Query("units") String units,#Query("cnt") String count);
}
See WeatherModel.java
I tested the API with your app key in the browser. It was successful. Maybe you should encode your URL. It has a blank space which is a special character.
Related
I am using Okhttp lib to send data to server. I want to set text and images in RequestBody. For uploading multiple image to server using Okhttp i follow this link. I have implemented that type of code in my app in another activity class and its work fine. I have checked this question that how to pass array in RequestBody.
My arrayList format is like this
blockList
{
block0
{
description0 = First block
image0 = {image1, image2}
video0 = videolink
disp_order0 = 0
block0 = 0
}
block1
{
description1 = second block
image1 = {image1,image2,image2}
video1 = videolink
disp_order1 = 1
block1 = 1
}
.....
}
My Requirement :-
Now i want to send multiple images as an array in single parameter. When i send first block then parameter names are description0,image0[],video1,disp_order and block0 and image0[] will contain first block images as array and same for other.
API is working fine because when i test in postman then i receive the data in server side. You can see in below..
Here is my java function that set the data in RequestBody and make a call to send that data on sever.
ProgressDialog pd;
private OkHttpClient client;
private void saveCastBoxOnServer(String castBoxTitle, String selectedCastBoxId, String selectedCategoryId,
String userId, String action, ArrayList<CastBoxBlock> blockList)
{
try
{
client = new OkHttpClient.Builder()
.retryOnConnectionFailure(true)
.build();
ArrayList<CastBoxBlock> blockArrayList = blockList;
int blockSize = blockArrayList.size();
MultipartBody.Builder multipartBuilderNew = new MultipartBody.Builder().setType(MultipartBody.FORM);
for (int i = 0; i < blockSize; i++)
{
String description = blockArrayList.get(i).getBlockDescription();
String descriptionField = "description"+i;
multipartBuilderNew.addFormDataPart(descriptionField, description);
/**This is used for distribution of images and videos. After that set that
* Images and video in multipartBuilder.
**/
CastBoxBlock model = blockArrayList.get(i);
ArrayList<SelectedMediaModel> mediaModels = model.getSelectedMediaModelArrayList();
int mediaModelsSize = mediaModels.size();
String passingVideoUri = "";
String videoUri = "";
for (int j = 0; j < mediaModelsSize; j++)
{
String mediaType = mediaModels.get(j).getMediaType();
if (mediaType.equals(StringKeyConstant.mediaVideo))
{
videoUri = mediaModels.get(j).getMediaPath();
if (passingVideoUri.trim().length()==0){
passingVideoUri = videoUri;
}else{
passingVideoUri = passingVideoUri + "," + videoUri;
}
}
else if (mediaType.equals(StringKeyConstant.mediaImage))
{
String imagePath = mediaModels.get(j).getMediaPath();
File sourceFile = new File(imagePath);
/**Changes whether JPEG or PNG**/
final MediaType MEDIA_TYPE = MediaType.parse(
constant.getFileExt(imagePath).endsWith("png") ? "image/png" : "image/jpeg");
String imageName = System.currentTimeMillis() + j + "_block_img.jpg";
String imageField = "image"+i+"["+j+"]";
multipartBuilderNew.addFormDataPart(imageField,imageName,
RequestBody.create(MEDIA_TYPE, sourceFile));
}
}
/**This is used to set the {#videoUri} block of videos and send to sever**/
String videoField = "video"+i;
multipartBuilderNew.addFormDataPart(videoField, passingVideoUri);
/**This will set the {#display_order} in multipartBuilder**/
String displayOrderField = "disp_order"+i;
String displayOrder = blockArrayList.get(i).getBlockIndex();
multipartBuilderNew.addFormDataPart(displayOrderField, displayOrder);
/**This will set the {#block} value in multipartBuilder**/
String blockField = "block"+i;
String block = ""+i;
multipartBuilderNew.addFormDataPart(blockField, block);
}
pd = new ProgressDialog(activity);
pd.setCancelable(false);
pd.setMessage(getResources().getString(R.string.please_wait));
pd.show();
RequestBody formBody = multipartBuilderNew
.addFormDataPart("cast_title", castBoxTitle)
.addFormDataPart("user_id", userId)
.addFormDataPart("cast_box", selectedCastBoxId)
.addFormDataPart("category", selectedCategoryId)
.addFormDataPart("action", action)
.build();
Request request = new Request.Builder()
.url(ApiUtils.ADD_FETCH_USER_CAST)
.post(formBody)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.e(TAG, "Get Api credential fail."+call.toString());
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException
{
try
{
if (pd != null){
pd.cancel();
pd.dismiss();
pd = null;
}
String castSavedResponse = response.body().string();
Log.i(TAG, "castSavedResponse = " + castSavedResponse);
}
catch (Exception e){
Log.e(TAG, "***Error : onResponse() method");
e.printStackTrace();
}
}
});
}
catch (Exception e){
Log.e(TAG, "***Error : saveCastBoxOnServer()");
e.printStackTrace();
}
}
Thanks in advance. If any one will help it would be very appreciate.
When i check your code then i note one things. I am no sure but i think you change your code on image[] place. you can just change your code as below. I hope this will help you and you got the solution.
Use this code
String imageField = "image"+i+"[]";
Instead of
String imageField = "image"+i+"["+j+"]";
when i passed simple images as an array in Okhttp then i do code as above. For uploading multiple images on server using Okhttp, i also follow this link as you follow.
I'm trying to build a very basic weather app in android studio. I am using AsyncClass to return multiple strings.
As you can see in the code, I used a class named "Wrapper" that is used to store my strings so I can just return a class object and use it in the onPostExecute method of the AsyncTask. The problem I am facing is that when I test the app, all of the returned Strings somehow are undefined (the default for the Wrapper class). This means the strings are not being updated in the doInBackground method and I can't seem to figure out why!
My Activity
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(MainActivity.class.getSimpleName(), "Can't connect to Google Play Services!");
}
private class Wrapper
{
String Temperature = "UNDEFINED";
String city = "UNDEFINED";
String country = "UNDEFINED";
}
private class GetWeatherTask extends AsyncTask<String, Void, Wrapper> {
private TextView textView;
public GetWeatherTask(TextView textView) {
this.textView = textView;
}
#Override
protected Wrapper doInBackground(String... strings) {
Wrapper w = new Wrapper();
String Temperature = "x";
String city = "y";
String country = "z";
try {
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
JSONObject topLevel = new JSONObject(builder.toString());
JSONObject main = topLevel.getJSONObject("main");
JSONObject cityobj = topLevel.getJSONObject("city");
Temperature = String.valueOf(main.getDouble("temp"));
city = cityobj.getString("name");
country = cityobj.getString("country");
w.Temperature= Temperature;
w.city= city;
w.country=country;
urlConnection.disconnect();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return w;
}
#Override
protected void onPostExecute(Wrapper w) {
textView.setText("Current Temperature: " + w.Temperature + " C" + (char) 0x00B0
+"\n" + "Current Location: "+ w.country +"\n" + "City: "+ w.city );
}
}
}
UPDATE:
turned out that that I was using the wrong url in my code,I was using :
http://api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&units=%s&appid=%s
Instead I should've been using:
http://api.openweathermap.org/data/2.5/forecast?lat=%f&lon=%f&units=%s&appid=%s
-aka instead of weather I should've been using forcast
Your error starts here
JSONObject main = topLevel.getJSONObject("main");
Probably because the topLevel object has no "main" key.
{
"city":{ },
"cod":"200",
"message":0.1859,
"cnt":40,
"list":[ ]
}
Throw your JSON into here. https://jsonformatter.curiousconcept.com/
You'll notice that there are many, many "main" keys that are within the "list" element, but you have to parse those starting from getJSONArray("list").
Basically, something like this
String city = "undefined";
String country = "undefined";
List<Double> temperatures = new ArrayList<Double>();
try {
JSONObject object = new JSONObject(builder.toString());
JSONObject jCity = object.getJSONObject("city");
city = jCity.getString("name");
country = jCity.getString("country");
JSONArray weatherList = object.getJSONArray("list");
for (int i = 0; i < weatherList.length(); i++) {
JSONObject listObject = weatherList.getJSONObject(i);
double temp = listObject.getJSONObject("main").getDouble("temp");
temperatures.add(temp);
}
} catch (JSONException e) {
e.printStackTrace();
}
return new Wrapper(city, country, temperatures);
After studying your code, either your try block is failing, which is returning your object, but empty, or there is something wrong with your JSON parsing. If you could show us the JSON you are trying to parse that would be a great help.
That being said, the fact that it is still showing as "UNDEFINED" is because that is how you initialised it, and becuase (the JSON parse is likely failing), the object is being returned in an un-edited state.
EDIT:
You are parsing the JSON wrong. You are trying to find an object called "main" in the top directory, however the main object only exists inside of an array called list!
Please look here for a more easy to see and visual representation: http://prntscr.com/dlhlrk
You can use this site to help visualise your JSON and create an appropriate soluton based upon it. https://jsonformatter.curiousconcept.com/
Looking at the API you posted earlier (api.openweathermap.org) you are trying to access variables that don't exist. I suggest you have a look at what the API returns and try getting the variables one by one if you are getting a JSONException
EDIT:
What API you are using? In your initial post you said it was http://api.openweathermap.org/data/2.5/weather but in a comment above you said it was http://api.openweathermap.org/data/2.5/forecast.
If you're using the weather API (as initially stated) you can use the below:
#Override
protected Wrapper doInBackground(String... strings) {
Wrapper w = new Wrapper();
try {
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
Log.d("JSON", builder.toString());
JSONObject topLevel = new JSONObject(builder.toString());
JSONObject main = topLevel.getJSONObject("main");
JSONObject sys = topLevel.getJSONObject("sys");
w.Temperature = String.valueOf(main.getDouble("temp"));
w.city = topLevel.getString("name");
w.country = sys.getString("country");
urlConnection.disconnect();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return w;
}
I am trying to use restFB API to get events for several FB companies pages since now until number of days in the future. Somehow it returns nothing. Facebook Graph API returns the results:
https://developers.facebook.com/tools/explorer/145634995501895/?method=GET&path=AmericanChemicalSociety%2Fevents%3Fsince%3Dnow%26until%3D%2B50%20day&version=v2.7
But it is not working when I am trying to implement it in Java:
private Map<String, ArrayList<JsonObject>> fetchEventsForPeriod(Integer daysAhead) {
Map<String, ArrayList<JsonObject>>mapOfEvents = new HashMap<String, ArrayList<JsonObject>>();
if (this.companiesNamesList.size() == 0) {
getCompanies();
}
for (String companyName : this.companiesNamesList) {
ArrayList<JsonObject>companyEventList = new ArrayList<JsonObject>();
Connection<JsonObject> eventListConnection = this.fbClient.fetchConnection(companyName + "/events",
JsonObject.class, Parameter.with("since", "now"), Parameter.with("until", "+ " + daysAhead + " day"));
while (eventListConnection.hasNext()) {
for (List<JsonObject> eventConnectionPage : eventListConnection) {
for (JsonObject event : eventConnectionPage) {
event.put("univNameId", companyName);
String imageURL = formImageURLFromId(event.get("id").toString());
event.put("imageURL", imageURL);
companyEventList.add(event);
}
}
eventListConnection = this.fbClient.fetchConnectionPage(eventListConnection.getNextPageUrl(), JsonObject.class);
}
mapOfEvents.put(companyName, companyEventList);
}
return mapOfEvents;
}
Basically giving me empty results
restFB is initialized correctly and working for other simpler requests:
private final String appAccessToken = "839761616150633|XMK9PSdojx6uCsOmoGccQC7XMTY";
private FacebookClient fbClient;
#SuppressWarnings("deprecation")
public FacebookRestFB() {
this.companiesList = new JsonArray();
this.companiesNamesList = new ArrayList<String>();
try {
this.fbClient = new DefaultFacebookClient(this.appAccessToken, Version.LATEST);
} catch (FacebookException ex) {
ex.printStackTrace(System.err);
}
}
Update #1
The issue is not yet solved. Any suggestion would be greatly appreciated
My web service publish push notification to APNs and APNs send to destination IOS device.
When apns contain Unicode emoji on alert body push notification and Iphone os can't decode my Unicode emoji '\uD83D\uDE0A' app already kill.
Push notification show same '\uD83D\uDE0A', No emoji shown on banner notification bar on top.
Android application works fine by GCM dispatches push notification But IOS not support.
Iphone-Ios supports only this format '\ue415'
Here code that from ActiveMQ subscribe chat payload get into web-service
public void onPublish(UTF8Buffer topic, Buffer msg, Runnable ack) {
try {
String body = msg.utf8().toString();
if (logger.isInfoEnabled()) {
logger.info("MQTT connection.listener.onPublish(), msg Received ["
+ body + "]");
}
if (body.contains("\"cmd\":\"chat\"")
&& body.contains("\"is_sender_msg\":true")) {
QueueMgr.addToChatQueue(body); //Changed true to false
}
else if(body.contains("\"cmd\":\"msg_seen\"")){
QueueMgr.addToChatReadSeenQueue(body);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
ack.run();
}
}
My code for create push notification on java
public static JSONObject constructePushJson(JSONObject jsonObject,String[] cloudkeyWithDevice) throws JSONException {
if(cloudkeyWithDevice[0] != null){
JSONObject pnAPIdata = new JSONObject();
if(cloudkeyWithDevice[1].equals("a") || cloudkeyWithDevice[1].equals("d")){
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_CMD, com.anyorg.constants.AppConstants.CMD_ANDROID_PUSH);
}
else{
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_CMD, com.anyorg.constants.AppConstants.CMD_IOS_PUSH);
}
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_APP_TOKEN, com.anyorg.constants.AppConstants.DEFAULT_APP_TOKEN);
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_DEVICE_TOKEN, cloudkeyWithDevice[0]);
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_USER_ID, jsonObject.getInt(com.anyorg.constants.AppConstants.FLD_TO_USER_ID));
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_DEVICE_ID, 0);
String alertMsg=StringEscapeUtils.unescapeJava(jsonObject.getString(com.anyorg.constants.AppConstants.FLD_BODY));
jsonObject.put(com.anyorg.constants.AppConstants.FLD_BODY,alertMsg);
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_ALERT_MSG, "AryaConnect: "+alertMsg);//(jsonObject.isNull("body")) ? jsonObject.getString("from_user_name")+": Sent a file" : jsonObject.getString("from_user_name")+": "+jsonObject.getString("body")
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_MSG, jsonObject);//jsonObject.getString(com.anyorg.constants.AppConstants.FLD_BODY)
pnAPIdata.put(com.anyorg.constants.AppConstants.FLD_CALLBACK_URL, callbackUrl);
pnAPIdata.put(com.anyorg.constants.AppConstants.MAC_ADDRESS_ID, jsonObject.getString("mobile_rec_id"));
return pnAPIdata;
}
else{
return null;
}
}
Publish to APNs code
public class ANSNotificationDispatcher implements NotificationDispatcher {
protected static final Logger logger = Logger
.getLogger(ANSNotificationDispatcher.class);
public static final String OS_NAME = AppConstants.OS_TYPE_IPHONE;
String keystore;
String password;
boolean production;
public ANSNotificationDispatcher() {
try {
keystore = AppConfig.getAPNKeystore();
password = AppConfig.getAPNKeystorePassword();
PushyAPNMgr.init(keystore, password, AppConfig.isAPNProdcution());
} catch (Throwable e) {
e.printStackTrace();
}
}
private void push(Payload payload, String token, String userId,
String deviceId) throws ConfigurationException,
DeviceUnregisteredException {
// QueueManager.addToIOsQueue(payLoad, token, userId, ivUserDeviceId);
long stime = System.currentTimeMillis();
try {
PushyAPNMgr.push(token, payload.toString());
if (logger.isInfoEnabled())
logger.info("push(): APN PN userId [" + userId
+ "], device id [" + deviceId + "] payoad [" + payload
+ "] Response time ["
+ (System.currentTimeMillis() - stime) + "]ms");
} catch (Exception e) {
e.printStackTrace();
throw new ConfigurationException();
}
}
public static Payload createComplexPayload(JSONObject jsonObject) {
PushNotificationPayload complexPayload = null;
try {
complexPayload = createPayload(jsonObject);
String msg = Common.getStringAsNull(jsonObject,
AppConstants.FLD_MSG);
if (!Common.isEmpty(msg)) {
complexPayload.addCustomDictionary(AppConstants.FLD_MSG, msg);
}
if (logger.isInfoEnabled()) {
logger.info("createComplexPayloadV2(): payload ["
+ complexPayload.getPayload().toString() + "]");
}
} catch (JSONException e) {
e.printStackTrace();
}
return complexPayload;
}
public void dispatch(JSONObject jsonObject, String jsonData)
throws NotificationException, DeviceUnregisteredException,
MultipleRegistartionIdException, ConfigurationException {
String deviceToken = Common.getStringAsNull(jsonObject,
AppConstants.FLD_DEVICE_TOKEN);
if (Common.isEmpty(deviceToken)) {
logger.error("dispatch(): device token is null, cmd [" + jsonData
+ "]");
return;
}
Payload payload = createComplexPayload(jsonObject);
String userId = Common.getStringAsNull(jsonObject,
AppConstants.FLD_USER_ID);
String deviceId = Common.getStringAsNull(jsonObject,
AppConstants.FLD_DEVICE_ID);
push(payload, deviceToken, userId, deviceId);
}
public static void handleInvalidTokeException(String token) {
}
public static void handleDeviceUnregisteredException(String token) {
}
}
Ios push notification managed by Ios OS
My Apache Catalina log
I am a web service cloud developer faceing this issue last one days for only Ios app. So please, if some body have knowledge or done before. please advise and refer me some idea.
Emoji in my push notifications link.
https://mixpanel.com/help/questions/articles/how-do-i-send-custom-parameters-like-emoji-in-my-push-notifications
Thanks
Finally, APNs issue resolve in (Ios app) on java web service code by this Unicode encode and decode process. (unescapeJava and escapeJava) from lib commons-lang-2.6.jar and class org.apache.commons.lang.StringEscapeUtils
emojiBytes = alertMsg.getBytes("UTF-8"); text = new String(emojiBytes, "UTF-8");
private static PushNotificationPayload createPayload(JSONObject jsonObject)
throws JSONException {
String alertMsg = Common.getStringUnicodeAsNull1(jsonObject,
AppConstants.FLD_ALERT_MSG);
byte[] emojiBytes=null;
String text=null;
try {
emojiBytes = alertMsg.getBytes("UTF-8");
text = new String(emojiBytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//String emojiAsString = new String(emojiBytes, Charset.forName("UTF-8"));
//System.out.println("#####alertMsg: "+text);
Integer badgeCnt;
if (jsonObject.has(AppConstants.FLD_BADGE_CNT)){
badgeCnt = Common.getIntegerAsNull(jsonObject,
AppConstants.FLD_BADGE_CNT);
}else{
badgeCnt = AppConstants.VAL_ZERO;
}
PushNotificationPayload payload = createPayload(badgeCnt, text);
return payload;
}
String alertMsg = Common.getStringUnicodeAsNull1(jsonObject,
AppConstants.FLD_ALERT_MSG);
public static String getStringUnicodeAsNull1(JSONObject jsonObject,
String key) {
try {
if(jsonObject.isNull(key))
return null;
else
return StringEscapeUtils.unescapeJava(jsonObject.getString(key));
} catch (JSONException je) {
return null;
}
}
Respected sir and ma'am, If there is any other solution of java APNs emoji Unicode on IOS Push Notification.
Then please give me some hints.Thanks
you shouldn't need to mess about with html decoding. As you say the code point for smiling face is \u263A. In PHP you can represent that in a UTF8-encoded string as "\xE2\x98\xBA"
Lightning bolt (actually 'high voltage sign') is \u26A1 or "\xE2\x9A\xA1" in UTF-8.
Both these characters are present in some non-emoji fonts as regular Unicode symbols. You can see with:
<?php
header('Content-type: text/html; charset=utf-8');
echo "\xE2\x9A\xA1";
echo "\xE2\x98\xBA";
or other things...
for the googlers. json_encode() adds double \
$message = "\ue04a";
$body['aps'] = array(
'alert' => $message,
'sound' => 'default',
'type' => $type,
'param' => $param
);
$payload = json_encode($body);
$payload = str_replace("\", "\\", $payload);
Please check with this two way... i think this is helpfull for you.
Here is my Json returned from the server
{"ErrorCode":1005,"Message":"Username does not exist"}
Here is my class for an error
public class ErrorModel {
public int ErrorCode;
public String Message;
}
and here is my conversion code.
public static ErrorModel GetError(String json) {
Gson gson = new Gson();
try
{
ErrorModel err = gson.fromJson(json, ErrorModel.class);
return err;
}
catch(JsonSyntaxException ex)
{
return null;
}
}
It is always throwing a JsonSyntaxException. Any ideas what could be my problem here?
EDIT: As requested, here is further elaboration.
My backend is an ASP.NET MVC 2 application acting as a rest API. The backend isn't the problem here, as my actions (and even server errors) all return Json (using the built in JsonResult). Here's a sample.
[HttpPost]
public JsonResult Authenticate(AuthenticateRequest request)
{
var authResult = mobileService.Authenticate(request.Username, request.Password, request.AdminPassword);
switch (authResult.Result)
{
//logic omitted for clarity
default:
return ExceptionResult(ErrorCode.InvalidCredentials, "Invalid username/password");
break;
}
var user = authResult.User;
string token = SessionHelper.GenerateToken(user.UserId, user.Username);
var result = new AuthenticateResult()
{
Token = token
};
return Json(result, JsonRequestBehavior.DenyGet);
}
The basic logic is to auth the user cretentials and either return an ExceptionModel as json or an AuthenticationResult as json.
Here is my server side Exception Model
public class ExceptionModel
{
public int ErrorCode { get; set; }
public string Message { get; set; }
public ExceptionModel() : this(null)
{
}
public ExceptionModel(Exception exception)
{
ErrorCode = 500;
Message = "An unknown error ocurred";
if (exception != null)
{
if (exception is HttpException)
ErrorCode = ((HttpException)exception).ErrorCode;
Message = exception.Message;
}
}
public ExceptionModel(int errorCode, string message)
{
ErrorCode = errorCode;
Message = message;
}
}
When the above authentication is called with invalid credentials, the error result is returned as expected. The Json returned is the Json above in the question.
On the android side, I first build an object with my key-value pairs.
public static HashMap<String, String> GetAuthenticationModel(String username, String password, String adminPassword, String abbr)
{
HashMap<String, String> request = new HashMap<String, String>();
request.put("SiteAbbreviation", abbr);
request.put("Username", username);
request.put("Password", password);
request.put("AdminPassword", adminPassword);
return request;
}
Then, I send off an http post and return as a string whatever is sent back.
public static String Post(ServiceAction action, Map<String, String> values) throws IOException {
String serviceUrl = GetServiceUrl(action);
URL url = new URL(serviceUrl);
URLConnection connection = url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String data = GetPairsAsString(values);
DataOutputStream output = new DataOutputStream(connection.getOutputStream());
output.writeBytes(data);
output.flush();
output.close();
DataInputStream input = new DataInputStream(connection.getInputStream());
String line;
String result = "";
while (null != ((line = input.readLine())))
{
result += line;
}
input.close ();
return result;
}
private static String GetServiceUrl(ServiceAction action)
{
return "http://192.168.1.5:33333" + action.toString();
}
private static String GetPairsAsString(Map<String, String> values){
String result = "";
Iterator<Entry<String, String>> iter = values.entrySet().iterator();
while(iter.hasNext()){
Map.Entry<String, String> pairs = (Map.Entry<String, String>)iter.next();
result += "&" + pairs.getKey() + "=" + pairs.getValue();
}
//remove the first &
return result.substring(1);
}
Then I take that result and pass it into my parser to see if it is an error
public static ErrorModel GetError(String json) {
Gson gson = new Gson();
try
{
ErrorModel err = gson.fromJson(json, ErrorModel.class);
return err;
}
catch(JsonSyntaxException ex)
{
return null;
}
}
But, JsonSyntaxException is always thrown.
Might help to know more about the exception, but the same code sample works fine here. I suspect there's a piece of code you omitted that's causing the problem (perhaps the creation/retrieval of the JSON string). Here's a code sample that worked fine for me on Java 1.6 and Gson 1.6:
import com.google.gson.Gson;
public class ErrorModel {
public int ErrorCode;
public String Message;
public static void main(String[] args) {
String json = "{\"ErrorCode\":1005,\"Message\":\"Username does not exist\"}";
Gson gson = new Gson();
ErrorModel err = gson.fromJson(json, ErrorModel.class);
System.out.println(err.ErrorCode);
System.out.println(err.Message);
}
}