For Loop reading infinity - android

I am trying to make a simple screen that shows you the amount of money you have earned by the second, so im trying to create a live feed type textveiw that updates every second with the amount of money you have earned, with my code when it runs on my phone it only reads "infinity" and when i tried to add in a 1 second delay it froze all together, here is the code that i wrote, i am using a for loop because i didnt know of a better way if anyone has a better way of achieving what i am trying to do please let me know..
// Calculate pay per second
double PPS = (HW/3600);
double OTPPS = (OTW/3600);
double HPDPS = (HPD*3600);
double money = 0;
double Reserve = 0;
loc = 0;
// Display
for(int i=0; i<HPDPS & loc!=7; i++)
{
money = (PPS+Reserve);
Reserve = (Reserve+money);
TextView textView = (TextView) this.findViewById(R.id.yourpay);
textView.setText(String.valueOf(money));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Thanks in advance for any help!
======================================================================================
Here is an edited version but i am still having a problem where it just displays infinity on the screen, how do i fix this? or how do i use the timer method?
public void sendMessage(View view) {
// Receive messages from options page
Intent intent = getIntent();
double HW = intent.getDoubleExtra(Options.MESSAGE_HW, 0);
double OTW = intent.getDoubleExtra(Options.MESSAGE_OTW, 0);
double HPD = intent.getDoubleExtra(Options.MESSAGE_HPD, 0);
// Calculate pay per second
double PPS = (HW/3600);
double OTPPS = (OTW/3600);
double HPDPS = (HPD*3600);
double money = 0;
double Reserve = 0;
// Display
for(int i=0; i<HPDPS; i++)
{
money = (PPS+Reserve);
Reserve = (Reserve+money);
TextView textView = (TextView) this.findViewById(R.id.yourpay);
textView.setText(String.valueOf(money));
}
// set textView
}

Better way is to user a Timer and TimerTask.
EDIT:
Here is a sample application code to user Timer and TimerTask:
final TextView t1 = (TextView) findViewById(R.id.textView1);
final Timer t =new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
t1.setText("Hello" + counter++); //Place your text data here
//Place your stopping condition over here. Its important to have a stopping condition or it will go in an infinite loop.
if(counter == 10)
t.cancel();
}
});
}
}, 1000, 1000);
Hope this helps.

[1] You are doing Bitwise ANDing (Bitwise ANDing -> &) here
for(int i=0; i<HPDPS & loc!=7; i++)
^
[2] Your loc in always 0, because you did loc=0 and in for loop loc is never updated
So loc!=7 is ALWAYS TRUE

Related

How to update whole output row on change of given Input?

I am having trouble with my output screen!
When I click on Click button with these inputs output screen looks like attached image, which is so far great!
But if I change my input, the program gives new answer by adding more rows with previous answers! I want only new answers on screen to be shown!
Also without updating input if I click on button same way screen adds up new rows!
I am including a picture of this also..
I used this code given below,
clickbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
aI = Double.parseDouble(Ia.getText().toString());
bI = Double.parseDouble(Ib.getText().toString());
cI = Double.parseDouble(Ic.getText().toString());
bisection();
}
});
private void bisection() {
if ((f(aI) < 0 && f(bI) > 0) || (f(aI) > 0 && f(bI) < 0)) {
for (int i = 0; i < cI; i++) {
View tableRow = LayoutInflater.from(this).inflate(R.layout.table_item, null, false);
TextView iteration = (TextView) tableRow.findViewById(R.id.index);
TextView a = (TextView) tableRow.findViewById(R.id.a);
TextView b = (TextView) tableRow.findViewById(R.id.b);
TextView x = (TextView) tableRow.findViewById(R.id.x);
TextView fx = (TextView) tableRow.findViewById(R.id.fx);
double root = (aI+bI)/2;
iteration.setText(" " + (i + 1));
a.setText(Double.toString(aI));
b.setText(Double.toString(bI));
x.setText(Double.toString(root));
fx.setText(Double.toString(f(root)));
tableLayout.addView(tableRow);
if(f(aI)*f(root) < 0){
bI = root;
}else if (f(aI)*f(root) >0) {
aI = root;
}
}
} else {
Toast.makeText(getApplicationContext(), R.string.popUpMsg,Toast.LENGTH_SHORT).show();
}
}
public static double f(double x){
return ((Math.pow(x,3))-x-4);
}
I have already found almost same problem has been solved in a post previously asked by someone else but I couldn't fix mine! Help me. Thanks!
In your button click listener method, add following line of code before calling bisection().
tableLayout.removeAllViews();
Whenever, you will click the button, previous output will be removed before calculating new input values.
Your code would look like this:
clickbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
aI = Double.parseDouble(Ia.getText().toString());
bI = Double.parseDouble(Ib.getText().toString());
cI = Double.parseDouble(Ic.getText().toString());
tableLayout.removeAllViews(); // Remove previous output
bisection();
}
});
first way; You have to use
removeAllViews();
Before adding. To do this, you have to have a layout variable around. ex;
linearLayout.removeAllViews();
Another way is adding the Textviews in the beginning with VIEW.INVISIBLE or VIEW.GONE
Whichever suits you.

