i have a url given to me to used for syncing the server time to my application,
Question is how to do that? anyone can explain to me what to do here thank i really appreciate it.
here's the URL = http://server10.instaforex.com:2012/TimeService/TimeService.svc/CurrentTime
here is my mainactivity code.
public class MainActivity extends Activity {
Timer timeoutTimer;
final Random myRandom = new Random();
GenerateTask genTask = new GenerateTask();
static String RAN_TEXT = "text";
class GenerateTask extends TimerTask {
boolean started = false;
public void run() {
if (started) {
System.out.println("generating");
final TextView textGenerateNumber = (TextView)findViewById(R.id.generatenumber);
RAN_TEXT = "";
for(int k=0;k<7;k++){
RAN_TEXT += myRandom.nextInt(10) + " ";
}
runOnUiThread(new Runnable() {
#Override
public void run() {
textGenerateNumber.setText(RAN_TEXT);
}
});
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonGenerate = (Button)findViewById(R.id.generateme);
buttonGenerate.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
System.out.println("click");
if (!genTask.started) {
genTask.started=true;
timeoutTimer = new Timer();
timeoutTimer.scheduleAtFixedRate(genTask, 0, 30000);
} else {
genTask.started=false;
timeoutTimer.cancel();
}
}
});
}
}
Try this..
First try to get the source of that html link using either one of solutions from the links of SO
solution 1 or solution 2
Second you can parse its content using parsers.
Third Display the parsed content as required time format.
Let me know if you face any difficulty..
It is unclear what your main activity is up to from the code you posted. It just concatenates some random numbers and sets them in a text area.
If you're looking to parse XML output returned by a HTTP client, there are many examples out there that show you how to do this. Take a look at this question - Android: parse XML from string problems
If NTP time is what you are really interested in, there are NTP clients for android that can help you sycn time correctly.
Use one of those solutions and you're good to go.
Related
So I understand the basics of java programming but when I'm trying to use my little knowledge in android studio it make everything harder having classes and different files needing to be referenced. Coming from python, when making a simple game I would define different functions, then run them in a game loop like
while running:
or something similar. I know to define something in java you go like
public void Example() {}
but when I use this in java, when I try to run the program my game either instantly crashes or doesnt load anything.
The code at the moment is
public class MainActivity extends AppCompatActivity {
//Variables
Boolean running = true;
public int years = 0;
//Setup Year Counter
TextView textView = (TextView) findViewById(R.id.year_counter);
//Advance Button
public void advance() {
ImageButton button = (ImageButton) findViewById(R.id.advance);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
years += 1;
textView.setText("" + years + "");
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Game Loop
while (running) {
advance();
}
}
}
And this results in the app not opening.
Any help at all would mean a lot to me.
Thanks in advance :)
Although I don't actually see a crash, since you didn't really upload one, I can see why you might think your app wont work.
What you are doing constantly in the while loop is that you are only setting the button's click listener over and over again.
public class MainActivity extends AppCompatActivity {
//Variables
Boolean running = true;
public int years = 0;
//Setup Year Counter
TextView textView;
ImageButton button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// you set up your views once, after the layout is inflated
setUpViews();
// you initialize your buttons functionality
initClickEvents();
//Game Loop
while (running) {
// do other stuff
}
}
private void setUpViews() {
textView = (TextView) findViewById(R.id.year_counter);
button = (ImageButton) findViewById(R.id.advance);
}
private void initClickEvents() {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
years += 1;
textView.setText("" + years + "");
}
});
}
}
I'd recommend working with a game engine.
If you want to stick with java, libGDX is an option.
But if language (and IDE) doesn't matter, than a better option is Godot. The reason why I recommend Godot over some of the more popular game engines is because it's open source, 100% free and plus GDScript (godot's scripting language) is heavily influenced by python.
If you want to make you own game engine in java check out this: https://java-design-patterns.com/patterns/game-loop/#
Keep in mind that the while loop is calling the advance method. So every loop you are setting the view for button and then setting an OnClickListener for it. Not everything needs to be in the while loop.
You must implement (override) the render method (it is called in the game loop).
I suggest trying a complete example in the documentation.
``
#Override
public void render() {
ScreenUtils.clear(0, 0, 0.2f, 1);
advance();
...
``
Here,I have all the the id of record store in database in arraylist.My main point is How to Keep that Record For Some Seconds and then proceed further .
public class AuctionStart extends AppCompatActivity {
ArrayList<String> arr;
TextView tv;
int i;
DatabaseReference drf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auction_start);
tv = (TextView) findViewById(R.id.aucnm);
Bundle b = getIntent().getExtras();
if (null != b) {
arr = b.getStringArrayList("list");
}
else {
Toast.makeText(this, "Sorryy", Toast.LENGTH_SHORT).show();
}
}
}
after this suppose display arraylist first element in textview for 3 seconds then simultaneously all.
It's simple and straight forward. You can use postDelayed(). Here is the code snippet may help you, to achieve setTimeout() like thing,
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
// This will executed after 3 seconds
// Your Logic here
}
},
3000);
and here is the code snippet can help you to run on interval like setInterval
new Timer().scheduleAtFixedRate(new TimerTask(){
#Override
public void run(){
//This will execute after every 5 second untill timer cancel()
}
},0,5000);
For your case, you can do it as given,
if (null != b) {
arr = b.getStringArrayList("list");
int index = 0;
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask(){
#Override
public void run(){
tv.setText(arr.get(index));
if(index == (arr.size() - 1)){
t.cancel();
}else{
index++;
}
}
},0,3000);
}
else {
Toast.makeText(this, "Sorryy", Toast.LENGTH_SHORT).show();
}
Use rx java and rxfirebase and there is function in rx java will repeat the process again but I don’t recommend that you can eather use cloud function and add background service on firebase cloud to togle a key to update your data since it’s real time it will auto refresh and btw you need to make sure about both of the movements will cost you money 🤪
I trying to make my textView appear in different place of the screen every minute or two (delay is not important). I've seen people are suggesting I use runOnUiThread to make a timer repeat the random function and the update the UI.
I'm really struggling getting my head around these different threads, just wondering if anyone could give me an example? Or should I research using something different?
Public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.digitalClock1);
Random r = new Random();
int x = r.nextInt(350 - 100);
int y = r.nextInt(800 - 100);
textView.setX(x);
textView.setY(y);
}
Try this method
public void doInback()
{
handler.postDelayed(new Runnable() {
#Override
public void run()
{
// TODO Auto-generated method stub
// Try the code that you want to repeat
doInback();
}
}, 1000);
}
just call the method where you want to use.
Create the runnable and the handler below
private Runnable runnable = new Runnable(){
#Override
public void run() {
handler.sendEmptyMessage(0);
}
};
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
//change the text position here
this.postDelayed(runnable , TIME_OUT_MS);
}
};
The TIME_OUT_MS is the time out you want in milliseconds.
And put this on the OnCreate() method of the activity
Thread thread =new Thread(runnable );
thread.start();
For a side project of mine, I'm devoloping an android app with java. I don't know java a lot but i'm trying ^^.
The project is to have an Alarm at a random time in a certain range. The problem is that my chronometer and button freeze, but everything still works! Does anyone has maybe another solution for the thread.sleep ??
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void StartChrono(View view) {
final Chronometer chrono = (Chronometer)findViewById(R.id.chronometer1);
chrono.setBase(SystemClock.elapsedRealtime());
chrono.start();
//Tick();
}
public int RandomTime(int min, int max)
{
int random = max - min;
Random rand= new Random();
random = rand.nextInt(random)+min;
return random;
}
public boolean CheckUp(int randomtime,int chronotime)
{
boolean check = false;
if(randomtime== chronotime)
{
check = true;
}
return check;
}
public void Tick()
{
boolean check = false;
int randomtime = RandomTime(20,150);
int time=1;
do
{
check = CheckUp(randomtime,time);
time = time +1;
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Error - 000");
alertDialog.setMessage("Could not check!");
alertDialog.show();
}
}while(check == false);
if(check == true)
{
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Yuy");
alertDialog.setMessage("Switch!");
alertDialog.show();
}
}
}
I wouldn't use Thread.sleep(), I would use a Timer.
You can set a time and the Timer automatically calls the associated task.
In Android it would work something like this:
http://android.okhelp.cz/timer-simple-timertask-java-android-example/
I used it once myself, but that is some time ago.
Btw.:
You don't have to write a method to check for a boolean value.
This also works:
boolean check = 5>3;
System.out.println("check: " + check);//"check true"
I'd definately use a Handler for this task: http://developer.android.com/reference/android/os/Handler.html
A basic example would be this:
long timeDelay = 1000; // Set this to your random number.
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do whatever you need to do after a specified interval.
}
}, timeDelay);
Instantiate the Handler inside your onCreate and keep the reference around so you can call it inside your method.
Just to clarify, why you can't use Thread.sleep() for "sleeping" a specific amount of time, is this: when you call Thread.sleep() you call it on the UI thread, so every component running on the UI thread (buttons, textfields and so on) will "sleep" for the given amount of time and hence you basically halt the whole application.
Also see the documentation for Thread.sleep:
Causes the thread which sent this message to sleep for the given
interval of time (given in milliseconds).
someone can tell me how to update a control Textview Android from a function? I have searched deep into the internet and see many people who ask the same question, I tested threads but could not work, someone has a simple working example of doing this? for example to call a function (which runs several times in a loop) and the function writes in the TextView, but the problem is that until the function is not finished running, it shows me the text.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
while(condition) //here freezes the UI and the text in textview only shows when the loop ends
{
HardWork();
}
}
public void HardWork() {
txtProgreso.append("Test Line" + "\n\n");
};
Thanks in advance.
If i understood you correctly
Use AsyncTask here, So you can update textview in onProgressUpdate method
private class SomeTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
while(condition) {
//do more
publishProgress("Some text value to you textview");
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
txtProgreso.append(values[0]);
}
}
I think what you're trying to ask is "how do I force my TextView to show its updated contents without returning control to the runloop?" (ie, returning out of your function).
If so, I'm afraid you're out of luck, such a thing is impossible to do with Android's UI model. The nearest thing to this that is possible is to keep track of your loop state, and set a timer that will call a function for you to update the TextView.
Here's an example. Suppose you want to put the text "this is a test" into a TextView, one character at a time:
private Handler mHandler = new Handler();
private String desiredText = new String("This is a test");
private Runnable mUpdateTextView = new Runnable() {
public void run() {
TextView textView = (TextView)findViewById(R.id.myTextView);
int lengthSoFar = textView.getText().length();
if (lengthSoFar < desiredText.length()) {
mTextView.setText(desiredText.substring(0, lengthSoFar + 1));
mHandler.postDelayed(100, mUpdateTextView);
}
}
};
protected void onStart() {
mHandler.postDelayed(100, mUpdateTextView);
}
I think some of my object visibility is incorrect here, and I don't have an Android environment handy to test on, but you get the general idea. Rather than a Handler you could also use a Timer, but it's a bit more heavyweight so it depends how often you want to be updating the UI.
You get the textview by doing the following.
TextView myTextView = (TextView)findViewById(R.id.textViewsId);
Then afterwards, you can change the TextView using the functions. For example, you can set the text using the following code.
myTextView.setText("New text example");
Are there any other updates to the control you are trying to do?