parse.com calling .save() causes all queries to stop working Android - android

I have two objects, a establishment object that belongs to a deal object that can be voted upon. If I up/down vote the same deal multiple times, the seventh time I vote the query just sits and does not do anything. The app does not crash, but it also does not save. If I go into another activity that requires a parse.com query that query also will not work. Here is my up vote logic (down voting is identical).
Assume all vars used are initialized before onCreate().
Are my queries getting backed up in a pipe somewhere?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
upVoteButton = (Button) findViewById(R.id.deal_up_vote_button);
upVoteButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
new UpVoteTask().execute();
}
});
}
// visually changes buttons if they are selected
private void setButtons(Boolean queryDb) {
if (queryDb == true) {
queryParse();
}
// if deal found correctly
if (deal != null) {
// if user found correctly
if (dealVoteUser != null) {
if (dealVoteUser.get("vote").toString().equals("0")) {
upVoteButton.setPressed(false);
downVoteButton.setPressed(true);
} else if (dealVoteUser.get("vote").toString().equals("1")) {
upVoteButton.setPressed(true);
downVoteButton.setPressed(false);
} else if (dealVoteUser.get("vote").toString().equals("2")) {
upVoteButton.setPressed(false);
downVoteButton.setPressed(false);
}
}
}
}
// queries parse and populates vars
private void queryParse(){
ParseQuery<ParseObject> queryDeal = ParseQuery.getQuery("Deal");
queryDeal.whereEqualTo("objectId", deal_id);
try {
deal = queryDeal.getFirst();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ParseQuery<ParseObject> queryDealVoteUser = ParseQuery
.getQuery("deal_vote_users");
queryDealVoteUser.whereEqualTo("deal", deal).whereEqualTo("user",
ParseUser.getCurrentUser());
try {
dealVoteUser = queryDealVoteUser.getFirst();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// UpVoteTask AsyncTask
private class UpVoteTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
if(upVoteProgressDialog != null){
upVoteProgressDialog.dismiss();
upVoteProgressDialog = null;
}
upVoteProgressDialog = new ProgressDialog(DealsDetailsActivity.this);
// Set progressdialog message
upVoteProgressDialog.setMessage("Saving...");
upVoteProgressDialog.setIndeterminate(false);
// Show progressdialog
upVoteProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
queryParse();
// if deal found correctly
if (deal != null) {
// if user has not voted yet
if (dealVoteUser == null) {
// create new and assign vote to 1
dealVoteUser = new ParseObject("deal_vote_users");
dealVoteUser.put("deal", deal);
dealVoteUser.put("user", ParseUser.getCurrentUser());
dealVoteUser.put("vote", 1);
up_votes = deal.getInt("up_votes") + 1;
down_votes = deal.getInt("down_votes");
// if user already down voted
} else if (dealVoteUser.get("vote").toString().equals("0")) {
// change vote to 1
dealVoteUser.put("vote", 1);
up_votes = deal.getInt("up_votes") + 1;
down_votes = deal.getInt("down_votes") - 1;
// if user already up voted
} else if (dealVoteUser.get("vote").toString().equals("1")) {
// already voted up, remove vote
dealVoteUser.put("vote", 2);
up_votes = deal.getInt("up_votes") - 1;
down_votes = deal.getInt("down_votes");
// if user already voted but cleared vote
} else if (dealVoteUser.get("vote").toString().equals("2")) {
// change vote to 1
dealVoteUser.put("vote", 1);
up_votes = deal.getInt("up_votes") + 1;
down_votes = deal.getInt("down_votes");
}
// calculate overall rating percentage
if ((up_votes + down_votes) != 0) {
rating = (up_votes / (up_votes + down_votes)) * 100;
} else if ((up_votes == 0) && (down_votes == 0)) {
rating = 0;
} else {
rating = 50;
}
deal.put("rating", rating);
deal.put("up_votes", up_votes);
try {
deal.save();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
dealVoteUser.save();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
// deal not found problem
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// visually change buttons without querying db
setButtons(false);
//remove progress dialogue
if(upVoteProgressDialog != null){
upVoteProgressDialog.dismiss();
upVoteProgressDialog = null;
}
}
}

Use the saveInBackground method - it will do the same as save, but also save it to your application's cache so that you won't get different values while the data is being saved, so it won't have any apparent effect on your application. It's the best method to save or find (it has a 'sister' method named findInBackground). It acts like an Async task and does not clog your main thread.

I switched all parse calls over to ._____InBackground() and I moved the save logic to onPause(). This way I am not making multiple save calls to parse if the user decides to change their vote multiple times.

Related

toolbar button disappearing when dialog closed

my app is fairly simple and always works IF my IOT device is up.
i need to load a popup and show the ReScan button on the toolbar if the device cannot be found.
the app preloads IPaddress="-" and loads 2 asyncTask(s)
one uses NsdManager.DiscoveryListener to find the mDNS name and loads the IP into IPaddress
this task watches to see IPaddress change and gets the presets from the device by JSON and sets up the UI or pops up the error dialog with instructions if not found.
MY PROBLEM:
when counter >= 15 , i show the "Rescan" Button on the toolbar with setMenuVisible() then popup the error dialog but when the button in the dialog is pressed to close the dialog, the "Rescan" Button disappears again.
Also times out in about 5 seconds.
how do i get the "Rescan" Button to stay?
.
private class getSettingsFromClock extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
String mlooper = IPaddress;
Log.i(TAG, "LOG getSettingsFromClock doInBackground started ");
int counter = 0;
while ( mlooper.equals("-") ) {
mlooper = IPaddress;
try {
Thread.sleep(600);
} catch (InterruptedException e) {
e.printStackTrace();
}
counter++;
if (counter >= 15) // in normal operation counter never goes above 3
{
Log.i(TAG, "LOG getSettingsFromClock - NO IP Found, count= " + counter );
runOnUiThread(new Runnable() {
#Override
public void run() {
setMenuVisible( true, R.id.action_rescan); // show rescan button on toolbar
try { // delay is debugging only
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
//scanning failed Popup Dialog
final Dialog dialog = new Dialog(context );
dialog.setContentView(R.layout.popup);
dialog.setTitle("Scan Error");
Button button = dialog.findViewById(R.id.Button01);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
Toast.makeText(getApplicationContext(),
"Could Not get presets from clock. \n check Clock is on and on WiFi\n and reload app.",
Toast.LENGTH_LONG).show();
}
});
break;
}
}
if( IPaddress != "-" )
{
// gets JSON here
} else
{
// add popup - IOT Not found
}
// JSON starts here
if (JSON_return != null) {
try {
// loads presets from JSON to UI here
} catch (final JSONException e) {
Log.e(TAG, "LOG, JSON parsing error: " + e.getMessage());
}
} else
{
Log.e(TAG, "LOG, Could Not get JSON from Clock.");
}
return null;
}
} // end asyncTask class
// remember to run on main thread
// NOTE; private Menu option_Menu; declared in MainActivity
// ie; setMenuVisible( true, R.id.action_rescan);
public void setMenuVisible(boolean visible, int id) {
if (option_Menu != null) {
option_Menu.findItem(id).setVisible(visible);
}
}
Mike M. had it, Thank You Mike
added onPrepareOptionsMenu()
added showRescan = visible; and invalidateOptionsMenu(); to setMenuVisible()
all work perfectly now.
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
try {
if( showRescan )
{
option_Menu.findItem(R.id.action_rescan).setVisible( true );
} else
{
option_Menu.findItem(R.id.action_rescan).setVisible( false );
}
}
catch(Exception e) {
Log.e(TAG, "onPrepareOptionsMenu error");
}
return true;
}
// when task is completed you can show your menu just by calling this method
// remember to run on main thread
// ie; setMenuVisible( true, R.id.action_rescan);
public void setMenuVisible(boolean visible, int id) {
if (option_Menu != null) {
option_Menu.findItem(id).setVisible(visible);
showRescan = visible;
invalidateOptionsMenu();
}
}

How to pass score parameter in play-services-turn-based methods?

I have just started exploring google-play-services-turnbased APIs. Till now I have been successful in creating a match. But from the documentation I haven't been able to figure out how to player's score after he completes his turn.
This is my onClickStartMatch method.
public void onStartMatchClicked() {
Intent intent =
Games.TurnBasedMultiplayer.getSelectOpponentsIntent(mHelper.getApiClient(), 1, 7, true);
startActivityForResult(intent, RC_SELECT_PLAYERS);
}
This is my onActivityResult method in my main activity class.
if (request == RC_SELECT_PLAYERS) {
if (response != RESULT_OK) {
// user canceled
return;
}
// Get the invitee list.
final ArrayList<String> invitees =
data.getStringArrayListExtra(Games.EXTRA_PLAYER_IDS);
// Get auto-match criteria.
Bundle autoMatchCriteria = null;
int minAutoMatchPlayers = data.getIntExtra(
Multiplayer.EXTRA_MIN_AUTOMATCH_PLAYERS, 0);
int maxAutoMatchPlayers = data.getIntExtra(
Multiplayer.EXTRA_MAX_AUTOMATCH_PLAYERS, 0);
if (minAutoMatchPlayers > 0) {
autoMatchCriteria = RoomConfig.createAutoMatchCriteria(
minAutoMatchPlayers, maxAutoMatchPlayers, 0);
} else {
autoMatchCriteria = null;
}
TurnBasedMatchConfig tbmc = TurnBasedMatchConfig.builder()
.addInvitedPlayers(invitees)
.setAutoMatchCriteria(autoMatchCriteria)
.build();
// Create and start the match.
Games.TurnBasedMultiplayer
.createMatch(mHelper.getApiClient(), tbmc)
.setResultCallback(new MatchInitiatedCallback());
}
This is my MatchInitiatedCallback class
public class MatchInitiatedCallback implements
ResultCallback<TurnBasedMultiplayer.InitiateMatchResult>,OnTurnBasedMatchUpdateReceivedListener {
#Override
public void onResult(TurnBasedMultiplayer.InitiateMatchResult result) {
// Check if the status code is not success.
Status status = result.getStatus();
if (status.isSuccess()) {
Log.d("turnbased","Turn Based Match Initiated successfully with result: "+status.getStatusMessage());
return;
}
TurnBasedMatch match = result.getMatch();
// If this player is not the first player in this match, continue.
if (match.getData() != null) {
showTurnUI(match);
return;
}
// Otherwise, this is the first player. Initialize the game state.
initGame(match);
// Let the player take the first turn
showTurnUI(match);
}
public void showTurnUI(TurnBasedMatch match){
if(match.getStatus() == TurnBasedMatch.MATCH_STATUS_ACTIVE){
if(match.getTurnStatus() == TurnBasedMatch.MATCH_TURN_STATUS_MY_TURN){
turnBasedMatchData = match.getData();
Games.TurnBasedMultiplayer.takeTurn(mHelper.getApiClient(),match.getMatchId(), "score:400".getBytes(Charset.forName("UTF-16")),null).setResultCallback(updateMatchResult());
}
}
}
public void initGame(TurnBasedMatch match){
Games.TurnBasedMultiplayer.takeTurn(mHelper.getApiClient(),match.getMatchId(),"score:605".getBytes(Charset.forName("UTF-16")),match.getParticipantId(Games.Players.getCurrentPlayerId(mHelper.getApiClient()))).setResultCallback(updateMatchResult());
}
public ResultCallback<TurnBasedMultiplayer.UpdateMatchResult> updateMatchResult(){
return null;
}
#Override
public void onTurnBasedMatchReceived(TurnBasedMatch turnBasedMatch) {
Log.d("turn-based","Player played his turn");
}
#Override
public void onTurnBasedMatchRemoved(String s) {
}
}
}
Also it would helpful if some can properly explain how to continue a game a game from start and when to submit score and how.
Figured it out. This is how you can do it.
public byte[] persist() {
JSONObject retVal = new JSONObject();
try {
retVal.put("turnCounter", 2);
retVal.put("score1",100);
retVal.put("score2",200);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String st = retVal.toString();
Log.d(TAG, "==== PERSISTING\n" + st);
return st.getBytes(Charset.forName("UTF-8"));
}
Games.TurnBasedMultiplayer.takeTurn(mHelper.getApiClient(),match.getMatchId(),persist(),null).setResultCallback(updateMatchResult());

MapView doesn't invalidate onProgressUpdated of Async Task

I'm using OSMdroid Mapview and using AsyncTask class to get some data, and I create overlays and try to redraw every time I get a msg.
Unfortunately I'm able to get data from a client and I'm able to create overlays to in onProgressUpdated, I've even called invalidate(); But nothing seems to happen. Not sure what is the problem?
Here's my AsyncTask:
public class TaskManager extends AsyncTask<Void, GeoPoint, Void>{
.....
public TaskManager(Master master,MapView mapview) {
//Construtor
}
#Override
protected Void doInBackground(Void... arg0) {
if(Constance.TCPIP) {
Log.d("APP","Inside TCPIP");
//Creation of TCPIP Sockets
try {
m_ssocket = new ServerSocket(Constance.PORT_NO);
Log.d("APP","ServerSocket: "+m_ssocket);
m_socket = m_ssocket.accept();
Log.d("APP","Accepted: "+m_socket);
} catch (IOException e) {
e.printStackTrace();
}
}
else if (Constance.UDPIP) {
//Creation of UDP Sockets
try {
m_dsocket = new DatagramSocket(Constance.PORT_NO);
} catch (SocketException e) {
e.printStackTrace();
}
}
else if (Constance.MCUDP) {
//Lock Wifi multicast
mMultiCastLock = new MultiCastLock(mMaster.getBaseContext());
mMultiCastLock.setMultiCastAcquire();
//Creation of MC-UDP Sockets
try {
m_mcsocket = new MulticastSocket(Constance.PORT_NO);
InetAddress address = InetAddress.getByName(Constance.GROUP_ADDR);
m_mcsocket.joinGroup(address);
} catch (IOException e) {
e.printStackTrace();
}
}
// Create a buffer to read datagrams into.
byte[] mSocketbuffer = new byte[Constance.DGRAM_LEN];
if(Constance.TCPIP) {
try {
m_inSocketData = new BufferedReader(new InputStreamReader(m_socket.getInputStream()));
Log.d("APP","Reading");
} catch (IOException e) {
e.printStackTrace();
}
} else {
// Create a packet to receive data into the buffer
m_inPacket = new DatagramPacket(mSocketbuffer, mSocketbuffer.length);
}
//prepare overlay items
prepareItemizedOverlay();
// Now loop forever, waiting to receive packets and printing them.
if(m_ssocket!=null || m_dsocket!=null || m_mcsocket!=null)
while (true) {
if (isCancelled()) break;
//Get Data
parseData();
//Make Packet Object
if(mMSG!=null) {
make(mMSG);
}
if(m_inPacket!=null && !Constance.TCPIP) {
// Reset the length of the packet before reusing it.
m_inPacket.setLength(mSocketbuffer.length);
}
}
return null;
}
#Override
protected void onProgressUpdate(GeoPoint... geoPoints){
OverlayItem overlayItem = new OverlayItem("Name", "Description", geoPoints[0]);
mItemizedOverlay.addOverlay(overlayItem);
mMapView.getOverlays().add(mItemizedOverlay);
mMapView.getController().animateTo(geoPoints[0]);
mMapView.invalidate();
}
#Override
protected void onCancelled() {
super.onCancelled();
if(Constance.TCPIP) {
if(m_ssocket!=null && m_socket!=null){
try {
m_ssocket.close();
m_socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else if(Constance.UDPIP) {
if(m_dsocket!=null)
m_dsocket.close();
} else if(Constance.MCUDP) {
if(m_mcsocket!=null)
m_mcsocket.close();
}
Log.d("APP","Task Ended");
}
private void parseData() {
if(Constance.TCPIP) {
// Wait to receive a socket data
try{
mMSG = m_inSocketData.readLine();
} catch (IOException e) {
e.printStackTrace();
}
} else {
// Wait to receive a datagram
try {
m_dsocket.receive(m_inPacket);
// Convert the contents to a string, and display them
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void make(String plot) {
//Make Object
mMSG = new MSG(plot);
//Overlay
mGeoPoint = mMSG.getGeoPoint();
publishProgress(mMSG.getGeoPoint());
}
private void prepareItemizedOverlay() {
/* itemized overlay */
Drawable newMarker = mMaster.getResources().getDrawable(R.drawable.ic_sensor);
mItemizedOverlay = new PlotItemOverlay(mMaster,mItemList,newMarker,
new ItemizedIconOverlay.OnItemGestureListener<OverlayItem>() {
#Override
public boolean onItemSingleTapUp(int index, OverlayItem item) {
Log.d("APP","HERE");
return true;
}
#Override
public boolean onItemLongPress(int index, OverlayItem item) {
return true;
}
}, mResourceProxy);
}
}
Everything seems to work, but nothing seems to happen, not sure what is the problem?
Finally resolved it. I was actually replacing my MapFragment class which led to all this loss of Object and a new object created was interfacing the old one, and so the data received to interfacing to the older MapFragment and not the new MapFragment. Got it resolved, once I found the logically analyzing the code. Anyways, thanks for the support #kurtzmarc you have been very helpful until now. I will continue same with OSMdroid to see any more things that I come up with.

Android - Call an Asynctask from an Asynctask with infinity loop

I have 2 Asynctask, 1 for get data (location) from server then set a marker on map with this location and another call 1st Asyntask in a loop for updating location.
Here my code:
public class AsynComp extends AsyncTask<Void, Void, Void> {
ProgressDialog taxiDialog;
#Override
protected Void doInBackground(Void... params) {
jsonComp = new JSONComp(find_url);
find_status = jsonComp.getJsonStatus(txt_search);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (find_status.equals("2013")) {
Toast.makeText(getBaseContext(), "no result",
Toast.LENGTH_SHORT).show();
} else if (find_status.equals("2012")) {
for (Marker marker:markers){
if(marker.getTitle().equals(compFollow)){
marker.remove();
}
}
for (int i=0; i<number;i++){
comp = new Comp(jsonComp.getJsondata(i));
SetMarkerComp(comp);
try {
Thread.sleep(1400);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public class AsynFollow extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
if (!taxiFollow.equals("")) {
number = 1;
txt_search = compFollow;
find_url = "http://192.111.125.80:8001/Default.aspx?username="
+ Id + "&password=" + Pass + "&sohieuxe="+txt_search;
while (!stop){
new AsynComp().execute();
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
taxiFollow = "";
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!compFollow.equals("")) {
Toast.makeText(getBaseContext(), "Follow "+compFollow, Toast.LENGTH_SHORT).show();
} else {
iv_theodoi.setVisibility(View.VISIBLE);
iv_theodoif.setVisibility(View.GONE);
Toast.makeText(getBaseContext(), "Plz choose a marker", Toast.LENGTH_SHORT).show();
}
}
}
And i have 2 buuton, 1 to call AsynFollow.execute(), another to stop it.
This code can run but app will force close after awhile.
Any solution? thanks.
P/s: i'm a newbie in android.
You shoulnd you asyncTask for this. For repetitive action, like changing status in some interval, use Timer class. In this way you can implement repetitive action which can be repeated in intervals.
In this way you can stop this time by on click listener. You can run two times and specify it's realtions using other variables.
If you're newbe, you should read about multitasking in Android: Timer, AsyncTask, Handler.
In my opinion this docs will tell you much more than thousands of comments in stackoverflow.

AsyncTask with Timer keeps on running

I have scheduled a AsyncTask using a Timer by following code
public void toCallAsynchronous() {
TimerTask doAsynchronousTask;
final Handler handler = new Handler();
Timer timer = new Timer();
doAsynchronousTask = new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
handler.post(new Runnable() {
public void run() {
try {
if(mLoggedIn)
{
DownloadRandomPicture download = new DownloadRandomPicture(this, mApi, CLIENT_ID, mImage);
download.execute();
}
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0,50000);//execute in every 50000 ms
}
#Override
protected Boolean doInBackground(Void... params) {
try {
if (mCanceled) {
return false;
}
// Get the metadata for a directory
Entry dirent = mApi.metadata(mPath, 1000, null, true, null);
if (!dirent.isDir || dirent.contents == null) {
// It's not a directory, or there's nothing in it
mErrorMsg = "File or empty directory";
return false;
}
// Make a list of everything in it that we can get a thumbnail for
ArrayList<Entry> thumbs = new ArrayList<Entry>();
for (Entry ent: dirent.contents) {
if (ent.thumbExists) {
// Add it to the list of thumbs we can choose from
thumbs.add(ent);
}
}
if (mCanceled) {
return false;
}
if (thumbs.size() == 0) {
// No thumbs in that directory
mErrorMsg = "No pictures in that directory";
return false;
}
// Now pick a random one
int index = (int)(Math.random() * thumbs.size());
Entry ent = thumbs.get(index);
String path = ent.path;
mFileLen = ent.bytes;
String cachePath = mContext.getCacheDir().getAbsolutePath() + "/" + IMAGE_FILE_NAME;
try {
mFos = new FileOutputStream(cachePath);
} catch (FileNotFoundException e) {
mErrorMsg = "Couldn't create a local file to store the image";
return false;
}
// This downloads a smaller, thumbnail version of the file. The
// API to download the actual file is roughly the same.
mApi.getThumbnail(path, mFos, ThumbSize.BESTFIT_960x640,
ThumbFormat.JPEG, null);
if (mCanceled) {
return false;
}
mDrawable = Drawable.createFromPath(cachePath);
// We must have a legitimate picture
return true;
} catch (DropboxUnlinkedException e) {
// The AuthSession wasn't properly authenticated or user unlinked.
} catch (DropboxPartialFileException e) {
// We canceled the operation
mErrorMsg = "Download canceled";
} catch (DropboxServerException e) {
// Server-side exception. These are examples of what could happen,
// but we don't do anything special with them here.
if (e.error == DropboxServerException._304_NOT_MODIFIED) {
// won't happen since we don't pass in revision with metadata
} else if (e.error == DropboxServerException._401_UNAUTHORIZED) {
// Unauthorized, so we should unlink them. You may want to
// automatically log the user out in this case.
} else if (e.error == DropboxServerException._403_FORBIDDEN) {
// Not allowed to access this
} else if (e.error == DropboxServerException._404_NOT_FOUND) {
// path not found (or if it was the thumbnail, can't be
// thumbnailed)
} else if (e.error == DropboxServerException._406_NOT_ACCEPTABLE) {
// too many entries to return
} else if (e.error == DropboxServerException._415_UNSUPPORTED_MEDIA) {
// can't be thumbnailed
} else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) {
// user is over quota
} else {
// Something else
}
// This gets the Dropbox error, translated into the user's language
mErrorMsg = e.body.userError;
if (mErrorMsg == null) {
mErrorMsg = e.body.error;
}
} catch (DropboxIOException e) {
// Happens all the time, probably want to retry automatically.
mErrorMsg = "Network error. Try again.";
} catch (DropboxParseException e) {
// Probably due to Dropbox server restarting, should retry
mErrorMsg = "Dropbox error. Try again.";
} catch (DropboxException e) {
// Unknown error
mErrorMsg = "Unknown error. Try again.";
}
return false;
}
protected void onProgressUpdate(Long... progress) {
int percent = (int)(100.0*(double)progress[0]/mFileLen + 0.5);
//mDialog.setProgress(percent);
}
#Override
protected void onPostExecute(Boolean result) {
//mDialog.dismiss();
if (result) {
// Set the image now that we have it
mView.setImageDrawable(mDrawable);
} else {
// Couldn't download it, so show an error
showToast(mErrorMsg);
}
}
I am calling this from onCreate of my activity. My async task basically downloads some data from server. Main activity allows user to login to server and then I go for fetching the data. The problem that I am facing is that each AsyncTask creates its own thread. Also, none of those goes to completion.The thread status is always running. Is there a way to check that the new AsyncTask is only launched when the earlier is finished.
Following links can helps you, please have a look, Thanks.
Android: Can I chain Async task sequentially (starting one after the previous asynctask completes)
and
Android calling AsyncTask right after an another finished
Try this way
public ArrayBlockingQueue<Runnable> threadList = new ArrayBlockingQueue<Runnable>(
2000, true);
public ThreadPoolExecutor threadPool = new ThreadPoolExecutor(0,
2000, 1000, TimeUnit.MILLISECONDS, threadList);
TimerTask t=new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
//your code here
}
};
ThreadPool.execute(t);
The line timer.schedule(doAsynchronousTask, 0,50000);//execute in every 50000 ms is responsible for the repetitive task.
As per the description of Timer class's schedule( TimerTaskObject, int start, int repete ) method , this will repeat a particular TimerTask for the defined time interval, i suggest you to change it as follows,
timer.schedule(doAsynchronousTask, 1000);//execute once after one second

Categories

Resources