How to Double Score the point for a word?

I have my first Android app and I am having difficulty on how can I double the point for a word/words whenever a player click an imageview. Basically, I want it to function like this: If the player hasn't click the imageview, the pointing system stays the same. If the player clicks the imageview the a message will pop-out (a toast perhaps telling the player that the points for the next 3 words will be doubled). How can I make this happen? How can I double the points for the 3 consecutive words without exceeding?
Here's my code for searching and calculation
//CALCULATE SCORE
private int optionTxtView = 0 ; //which textview to use for addition purposes
private int addClick = 0 ; //No. of clicks for search for calculation
private void calculate(){
x = Integer.parseInt(tv3.getText().toString().replaceAll("\\s",""));
y = Integer.parseInt(tv2.getText().toString().replaceAll("\\s",""));
z = x + y;
score.setText(Integer.toString(z));
}
//SEARCH WORD, DISPLAYING SCORE
public void viewWord(View view)
{
String s1= search.getText().toString(); //What word to search
String s2= dbHelper.getData(s1); // If in db, display equivalent score
if(optionTxtView == 0){
//display the score on textview1
tv2.setText(s2);
optionTxtView = 1;
}
else{
if(optionTxtView == 1){
//display the score on textview2
tv3.setText(s2);
optionTxtView = 0;
}
}
//Display search word/s
adapter.add(text.getText().toString());
adapter.notifyDataSetChanged();
if(addClick ==0){
calculate();
addClick = 1;
text.setText("");
generatedString="";
}
else{
if(addClick == 1){
calculate();
addClick = 2;
text.setText("");
generatedString="";
}}
boolean sDouble = false
imgView.setOnClickListener(new View.OnClickListener() {
//#Override
public void onClick(View v) {
// Show your Toast message
// double = true;
}
});
and where you are running your game code check the value of sDouble, if its true then double the scoring system inside a for loop, or set an integer value to 0 and increment it for next 3 words, after that set the value of sDouble back to false.
You may also need to make sure that the user doesn't click on the image for the next 3 tries after clicking it once.
Update:
Since your score is a String, you need to parse it to an Integer before performing any mathematical operation, use Integer.parseInt(s2).

Calling Async task in a loop?

I want to call an Async task in a loop and execute it a few times in parallel.
I have a List of items which I split out into smaller lists with 10 items in each list.
Then for every small List I execute the Async task using THREAD_POOL_EXECUTOR.
Problem is, its not working. I'm thinking its because I use the same list each time when it is passed to the AsyncTask - and I think it may be passed as reference.
Do I need to somehow create new Lists dynamically?
//split the ListItems into 10s
if (actualThumbs.size() > 10){
List<List<ListItem>> parts = chopped(actualThumbs, 10); // this splits it into parts of 10
List< ListItem > listToSend = new ArrayList<ListItem>(); //this is the list to pass
for(int i = 0; i < parts.size(); i++){ //for every part
for(int x = 0; x < parts.get(i).size(); x++){ //for everything in that part
//add to its own List
listToSend.add(parts.get(i).get(x));
}
//this is the async task
loadActualThumbs thumbs = new loadActualThumbs();
//execute multiple threads
thumbs.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,listToSend );
listToSend.clear(); //clearing the list ready for a new one - PROBLEM?
}
}
else
{
//else just execute AsyncTask normally, this works OK
loadActualThumbs thumbs = new loadActualThumbs();
thumbs.execute(actualThumbs);
}
EDIT:
I tried changing my code, to instead add every List that I want to send to the Async task to another List, and then loop through that List of Lists and send each one:
if (actualThumbs.size() > 10){
List<List<ListItem>> parts = chopped(actualThumbs, 10);
List< ListItem > listToSend = new ArrayList<ListItem>();
List<List<ListItem>> sendMe = new ArrayList<List<ListItem>>();
for(int i = 0; i < parts.size(); i++){ //for every part
for(int x = 0; x < parts.get(i).size(); x++){ //for everything in that part
//add to its own ListItem?
listToSend.add(parts.get(i).get(x));
}
sendMe.add(listToSend);// add the List to this List
listToSend.clear();
}
for(int e = 0; e<sendMe.size();e++){ //loop through the list of lists
loadActualThumbs thumbs = new loadActualThumbs();
//execute multiple threads?
thumbs.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,sendMe.get(e) ); // execute async with correct List
}
}
else
{
if (actualThumbs.size() > 0){
//load actual thumbnails
loadActualThumbs thumbs = new loadActualThumbs();
thumbs.execute(actualThumbs);
}
}
Your code should look like this now :
List<List<ListItem>> parts = chopped(actualThumbs, 10);
for(List<ListItem> list : parts) {
new loadActualThumbs().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, list);
}
I am actually not sure what size the threadpool is or if it's a cached thread pool, but you can create your own threadpool with Executors.newCachedThreadPool() and Executors.newFixedThreadPool(int count)... but I'd just go with the AsyncTask.THREAD_POOL_EXECUTOR....should work :)
If you need to execute your asynctask for particular interval of time then you may make use of Timer for same ..
Like this ..
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
try {
System.out
.println("=================== I am in pooling state ===============");
GetBookingStatusAsyncTask performBackgroundTask = new GetBookingStatusAsyncTask();
performBackgroundTask.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
};
Now when you need to kill this timer ..
timer.cancel();
timer = null;
Also make use of boolean check so as to avaoid infinite loop .. i.e if true then execute AsyncTask .. and if false then stop AsyncTask .. just like ..
public void callAsynchronousTask(boolean b) {
// timer.cancel();
if (b) {
System.out.println("============= Check for timer check " + tcheck);
// execute in every 10000 ms
tcheck++;
} else {
System.out
.println("============= Check for timer check + cancelling timer task "
+ tcheck);
timer.cancel();
timer = null;
System.out.println("=============timer is ===" + timer);
// finish();
return;
}
}
When you need to close this task then simply of true / false condition pass like ..you need to pass this in your AsyncTask.
callAsynchronousTask(true); / callAsynchronousTask(false);
Hope it helps!..

