I am making an android/Java remake of the cookie clicker as a first android project and am having trouble comprehending how the auto-click function works. This is my first time operating outside of the comfortable world of VB.net.
I have one button, a textview for score and a textview for score per second. What I am finding difficult is figuring out how to have the program listen for a button click while simultaneously running a loop adding the score per second.
This is what I have right now.
Code:
public class Huslte extends ActionBarActivity {
int iScore = 0;
int iScorePerSecond = 1;
int iScorePerClick = 1;
boolean bGameon = true; //used to break loop.. I guess
//TextView tScore = (TextView)findViewById(R.id.textView01); doesn't work here for some reason
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_huslte);
TextView tScore = (TextView)findViewById(R.id.textView01);
TextView tScorePerSecond = (TextView)findViewById(R.id.textView);
//Set textViews to correct starting values
tScore.setText("" + iScore);
tScorePerSecond.setText("" + iScorePerSecond);
//I tried to put the loop in here. with a do while bGameon = true and add score. This just caused the
//game to seize. I assumed the the _Click below was considered a separate virtual thread
//constantly looping and listening for a button press. I think I was wrong.
}
public void bHustle_Click (View v) { // bHustle is my button, this is a header listening for it
TextView tScore = (TextView)findViewById(R.id.textView01);
//when the button is pressed, add to the score
iScore = iScore + iScorePerClick;
tScore.setText("" + iScore);
}...
I want to add a loop that waits 1 second before adding the score per second to the total score. If I create a loop in the main on create area, it freezes the game. So I assume I need to add the button click function within the main loop.
Question is, if I listen for the button click during the loop and the loop waits 1 second every time it cycles, doesn't that give the user a stupidly short window to actually click to add score?
I'm all for increasing the difficulty, but that's not what I'm trying to do.
How would I have the button listener running at the same time as the score adding loop while sticking on a single thread.
(also, does more than one thread = more than one core needed? or are they virtual threads?)
Related
Hello to all!
I have not participated much in the forum, though I have been reading you for a while So... I am going to ask for your help
I'm trying to make a custom paint with the finger (to draw, to take notes, whatever) and I'm having some troubles.
Up to now, from what I have read, I'm using a class extended from View implementing OnTouchListener , and using the onDraw() method, with the onTouch event. I detect when the screen is touched (pressed, or dragged to "paint" in the screen) with the onTouch method, store the last point in an array, and in the onDraw method, I paint all the array.
-As my knowledge goes, in the onDraw method, you have to re-paint all the canvas (this is translated to my problem, to repaint all the stroke or "painting"). Is this correct or I am doing anything wrong? Is there any way to only update the current canvas, and not have to re-paint all the screen? Maybe using othe classes or other methods, but I have found nothing in the net (maybe I'm not looking in the correct places).
- The second problem I found is that when I drag the finger across the screen, sometimes the ontouch method doesen't capture all the points I have "touched" with the finger. I mean, I don't want to capture ALL the points, but when I drag the finger with moderate speed (not very fast) there are important gaps in between. Is there a way to optimize this and try to capture more points in between?
So far, this is the code I have relevant to the issues I'm explaining:
I'm trying to copy the code but I get a error (It sais I can not post outside links, but I'm not posting any links, just the code)
Code:
private ArrayList<PointStroke > stroke= new ArrayList<PointStroke >();
protected void onDraw(Canvas canvas) {
Paint p = new Paint();
p.setColor(Color.RED);
int signLength = stroke.size();
PointStroke pf;
PointStroke pfant;
for (int index = 0; index < signLength; index++) {
pf = stroke.get(index);
canvas.drawCircle(pf.x,pf.y,7,p);
if (index > 0 ) {
pfant = stroke.get(index-1);
canvas.drawLine(pfant.x, pfant.y, pf.x, pf.y, p);
}
}
canvas.drawCircle(x,y,7,p);
invalidate();
}
@Override
public boolean onTouch(View v, MotionEvent event) {
x = event.getX();
y = event.getY();
pr = event.getPressure();
sz = event.getSize();
long now = System.currentTimeMillis();
stroke.add(new PointStroke(x,y,pr,sz,now));
return true;
}
private class PointStroke{
public float x;
public float y;
public float pr;
public float sz;
public long time;
public PointStroke(float newX, float newY, float newPR, float newSZ, long newTIME) {
x = newX;
y = newY;
pr = newPR;
sz = newSZ;
time = newTIME;
}
}
Thanks for all your answers and the time to read and answer!
I'm getting a Null Pointer when I call a database method inside a listener. If the method call is outside the listener, it runs, but the data I want to pass is empty.
Help
(Note: I do comment-out one of the myDbHelper calls as req'd) LOL
Code:
/** Set Search Button Listener */
searchButton.setOnClickListener(button_listener);
searchButton = (Button) findViewById(R.id.searchButton);
myDbHelper.getRow(s); // Ok, but "s" is empty!
}
private OnClickListener button_listener = new OnClickListener() {
public void onClick(View v) {
EditText search = (EditText) findViewById(R.id.searchBox);
String s = search.getText().toString();
myDbHelper.getRow(s); // Throws Null Pointer Exception
}
};
Wow, same post on THREE different forums, 200 total views, no responses...bummer
I really don't have any idea why this is throwing the Null Pointer inside of the onClick. I've Googled 100 times for solutions and just can't find anything.
I guess I'll just gut all the code from the database helper class and put it in my main Activity; only thing I can think of doing right now LOL
Woo friggn' hoo!! I got it working.
And to the hundreds out there that may be struggling on the same thing, let me know when you've got 100 debugging hours in first and then I'll help ROFL
Hey guys,
Is there any way to get the Android browser to handle key presses the same way a normal browser would? I'm mostly thinking about the arrow keys here. Usually, it just moves to the next link on the page. For example, try loading slides.html5rocks.com on an android device. Pushing the arrow keys should move to the next slide but instead it just highlights the links on the first slide. I'm trying this with a bluetooth keyboard but I assume it's the same on devices with physical keyboards.
On a side note, that website allows for swiping between slides. However, it does not do this when loaded in a desktop browser. Does anyone know how they did this?
Thanks
Edit: I just noticed that I posted this in the development section. I probably should have been in general. Sorry!
What exactly you want to get? Referenced site (html5rocks) work well (switching slides and so on) in HTML5 compliant browsers. For example in Google Chrome or in Firefox. Actually in Firefox 3.6.17 (version that I've tested) it works not exactly as expected but the mostly. And in my Android builtin browser it works probably as proposed. Left/right dragging gesture (on touch screen) has the same effect as pressing right/left button in desktop browser - swapping to the next/previous slide.
Anyways, if you'd like to deal with browser events, you probably should look at WebView class.
Yes, perhaps this was a bad example. What I'm wondering is if it is possible for android to interpret the arrow keys on a physical keyboard the same was as a desktop. This this particular example, you can just swipe, but I would like to be able to use the arrow keys on my keyboard to do this, just like I would on a desktop.
Maybe a better example would be http://htmlfive.appspot.com/static/gifter.html
this is impossible to use in android
the arrow keys should move your character, but they just scroll the page
I see... Well, the hack below should do what you want, but for some reason it doesn't.
Code:
public class WebActivity extends Activity {
private static final String TAG = "WebActivity";
WebView webView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webView = (WebView) findViewById(R.id.webview);
webView.setWebViewClient(new HelloWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.setOnKeyListener(onKeyListener);
webView.addJavascriptInterface(new JavaScriptInterface(), "Android"); // this is for debug only
webView.loadUrl("http://htmlfive.appspot.com/static/gifter.html");
// webView.loadUrl("file:///android_asset/gifter.html");
}
// This is for debug - redirect Android.log() javascript calls to Log.d().
// 'Android' here - is an 'interfaceName argument' of addJavascriptInterface() call above
public class JavaScriptInterface {
public void log(String message) {
Log.d(TAG, message);
}
}
private void simulateKeyEvent(String key, int code, boolean keyDown) {
Log.d(TAG, "simulateKeyEvent('" + key + "', " + code + ", " + keyDown + ")");
webView.loadUrl("javascript:(function(){var e=document.createEvent('KeyboardEvent');e.initKeyboardEvent('" + (keyDown ? "keydown" : "keyup" ) + "',true,true,null,'" + key + "',0,0,0," + code + ",0);document.body.dispatchEvent(e);})()");
}
OnKeyListener onKeyListener = new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
Log.d(TAG, ".onKey(): keyCode = " + keyCode + ", action = " + event.getAction());
int code;
String key;
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_DPAD_LEFT:
code = 37; // JavaScript KeyboardEvent.keyCode value for left arrow
key = "Left";
break;
case KeyEvent.KEYCODE_DPAD_UP:
code = 38; // ...
key = "Up";
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
code = 39;
key = "Right";
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
code = 40;
key = "Down";
break;
default:
Log.d(TAG, "Unknown key");
return false;
}
boolean keyDown;
switch (event.getAction()) {
case KeyEvent.ACTION_DOWN:
keyDown = true;
break;
case KeyEvent.ACTION_UP:
keyDown = false;
break;
default:
Log.d(TAG, "Unknown action");
return false;
}
simulateKeyEvent(key, code, keyDown);
return true;
}
};
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
Looks like the problem is in the implementation of initKeyboardEvent() in WebKit (or V8?). It always produces KeyboardEvent object with 0 values of keyCode and keyChar. So this code doesn't working in my Chrome too: event is dispatched, appropriate handler is called, but keyCode is 0.
Probably there is some other way to simulate keyboard event for JavaScript running within WebView. Or maybe there is some way to redefine KeyEvent processing by WebView. I think you should look for something like this.
This is interesting subject. If you'll find a solution, please write here about it.
References:
http://developer.android.com/resources/tutorials/views/hello-webview.html - basics of WebView usage
http://developer.android.com/reference/android/webkit/WebView.html - WebView in more details
http://lexandera.com/2009/01/injecting-javascript-into-a-webview/ - about interacting with JavaScript from WebView
http://stackoverflow.com/questions/1897333/firing-a-keyboard-event-on-chrome (and many other topics) - about problems with simulating keyboard events on WebKit
this is really frustrating. No matter what I do, I just end up with keycode 0. google really needs to fix the problem with initKeyboardEvent. Oh well..
Thanks for you help
Hello. New here and I hope this post is okay. The "Is this a question?" checkbox says it not the QA forum but it is?
Working on an app that all it's supposed to do is repeat taking a picture every 5 seconds after pressing a button. Now, I've looked at handler, timer, etc but I can't figure out the right way to do it. This is the code currently, and the onCameraClick of course runs when the button on the screen is pressed. I want that button to activate some kind of repeater so the picture gets taken every 5000ms.
Code:
public class CameraImage extends Activity {
public static int cameraID = 0;
public static ImageView image;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cameraimage);
image = (ImageView) findViewById(R.id.imgView);
}
public void onCameraClick(View v)
{
cameraID = 1;
Intent i = new Intent(CameraImage.this, CameraView.class);
startActivityForResult(i, 9999);
}
}
Now, this is something I'd definitely like to use but I'm not sure how to implement this correctly into the code above. Been trying trial and error for past few hours and nothing. Tried out a timer example someone put on another website, 10792454/image-capture-in-android-automatically but not much there.
At the same time however though, I'm not sure if the code should go in the other class with all the functions to run the camera. Any suggestions/tip or help I'd greatly appreciate it.
Try a loop. I'm not sure if you have tried this or if it will work with launching an activity, but it sounds like that is what you want to do. I don't know how you determine when to stop taking pictures but you can use a "for loop" or a "while loop".
example "for loop":
Code:
for (int i; i > someNumber; i++){
//Your code here
}
someNumber would be perhaps the number of pictures you want to take and you can use i to number each picture.
example "while loop":
Code:
Boolean buttonClick = false;
onCreate(){
OnButtonClick(){
OnClick(){
if(buttonClick == true){
buttonClick = false;
}else{
buttonClick = true;
}
onCameraStart(buttonClick);
}
public void onCameraStart(boolean runCamera){
while (runCamera == true){
//Your code here
}
}
This example I showed you how you would be able to start the camera on the first click and stop it when clicked again. The OnButtonClick would be the OnClickListener for your button.
Both these examples may need a little refinement but this should point you in the right direction. Hope this helps. You can put these in threads and pause the thread at the end of the loop for 5 secs so it will wait (I think).
It's simple use a timer and invoke it on first click
Sent from my GT-S5302 using Tapatalk 2
I want to add a item to the child Today from another activity to the ExpandableListView. The activity where I want to add it is named LocHistory, here is a the code to add something to the list:
Code:
static void addListData(final Context context) {
List<NewsItem> list = listDataChild.get("Today");
NewsItem newsData = new NewsItem();
newsData = new NewsItem();
newsData.setHeadline("11.11111, 1.1111");
newsData.setSpeed("1.11KM/H");
newsData.setDirection("111");
newsData.setDate("11-1-1111 11:11:11");
list.add(0, newsData);
listDataChild.put("Today", list);
}
This is working when I have call the function in the same class (LocHistory). But when I call it in MainActivity like this:
Code:
public class MainActivity extends Activity {
Button button2;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button2 = (Button) this.findViewById(R.id.button2);
button2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
LocHistory.addListData(getBaseContext());
}
});
}
}
Then there is nothing added to the list. Is it possible to add a item from another activity to ExpandableListView? I want if there's something added that the class LocHistory is not going to open, so I think startActivity with a intent is not a option here (but i'm not sure).
(The java sources can be found here:
MainActivity.java pastebin.com/YWyfznwv
LocHistory.java - pastebin.com/XJ274C61
NewsItem.java - pastebin.com/uhmXbnhJ
ExpandableListAdapter.java - pastebin.com/5jPV8daz)
Alwaysup said:
I want to add a item to the child Today from another activity to the ExpandableListView. The activity where I want to add it is named LocHistory, here is a the code to add something to the list:
Code:
static void addListData(final Context context) {
List<NewsItem> list = listDataChild.get("Today");
NewsItem newsData = new NewsItem();
newsData = new NewsItem();
newsData.setHeadline("11.11111, 1.1111");
newsData.setSpeed("1.11KM/H");
newsData.setDirection("111");
newsData.setDate("11-1-1111 11:11:11");
list.add(0, newsData);
listDataChild.put("Today", list);
}
This is working when I have call the function in the same class (LocHistory). But when I call it in MainActivity like this:
Code:
public class MainActivity extends Activity {
Button button2;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button2 = (Button) this.findViewById(R.id.button2);
button2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
LocHistory.addListData(getBaseContext());
}
});
}
}
Then there is nothing added to the list. Is it possible to add a item from another activity to ExpandableListView? I want if there's something added that the class LocHistory is not going to open, so I think startActivity with a intent is not a option here (but i'm not sure).
(The java sources can be found here:
MainActivity.java pastebin.com/YWyfznwv
LocHistory.java - pastebin.com/XJ274C61
NewsItem.java - pastebin.com/uhmXbnhJ
ExpandableListAdapter.java - pastebin.com/5jPV8daz)
Click to expand...
Click to collapse
In Android, try to use as few static variables and methods as possible. To get a non-static access to the method, make it public and get an instance of the list adapter in the activity (via list.getAdapter () or create a new one and set the listAdapter in the expListView).
If you really want to access it through 2 activities, I'm sorry, there's no way of doing this directly. You'd have to save it in a file or your SharedPreferences and get the items once you get to the other activity.
And also, why do you need that context object in addListData()? That could lead to memory leak...
In this thread you can find a solution. There is a library called EventBus which they used. Read it completely (just 2 pages).
http://forum.xda-developers.com/showthread.php?t=2332069
By the way,
When I log the listDataChild in the function addListData then it seems that the item is added under the child Today (the logging is only working when I first open the class LocHistory and close it). The prepareListData function is called in the onCreate method. Is it maybe that function overrides the listDataChild that is created by the function addListData?
SimplicityApks said:
In Android, try to use as few static variables and methods as possible. To get a non-static access to the method, make it public and get an instance of the list adapter in the activity (via list.getAdapter () or create a new one and set the listAdapter in the expListView).
If you really want to access it through 2 activities, I'm sorry, there's no way of doing this directly. You'd have to save it in a file or your SharedPreferences and get the items once you get to the other activity.
And also, why do you need that context object in addListData()? That could lead to memory leak...
Click to expand...
Click to collapse
Sorry for the context object in addListData() is was doing some test with SharedPreferences and then I've to use the context object (I've removed now). Can you call list.getAdapter() from another activity?
nikwen said:
In this thread you can find a solution. There is a library called EventBus which they used. Read it completely (just 2 pages).
http://forum.xda-developers.com/showthread.php?t=2332069
Click to expand...
Click to collapse
Thanks for the link, I will study this. Altough I not prefer to include an other library
Alwaysup said:
By the way,
When I log the listDataChild in the function addListData then it seems that the item is added under the child Today (the logging is only working when I first open the class LocHistory and close it). The prepareListData function is called in the onCreate method. Is it maybe that function overrides the listDataChild that is created by the function addListData?
Sorry for the context object in addListData() is was doing some test with SharedPreferences and then I've to use the context object (I've removed now). Can you call list.getAdapter() from another activity?
Thanks for the link, I will study this. Altough I not prefer to include an other library
Click to expand...
Click to collapse
The event Bus is a cool library, but the question is whether it's worth including a lib to do just that. You can usually try to combine both activities into one with Fragments and a ViewPager.
The list can only be accessed in its own activity, so list.getAdapter() won't work. But u can still write the data to a file on the SD card or use a SQLite database (or SharedPreferences for non-objects).
I found out that what's probably better is to use less activities or use SharedPreferences wherever it's possible since it's cleaner and faster.
Had a similar problem a while ago (but I needed to pass data to a starting activity) and solved it using a Bundle (via Intent), but then realized the app is much nicer combining both activities...
SimplicityApks said:
The event Bus is a cool library, but the question is whether it's worth including a lib to do just that. You can usually try to combine both activities into one with Fragments and a ViewPager.
The list can only be accessed in its own activity, so list.getAdapter() won't work. But u can still write the data to a file on the SD card or use a SQLite database (or SharedPreferences for non-objects).
I found out that what's probably better is to use less activities or use SharedPreferences wherever it's possible since it's cleaner and faster.
Had a similar problem a while ago (but I needed to pass data to a starting activity) and solved it using a Bundle (via Intent), but then realized the app is much nicer combining both activities...
Click to expand...
Click to collapse
I agree. The less Activities, the better the app. (At least until all Activities are crowded. )
As you guys pointed out, I'm now using SharedPreferences. I'm using this code:
Code:
private static int startOf(String day) {
Date date = new Date(System.currentTimeMillis());
//TimeZone tzGMT = TimeZone.getTimeZone("GMT");
Calendar cal = Calendar.getInstance();
//cal.setTimeZone(tzGMT);
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
// change to seconds
long ltimeM = cal.getTimeInMillis();
int iTimeStamp = 0;
if (day == "today") {
iTimeStamp = (int) (ltimeM / 1000);
} else if (day == "yesterday") {
iTimeStamp = (int) ((ltimeM / 1000) - 86400);
}
cal.set(Calendar.HOUR_OF_DAY, cal.getActualMinimum(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, cal.getActualMinimum(Calendar.MINUTE));
cal.set(Calendar.SECOND, cal.getActualMinimum(Calendar.SECOND));
//return Integer.toString(iTimeStamp);
return (int) iTimeStamp;
}
static void addListData (int TimeStamp, final String lat, final String lng, final String speed,
final String direction, final Context context){
int todaystamp = startOf("today");
int yesterdaystamp = startOf("yesterday");
String Datetime = DateFormat.format("dd-MM-yyyy kk:mm:ss", new Date(TimeStamp * 1000L)).toString();
SharedPreferences pref = context.getSharedPreferences("myPrefs", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
if (TimeStamp >= todaystamp) {
editor.putString("Today", "*headline=" + lat + ", " + lng + ";speed=" + speed + ";direction=" + direction + ";date=" + Datetime + ";");
} else if (TimeStamp >= yesterdaystamp) {
editor.putString("Yesterday", "*headline=" + lat + ", " + lng + ";speed=" + speed + ";direction=" + direction + ";date=" + Datetime + ";");
} else if (TimeStamp < yesterdaystamp) {
editor.putString("Older", "*headline=" + lat + ", " + lng + ";speed=" + speed + ";direction=" + direction + ";date=" + Datetime + ";");
}
editor.commit();
}
But now I'm stuck with one problem, when I add a item to the SharedPreferences on the same key it will overwrite the previous data. How can I add data to the same key without overwriting the previous data? Is it maybe possible to first get the data and then join the item to the data after that add the data to the SharedPreferences?
Any help you guys can provide me would be greatly appreciated! :good:
Alwaysup said:
As you guys pointed out, I'm now using SharedPreferences. I'm using this code:
Code:
static void addListData (int TimeStamp, final String lat, final String lng, final String speed,
final String direction, final Context context){
int todaystamp = startOf("today");
int yesterdaystamp = startOf("yesterday");
String Datetime = DateFormat.format("dd-MM-yyyy kk:mm:ss", new Date(TimeStamp * 1000L)).toString();
SharedPreferences pref = context.getSharedPreferences("myPrefs", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
if (TimeStamp >= todaystamp) {
editor.putString("Today", "*headline=" + lat + ", " + lng + ";speed=" + speed + ";direction=" + direction + ";date=" + Datetime + ";");
} else if (TimeStamp >= yesterdaystamp) {
editor.putString("Yesterday", "*headline=" + lat + ", " + lng + ";speed=" + speed + ";direction=" + direction + ";date=" + Datetime + ";");
} else if (TimeStamp < yesterdaystamp) {
editor.putString("Older", "*headline=" + lat + ", " + lng + ";speed=" + speed + ";direction=" + direction + ";date=" + Datetime + ";");
}
editor.commit();
}
But now I'm stuck with one problem, when I add a item to the SharedPreferences on the same key it will overwrite the previous data. How can I add data to the same key without overwriting the previous data? Is it maybe possible to first get the data and then join the item to the data after that add the data to the SharedPreferences?
Any help you guys can provide me would be greatly appreciated! :good:
Click to expand...
Click to collapse
SharedPreferences does not save data in subcategories, so the tag you give it to save a variable is then connected to that variable and if you use it again, it will be overridden (as you found out).
If you want to stick to the SharedPreferences, you have to give each item a unique tag, so you would normally add a counter to save "Today_1", "Today_2", Today_3", ...
then you save that counter also so that you know how many items you saved.
If you want to do it nicely though, check out the SQLite database. It is a little mor work and requires some knowledge about databases, but I think it's worth it.
Try static handlers. worth simple logic helps u to update ur activity from any thread or activity.