Changing TextView dynamically with time in Android - android-activity

I am a beginner in android. I want to change my text view with time.
My activity lasts for 5 seconds and i want to display the count down time.
I tried using Thread timer,but it doesnt work.
Simply i want to show the numbers like
In the Beginning: 5,
After a second: 4,
After 2 seconds: 3,
,, : 2,
,, : 1,
Please suggest me how to code this.

Use a CountDownTimer:
#Override
protected void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView txtCount = (TextView) findViewById(R.id.txtCount);
final int secs = 5;
new CountDownTimer((secs +1) * 1000, 1000) // Wait 5 secs, tick every 1 sec
{
#Override
public final void onTick(final long millisUntilFinished)
{
txtCount.setText("" + (int) (millisUntilFinished * .001f));
}
#Override
public final void onFinish()
{
txtCount.setText("GO!");
}
}.start();
}

Related

how to set a limited time to my console application

I was thinking how to set a limited period on my console application.
For instance, I want to give just 10 seconds to users to choose or do something when they just come in.
If time exceeds 10 seconds, then the user should get a warning.
Here is my code. I tried to first convert it to string and then to int, but something is wrong...
using System;
using System.Threading;
namespace exercise
{
class Program
static void Main(string[] args)
{
Timer t = new Timer(TimerCallback, null, 0, 2000);
// Wait for the user to hit <Enter>
Console.ReadLine();
}
private static void TimerCallback(Object o)
{
bool loop = true; // Console.WriteLine("{0:h:mm:ss.fff}.\n", DateTime.Now); ----> Creating timer
string b = DateTime.Now.ToString();
// Display the date/time when this method got called.
Console.WriteLine("In TimerCallback: " + b);
int c = Convert.ToInt32(b);
// Force a garbage collection to occur for this demo.
if (c == 10000)
{
Console.WriteLine(" your time is runnig out , hurry up brow");
}
GC.Collect();
}
}
You can use DateTime.ParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff"
to pass a string to datetime, but you will parse the datetime, not the amounts of time passed.
You can store the number of calls in a static field and check the 10 seconds that way.
class Program
{
private static int timerCounter = 1;
static void Main(string[] args)
{
Timer t = new Timer(TimerCallback, null, 0, 2000);
// Wait for the user to hit <Enter>
Console.ReadLine();
}
private static void TimerCallback(Object o)
{
bool loop = true; // Console.WriteLine("{0:h:mm:ss.fff}.\n", DateTime.Now); ----> Creating timer
string b = DateTime.Now.ToString();
// Display the date/time when this method got called.
Console.WriteLine("In TimerCallback: " + b);
// timer callback is every 2 seconds, so every 5th call is 10 sec
if (timerCounter % 5 == 0)
{
timerCounter = 1;
Console.WriteLine(" your time is runnig out , hurry up brow");
}
timerCounter++;
GC.Collect();
}
}

How can I save each spinner value in sqlite database?

This is my save button button code of my database.
btnsave.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
pd.setFname(et1.getText().toString());
pd.setLname(et2.getText().toString());
pd.setPhone(et3.getText().toString());
pd.setRelation(spinner1.getSelectedItem().toString());
int spinner_pos=spinner1.getSelectedItemPosition();
String[]relation=getResources().getStringArray(R.array.addrelation);
String mg = he.save(pd);
m.setText(mg);
}
});
It is only saving the first spinner value in every record.
the fast way is to use a loop inside setOnclickListner (there can be some better to do this):
btnsave.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
int nSpinnerItemsCount = spinner1.getCount();
for(int nCounter = 0; nCounter < nSpinnerItemsCount; nCounter ++)
{
pd.setFname(et1.getText().toString());
pd.setLname(et2.getText().toString());
pd.setPhone(et3.getText().toString());
pd.setRelation(spinner1.getItemAtPosition(nCounter).toString());
String mg = he.save(pd);
m.setText(mg);
}
});
spinner1.getItemAtPosition(nCounter).toString() is the key. on your code your use
int spinner_pos=spinner1.getSelectedItemPosition();
By default it always return the index of the first element inside the spinner (if other element is selected).
So by using spinner1.getCount, a loop and getItemAtPosition you have all elements in the spinner and do what you want to do.
Hope that helps.

Android Date Picker will not send data to a new Activity

I am using Androids Date Picker to select a date. Once the user presses the button, the data should send to the next activity. I verified that when the button is pressed, the correct date shows in the Date Picker file but the data that I want to go to the next Activity is showing null.
public class MainActivity extends ActionBarActivity {
int day;
int month;
int year;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnNextScreen = (Button) findViewById(R.id.dateAccept);
final DatePicker date = (DatePicker) findViewById(R.id.datePicker);
//Listening to button event
btnNextScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Starting a new Intent
Intent nextScreen = new Intent(getApplicationContext(), secondscreen.class);
Intent process = new Intent(getApplicationContext(),processing.class);
day =date.getDayOfMonth();
month =date.getMonth()+1;
year=date.getYear();
process.putExtra("Day", day);
process.putExtra("Month", month);
process.putExtra("Year", year);
//Sending data to another Activity
startActivity(process);
startActivity(nextScreen);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The Processing class I have is
public class processing extends MainActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.third_screen);
//TextView txthour = (TextView) findViewById(R.id.hours);
// TextView txtmin = (TextView) findViewById(R.id.min);
TimePicker workStart= (TimePicker) findViewById(R.id.timetobeatwork);
int workhour= workStart.getCurrentHour();
int workmin= workStart.getCurrentMinute();
System.out.println(workhour);
System.out.println(workmin);
Intent i = getIntent();
// Receiving the Data
final String hour = i.getStringExtra("Hour");
final String minute = i.getStringExtra("Min");
final String day = i.getStringExtra("Day");
final String month = i.getStringExtra("Month");
final String year = i.getStringExtra("Year");
// Displaying Received data
System.out.println("hour "+hour);
System.out.println("min "+minute);
System.out.println("day "+day);
System.out.println("month "+month);
System.out.println("year "+year);
}
The output I get is
07-16 08:22:41.486 2664-2664/com.erikkniaz.myapp.myapplication I/System.out﹕ min 8
07-16 08:22:41.486 2664-2664/com.erikkniaz.myapp.myapplication I/System.out﹕ hour 22
07-16 08:22:41.486 2664-2664/com.erikkniaz.myapp.myapplication I/System.out﹕ day null
07-16 08:22:41.486 2664-2664/com.erikkniaz.myapp.myapplication I/System.out﹕ month null
07-16 08:22:41.491 2664-2664/com.erikkniaz.myapp.myapplication I/System.out﹕ year null
i figured it out. You have to pass the data through all the screens in order. I was trying to send the data from screen 1 to screen 3. Have to do screen 1 -> screen 2-> screen 3