how to run AsyncTask every min?

I am trying to run AsyncTask every 1 minute, by using handler,but it doesn't work:(
In AsyncTask I am reading data from Sqlite DB and drawing result in mapview, aim of doing like that is another service updating my Sqlite every 1 min by taking real data from server and i want keep mapview updated too.
Is there any possible way of calling AsyncTask every minute rather than using Handler?
public Runnable getData;
private final Handler _handler = new Handler();
private static int DATA_INTERVAL = 60 * 1000;
getData = new Runnable()
{
public void run()
{
getDataFrame();
}
private void getDataFrame() {
// TODO Auto-generated method stub
_handler.postDelayed(MapViewActivity.this.getData, DATA_INTERVAL);
new DrawFromDataTask();
}
};
DrawFromDataTask is described below:
private class DrawFromDataTask extends AsyncTask<Void, Integer, FriendItemizedOverlay> {
#Override
protected FriendItemizedOverlay doInBackground(Void... params) {
// TODO Auto-generated method stub
mDbAdapter.open();
List<Refresher> nearFriends = mDbAdapter.getAllRecords();
for(Refresher friend : nearFriends)
{
double lat = Double.parseDouble(friend.Latitude);
double lon = Double.parseDouble(friend.Longitude);
OverlayItem item = new OverlayItem(new GeoPoint((int)(lat * 1000000),
(int)(lon* 1000000)),
"" + friend.name,
"" + friend.type);
mFriendOverlay.addOverlay(item);
}
return mFriendOverlay;
}
protected void onProgressUpdate(Integer... progress) {
setProgress(progress[0]);
}
protected void onPostExecute(FriendItemizedOverlay result) {
System.out.println("in AsyncTask execution!");
Location loc = get_location();
final double mLatitude = loc.getLatitude();
final double mLongitude = loc.getLongitude();
// get the last location from the database
GeoPoint lastLocation = new GeoPoint(
(int) (mLatitude * 1E6),
(int) (mLongitude * 1E6));
Drawable marker = getResources().getDrawable(R.drawable.arrow);
int amountOFplayers = result.size()-1;
for (int j=0; j<amountOFplayers; j++) {
result.getItem(amountOFplayers).setMarker(marker);
}
//System.out.println("Number of overlays -- "+amountOFplayers);
mMapView.postInvalidate();
//mMapView.invalidate();
// animate to last location
mMapController.animateTo(lastLocation);
// zoom to the required level
mMapController.setZoom(ZOOM_LEVEL);
}
}
Use the broadcast intent that runs on minute tick and then just execute the Async task. It is more accurate.
http://developer.android.com/reference/android/content/Intent.html#ACTION_TIME_TICK
Make sure you create new instance every time, since the thread object cannot be reused/relaunched unless you create new instance.
http://developer.android.com/guide/components/processes-and-threads.html
Just use a Timer, TimerTask and run in a fixed rate scheduleAtFixedRate()
Instead of using a service to poll the server every one minute, why dont you use Google Cloud Messaging for android(previously C2DM).. In that way you can send some notification to your app that yes data is changed on the server, which then leads you to change some data in your db if needed ,and then start the thread.
But yes I sincerely dont have any idea about your actual requirements

