Can't find getDateTimeInstance method in android ADT - android

I am a newer to Android development. now I want to show current system time in a thread via textview control. I get some example and can start the thread to draw text in textview control.
but when I trid to get system current time via below link:Display the current time and date in an Android application, I got errors,The error saying:getDateTimeInstance() is undefined for the type DateFormat.
Why this answer didn't work for me ? thx.
below is the code for your reference:
public class MainActivity extends Activity {
private TextView timeView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(){
public void run(){
System.out.println("Thread is running!!");
timeView = (TextView)findViewById(R.id.textView1);
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
timeView.setText("I am Fired via Non-UI thread:"+s);
}
}.start();
}

Updatin ui in a thread not possible
timeView.setText("I am Fired via Non-UI thread:"+s);
Use runOnUiThread. Inside thread's run method
runOnUiThread(new Runnable() {
#Override
public void run() {
timeView.setText("I am Fired via Non-UI thread:"+s);
}
});
Also initialize textview in outside the thread
timeView = (TextView)findViewById(R.id.textView1)
Also check this
http://developer.android.com/reference/java/text/DateFormat.html
Check your import statement.
import java.text.DateFormat // import this
instead of
import android.text.format.DateFormat;

Related

update textview from inside of thread?

There is an int value that continuously get updated inside a thread and I want to show the value in a textview but i m unable to use findviewbyid inside of thread ?
How to refer to that textview from inside that thread and update it accordingly?
Here is my code:
package com.example.raj.testview;
import android.widget.TextView;
public class TextChange implements Runnable
{
public void run()
{
TextView tv=(TextView)findViewById(R.id.tv);
for(int i=0;i<10000;i++)
{
tv.setText(String.valueOf(i));
}
}
}
You cannot change UI elements from a non-UI thread. Try using runOnUiThread.
runOnUiThread(new Runnable(){
#Override
public void run(){
// change UI elements here
}
});

Clearing TextView in Android

I'm facing this problem with TextView. It is not erasing the previous instances of data.
When I'm running my application in emulator it displays output data in TextView. That's fine. But when I'm clicking back button in my emulator and re opening the application it does not clear the previous data. Instead it appends the data to already existing data.
Any help is appreciated.
My code is as below:
public class MainActivity extends ActionBarActivity
{
private TextView mTextView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.text_test);
new Thread(new TestLocalHost()).start();
}
private class TestLocalHost implements Runnable
{
#Override
public void run()
{
final String s = JSONParser.doGet("http://192.168.0.107:15071/GetResult.ashx?op=getInfo",null);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
mTextView.setText(s);
}
});
}
}
}
It's happening because your app still lives in the emulator memory, you need to force kill it if you want your app to run again from scratch.
You should click on the "running processes" button and swipe left/right the app process.
In the scenario that you described the activity wasn't destroyed yet, and when you reopen it only its onResume() method is being called.

Android handler and runnable nullpointer

I have a problem
I am using handler and runnable to update timer inside my app, inside my Runnable I am updating textview, after 1minut I want to show some content, everything works fine until I rotate the screen, every textview is now null, and I couldnt figure out why.
My code:
Runnable mTimer = new Runnable() {
#Override
public void run() {
textView.setText(DateFormat.format("mm:ss", timers - System.currentTimeMillis()));
test();
mHandler.postDelayed(this, TIME);
}
};
Any ideas why this might happen?
Handler probably delivers a Runnable to an Activity that was recycled. Proper use of Handler is like
private Handler mHandler;
private TextView mTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler();
setContentView(R.layout.yourView);
mTextView = findViewById(R.id.text);
}
#Override
protected void onStart() {
super.onStart();
//start updating every time Activity is started
handler.postDelayed(mTimer, oneMinuteDelay);
}
#Override
protected void onStop() {
super.onStop();
//make sure to remove all messages
handler.removeCallbacksAndMessages(null);
}
In theory, this (null views) should not happen.
When you change the screen orientation, the activity leaves the screen and becomes useless, but it still exists and references the views. Your runnable references the instance of activity that has created it, so the activity cannot die while the runnable is still there. At least, so it was. Which Android version do you use?
It seems I understand what you mean. You mean null contents in the views. You have to create a static variable, say, lastInstance:
class MyActivity extends Activity {
static MyActivity lastInstance;
void onCreate(...) {
...
lastInstance = this;
}
// no need to reference an instance of any Activity, so static
static class MyRunnable implements Runnable {
#Override
public void run() {
lastInstance.textView.setText(DateFormat.format("mm:ss", timers - System.currentTimeMillis()));
lastInstance.test();
mHandler.postDelayed(this, TIME);
}
}
static Runnable mTimer = new MyRunnable();
}
I do not recommend android:configChanges="screenSize|keyboardHidden|orientation" because this is not the only case when Android recreates an Activity, so this way you will not fix any bugs, you will just make them more difficult to reproduce.
For this thing you have to specify in your manifest with the specified line in your activity tag then your issue will be fixed.
i.e,
<activity android:name="your activity"
android:configChanges="screenSize|keyboardHidden|orientation">
</activity>
Then it will work for you on rotating the screen also.
Edited Answer
Better check that textview If it is null create a reference and then add the data it may fix your issue. or meanwhile you can pass your old data from onSavedInstance();
and you can get the data from onCreate(SavedInstance savedinstance)
here it will returns that prevoius data what you are setted in onsavedInstance Method.
try this for data exchange it will work
After rotate your activity recreates, so textView is null.
Please remove the handler code from the runnable. Also first create object of handler then write the handlers post delayed method where you want. Main use of handler is to update UI from thread.
If the Activity doesn't crash when you turn round the device, it means that the textView is there. If you see nulls on the screen it is the content of the textView that is being set as null.
In the text, the only variable I see is timers.
Where is this variable defined and where is it being set?
First check that you properly initialize the handler as below :
handler = new Handler();
The null pointer error may come if you not initialize the handler.

