Wrong Time Unit - java

I need may load at first bacground (setContentView(R.layout.activity_logo); ) after (6 second) Text in TextView4. but program make wrong. After start application, app wait 6 second and next build setContentView(R.layout.activity_logo); and write to TextView4
Why?
Thanks
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logo);
try {
TimeUnit.SECONDS.sleep(6);
TextView textview4 = (TextView) findViewById(R.id.textView4);
textview4.setText("alalaalalalalalal");
} catch (InterruptedException e) {
e.printStackTrace();
}
}

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logo);
Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
TextView textview4 = (TextView) findViewById(R.id.textView4);
textview4.setText("alalaalalalalalal");
}
}, 6000);
}

sleep() blocks the UI thread and your UI cannot draw itself.
Use e.g. a Handler and postDelayed() to post a Runnable to run at a later time without blocking the UI thread.

Related

Can the text of an Android TextView be set outside of the onCreate() method?

I'm trying to set the text of a TextView in my Android app using the following function:
#Override
public void onOSSubscriptionChanged(OSSubscriptionStateChanges stateChanges) {
if (!stateChanges.getFrom().getSubscribed() && stateChanges.getTo().getSubscribed()) {
new AlertDialog.Builder(this)
.setMessage("You have successfully subscribed to push notifications!")
.show();
// Get player ID and output to Main Activity
TextView playerIdView = findViewById(R.id.playerIdView);
playerIdView.setText(stateChanges.getTo().getUserId());
}
Log.i("Debug", "onOSPermissionsChanged: " + stateChanges);
}
This uses the OneSignal API to get the user's unique ID, which is returned as a string. After some debugging I realised the contents of a TextView can't be changed outside of the onCreate() method. However, the stateChanges parameter is required, which only exists within onOSSubscriptionChanged. Is there any way of getting around this?
EDIT: the error was elsewhere. stateChanges.getTo().getUserId() was returning null.
You need to set it on UI thread
playerIdView.post(new Runnable() {
public void run() {
playerIdView.setText(stateChanges.getTo().getUserId());
}
});
or
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = new Runnable() {
#Override
public void run() {
playerIdView.setText(stateChanges.getTo().getUserId());}
};
mainHandler.post(myRunnable);
you need to initialize you textview in your onCreateView() method and after that you can use that textView pretty much anywhere as long as you are in UI thread. So change your code to below:
Declare your textview globally so that you can use it anywhere in your activity instance.
TextView playerIdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
playerIdView = findViewById(R.id.playerIdView);
}
and then in your onSSubscription method just do the following:
#Override
public void onOSSubscriptionChanged(OSSubscriptionStateChanges stateChanges) {
if (!stateChanges.getFrom().getSubscribed() && stateChanges.getTo().getSubscribed()) {
new AlertDialog.Builder(this)
.setMessage("You have successfully subscribed to push notifications!")
.show();
// Get player ID and output to Main Activity
playerIdView.setText(stateChanges.getTo().getUserId());
}
Log.i("Debug", "onOSPermissionsChanged: " + stateChanges);
}
Try This
runOnUiThread(new Runnable(){
#override
public void run() {
playerIdView.setText(stateChanges.getTo().getUserId());
}
})

Android blank background asynctask