android pass a number through onclicklistener

I am trying to ask a user for 2 numbers x and y. When the user clicks the button it will subtract y from x and give the total. What I would like it to do is save the total, and the next time you click the button, it will subtract y from the total. I know I am not passing the total back through again, but I am not sure where to begin.
subtract.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) throws NumberFormatException {
if (v == subtract)
{
NumberFormat currencyFormatter;
currencyFormatter = NumberFormat.getCurrencyInstance(currentLocale);
String bString;
String x = startingmoney.getText().toString();
String y = submoney.getText().toString ();
double total = 0.00;
double xm = 0.00;
double ym =0.00;
try
{
xm = Double.parseDouble(x);
}
catch(NumberFormatException n)
{
xm = 0.00;
}
try
{
ym = Double.parseDouble(y);
}
catch(NumberFormatException n)
{
ym = 0.00;
}
total = xm -ym;
bString = currencyFormatter.format(total);
endmoney.setText(bString);
tracker.setText("you have entered " + bString +"\n" + tracker.getText().toString());
There are many ways to do this. One possible way is to make the variable "x" and "y" static. This may not meet your requirement, since you may change the value of "x" and "y" dynamically.
Another way is to change the implement of OnClickListener. You can use it as,
class MyOnClickListener implements OnClickListener
and pass the class (the class which calls "setOnClickListener") to MyOnClickListener, that is, the constructor of MyOnClickListener is like,
MyOnClickListener(CLASS clazz){
this.clazz = clazz;
}
And you can do subtraction with clazz.getX() and clazz.getY().

Categories

Resources