Customize toast in asyntask in android - android-asynctask

I just wanna ask if it is possible to use my customize toast in onPostExecute of my Asyntask in android. If yes then how? I tried to put it on the onPostExecute but I got a lot red lines. Here is my code for my customize toast:
Typeface tfR= Typeface.createFromAsset(getAssets(), "Gothic_Regular.TTF");
LayoutInflater inflater = getLayoutInflater();
View layouttoast = inflater.inflate(R.layout.toast_bg, (ViewGroup)findViewById(R.id.toastAttribute));
TextView msg = ((TextView) layouttoast.findViewById(R.id.txt_toast));
msg.setTypeface(tfR);
msg.setText(toast_msg);
msg.setTextSize(TypedValue.COMPLEX_UNIT_PX,16);
Toast mytoast = new Toast(getBaseContext());
mytoast.setView(layouttoast);
mytoast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
mytoast.setDuration(Toast.LENGTH_SHORT);
mytoast.show();
Then I want to put it here:
public class DoPost extends AsyncTask<String, Void, Boolean>
{
Exception exception = null;
Context mContext = null;
. . . . .
public DoPost(Context context, String username, String password,
String reportcode, String remarks, String date, String province,
String infotype, String competitor, ArrayList<String> brands,
ArrayList<String> segments)
{
mContext = context;
. . . .
databaseHandler = new DatabaseHandler(context);
if (databaseHandler != null)
{
databaseHandler.close();
databaseHandler.createDB();
}
}
protected void onPreExecute()
{
progressDialog = new ProgressDialog(mContext);
progressDialog.setMessage("Uploading attachment details....");
progressDialog.show();
progressDialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... arg0)
{
try {
JSONObject jObject = new JSONObject();
Log.d("DoPost Constants.FILE_URI", Constants.FILE_URI.toString());
Log.d("DoPost create SELECTEDFILE URI", SelectedFiles.listFileUri.toString());
Log.d("DoPost create SELECTEDFILE FILENAME", SelectedFiles.listFileName.toString());
// String filename = "Chapt-19.pdf";
String filename = "";
try {
JSONArray jArraySubrands = new JSONArray();
JSONArray jArrayConsumerSegments = new JSONArray();
JSONArray jArrayReportUpload = new JSONArray();
for (int i = 0; i < Constants.SHARED_PREFERENCES_SUBBRANDS.size(); i++)
{
JSONObject brand = new JSONObject();
brand.put("Id", _brands.get(i));
jArraySubrands.put(brand);
}
for (int j = 0; j < Constants.SHARED_PREFERENCES_SEGMENTS.size(); j++)
{
JSONObject consumerSegments = new JSONObject();
consumerSegments.put("Id", _segments.get(j));
jArrayConsumerSegments.put(consumerSegments);
}
for (int i = 0; i < Constants.ARRAYLIST_FILENAME.size(); i++)
{
JSONObject jObjectReportUpload = new JSONObject();
filename = Constants.ARRAYLIST_FILENAME.get(i);
jObjectReportUpload.put("ReportUploadId", 0);
jObjectReportUpload.put("Filename", filename);
jObjectReportUpload.put("TempFilename", filename);
jObjectReportUpload.put("Description", "Image Testing");
jObjectReportUpload.put("ReportUploadTypeId", 1);
jObjectReportUpload.put("ReportId", 0);
jArrayReportUpload.put(jObjectReportUpload);
Log.d("filename: ", filename);
}
jObject.put("ReportId", 0);
jObject.put("ReportCode", _code);
jObject.put("Title", "Mobile Developer");
jObject.put("Remarks", _remarks);
jObject.put("DateObserved", _date);
jObject.put("ProvinceId", _province);
jObject.put("InformationTypeId", _infotype);
jObject.put("ReportTypeId", 1);
jObject.put("IsCompetitor", _competitor);
jObject.put("SubBrands", jArraySubrands);
jObject.put("ConsumerSegments", jArrayConsumerSegments);
jObject.put("ReportUploads", jArrayReportUpload);
} catch (Exception e)
{
e.printStackTrace();
}
ResponseHandler<String> resonseHandler = new BasicResponseHandler();
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpPost httpPost = new HttpPost("http://phsjghhghghulchghg4.hgh.com:1214/api/reports");
HttpClient httpclient = new DefaultHttpClient(httpParameters);
httpPost.addHeader("Authorization","Basic "+ Base64.encodeToString((_username + ":" + _password).getBytes(),Base64.NO_WRAP));
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "application/json");
httpPost.setEntity(new ByteArrayEntity(jObject.toString().getBytes(HTTP.UTF_8)));
String response = httpclient.execute(httpPost).toString();
Log.i("response: ", response);
Log.i("JSON", jObject.toString());
} catch (ClientProtocolException e)
{
e.printStackTrace();
Log.e("Header","ClientProtocolException in callWebService(). "+ e.getMessage());
error = String.valueOf(e);
return false;
}
catch (IOException e)
{
e.printStackTrace();
Log.e("Header","IOException in callWebService(). " + e.getMessage());
error = String.valueOf(e);
return false;
}
return true;
}
protected void onPostExecute(Boolean valid)
{
progressDialog.dismiss();
Log.d("RESULT", String.valueOf(valid));
if(valid){
//Customzize toast here.
new DoPost(mContext,_username, _password, _code, _remarks, _date, _province, _infotype,_competitor,_brands, _segments).execute();
}else{
//Customzize toast here.
}
}

