How to enable a button after 5 seconds - android-layout

everyone! I need to make a Button disabled for 5 seconds, and the caption of the button must be "Skip" plus the time the button will stay disabled.
I have made a class CTimer that extends Thread, and defined the run method with run(Button). The run method receives the Button which Caption will be modified and is as follows:
public void run(Button skip){
for ( int i=5; i<0; i--)
{
skip.setText("Skip (" + i + ")");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
skip.setEnabled(true);
}
The problem is that the code does not work, any thouhts, anyone?

I have tried the following code & it works fine for me:
public class Main_TestProject extends Activity
{
private Button b;
private int index = 5;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b = (Button) findViewById(R.id.my_button);
b.setEnabled(false);
hHandler.sendEmptyMessage(0);
}
private Handler hHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
if(index > 0)
{
try
{
b.setText("Skip (" + String.valueOf(index) + ")");
index--;
Thread.sleep(1000);
hHandler.sendEmptyMessage(0);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
b.setEnabled(true);
}
}
};
}

Related

Go to another activity not main activity after splash screen

I have a splash screen in which i am checking user is logged in or not if logged in go to dashboard otherwise go to login activity. I am using sharedpref. Issue is (which I am unable to resolve) after splash screen login screen appears for a brief moment than dashboard. Splash > Login > Dash what i Want is Splash > Dash (if user logged in). Login is the main activity of my project. Here is the code:
public class SplashScreen extends AppCompatActivity {
private SessionManager sessionManager;
private BroadcastReceiver broadcastReceiver;
private SharedPreferences prefs;
private boolean isLogin;
private int accessID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sessionManager = new SessionManager(this);
broadcastReceiver = new CheckNetStatus();
broadcastIntent();
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onResume(){
super.onResume();
new CheckNetStatus().onReceive(SplashScreen.this,new
Intent(ConnectivityManager.CONNECTIVITY_ACTION));
try {
prefs = getSharedPreferences(SessionManager.PREF_NAME, 0); // Declare
SharedPreferences
accessID = prefs.getInt(SessionManager.KEY_ACCESSID, 0); // get Access Id from
SharedPreferences
isLogin = Utils.getLoginStatus(SplashScreen.this); // Check Login is true or false
} catch (Exception e) {
e.printStackTrace();
}
Thread splashTread = new Thread() {
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void run() { // run thread
try {
synchronized (this) {
Thread.sleep(3000); // Screen stay for 3 sec.
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (isLogin)
{
// if (accessID == 0) { // access Id is ZERO open AddMoneyActivity.class
// try {
// } catch (Exception e) {
// e.printStackTrace();
// }
// } else if (accessID == 1) {// access Id is ONE open
ProfileStepOneActivity.class
try {
Intent intent = new Intent(SplashScreen.this, Dashboard.class);
startActivity(intent);
finishAffinity(); // Finish stack
} catch (Exception e) {
e.printStackTrace();
}
} else {// Login is False goto Login Activity
try {
Intent intent = new Intent(SplashScreen.this, MainActivity.class);
startActivity(intent);
finish();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
};
splashTread.start();
}
public void broadcastIntent() {
registerReceiver(broadcastReceiver, new
IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
#Override
protected void onPause() {
super.onPause();
try {
LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);
//unregisterReceiver(broadcastReceiver);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onStop(){
super.onStop();
try {
LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);
// unregisterReceiver(broadcastReceiver);
} catch (Exception e) {
e.printStackTrace();
}
}
}
My mistake....i was redirecting to main activity ie login activity in netstats class(where i was checking the net connection) ie why it was showing login screen for a moment issue resolved now

the changes are not visible in window for vaadin 7

I have a window in vaadin 7, and I would like to show changes as there are made, because I have longer task working its think. I stumble upon this site but I have to move the window to see the changes. In the window that I have, I call next class with :
new PushyUI();
the class called:
public class PushyUI extends UI {
Chart chart = new Chart(ChartType.AREASPLINE);
DataSeries series = new DataSeries();
PushyUI() {
chart.setSizeFull();
setContent(chart);
// Prepare the data display
Configuration conf = chart.getConfiguration();
conf.setTitle("Hot New Data");
conf.setSeries(series);
// Start the data feed thread
new FeederThread().start();
}
class FeederThread extends Thread {
int count = 0;
#Override
public void run() {
try {
// Update the data for a while
while (count < 6) {
Thread.sleep(1000);
getUI().access(new Runnable() {
#Override
public void run() {
double y = Math.random();
series.add(new DataSeriesItem(count++, y),
true, count > 10);
}
});
}
// Inform that we have stopped running
getUI().access(new Runnable() {
#Override
public void run() {
setContent(new Label("Done!"));
}
});
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
How could I see the changes without have to moving the window around ? Thanks
I found the solution here . I manage to modified so it works for me.
layout = new HorizontalLayout();
layout.setSpacing(true);
layout.setSizeFull();
// Add a normal progress bar
sample = new ProgressBar();
layout.addComponent(sample);
layout.setComponentAlignment(sample, Alignment.MIDDLE_CENTER);
startButton = new Button("Start", new Button.ClickListener() {
#Override
public void buttonClick(final ClickEvent event) {
sample.setValue(0f);
sample.setVisible(true);
startButton.setEnabled(false);
UI.getCurrent().setPollInterval(500);
launchProgressUpdater(UI.getCurrent(), 10);
}
});
startButton.setStyleName(ValoTheme.BUTTON_SMALL);
layout.addComponent(startButton);
layout.setComponentAlignment(startButton, Alignment.MIDDLE_CENTER);
...
private void launchProgressUpdater(UI ui, int maxProgress) {
new Thread(() -> {
for (int progress = 1; progress <= maxProgress; progress++) {
try {
Thread.sleep(1000);
} catch (final InterruptedException e) {
throw new RuntimeException("Unexpected interruption", e);
}
updateProgressBar(ui, progress, maxProgress);
}
}).start();
}
private void updateProgressBar(UI ui, int progress, int maxProgress) {
ui.access(() -> {
final float newValue;
if (progress == maxProgress) {
ui.setPollInterval(-1);
startButton.setEnabled(true);
newValue = 0f;
sample.setVisible(!sample.isIndeterminate());
} else {
newValue = (float) progress / maxProgress;
}
sample.setValue(newValue);
Notification.show("Value changed:", Float.toString(newValue), Notification.Type.TRAY_NOTIFICATION);
});
}

Unable to hide Action Bar before starting another activity

I'm trying to first create an activity, then after 2 seconds, I want to hide the action bar and then after another 2 secs, I want to start another activity but this code - getActionBar().hide() isn't working. Here is my code -
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
//final ActionBar actionbar = getActionBar();
Thread timer1 = new Thread() {
public void run(){
try{
sleep(2000);
} catch(InterruptedException e){
e.printStackTrace();
} finally{
getActionBar().hide();
}
}
};
timer1.start();
Thread timer2 = new Thread() {
public void run(){
try{
sleep(2000);
} catch(InterruptedException e){
e.printStackTrace();
} finally{
Intent intent = new Intent("app.lost_and_found_0.STARTINGPOINT");
startActivity(intent);
}
}
};
timer2.start();
}
Is there something wrong I'm doing wrong?
My application theme is set to Theme.Holo.Light in manifest file.
Use getSupportActionBar() instead of getActionBar(). As on the class, you need to extend ActionBarActivity.

Yet another "Can't create handler inside thread that has not called Looper.prepare()" topic

I have this code which is an Activity that when started will check for internet connection, if there is a connection, then life goes on. Else a dialog appears to turn on the connection. However I made a thread that each 10 seconds will check for connection and in case the connection was lost it will display the dialog again.
package greensmartcampus.eu.smartcampususerfeedbackapp;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.net.InetAddress;
public class HomeScreen extends AbstractPortraitActivity {
private static final int WIFI_REQUEST_CODE = 1;
private boolean networkSettingsDialogOpened = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
this.runOnUiThread(new Runnable() {
#Override
public void run() {
while (!HomeScreen.this.isInternetAvailable()) {
if (!networkSettingsDialogOpened)
HomeScreen.this.createNetErrorDialog();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
(...)
private boolean isInternetAvailable() {
try {
final InetAddress ipAddr = InetAddress.getByName("google.com");
if (ipAddr.equals("")) {
return false;
} else {
return true;
}
} catch (Exception e) {
return false;
}
}
private void createNetErrorDialog() {
networkSettingsDialogOpened = true;
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("You need a network connection to use this application. Please turn on mobile network or Wi-Fi in Settings.")
.setTitle("Unable to connect")
.setCancelable(false)
.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivityForResult(i, WIFI_REQUEST_CODE);
}
}
)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
HomeScreen.this.finish();
}
}
);
final AlertDialog alert = builder.create();
alert.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == WIFI_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
networkSettingsDialogOpened = false;
Toast.makeText(HomeScreen.this, "Returned Ok",
Toast.LENGTH_LONG).show();
}
if (resultCode == RESULT_CANCELED) {
networkSettingsDialogOpened = false;
Toast.makeText(HomeScreen.this, "Returned Canceled",
Toast.LENGTH_LONG).show();
}
}
}
}
However I am getting the following error:
02-03 18:13:14.525 2683-2699/greensmartcampus.eu.smartcampususerfeedbackapp E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-193
Process: greensmartcampus.eu.smartcampususerfeedbackapp, PID: 2683
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.app.Dialog.<init>(Dialog.java:108)
at android.app.AlertDialog.<init>(AlertDialog.java:125)
at android.app.AlertDialog$Builder.create(AlertDialog.java:967)
at greensmartcampus.eu.smartcampususerfeedbackapp.HomeScreen.createNetErrorDialog(HomeScreen.java:97)
at greensmartcampus.eu.smartcampususerfeedbackapp.HomeScreen.access$200(HomeScreen.java:15)
at greensmartcampus.eu.smartcampususerfeedbackapp.HomeScreen$1.run(HomeScreen.java:29)
Note: Line 97 is the one containing:
final AlertDialog alert = builder.create();
I googled alot, I am already using the cliche answer of runOnUiThread, but it doesn't fix it.
What am I missing?
The way you are checking the internet I guess you are causing your UI thread to sleep. You should do it like this.
Create one Handler and Thread running flag:
Handler mHandler = new Handler();
boolean isRunning = true;
Then, use this thread from your onCreate() method :
new Thread(new Runnable() {
#Override
public void run() {
while (isRunning) {
try {
Thread.sleep(10000);
mHandler.post(new Runnable() {
#Override
public void run() {
if(!HomeScreen.this.isInternetAvailable()){
if (!networkSettingsDialogOpened)
HomeScreen.this.createNetErrorDialog();
}
}
});
} catch (Exception e) {
}
}
}
}).start();
Change this method slightly
private boolean isInternetAvailable() {
try {
final InetAddress ipAddr = InetAddress.getByName("google.com");
if (ipAddr.equals("")) {
return false;
} else {
isRunning = true;
return true;
}
} catch (Exception e) {
return false;
}
}
You can't call Thread.sleep() from code that is running on the UI thread. This is your code:
this.runOnUiThread(new Runnable() {
#Override
public void run() {
while (!HomeScreen.this.isInternetAvailable()) {
if (!networkSettingsDialogOpened)
HomeScreen.this.createNetErrorDialog();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
You jest need to run the bit of code that shows the Dialog on the UI thread. Try this instead:
new Thread(new Runnable() {
#Override
public void run() {
while (!HomeScreen.this.isInternetAvailable()) {
if (!networkSettingsDialogOpened)
// Show the Dialog on the UI thread
HomeScreen.this.runOnUiThread(new Runnable() {
#Override
public void run() {
HomeScreen.this.createNetErrorDialog();
}
});
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();

InstantiationException while getLocation on Nokia device

New to Nokia development. I am trying to write a hello world for get GPS coordinates of my current location. What am I doing wrong here ?
public class HomeScreen extends MIDlet {
public HomeScreen() {
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
}
protected void pauseApp() {
}
protected void startApp() throws MIDletStateChangeException {
Displayable current = Display.getDisplay(this).getCurrent() ;
if (current == null) {
UpdateJourney updateJourney = new UpdateJourney(this) ;
Display.getDisplay(this).setCurrent(updateJourney) ;
}
}
}
public class UpdateJourney extends Form implements CommandListener, Runnable {
private LocationProvider myLocation;
private Criteria myCriteria;
private Location myCurrentLocation;
private HomeScreen helloScreen;
private Command exitCommand;
private Thread getLocationThread = new Thread(this);;
public UpdateJourney(HomeScreen helloScreen) {
super("Taxeeta");
StringItem helloText = new StringItem("", "Taxeeta");
super.append(helloText);
this.helloScreen = helloScreen;
getLocationThread.start();
}
public double getMyLatitude() {
return myCurrentLocation.getQualifiedCoordinates().getLatitude();
}
public double getMyLongitude() {
return myCurrentLocation.getQualifiedCoordinates().getLongitude();
}
public void commandAction(Command command, Displayable arg1) {
if (command == exitCommand) {
helloScreen.notifyDestroyed();
}
}
public void run() {
myCriteria = new Criteria();
myCriteria.setHorizontalAccuracy(500);
try {
myLocation = LocationProvider.getInstance(myCriteria);
myCurrentLocation = myLocation.getLocation(60);
} catch (LocationException e) {
e.printStackTrace();
System.out
.println("Error : Unable to initialize location provider");
return;
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Error: Waited enough for location to return");
return;
}
System.out.println("Location returned Lat:"
+ myCurrentLocation.getQualifiedCoordinates().getLatitude()
+ " Lng:"
+ myCurrentLocation.getQualifiedCoordinates().getLongitude());
exitCommand = new Command("Location returned Lat:"
+ myCurrentLocation.getQualifiedCoordinates().getLatitude()
+ " Lng:"
+ myCurrentLocation.getQualifiedCoordinates().getLongitude(),
Command.EXIT, 1);
addCommand(exitCommand);
setCommandListener(this);
}
}
In the application descriptor I had UpdateJourney as the MIDlet, I changed it to HomeScreen and it worked.

Resources