GWT client side cropping

I'm stuck on integrating gwt with JCrop or imgareaselect javascript libraries
I have an image, which url is changing each time the client change the file choosen from its filesystem (using an upload widget).
I want the user select the area in its image, this way i will be able to have images with aspect ratio respected respect to the client wishes.
Problem is i can't succed in making imgareaselect or jcrop called on load event, each time i have null, if i try jquery ("imagepreview") jquery is unknow at execution time, if i try some $("#imagepreview") i get a $ is undefined...
PLEASE any help...
Regards.
public class ThisWidget extends LayoutContainer {
public void onRender(Element parent, int index) {
super.onRender(parent, index);
setLayout(new VBoxLayout());
setWidth("100%");
final FormPanel uploadPhotoPanel = new FormPanel();
uploadPhotoPanel.setWidth("100%");
uploadPhotoPanel.setHeight("150px");
Label label = new Label("Ajouter une photo");
add(label);
uploadPhotoPanel.setAction(GWT.getModuleBaseURL()
+ "photoload/uploadpreview.ctz");
uploadPhotoPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
uploadPhotoPanel.setMethod(FormPanel.METHOD_POST);
final FileUploadField file = new FileUploadField();
file.setName("FILE");
uploadPhotoPanel.add(file);
file.addHandler(new ChangeHandler() {
#Override
public void onChange(ChangeEvent event) {
uploadPhotoPanel.submit();
}
}, ChangeEvent.getType());
final Button btn = new Button("Ajouter",
new SelectionListener<ButtonEvent>() {
#Override
public void componentSelected(ButtonEvent ce) {
uploadPhotoPanel.submit();
}
});
final Image previewimage;
previewimage = new Image();
DOM.setElementAttribute(previewimage.getElement(), "id",
"previewimage");
previewimage.setSize("200px", "200px");
previewimage.addLoadHandler(new LoadHandler(){
protected native void onPreviewLoad() /*-{
document.getElementById("previewimage").imgAreaSelect({
aspectRatio : '1:1',
handles : true,
fadeSpeed : 200
});
}-*/;
#Override
public void onLoad(LoadEvent event) {
onPreviewLoad();
}});
uploadPhotoPanel
.addSubmitCompleteHandler(new SubmitCompleteHandler() {
#Override
public void onSubmitComplete(SubmitCompleteEvent event) {
previewimage.setUrl(GWT.getModuleBaseURL()
+ "photoload/downloadpreview.ctz?tsp="
+ System.currentTimeMillis());
}
});
add(uploadPhotoPanel);
add(previewimage);
add(btn);
}
Use $wnd.$("#imagepreview") or $wnd.jquery("#imagepreview").
(Updated to fix the forgotten #)

gwt client session time out

I am using gwt 2.3 with gwtp framework.In this application I wan to maintain a session time of 5 mins.This means if current user is not doing up to 5 min and he comes after five min then on his first event/action on screen a he should be be logged out.
In gwt there is class named Timer which can be used in this issues.But I am not getting how to recognize action of user on the screen.I did google on it, & found the code for gwt-ext.Below is the code of gwt-ext
Ext.get(“pagePanel”).addListener(“click”, new EventCallback() {
#Override
public void execute(EventObject e) {
MessageBox.alert(“On Mouse Click”);
}
});
Ext.get(“pagePanel”).addListener(“keydown”, new EventCallback() {
#Override
public void execute(EventObject e) {
MessageBox.alert(“On Key Press Click”);
}
});
In above code tag in working properly so I am attaching link from where I got this code.here
Same type of code I am looking in gwt.If there any other better way to do this then please let me know. Thanks in advance
If action/event can be really everythin, I would solve it with a
NativePreviewHandler in the following way:
boolean expired;
final Timer logoutTimer = new Timer() {
#Override
public void run() {
expired = true;
}
};
NativePreviewHandler nph = new NativePreviewHandler() {
#Override
public void onPreviewNativeEvent(NativePreviewEvent event) {
if (!expired) {
logoutTimer.cancel();
logoutTimer.schedule(300000);
} else {
// do your logout stuff here
}
}
};
Event.addNativePreviewHandler(nph);
If the user shell be logged out without a new action after 5 minutes:
final Timer logoutTimer = new Timer() {
#Override
public void run() {
// do your logout stuff here
}
};
NativePreviewHandler nph = new NativePreviewHandler() {
#Override
public void onPreviewNativeEvent(NativePreviewEvent event) {
// Of course do this only when logged in:
logoutTimer.cancel();
logoutTimer.schedule(300000);
}
};
Event.addNativePreviewHandler(nph);