I have a webpage whose backend is in Java and the framework is very old (Apache Struts Framework)
The webpage contains buttons textboxes and tables which we can fill and press Add , delete and edit button
All this code is currently written in Action file in java
We need to convert this code and put it in a new Controller file (Rest Controller)
Action files will still be present we just need them till loading JSP onto the page
Once JSP is loaded every button click,event handler (i.e. Add, delete, edit) should be handled by controller
Earlier button clicks were going to Action like formSubmit
We will still need to keep the Action file because we are using Struts framework so we will require action file
Giving an example of two files of how they look after migration -
Apache Struts Action Code-
public final ActionForward updateUserDetails(final ActionMapping mapping,
final ActionForm form, final HttpServletRequest request,
final HttpServletResponse response) throws IOException {
UserAdminForm uForm = (UserAdminForm) form;
UserAdminVO vo = userManager.getUserByUserPk(Integer.parseInt(uForm.getUserPK()));
String olddiscoverId = vo.getDiscoverId();
String oldDiscoverAccess = vo.getDiscoverAccess();
try {
if(!ISC.SUPER_USER_ROLE.equals(workContext.getRole()) && !workContext.getUser().equalsIgnoreCase(uForm.getUserID())) {
manager.logError("** Possible breach: Logged in user[" + workContext.getUser() + "] is attempting to update details for " + uForm.getUserID() + ". **");
processErrorMessages(CConstant.USER_MISSMATCH_FOR_UPDATE_OPERATION,
request);
return mapping.findForward(CConstant.ACTION_FORWARD_SUCCESS);
}
setLandingPageAndOtherDetailsForUserUpdate(uForm, vo);
if (manager.isDebugEnabled()) {
manager.logDebug("User admin VO from user form =" + vo);
manager.logDebug("Old user id : " + uForm.getOldUserID()
+ " New User id : " + uForm.getUserID());
}
DiscoverResponse discoverResponse = null;
if("true".equalsIgnoreCase(globalSysParamManager.getParamValue(ENABLE_DISCOVER_SYSTEM_FEATURE))){
discoverResponse = updateDiscoverAccess(oldDiscoverAccess, olddiscoverId, vo);
if(discoverResponse!=null && CConstant.ERROR_STR.equalsIgnoreCase(discoverResponse.getResult())){
vo.setDiscoverAccess(oldDiscoverAccess);
}
}
userManager.updateUser(vo);
syncOtherUsersWithDiscover(vo);
refreshWorkContext(vo);
processSuccessMessage(CConstant.USER_UPDATE_SUCCESS, discoverResponse, request);
} catch (BusinessServiceException e) {
manager.logError("Error in User Update Action", e);
ActionMessages messages = new ActionMessages();
messages.add(
ActionMessages.GLOBAL_MESSAGE,
new ActionMessage(e.getErrorCode(), new Object[] { e
.getMessage() }));
saveErrors(request, messages);
} catch (BusinessServiceCommonsException e) {
manager.logError("Error in User Update Action", e);
ActionMessages messages = new ActionMessages();
messages.add(
ActionMessages.GLOBAL_MESSAGE,
new ActionMessage(e.getErrorCode(), new Object[] { e
.getMessage() }));
saveErrors(request, messages);
}
try {
loadCarparks(uForm, vo);
request.getSession(false).setAttribute(PARK_FOR_LOCATION,
uForm.getCarparkList());
} catch (BusinessServiceException e) {
manager.logError("Error in User Display Action ", e);
processBusinessServiceException(e, request);
}
if ("true".equals(uForm.getPasswordExpired())) {
response.sendRedirect(request.getContextPath()
+ "/logout.cprms?doLogout=true");
return null;
}
return mapping.findForward(CConstant.ACTION_FORWARD_SUCCESS);
}
Rest Controller Code -
#PutMapping
public ResponseEntity<Object> updateUser(#RequestBody UserAdminForm userAdminForm, HttpServletRequest request){
List<String> errorMessages = validateUserDetails(userAdminForm);
if(!errorMessages.isEmpty()){
return new ResponseEntity<>(errorMessages, HttpStatus.BAD_REQUEST);
}
ICWorkContext workContext = ControllerUtility.initializeWorkContext(userAdminForm.getLocationId(),request);
var userAdminVO = userManager.getUser(userAdminForm.getUserID());
String oldDiscoverId = userAdminVO.getDiscoverId();
String oldDiscoverAccess = userAdminVO.getDiscoverAccess();
DiscoverResponse discoverResponse = null;
try {
if(!ISC.SUPER_USER_ROLE.equals(workContext.getRole()) && !workContext.getUser().equalsIgnoreCase(userAdminForm.getUserID())) {
LOGGER.logError("** Possible breach: Logged in user[" + workContext.getUser() + "] is attempting to update details for " + userAdminForm.getUserID() + ". **");
String errorMessage = messages.getMessage(CConstant.USER_MISSMATCH_FOR_UPDATE_OPERATION);
return new ResponseEntity<>(errorMessage,HttpStatus.NOT_ACCEPTABLE);
}
setLandingPageAndOtherDetailsForUserUpdate(userAdminForm, userAdminVO,workContext);
if("true".equalsIgnoreCase(globalSysParamManager.getParamValue(ENABLE_DISCOVER_SYSTEM_FEATURE))){
discoverResponse = updateDiscoverAccess(oldDiscoverAccess, oldDiscoverId, userAdminVO);
if(discoverResponse!=null && CConstant.ERROR_STR.equalsIgnoreCase(discoverResponse.getResult())){
userAdminVO.setDiscoverAccess(oldDiscoverAccess);
}
}
userManager.updateUser(userAdminVO);
syncOtherUsersWithDiscover(userAdminVO);
refreshWorkContext(userAdminVO,workContext);
} catch (Exception exception) {
LOGGER.logError("Error in Update User API", exception);
return new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE);
}
Map<String, Object> response = new HashMap<>(2);
List<String> successMessages = new ArrayList<>(2);
successMessages.add(messages.getMessage(CConstant.USER_UPDATE_SUCCESS));
getDiscoverResponseMessage(discoverResponse, response, successMessages);
response.put(SUCCESS_MESSAGE,successMessages);
return new ResponseEntity<>(response,HttpStatus.OK);
}
I want to migrate this Action Code to Rest Controller -
public final ActionForward displayAllLeaves(final ActionMapping mapping,
final ActionForm form, final HttpServletRequest request,
final HttpServletResponse response) throws IOException,
ServletException {
boolean checkFlag = true;
LumpConfigFB lumpConfigFB = (LumpConfigFB) form;
storeProductWithoutDNAToRequest(request);
try {
LumpConfigVO lumpConfigVO = new LumpConfigVO();
if ((null == workContext.getCarparkPK())
|| "".equals(workContext.getCarparkPK())) {
BusinessServiceException businessServiceException = new BusinessServiceException(
CPRMSConstant.NO_C_ERROR);
businessServiceException
.setErrorCode(CConstant.NO_C_ERROR);
processBusinessServiceException(businessServiceException,
request);
return mapping
.findForward(CConstant.ACTION_FORWARD_SUCCESS);
}
// populateVO
populateLumpConfigVO(lumpConfigFB, lumpConfigVO);
lumpConfigManager.displayAllLeaves(lumpConfigVO);
if (((null != lumpConfigVO.getMappedLumpDefList()) && (lumpConfigVO
.getMappedLumpDefList().size() > 0))
|| ((null != lumpConfigVO.getUnmappedLumpDefList()) && (lumpConfigVO
.getUnmappedLumpDefList().size() > 0))) {
List<LumpConfigVO> mappedLumpDefList = lumpConfigVO
.getMappedLumpDefList();
HashMap<String, LumpConfigVO> lumpNameMap = new HashMap<String, LumpConfigVO>();
List<String> lumpNameList = new ArrayList<String>();
if (null != mappedLumpDefList && mappedLumpDefList.size() > 0) {
for (LumpConfigVO configVO : mappedLumpDefList) {
lumpNameList.add(configVO.getLumpName());
lumpNameMap.put(configVO.getLumpName(), configVO);
}
mappedLumpDefList.clear();
Collections.sort(lumpNameList,
String.CASE_INSENSITIVE_ORDER);
for (String lumpName : lumpNameList) {
mappedLumpDefList.add(lumpNameMap.get(lumpName));
}
lumpConfigFB.setMappedLumpDefList(mappedLumpDefList);
}
List<LumpConfigVO> unMappedLumpDefList = lumpConfigVO
.getUnmappedLumpDefList();
if (null != unMappedLumpDefList
&& unMappedLumpDefList.size() > 0) {
Collections.sort(unMappedLumpDefList, new LumpComparator());
lumpConfigFB.setUnmappedLumpDefList(unMappedLumpDefList);
}
} else {
lumpConfigFB.setMappedLumpDefList(null);
lumpConfigFB.setUnmappedLumpDefList(null);
BusinessServiceException businessServiceException = new BusinessServiceException(
CConstant.LEAF_NOT_FOUND_ERROR);
businessServiceException
.setErrorCode(CConstant.LEAF_NOT_FOUND_ERROR);
processBusinessServiceException(businessServiceException,
request);
checkFlag = false;
}
if (null != request.getAttribute("jobid")
&& !"".equals(request.getAttribute("jobid"))) {
String jobId = (String) request.getAttribute("jobid");
ActionErrors actionErrors = new ActionErrors();
ActionMessages messages = new ActionMessages();
if ("failure".equals(request.getAttribute("jobid").toString())) {
String errorCode = (String) request
.getAttribute("errorcode");
actionErrors.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage(errorCode));
saveErrors(request, (ActionMessages) actionErrors);
} else {
actionErrors.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage(CConstant.AGGR_QUEUE_SUCCESS,
jobId));
messages.add(actionErrors);
saveMessages(request, messages);
}
}
} catch (BusinessServiceException businessServiceException) {
processBusinessServiceException(businessServiceException, request);
checkFlag = false;
}
return mapping.findForward(CConstant.ACTION_FORWARD_SUCCESS);
}
I have also written a Rest Controller Code for this Action file but I am not sure If I am going right -
public class LeavesController {
#Autowired
private LumpConfigManager lumpConfigManager;
#GetMapping
public ResponseEntity<List<LumpConfigVO>> getAllLeaves(HttpServletRequest request) {
try {
LumpConfigVO lumpConfigVO = new LumpConfigVO();
if ((null == workContext.getCarparkPK())
|| "".equals(workContext.getCarparkPK())) {
throw new BusinessServiceException(CPRMSConstant.NO_CARPARK_ERROR);
}
populateLumpConfigVO(lumpConfigFB, lumpConfigVO);
lumpConfigManager.displayAllLeaves(lumpConfigVO);
if (((null != lumpConfigVO.getMappedLumpDefList()) && (lumpConfigVO
.getMappedLumpDefList().size() > 0))
|| ((null != lumpConfigVO.getUnmappedLumpDefList()) && (lumpConfigVO
.getUnmappedLumpDefList().size() > 0))) {
List<LumpConfigVO> mappedLumpDefList = lumpConfigVO
.getMappedLumpDefList();
HashMap<String, LumpConfigVO> lumpNameMap = new HashMap<String, LumpConfigVO>();
List<String> lumpNameList = new ArrayList<String>();
if (null != mappedLumpDefList && mappedLumpDefList.size() > 0) {
for (LumpConfigVO configVO : mappedLumpDefList) {
lumpNameList.add(configVO.getLumpName());
lumpNameMap.put(configVO.getLumpName(), configVO);
}
mappedLumpDefList.clear();
Collections.sort(lumpNameList,
String.CASE_INSENSITIVE_ORDER);
for (String lumpName : lumpNameList) {
mappedLumpDefList.add(lumpNameMap.get(lumpName));
}
}
List<LumpConfigVO> unMappedLumpDefList = lumpConfigVO
.getUnmappedLumpDefList();
if (null != unMappedLumpDefList
&& unMappedLumpDefList.size() > 0) {
Collections.sort(unMappedLumpDefList, new LumpComparator());
}
return ResponseEntity.ok(lumpConfigVO);
} else {
throw new BusinessServiceException(CPRMSConstant.LEAF_NOT_FOUND_ERROR);
}
} catch (BusinessServiceException businessServiceException) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, businessServiceException.getMessage(), businessServiceException);
}
}
// helper method for populating LumpConfigVO from LumpConfigFB
private void populateLumpConfigVO(LumpConfigFB lumpConfigFB, LumpConfigVO lumpConfigVO) {
// implementation here
}
// helper method for storing product without DNA to request
private void storeProductWithoutDNAToRequest(HttpServletRequest request) {
// implementation here
}
// other helper methods and properties omitted
}
Related
Here the code that I used to save data and I use #Transactional. I want to write a test for this method, but it fails.
#Transactional(rollbackFor = BadRequestException.class, propagation = Propagation.REQUIRES_NEW)
public void saveContent(ContentAbstractEntity content) {
mongoTemplate.setSessionSynchronization(SessionSynchronization.ALWAYS);
TransactionBody txnBody =
(() -> {
ContentAbstractEntity contentAbstractEntity = contentRepository.save(content);
if (content instanceof LearningContent) {
LearningContent learningContent = (LearningContent) content;
Long tutorCountInDB = tutorRepository.countBy_idIn(learningContent.getTutorIds());
if (!countryRepository.existsBySyllabuses_grades_subjects__id(
learningContent.getSubjectId()))
throw new BadRequestException("Subject is not found");
Topic topic = topicRepository.findBy_id(learningContent.getTopicId());
if (topic == null) throw new BadRequestException("Topic is not found");
List<ObjectId> lessonIds =
topic.getLessons().stream().map(m -> m.get_id()).collect(Collectors.toList());
boolean allLessonsExists =
learningContent.getLessonIds().stream().allMatch(a -> lessonIds.contains(a));
if (!allLessonsExists) throw new BadRequestException("Lessons are not mismatched");
if (tutorCountInDB != learningContent.getTutorIds().size()) {
throw new BadRequestException("Tutors are not matched");
}
}
return "Successfully inserted";
});
MongoClient client = MongoClients.create(uri);
ClientSession clientSession = client.startSession();
try {
clientSession.withTransaction(txnBody);
} catch (BadRequestException e) {
throw new BadRequestException(e.getMessage());
} finally {
clientSession.close();
}
}
I tried to write a test for the above code, but it returns an error
#Test
void whenSaveContent() throws Exception {
ContentAbstractDto contentAbstractDto = new ContentAbstractDto();
ContentAbstractEntity content = learningVideo();
if (contentAbstractDto instanceof LearningDocsDto) {
LearningDocsDto learninfDocsDto = (LearningDocsDto) contentAbstractDto;
// ToDo when a Doc Saves and Assessment saves
}
when(contentRepository.save(content)).thenReturn(content);
if (content instanceof LearningContent) {
LearningContent learningContent = (LearningContent) content;
Long tutorCountInDB = (long) learningContent.getTutorIds().size();
when(tutorRepository.countBy_idIn(learningContent.getTutorIds())).thenReturn(tutorCountInDB);
when(subjectRepository.existsBy_id(learningContent.getSubjectId())).thenReturn(true);
Topic topic = getTopic();
when(topicRepository.findBy_id(learningContent.getTopicId())).thenReturn(topic);
if (topic == null) throw new BadRequestException("Topic is not found");
List<ObjectId> lessonIds =
topic.getLessons().stream().map(m -> m.get_id()).collect(Collectors.toList());
boolean allLessonsExists =
learningContent.getLessonIds().stream().allMatch(a -> lessonIds.contains(a));
if (!allLessonsExists) throw new BadRequestException("Lessons are not mismatched");
if (tutorCountInDB != learningContent.getTutorIds().size()) {
throw new BadRequestException("Tutors are not matched");
}
}
I have a Utility function which I use to check if user has done few operations or not. If not, Then I need to send the results back to MainActivity.
public static boolean checkUserIsDone(String receiverPhoneNumber, String senderNumber ) {
hasApp = false;
HashMap<String, Object> parseParams = new HashMap<>();
parseParams.put("phoneNumber", receiverPhoneNumber);
parseParams.put("senderNumber", senderNumber);
ParseCloud.callFunctionInBackground("GetUserByPhoneNumber", parseParams, new FunctionCallback<String>() {
public void done(String result, ParseException e) {
if (e == null && result.equals("success")) {
hasApp = true;
} else {
hasApp = false;
Log.e("Error: ", e.getMessage());
}
}
});
return hasApp;
}
i use Wicket.Ajax.ajax in pair with AbstractDefaultAjaxBehavior to sent some javascript calculated data to the java. But after event has fired from javascript and comes to Java, browser has been redirected to callback url.
...web/product/1?7&6-1.IBehaviorListener.0-idsPanelPlace%3Floggged_id=332797
logggedidAjax = new AbstractDefaultAjaxBehavior() {
#Override
protected void respond(AjaxRequestTarget target) {
StringValue loggged_vkid = getRequest().getQueryParameters().getParameterValue("loggged_id");
String loggedId = (loggged_id != null) ? loggged_id.toString() : "null";
logger.info("ajax has comming with logged ID " + loggedId);
}
#Override
public void renderHead(final Component component, IHeaderResponse response) {
super.renderHead(component, response);
String componentMarkupId = getMarkupId();
Map<String, Object> map = new HashMap<>();
map.put("callbackUrl", logggedidAjax.getCallbackUrl());
PackageTextTemplate ptt = new PackageTextTemplate(VKIDsPanel.class, "id_callback.js");
OnDomReadyHeaderItem onDomReadyHeaderItem = OnDomReadyHeaderItem.forScript(ptt.asString(map));
response.render(onDomReadyHeaderItem);
}
};
add(logggedidAjax);
As for js code -
var wcall = Wicket.Ajax.ajax({ u: '${callbackUrl}' + '?loggged_id='+ response.session.mid });
Why browser redirected to the url, since it is Ajax? How to prevent redirection?
I'm not sure what's going wrong in your code, but the following should be easier:
logggedidAjax = new AjaxEventBehavior("domready") {
#Override
protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
super.updateAjaxAttributes(attributes);
String loggedId = "return {'logged_id': response.session.mid}";
attributes.getDynamicExtraParameters().add(loggedId);
}
#Override
protected void onEvent(AjaxRequestTarget target) {
StringValue loggged_vkid = getRequest().getQueryParameters().getParameterValue("loggged_id");
String loggedId = (loggged_id != null) ? loggged_id.toString() : "null";
logger.info("ajax has comming with logged ID " + loggedId);
}
};
add(logggedidAjax);
I make the HttpURLConnection to get data from MySQL (android+jsp+MySQL) in my android's AsyncTask.
when I start 'A activity', the first is OK. I can start doInBackground. but when I start the 'A activity' next, I can't start doInBackgound when I start 'A activity' repeatedly.
I want to start doInBackground whenever I start the 'A activity' repeatedly.
because I get data from MySQL in doInBackground.
I used to "task.cancel(true)" but this not working.
I'm nuwbe in android, please tell me how to start doInBackground repeatedly.
thank advance.
behind is my code.
oncreate code
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_confirm_inventory);
...........
connectJSP = new getInventoryFromMySQL();
connectJSP.execute();
...........
}
onBackPressed code
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawer(GravityCompat.END);
} else {
connectJSP.cancel(true);
super.onBackPressed();
}
}
AsyncTask code
private class getInventoryFromMySQL extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... sId) {
String sResult = "Error";
try {
//URL setting and access
URL url = new URL("http://-----.com/*****.jsp");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//setting
conn.setRequestMethod("POST");
// connection values
String sendBicycleName = bicycleName;
String sendBicycleYear = bicycleYear;
//StringBuffer
StringBuffer buffer = new StringBuffer();
buffer.append("sendBicycleName").append("=").append(sendBicycleName).append("&");
buffer.append("sendBicycleYear").append("=").append(sendBicycleYear);
//put data into JSP
OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
osw.write(buffer.toString());
osw.flush();
//get data from JSP
InputStreamReader tmp = new InputStreamReader(conn.getInputStream(), "UTF-8");
BufferedReader reader = new BufferedReader(tmp);
String str;
//fit the order with JSP(garbage values)
reader.readLine(); reader.readLine(); reader.readLine(); reader.readLine();
//get data from JSP
for(;;) {
if((str = reader.readLine()) != null && (str != "") && (str != " ") && (str != "null")) {
mysqlStoreId[countInventory] = str;
for(int c=0; c<5; c++) {
for(int s=0; s<8; s++) {
str = reader.readLine();
mysqlInventory[countInventory][c][s] = Integer.parseInt(str);
}
}
countInventory++;
} else if(str == null && str == "null") {
//finish for if values equals null
break;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sResult;
}
}
I find the answer. I check all code's log.
the problem is that 'doInBackground' have an error. there is no an else in 'for(;;)' so AsyncTack make 'onCancelled()'. but I'm not write the 'onCancelled()' code.
when I add onCancelled(), I can cancel(true) and re-start the Asynctask.
Thank!
This is driving me crazy. I wrote a code quite a while ago that was working, and opened it again and it happens that I am not able to transfer my assets from the mobile to the wearable device.
public Bitmap loadBitmapFromAsset(Asset asset) {
if (asset == null) {
throw new IllegalArgumentException("Asset must be non-null");
}
// convert asset into a file descriptor and block until it's ready
Log.d(TAG, "api client" + mApiClient);
DataApi.GetFdForAssetResult result = Wearable.DataApi.getFdForAsset(mApiClient, asset).await();
if (result == null) {
Log.w(TAG, "getFdForAsset returned null");
return null;
}
if (result.getStatus().isSuccess()) {
Log.d(TAG, "success");
} else {
Log.d(TAG, result.getStatus().getStatusCode() + ":" + result.getStatus().getStatusMessage());
}
InputStream assetInputStream = result.getInputStream();
if (assetInputStream == null) {
Log.w(TAG, "Requested an unknown Asset.");
return null;
}
// decode the stream into a bitmap
return BitmapFactory.decodeStream(assetInputStream);
}
And this is the code from which I call the loadBitmapFrom Asset method.
DataMap dataMap = DataMapItem.fromDataItem(event.getDataItem()).getDataMap();
ArrayList<DataMap> dataMaps = dataMap.getDataMapArrayList("dataMaps");
ArrayList<String> names = new ArrayList<>();
ArrayList<String> permalinks = new ArrayList<>();
ArrayList<Asset> images = new ArrayList<>();
for (int i = 0 ; i < dataMaps.size() ; i++) {
Log.d(TAG, dataMaps.get(i).getString("name"));
names.add(dataMaps.get(i).getString("name"));
permalinks.add(dataMaps.get(i).getString("permalink"));
images.add(dataMaps.get(i).getAsset("image"));
}
editor.putInt("my_selection_size", names.size());
for (int i=0; i <names.size() ; i++) {
editor.putString("my_selection_name_" + i, names.get(i));
editor.putString("my_selection_permalink_" + i, permalinks.get(i));
Log.d(TAG, "asset number " + i + " " + images.get(i));
Bitmap bitmap = loadBitmapFromAsset(images.get(i));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
editor.putString("my_selection_image_" + i, encoded);
}
And on the mobile side :
private void sendData(PutDataMapRequest dataMap) {
PutDataRequest request = dataMap.asPutDataRequest();
request.setUrgent();
com.google.android.gms.common.api.PendingResult<DataApi.DataItemResult> pendingResult = Wearable.DataApi.putDataItem(mApiClient, request);
pendingResult.setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
#Override
public void onResult(DataApi.DataItemResult dataItemResult) {
com.orange.radio.horizon.tools.Log.d(TAG, "api client : " + mApiClient);
if (dataItemResult.getStatus().isSuccess()) {
com.orange.radio.horizon.tools.Log.d(TAG, "message successfully sent");
} else if (dataItemResult.getStatus().isInterrupted()) {
com.orange.radio.horizon.tools.Log.e(TAG, "couldn't send data to watch (interrupted)");
} else if (dataItemResult.getStatus().isCanceled()) {
com.orange.radio.horizon.tools.Log.e(TAG, "couldn't send data to watch (canceled)");
}
}
});
Log.d(TAG, "Sending data to android wear");
}
class ConfigTask extends AsyncTask<String, Void, String> {
ArrayList<WatchData> mitems;
int mType;
public ConfigTask(ArrayList<WatchData> items, int type)
{
mitems = items;
mType = type;
}
protected String doInBackground(String... str)
{
DataMap dataMap;
ArrayList<DataMap> dataMaps = new ArrayList<>();
Bitmap bitmap = null;
for (int i = 0 ; i < mitems.size() ; i++) {
dataMap = new DataMap();
URL url = null;
try {
url = new URL(mitems.get(i).mUrlSmallLogo);
Log.d(TAG, "url : " + url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
Asset asset = createAssetFromBitmap(bitmap);
dataMap.putAsset("image", asset);
dataMap.putString("name", mitems.get(i).mName);
dataMap.putString("permalink", mitems.get(i).mPermalink);
dataMaps.add(dataMap);
}
PutDataMapRequest request = null;
switch (mType) {
case 0 :
request = PutDataMapRequest.create(SELECTION_PATH);
break;
case 1 :
request = PutDataMapRequest.create(RADIOS_PATH);
break;
case 2 :
request = PutDataMapRequest.create(PODCASTS_PATH);
break;
}
request.getDataMap().putDataMapArrayList("dataMaps", dataMaps);
request.getDataMap().putString("", "" + System.currentTimeMillis()); //random data to refresh
Log.d(TAG, "last bitmap : " + bitmap);
Log.d(TAG, "===============================SENDING THE DATAMAP ARRAYLIST==================================");
sendData(request);
return "h";
}
protected void onPostExecute(String name)
{
}
}
When executing that code, I see the following error happening :
02-02 14:47:59.586 7585-7601/? D/WearMessageListenerService﹕ 4005:ASSET_UNAVAILABLE
I saw that related thread Why does Wearable.DataApi.getFdForAsset produce a result with status 4005 (Asset Unavailable)? but it didn't really help me
I recently had the same problem... I solved it by updating the Google play service, and adding the same signing configuration to both the app and the wearable module. If it doesn't work on the first build go to "invalidate caches / restart" in files and it should work.