I think I've found out what's going on. Your scope is wrong. currently your code is running in AsyncTask, not Activity! That's why you cannot use getAssets, getLayoutInflater, findViewById, getBaseContext. Create your AsyncTask in your xxxActivity. And use Your xxxActivity.this.findViewById, and so on.

Related

Migrating Apache Struts Action to Spring Rest Controller

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
}

Return a new thymeleaf page fragment and some file from spring controller

Tell me how to properly implement the spring controller. I want it to return a new thymeleafe page fragment and Excel file at the same time.
I know how to implement a controller to return a page fragment:
#GetMapping("/some_url")
public String updateFragment(Model model) {
model.addAttribute("attribute", someAtribute);
return "some_page :: fragment";
}
And I know how to implement a controller for downloading files:
#GetMapping("some_url")
public void getReport(HttpServletResponse response) throws IOException {
response.setContentType("application/octet-stream");
String headerKey = "Content-Disposition";
String headerValue = "attachment; filename=file.xlsx";
response.setHeader(headerKey, headerValue);
try {
FileInputStream inputStream = new FileInputStream(new File("path_to_file"));
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
int row = 12;
Row exampleRow = sheet.getRow(12);
int count = 1;
for (SIZForKomplex s : objectList) {
if (s.getNumber() != 0) {
sheet.getRow(row).setRowStyle(exampleRow.getRowStyle());
sheet.getRow(row).setHeight(exampleRow.getHeight());
for (int i = 0; i < 8; i++) {
sheet.getRow(row).getCell(i).setCellStyle(exampleRow.getCell(i).getCellStyle());
}
sheet.getRow(row).getCell(0).setCellValue(count);
sheet.getRow(row).getCell(1).setCellValue(s.getNomenclatureNumber());
sheet.getRow(row).getCell(2).setCellValue(s.getNamesiz());
sheet.getRow(row).getCell(3).setCellValue(s.getSize());
sheet.getRow(row).getCell(4).setCellValue(s.getHeight());
sheet.getRow(row).getCell(5).setCellValue(s.getNumber());
sheet.getRow(row).getCell(6).setCellValue(sizRepository.findById(s.getId()).orElseThrow().getEd_izm());
sheet.getRow(row).getCell(7).setCellValue(" ");
row++;
count++;
}
}
inputStream.close();
ServletOutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException | EncryptedDocumentException
ex) {
ex.printStackTrace();
}
}
But how do I combine this. I need to update the data on the page and download the Excel file

loopj JsonObject with inside JsonArray JsonObjects

I have a Webservice which give me back this:
{"result":[{"Id":"20","temperatura":"34","humedad":"29","Insertado":"2016-07-01 12:19:42"},{"Id":"21","temperatura":"34","humedad":"29","Insertado":"2016-07-01 12:34:42"},{"Id":"22","temperatura":"35","humedad":"28","Insertado":"2016-07-01 12:49:43"},{"Id":"23","temperatura":"35","humedad":"19","Insertado":"2016-07-01 13:29:06"},{"Id":"24","temperatura":"31","humedad":"18","Insertado":"2016-07-01 13:44:07"},{"Id":"25","temperatura":"33","humedad":"16","Insertado":"2016-07-01 13:59:10"}]}
This is an Object, which has and Array, and the array has many objects.
Here is my code. I am using loopj library-
private void CaptarParametros(String idObjeto) {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put(UtilitiesGlobal.SENSOR_ID, idObjeto);
RequestHandle post = client.post(this, SENSORS_URL, params, new JsonHttpResponseHandler() {
#Override
public void onStart() {
// called before request is started
}
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// called when response HTTP status is "200 OK"
JSONObject jsonobject = null;
JSONObject dht11JSONbject = null;
JSONArray dht11JSONarray = null;
try {
jsonobject = new JSONObject(String.valueOf(response));
dht11JSONbject = jsonobject.getJSONObject("result");
dht11JSONarray = new JSONArray(dht11JSONbject);
JSONArray dht11 = dht11JSONarray.getJSONArray(0);
for (int i = 0; i < dht11JSONarray.length(); i++) {
JSONObject item = dht11.getJSONObject(i);
String temperatura = item.getString("temperatura");
String humedad = item.getString("temperatura");
//Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " + usuarioiJSONbject);
Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " + temperatura + humedad);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
But I get error like this:
org.json.JSONException: Value [{"Id":"19","temperatura":"35","humedad":"16","Insertado":"2016-07-01 12:19:24"}] at result of type org.json.JSONArray cannot be converted to JSONObject
I would appreciate any help.- I need to extract "temperature" and humedad" in separate arrays since later I have to use it in MPAndroidChat to make tow linechart, one chart for one set of parameters and another one for other parameters.
Solution is here:
try {
jsonobject = new JSONObject(String.valueOf(response));
//dht11JSONbject = jsonobject.getJSONObject("result");
List<String> allNames = new ArrayList<String>();
JSONArray cast = jsonobject.getJSONArray("result");
for (int i=0; i<cast.length(); i++) {
JSONObject parametrosdht11 = cast.getJSONObject(i);
String temperatura = parametrosdht11.getString("temperatura");
String humedad = parametrosdht11.getString("humedad");
allNames.add(temperatura);
allNames.add(humedad);
//Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " + usuarioiJSONbject);
Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " +"temperatura: "+ temperatura +" humedad: " +humedad);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
We have a String with many sub_objects, then we have to put them into an array or List.
Take the solution from:
how to parse JSONArray in android

How can I start AsyncTask's doInBackground repeatedly when I start the 'A activity'? [complete]

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!

Transferring assets : Error code 4005 ASSET_UNAVAILABLE

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.

Resources