I'm doing an Android project with Asynctask, and I can't set TextView text to be "Loading", it is just blank until the AsyncTask loads. How could I overcome this problem?
Code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("Loading today's fixtures & results");
HTMLParser parser = null;
try {
parser = new HTMLoadTask().execute("http://www.skysports.com/football/fixtures-results").get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
You should remove the get() call in the end, as this waits for the task to finish and then it retrieves the result. This will lock-up the UI-thread.
get()
Waits if necessary for the computation to complete, and then retrieves its result.
I donĀ“t know what you are doing in the AsyncTask, but in onPostExecute() you should handle the result and set the text of the textview.

Errors in fragment class

So I am converting my application, after loads of research I decided to convert my Activities into Fragments. That was a success, but now the slightly harder part comes in, to implement the code from my Activity to the fragments. So I used getView(). and getActivity(). to fix the issues, and all was fine. As you can see below...
public class HomeFragment extends Fragment {
public static HomeFragment newInstance(String title) {
HomeFragment homeFragment = new HomeFragment();
Bundle bundle = new Bundle();
bundle.putString("title", title);
homeFragment.setArguments(bundle);
return homeFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_activity_home, container, false);
// Time function - Displays timeview on Card
final boolean keepRunning = true;
Thread thread = new Thread(){
#Override
public void run(){
while(keepRunning){
// Make the thread wait half a second (if you're only showing time up to seconds, it doesn't need to be updating constantly)
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Toast.makeText(getActivity().getApplicationContext(), "Default Signature Fail", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
getActivity().runOnUiThread(new Runnable(){
#Override
public void run(){
TextView time = (TextView) getView().findViewById(R.id.time);
time.setText(DateUtils.formatDateTime(getActivity().getBaseContext(), System.currentTimeMillis(),DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_12HOUR));
}
});
}
}
};
thread.start();
// Date function - Displays dateview on Card
final boolean keepRunning1 = true;
Thread thread_two = new Thread(){
#Override
public void run(){
while(keepRunning1){
// Make the thread wait half a second. If you want...
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Toast.makeText(getActivity().getApplicationContext(), "Default Signature Fail", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
getActivity().runOnUiThread(new Runnable(){
#Override
public void run(){
TextView date = (TextView) getView().findViewById(R.id.date);
date.setText(DateUtils.formatDateTime(getActivity().getBaseContext(), System.currentTimeMillis(),DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR));
}
});
}
}
};
thread_two.start();
return view;
}
}
When running the application, it displays the app for approx 2 secs and then force closes, so I checked the logs for any errors. And this came up --
05-20 16:54:17.213: E/AndroidRuntime(26473): java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
05-20 16:54:17.213: E/AndroidRuntime(26473): at com.activelauncher.fragments.HomeFragment$1$1.run(HomeFragment.java:54)
I'm fairly new to Fragments I have had more experience working with Activities so I don't know what the issue is here. So I check line 54 and it was this line --
time.setText(DateUtils.formatDateTime(getActivity().getBaseContext(), System.currentTimeMillis(),DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_12HOUR));
However I don't see any issues or errors there? Is there something I am missing?
Thanks for reading this.
Change this
TextView time = (TextView) getView().findViewById(R.id.time);
to
TextView time = (TextView) view.findViewById(R.id.time);
And make this final
final View view;
Simailarly
TextView date = (TextView) view.findViewById(R.id.date);
Try this..
Change this..
TextView time = (TextView) getView().findViewById(R.id.time);
time.setText(DateUtils.formatDateTime(getActivity().getBaseContext(), System.currentTimeMillis(),DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_12HOUR));
to
TextView time = (TextView) view.findViewById(R.id.time);
time.setText(""+DateUtils.formatDateTime(getActivity().getBaseContext(), System.currentTimeMillis(),DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_12HOUR));
and also
TextView date = (TextView) view.findViewById(R.id.date);
date.setText(""+DateUtils.formatDateTime(getActivity().getBaseContext(), System.currentTimeMillis(),DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR));

How to make app wait and then start activity or go back?

I want my activity to show a screen for 3 seconds, then go back to previous screen. But when i use
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome_layout);
TextView tvResult = (TextView)findViewById(R.id.textView1)
Thread.sleep(3000);
Intent i = new Intent(this,myActivity.class);
startActivity(i);
But unfortunately, this does not work. This doesent show the activity waits 3 seconds and goes back. However, i want it to show its contents before going back. How can i do it ?
You should remove this Thread.sleep(3000); which block the ui thread. You should never block the ui thred. You can use a Handler postDelayed with a delay and then startActivtiy.
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
#Override
public void run(){
// do something
}
}, 3000);
To go back to previous Activity you can call finish().
Also if you need to go back to the previous activity for 3 seconds why do you need
Intent i = new Intent(this,myActivity.class);
startActivity(i);
Calling finish() will do the job
This is not the recommended way to do this.
Using Thread.sleep you're blocking the main UI thread for 3000 milliseconds. This means that nothing in the activity will work until 3 seconds are passed.
Instead, you could do this:
edited: now it works well.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome_layout);
TextView tvResult = (TextView)findViewById(R.id.textView1)
new Thread(new Runnable()
{
#Override
public void run()
{
try
{
Thread.sleep(3000);
Intent i = new Intent(getApplicationContext(), myActivity.class);
startActivity(i);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}

Make this function repeat using runOnUiThread to update textview location

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();

Categories

Resources