AsyncTask behavior confusion

I have this project:
Im trying to undestand where is the problem and how can be solved, but a this simply point I really dont know where is the problem.
I have a button and a TextView.
When the button is clicked this procedure is called:
android:onClick="pulsaboton"
And the TextView show me the output.
This is Main_Activity.java
package com.example.pruebasonidos;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
public String cadena1="", cadena2="";
public TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textview01);
}
public class generamusica extends AsyncTask<String, Integer, Integer>
{
#Override
protected void onPreExecute(){
tv.setText(tv.getText().toString()+"Pre Execute");
}
#Override
protected Integer doInBackground(String...strings) {
String cadena=strings[0];
tv.setText(tv.getText().toString()+cadena);
return null;
}
#Override
protected void onPostExecute(Integer bytes){
tv.setText(tv.getText().toString()+"Post Execute");
}
}
public void pulsaboton(View v) {
cadena1="123"; cadena2="111";
tv.setText("");
new generamusica().execute(cadena1);
new generamusica().execute(cadena2);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
When pulsaboton is clicked, textview1 display this:
PreExecutePreExecute123111PostExecutePostExecute
I want this output:
PreExecute123PostExecutePreExecute111PostExecute
What is the error????
WARNING: INTERFACE MODIFICATION EXECUTED OUTSIDE OF UI THREAD!
protected Integer doInBackground(String...strings) {
...
tv.setText(tv.getText().toString()+cadena);
...
}
Why do you think AsyncTask exposes onPreExecute and onPostExecute? Couldn't you just do all of your interface work in doInBackground, before and after your async code?
In Android, the UI needs to be accessed from the main thread, the foreground thread; which doInBackground is not run in.
If you need to post updates to your UI during the execution of an AsyncTask, use the publishProgress mechanism.
Edit: "properly" accesing the interface is a lot more complex that just using onPreExecute and onPostExecute. See this blog post. Maybe you should try the Loader API, it's less troublesome.
When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution..
http://developer.android.com/reference/android/os/AsyncTask.html
You are updating ui on the background thread which is not possible. You need to update ui on the ui thread
In doInBackground()
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
String cadena=strings[0];
tv.setText(tv.getText().toString()+cadena); ;
}
});
For your required output Call these two lines in onPostExecute,
cadena2="111";
new generamusica().execute(cadena2);
And dont try to update the UI in background thread.
See This for more info

Whats wrong with my Thread()-code?

I have a question regarding an Android application. I want to, later on, create a game and i am currently trying out classes and functions that I need to understand.
At the moment im trying to get a grip of how to use threads in a good way, but my application is "force closing" when i touch the button.
For this test application, all have on the screen is one TextView and one button.
The button is calling threadStart() when pressed. (onClick in xml)
And what i want it to do is to create a thread which increases the variable value by 1 and then report to the UI thread which then update the textview with the new value.
Can someone see what i am doing wrong with this small pice of code?
package com.weldeborn.tc;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
public class ThreadCounter extends Activity {
TextView txtCounter1;
int value=0;
final Handler mHandler = new Handler();
final Runnable mUpdateResults = new Runnable() {
public void run() {
updateResult();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtCounter1 = (TextView) findViewById(R.id.counter1);
}
protected void threadStart() {
Thread t = new Thread() {
public void run() {
doSomething();
mHandler.post(mUpdateResults);
}
};
t.start();
}
private void doSomething() {
value = value+1;
}
private void updateResult() {
txtCounter1.setText(value);
}
}
My code is based on an example from Android Developer: The Common Tasks and how to do them section under the "Handling Expensive Operations in the UI Thread" heading.
I am thankful for any help.
setText doesn't work correctly when you pass an integer, directly. Try converting it to String before:
txtCounter1.setText(String.valueOf(value));
Also, check this answer about the usage of threads that need to update the UI.
if threadStart is your onClick the signature needs to be
public void threadStart(View v)

Categories

Resources